A Python UPnP Media Server
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

306 lines
7.6 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2006 John-Mark Gurney <gurney_j@resnet.uoregon.edu>
  3. __version__ = '$Change$'
  4. # $Id$
  5. ffmpeg_path = '/usr/local/bin/ffmpeg'
  6. import FileDIDL
  7. import errno
  8. import itertools
  9. import os
  10. import sets
  11. import stat
  12. from DIDLLite import StorageFolder, Item, VideoItem, AudioItem, TextItem, ImageItem, Resource
  13. from twisted.web import resource, server, static
  14. from twisted.python import log
  15. from twisted.internet import abstract, interfaces, process, protocol, reactor
  16. from zope.interface import implements
  17. __all__ = [ 'registerklassfun', 'registerfiletoignore',
  18. 'FSObject', 'FSItem', 'FSDirectory',
  19. 'FSVideoItem', 'FSAudioItem', 'FSTextItem', 'FSImageItem',
  20. 'mimetoklass',
  21. ]
  22. mimedict = static.loadMimeTypes()
  23. _klassfuns = []
  24. def registerklassfun(fun):
  25. _klassfuns.append(fun)
  26. _filestoignore = {
  27. '.DS_Store': None
  28. }
  29. def registerfiletoignore(f):
  30. _filestoignore[f] = None
  31. # Return this class when you want the file to be skipped. If you return this,
  32. # no other modules will be applied, and it won't be added. Useful for things
  33. # like .DS_Store which are known to useless on a media server.
  34. class IgnoreFile:
  35. pass
  36. def statcmp(a, b, cmpattrs = [ 'st_ino', 'st_dev', 'st_size', 'st_mtime', ]):
  37. if a is None or b is None:
  38. return False
  39. for i in cmpattrs:
  40. if getattr(a, i) != getattr(b, i):
  41. return False
  42. return True
  43. class FSObject(object):
  44. def __init__(self, path):
  45. self.FSpath = path
  46. self.pstat = None
  47. def checkUpdate(self):
  48. # need to handle no such file or directory
  49. # push it up? but still need to handle disappearing
  50. try:
  51. nstat = os.stat(self.FSpath)
  52. if statcmp(self.pstat, nstat):
  53. return self
  54. self.pstat = nstat
  55. self.doUpdate()
  56. except OSError, x:
  57. log.msg('os.stat, OSError: %s' % x)
  58. if x.errno in (errno.ENOENT, errno.ENOTDIR, errno.EPERM, ):
  59. # We can't access it anymore, delete it
  60. self.cd.delItem(self.id)
  61. return None
  62. else:
  63. raise
  64. return self
  65. def doUpdate(self):
  66. raise NotImplementedError
  67. def __repr__(self):
  68. return '<%s.%s: path: %s, id: %s, parent: %s, title: %s>' % \
  69. (self.__class__.__module__, self.__class__.__name__,
  70. self.FSpath, self.id, self.parentID, self.title)
  71. class NullConsumer(file, abstract.FileDescriptor):
  72. implements(interfaces.IConsumer)
  73. def __init__(self):
  74. file.__init__(self, '/dev/null', 'w')
  75. abstract.FileDescriptor.__init__(self)
  76. def write(self, data):
  77. pass
  78. class DynamTransfer(protocol.ProcessProtocol):
  79. def __init__(self, path, mods, request):
  80. self.path = path
  81. self.mods = mods
  82. self.request = request
  83. def outReceived(self, data):
  84. self.request.write(data)
  85. def outConnectionLost(self):
  86. if self.request:
  87. self.request.unregisterProducer()
  88. self.request.finish()
  89. self.request = None
  90. def errReceived(self, data):
  91. pass
  92. #log.msg(data)
  93. def stopProducing(self):
  94. if self.request:
  95. self.request.unregisterProducer()
  96. self.request.finish()
  97. if self.proc:
  98. self.proc.loseConnection()
  99. self.proc.signalProcess('INT')
  100. self.request = None
  101. self.proc = None
  102. pauseProducing = lambda x: x.proc.pauseProducing()
  103. resumeProducing = lambda x: x.proc.resumeProducing()
  104. def render(self):
  105. mods = self.mods
  106. path = self.path
  107. request = self.request
  108. vcodec = mods[0]
  109. if mods[0] not in ('xvid', 'mpeg2', ):
  110. vcodec = 'xvid'
  111. mimetype = { 'xvid': 'video/avi', 'mpeg2': 'video/mpeg', }
  112. mimetype = { 'xvid': 'video/x-msvideo', 'mpeg2': 'video/mpeg', }
  113. request.setHeader('content-type', mimetype[vcodec])
  114. if request.method == 'HEAD':
  115. return ''
  116. optdict = {
  117. 'xvid': [ '-vcodec', 'xvid',
  118. #'-mv4', '-gmc', '-g', '240',
  119. '-f', 'avi', ],
  120. 'mpeg2': [ '-vcodec', 'mpeg2video', #'-g', '60',
  121. '-f', 'mpeg', ],
  122. }
  123. audio = [ '-acodec', 'mp3', '-ab', '192', ]
  124. args = [ 'ffmpeg', '-i', path, '-b', '8000',
  125. #'-sc_threshold', '500000', '-b_strategy', '1', '-max_b_frames', '6',
  126. ] + optdict[vcodec] + audio + [ '-', ]
  127. #log.msg(*[`i` for i in args])
  128. self.proc = process.Process(reactor, ffmpeg_path, args,
  129. None, None, self)
  130. self.proc.closeStdin()
  131. request.registerProducer(self, 1)
  132. return server.NOT_DONE_YET
  133. class DynamicTrans(resource.Resource):
  134. isLeaf = True
  135. def __init__(self, path, notrans):
  136. self.path = path
  137. self.notrans = notrans
  138. def render(self, request):
  139. #if request.getHeader('getcontentfeatures.dlna.org'):
  140. # request.setHeader('contentFeatures.dlna.org', 'DLNA.ORG_OP=01;DLNA.ORG_CI=0')
  141. # # we only want the headers
  142. # self.notrans.render(request)
  143. # request.unregisterProducer()
  144. # return ''
  145. if request.postpath:
  146. # Translation request
  147. return DynamTransfer(self.path, request.postpath, request).render()
  148. else:
  149. return self.notrans.render(request)
  150. class FSItem(FSObject, Item):
  151. def __init__(self, *args, **kwargs):
  152. FSObject.__init__(self, kwargs['path'])
  153. del kwargs['path']
  154. mimetype = kwargs['mimetype']
  155. del kwargs['mimetype']
  156. kwargs['content'] = DynamicTrans(self.FSpath,
  157. static.File(self.FSpath, mimetype))
  158. Item.__init__(self, *args, **kwargs)
  159. self.url = '%s/%s' % (self.cd.urlbase, self.id)
  160. self.mimetype = mimetype
  161. def doUpdate(self):
  162. self.res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
  163. self.res.size = os.path.getsize(self.FSpath)
  164. self.res = [ self.res ]
  165. self.res.append(Resource(self.url + '/mpeg2', 'http-get:*:%s:*' % 'video/mpeg'))
  166. self.res.append(Resource(self.url + '/xvid', 'http-get:*:%s:*' % 'video/x-msvideo'))
  167. Item.doUpdate(self)
  168. def ignoreFiles(path, fobj):
  169. if os.path.basename(path) in _filestoignore:
  170. return IgnoreFile, None
  171. return None, None
  172. def defFS(path, fobj):
  173. if os.path.isdir(path):
  174. # new dir
  175. return FSDirectory, { 'path': path }
  176. elif os.path.isfile(path):
  177. # new file - fall through to below
  178. pass
  179. else:
  180. log.msg('skipping (not dir or reg): %s' % path)
  181. return None, None
  182. klass, mt = FileDIDL.buildClassMT(FSItem, path)
  183. return klass, { 'path': path, 'mimetype': mt }
  184. def dofileadd(cd, parent, path, name):
  185. klass = None
  186. fsname = os.path.join(path, name)
  187. try:
  188. fobj = open(fsname)
  189. except:
  190. fobj = None
  191. for i in itertools.chain(( ignoreFiles, ), _klassfuns, ( defFS, )):
  192. try:
  193. try:
  194. fobj.seek(0) # incase the call expects a clean file
  195. except:
  196. pass
  197. #log.msg('testing:', `i`, `fsname`, `fobj`)
  198. klass, kwargs = i(fsname, fobj)
  199. if klass is not None:
  200. break
  201. except:
  202. #import traceback
  203. #traceback.print_exc(file=log.logfile)
  204. pass
  205. if klass is None or klass is IgnoreFile:
  206. return
  207. #log.msg('matched:', os.path.join(path, name), `i`, `klass`)
  208. return cd.addItem(parent, klass, name, **kwargs)
  209. class FSDirectory(FSObject, StorageFolder):
  210. def __init__(self, *args, **kwargs):
  211. path = kwargs['path']
  212. del kwargs['path']
  213. StorageFolder.__init__(self, *args, **kwargs)
  214. FSObject.__init__(self, path)
  215. # mapping from path to objectID
  216. self.pathObjmap = {}
  217. def doUpdate(self):
  218. # We need to rescan this dir, and see if our children has
  219. # changed any.
  220. doupdate = False
  221. children = sets.Set(os.listdir(self.FSpath))
  222. for i in self.pathObjmap.keys():
  223. if i not in children:
  224. doupdate = True
  225. # delete
  226. self.cd.delItem(self.pathObjmap[i])
  227. del self.pathObjmap[i]
  228. for i in children:
  229. if i in self.pathObjmap:
  230. continue
  231. # new object
  232. nf = dofileadd(self.cd, self.id, self.FSpath, i)
  233. if nf is not None:
  234. doupdate = True
  235. self.pathObjmap[i] = nf
  236. # sort our children
  237. self.sort(lambda x, y: cmp(x.title, y.title))
  238. # Pass up to handle UpdateID
  239. if doupdate:
  240. StorageFolder.doUpdate(self)
  241. def __repr__(self):
  242. return ('<%s.%s: path: %s, id: %s, parent: %s, title: %s, ' + \
  243. 'cnt: %d>') % (self.__class__.__module__,
  244. self.__class__.__name__, self.FSpath, self.id,
  245. self.parentID, self.title, len(self))