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.

325 lines
8.2 KiB

  1. #!/usr/bin/env python
  2. # Copyright 2006-2008 John-Mark Gurney <jmg@funkthat.com>
  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 Container, StorageFolder, Item, VideoItem, AudioItem, TextItem, ImageItem, Resource, ResourceList
  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
  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
  62. else:
  63. raise
  64. def doUpdate(self):
  65. raise NotImplementedError
  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. vcodec = mods[0]
  108. if mods[0] not in ('xvid', 'mpeg2', ):
  109. vcodec = 'xvid'
  110. mimetype = { 'xvid': 'video/avi', 'mpeg2': 'video/mpeg', }
  111. mimetype = { 'xvid': 'video/x-msvideo', 'mpeg2': 'video/mpeg', }
  112. request.setHeader('content-type', mimetype[vcodec])
  113. if request.method == 'HEAD':
  114. return ''
  115. audiomp3 = [ '-acodec', 'mp3', '-ab', '192', ]
  116. audiomp2 = [ '-acodec', 'mp2', '-ab', '256', ]
  117. optdict = {
  118. 'xvid': [ '-vcodec', 'xvid',
  119. #'-mv4', '-gmc', '-g', '240',
  120. '-f', 'avi', ] + audiomp3,
  121. 'mpeg2': [ '-vcodec', 'mpeg2video', #'-g', '60',
  122. '-f', 'mpeg', ] + audiomp2,
  123. }
  124. args = [ 'ffmpeg', '-i', path, '-b', '4000',
  125. #'-sc_threshold', '500000', '-b_strategy', '1', '-max_b_frames', '6',
  126. ] + optdict[vcodec] + [ '-', ]
  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. self.checkUpdate()
  162. def doUpdate(self):
  163. #print 'FSItem doUpdate:', `self`
  164. self.res = ResourceList()
  165. r = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
  166. r.size = os.path.getsize(self.FSpath)
  167. self.res.append(r)
  168. if self.mimetype.split('/', 1)[0] == 'video':
  169. self.res.append(Resource(self.url + '/mpeg2',
  170. 'http-get:*:%s:*' % 'video/mpeg'))
  171. self.res.append(Resource(self.url + '/xvid',
  172. 'http-get:*:%s:*' % 'video/x-msvideo'))
  173. Item.doUpdate(self)
  174. def ignoreFiles(path, fobj):
  175. bn = os.path.basename(path)
  176. if bn in _filestoignore:
  177. return IgnoreFile, None
  178. elif bn[:2] == '._' and open(path).read(4) == '\x00\x05\x16\x07':
  179. # AppleDouble encoded Macintosh Resource Fork
  180. return IgnoreFile, None
  181. return None, None
  182. def defFS(path, fobj):
  183. if os.path.isdir(path):
  184. # new dir
  185. return FSDirectory, { 'path': path }
  186. elif os.path.isfile(path):
  187. # new file - fall through to below
  188. pass
  189. else:
  190. log.msg('skipping (not dir or reg): %s' % path)
  191. return None, None
  192. klass, mt = FileDIDL.buildClassMT(FSItem, path)
  193. return klass, { 'path': path, 'mimetype': mt }
  194. def dofileadd(cd, parent, path, name):
  195. klass = None
  196. fsname = os.path.join(path, name)
  197. try:
  198. fobj = open(fsname)
  199. except:
  200. fobj = None
  201. for i in itertools.chain(( ignoreFiles, ), _klassfuns, ( defFS, )):
  202. try:
  203. try:
  204. fobj.seek(0) # incase the call expects a clean file
  205. except:
  206. pass
  207. #log.msg('testing:', `i`, `fsname`, `fobj`)
  208. klass, kwargs = i(fsname, fobj)
  209. if klass is not None:
  210. break
  211. except:
  212. #import traceback
  213. #traceback.print_exc(file=log.logfile)
  214. pass
  215. if klass is None or klass is IgnoreFile:
  216. return
  217. #print 'matched:', os.path.join(path, name), `i`, `klass`
  218. return cd.addItem(parent, klass, name, **kwargs)
  219. class FSDirectory(FSObject, StorageFolder):
  220. def __init__(self, *args, **kwargs):
  221. path = kwargs['path']
  222. del kwargs['path']
  223. StorageFolder.__init__(self, *args, **kwargs)
  224. FSObject.__init__(self, path)
  225. # mapping from path to objectID
  226. self.pathObjmap = {}
  227. self.indoUpdate = False
  228. def doUpdate(self):
  229. # We need to rescan this dir, and see if our children has
  230. # changed any.
  231. if self.indoUpdate:
  232. return
  233. #import traceback
  234. #traceback.print_stack()
  235. self.indoUpdate = True
  236. doupdate = False
  237. children = sets.Set(os.listdir(self.FSpath))
  238. for i in self.pathObjmap.keys():
  239. if i not in children:
  240. doupdate = True
  241. # delete
  242. self.cd.delItem(self.pathObjmap[i])
  243. del self.pathObjmap[i]
  244. for i in children:
  245. if i in self.pathObjmap:
  246. continue
  247. # new object
  248. nf = dofileadd(self.cd, self.id, self.FSpath, i)
  249. if nf is not None:
  250. doupdate = True
  251. self.pathObjmap[i] = nf
  252. # sort our children
  253. self.sort(lambda x, y: cmp(x.title, y.title))
  254. # Pass up to handle UpdateID
  255. if doupdate:
  256. # Calling StorageFolder.doUpdate results in calling
  257. # ourselves.
  258. Container.doUpdate(self)
  259. self.indoUpdate = False
  260. def __repr__(self):
  261. return ('<%s.%s: path: %s, id: %s, parent: %s, title: %s, ' + \
  262. 'cnt: %d>') % (self.__class__.__module__,
  263. self.__class__.__name__, self.FSpath, self.id,
  264. self.parentID, self.title, len(self))