A Python UPnP Media Server

298 lines
7.7 KiB

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