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.

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