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.

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