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.

307 lines
7.7 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. audiomp3 = [ '-acodec', 'mp3', '-ab', '192', ]
  117. audiomp2 = [ '-acodec', 'mp2', '-ab', '256', ]
  118. optdict = {
  119. 'xvid': [ '-vcodec', 'xvid',
  120. #'-mv4', '-gmc', '-g', '240',
  121. '-f', 'avi', ] + audiomp3,
  122. 'mpeg2': [ '-vcodec', 'mpeg2video', #'-g', '60',
  123. '-f', 'mpeg', ] + audiomp2,
  124. }
  125. args = [ 'ffmpeg', '-i', path, '-b', '4000',
  126. #'-sc_threshold', '500000', '-b_strategy', '1', '-max_b_frames', '6',
  127. ] + optdict[vcodec] + [ '-', ]
  128. #log.msg(*[`i` for i in args])
  129. self.proc = process.Process(reactor, ffmpeg_path, args,
  130. None, None, self)
  131. self.proc.closeStdin()
  132. request.registerProducer(self, 1)
  133. return server.NOT_DONE_YET
  134. class DynamicTrans(resource.Resource):
  135. isLeaf = True
  136. def __init__(self, path, notrans):
  137. self.path = path
  138. self.notrans = notrans
  139. def render(self, request):
  140. #if request.getHeader('getcontentfeatures.dlna.org'):
  141. # request.setHeader('contentFeatures.dlna.org', 'DLNA.ORG_OP=01;DLNA.ORG_CI=0')
  142. # # we only want the headers
  143. # self.notrans.render(request)
  144. # request.unregisterProducer()
  145. # return ''
  146. if request.postpath:
  147. # Translation request
  148. return DynamTransfer(self.path, request.postpath, request).render()
  149. else:
  150. return self.notrans.render(request)
  151. class FSItem(FSObject, Item):
  152. def __init__(self, *args, **kwargs):
  153. FSObject.__init__(self, kwargs['path'])
  154. del kwargs['path']
  155. mimetype = kwargs['mimetype']
  156. del kwargs['mimetype']
  157. kwargs['content'] = DynamicTrans(self.FSpath,
  158. static.File(self.FSpath, mimetype))
  159. Item.__init__(self, *args, **kwargs)
  160. self.url = '%s/%s' % (self.cd.urlbase, self.id)
  161. self.mimetype = mimetype
  162. def doUpdate(self):
  163. self.res = Resource(self.url, 'http-get:*:%s:*' % self.mimetype)
  164. self.res.size = os.path.getsize(self.FSpath)
  165. self.res = [ self.res ]
  166. self.res.append(Resource(self.url + '/mpeg2', 'http-get:*:%s:*' % 'video/mpeg'))
  167. self.res.append(Resource(self.url + '/xvid', 'http-get:*:%s:*' % 'video/x-msvideo'))
  168. Item.doUpdate(self)
  169. def ignoreFiles(path, fobj):
  170. if os.path.basename(path) in _filestoignore:
  171. return IgnoreFile, None
  172. return None, None
  173. def defFS(path, fobj):
  174. if os.path.isdir(path):
  175. # new dir
  176. return FSDirectory, { 'path': path }
  177. elif os.path.isfile(path):
  178. # new file - fall through to below
  179. pass
  180. else:
  181. log.msg('skipping (not dir or reg): %s' % path)
  182. return None, None
  183. klass, mt = FileDIDL.buildClassMT(FSItem, path)
  184. return klass, { 'path': path, 'mimetype': mt }
  185. def dofileadd(cd, parent, path, name):
  186. klass = None
  187. fsname = os.path.join(path, name)
  188. try:
  189. fobj = open(fsname)
  190. except:
  191. fobj = None
  192. for i in itertools.chain(( ignoreFiles, ), _klassfuns, ( defFS, )):
  193. try:
  194. try:
  195. fobj.seek(0) # incase the call expects a clean file
  196. except:
  197. pass
  198. #log.msg('testing:', `i`, `fsname`, `fobj`)
  199. klass, kwargs = i(fsname, fobj)
  200. if klass is not None:
  201. break
  202. except:
  203. #import traceback
  204. #traceback.print_exc(file=log.logfile)
  205. pass
  206. if klass is None or klass is IgnoreFile:
  207. return
  208. #log.msg('matched:', os.path.join(path, name), `i`, `klass`)
  209. return cd.addItem(parent, klass, name, **kwargs)
  210. class FSDirectory(FSObject, StorageFolder):
  211. def __init__(self, *args, **kwargs):
  212. path = kwargs['path']
  213. del kwargs['path']
  214. StorageFolder.__init__(self, *args, **kwargs)
  215. FSObject.__init__(self, path)
  216. # mapping from path to objectID
  217. self.pathObjmap = {}
  218. def doUpdate(self):
  219. # We need to rescan this dir, and see if our children has
  220. # changed any.
  221. doupdate = False
  222. children = sets.Set(os.listdir(self.FSpath))
  223. for i in self.pathObjmap.keys():
  224. if i not in children:
  225. doupdate = True
  226. # delete
  227. self.cd.delItem(self.pathObjmap[i])
  228. del self.pathObjmap[i]
  229. for i in children:
  230. if i in self.pathObjmap:
  231. continue
  232. # new object
  233. nf = dofileadd(self.cd, self.id, self.FSpath, i)
  234. if nf is not None:
  235. doupdate = True
  236. self.pathObjmap[i] = nf
  237. # sort our children
  238. self.sort(lambda x, y: cmp(x.title, y.title))
  239. # Pass up to handle UpdateID
  240. if doupdate:
  241. StorageFolder.doUpdate(self)
  242. def __repr__(self):
  243. return ('<%s.%s: path: %s, id: %s, parent: %s, title: %s, ' + \
  244. 'cnt: %d>') % (self.__class__.__module__,
  245. self.__class__.__name__, self.FSpath, self.id,
  246. self.parentID, self.title, len(self))