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.

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