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.

300 lines
7.9 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. request.setHeader('transferMode.dlna.org', 'Streaming')
  159. request.setHeader('contentFeatures.dlna.org', 'DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=017000 00000000000000000000000000')
  160. return self.notrans.render(request)
  161. class FSItem(FSObject, Item):
  162. def __init__(self, *args, **kwargs):
  163. FSObject.__init__(self, kwargs.pop('path'))
  164. mimetype = kwargs.pop('mimetype')
  165. kwargs['content'] = DynamicTrans(self.FSpath,
  166. static.File(self.FSpath, mimetype))
  167. Item.__init__(self, *args, **kwargs)
  168. self.url = '%s/%s' % (self.cd.urlbase, self.id)
  169. self.mimetype = mimetype
  170. self.checkUpdate()
  171. def doUpdate(self):
  172. #print 'FSItem doUpdate:', `self`
  173. self.res = ResourceList()
  174. r = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
  175. r.size = os.path.getsize(self.FSpath)
  176. self.res.append(r)
  177. if self.mimetype.split('/', 1)[0] == 'video':
  178. self.res.append(Resource(self.url + '/mpeg2',
  179. 'http-get:*:%s:*' % 'video/mpeg'))
  180. self.res.append(Resource(self.url + '/xvid',
  181. 'http-get:*:%s:*' % 'video/x-msvideo'))
  182. Item.doUpdate(self)
  183. def ignoreFiles(path, fobj):
  184. bn = os.path.basename(path)
  185. if bn in _filestoignore:
  186. return IgnoreFile, None
  187. elif bn[:2] == '._' and open(path).read(4) == '\x00\x05\x16\x07':
  188. # AppleDouble encoded Macintosh Resource Fork
  189. return IgnoreFile, None
  190. return None, None
  191. def defFS(path, fobj):
  192. if os.path.isdir(path):
  193. # new dir
  194. return FSDirectory, { 'path': path }
  195. elif os.path.isfile(path):
  196. # new file - fall through to below
  197. pass
  198. else:
  199. log.msg('skipping (not dir or reg): %s' % path)
  200. return None, None
  201. klass, mt = FileDIDL.buildClassMT(FSItem, path)
  202. return klass, { 'path': path, 'mimetype': mt }
  203. def dofileadd(path, name):
  204. klass = None
  205. fsname = os.path.join(path, name)
  206. try:
  207. fobj = open(fsname)
  208. except:
  209. fobj = None
  210. for i, debug in itertools.chain(( (ignoreFiles, False), ), _klassfuns, ( (defFS, False), )):
  211. try:
  212. try:
  213. # incase the call expects a clean file
  214. fobj.seek(0)
  215. except:
  216. pass
  217. #log.msg('testing:', `i`, `fsname`, `fobj`)
  218. klass, kwargs = i(fsname, fobj)
  219. if klass is not None:
  220. break
  221. except:
  222. if debug:
  223. import traceback
  224. traceback.print_exc(file=log.logfile)
  225. if klass is None or klass is IgnoreFile:
  226. return None, None, None, None
  227. #print 'matched:', os.path.join(path, name), `i`, `klass`
  228. return klass, name, (), kwargs
  229. class FSDirectory(FSObject, StorageFolder):
  230. def __init__(self, *args, **kwargs):
  231. path = kwargs['path']
  232. del kwargs['path']
  233. StorageFolder.__init__(self, *args, **kwargs)
  234. FSObject.__init__(self, path)
  235. def genCurrent(self):
  236. return ((x.id, os.path.basename(x.FSpath)) for x in self )
  237. def genChildren(self):
  238. return os.listdir(self.FSpath)
  239. def createObject(self, i):
  240. return dofileadd(self.FSpath, i)
  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))