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.

233 lines
10 KiB

  1. import os
  2. import subprocess
  3. import sys
  4. import time
  5. from .utils import *
  6. class PostProcessor(object):
  7. """Post Processor class.
  8. PostProcessor objects can be added to downloaders with their
  9. add_post_processor() method. When the downloader has finished a
  10. successful download, it will take its internal chain of PostProcessors
  11. and start calling the run() method on each one of them, first with
  12. an initial argument and then with the returned value of the previous
  13. PostProcessor.
  14. The chain will be stopped if one of them ever returns None or the end
  15. of the chain is reached.
  16. PostProcessor objects follow a "mutual registration" process similar
  17. to InfoExtractor objects.
  18. """
  19. _downloader = None
  20. def __init__(self, downloader=None):
  21. self._downloader = downloader
  22. def set_downloader(self, downloader):
  23. """Sets the downloader for this PP."""
  24. self._downloader = downloader
  25. def run(self, information):
  26. """Run the PostProcessor.
  27. The "information" argument is a dictionary like the ones
  28. composed by InfoExtractors. The only difference is that this
  29. one has an extra field called "filepath" that points to the
  30. downloaded file.
  31. This method returns a tuple, the first element of which describes
  32. whether the original file should be kept (i.e. not deleted - None for
  33. no preference), and the second of which is the updated information.
  34. In addition, this method may raise a PostProcessingError
  35. exception if post processing fails.
  36. """
  37. return None, information # by default, keep file and do nothing
  38. class FFmpegPostProcessorError(PostProcessingError):
  39. pass
  40. class AudioConversionError(PostProcessingError):
  41. pass
  42. class FFmpegPostProcessor(PostProcessor):
  43. def __init__(self,downloader=None):
  44. PostProcessor.__init__(self, downloader)
  45. self._exes = self.detect_executables()
  46. @staticmethod
  47. def detect_executables():
  48. def executable(exe):
  49. try:
  50. subprocess.Popen([exe, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  51. except OSError:
  52. return False
  53. return exe
  54. programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
  55. return dict((program, executable(program)) for program in programs)
  56. def run_ffmpeg(self, path, out_path, opts):
  57. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  58. raise FFmpegPostProcessorError(u'ffmpeg or avconv not found. Please install one.')
  59. cmd = ([self._exes['avconv'] or self._exes['ffmpeg'], '-y', '-i', encodeFilename(path)]
  60. + opts +
  61. [encodeFilename(self._ffmpeg_filename_argument(out_path))])
  62. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  63. stdout,stderr = p.communicate()
  64. if p.returncode != 0:
  65. stderr = stderr.decode('utf-8', 'replace')
  66. msg = stderr.strip().split('\n')[-1]
  67. raise FFmpegPostProcessorError(msg)
  68. def _ffmpeg_filename_argument(self, fn):
  69. # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
  70. if fn.startswith(u'-'):
  71. return u'./' + fn
  72. return fn
  73. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  74. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, nopostoverwrites=False):
  75. FFmpegPostProcessor.__init__(self, downloader)
  76. if preferredcodec is None:
  77. preferredcodec = 'best'
  78. self._preferredcodec = preferredcodec
  79. self._preferredquality = preferredquality
  80. self._nopostoverwrites = nopostoverwrites
  81. def get_audio_codec(self, path):
  82. if not self._exes['ffprobe'] and not self._exes['avprobe']: return None
  83. try:
  84. cmd = [self._exes['avprobe'] or self._exes['ffprobe'], '-show_streams', encodeFilename(self._ffmpeg_filename_argument(path))]
  85. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
  86. output = handle.communicate()[0]
  87. if handle.wait() != 0:
  88. return None
  89. except (IOError, OSError):
  90. return None
  91. audio_codec = None
  92. for line in output.decode('ascii', 'ignore').split('\n'):
  93. if line.startswith('codec_name='):
  94. audio_codec = line.split('=')[1].strip()
  95. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  96. return audio_codec
  97. return None
  98. def run_ffmpeg(self, path, out_path, codec, more_opts):
  99. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  100. raise AudioConversionError('ffmpeg or avconv not found. Please install one.')
  101. if codec is None:
  102. acodec_opts = []
  103. else:
  104. acodec_opts = ['-acodec', codec]
  105. opts = ['-vn'] + acodec_opts + more_opts
  106. try:
  107. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  108. except FFmpegPostProcessorError as err:
  109. raise AudioConversionError(err.message)
  110. def run(self, information):
  111. path = information['filepath']
  112. filecodec = self.get_audio_codec(path)
  113. if filecodec is None:
  114. raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
  115. more_opts = []
  116. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  117. if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
  118. # Lossless, but in another container
  119. acodec = 'copy'
  120. extension = 'm4a'
  121. more_opts = [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  122. elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
  123. # Lossless if possible
  124. acodec = 'copy'
  125. extension = filecodec
  126. if filecodec == 'aac':
  127. more_opts = ['-f', 'adts']
  128. if filecodec == 'vorbis':
  129. extension = 'ogg'
  130. else:
  131. # MP3 otherwise.
  132. acodec = 'libmp3lame'
  133. extension = 'mp3'
  134. more_opts = []
  135. if self._preferredquality is not None:
  136. if int(self._preferredquality) < 10:
  137. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  138. else:
  139. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  140. else:
  141. # We convert the audio (lossy)
  142. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  143. extension = self._preferredcodec
  144. more_opts = []
  145. if self._preferredquality is not None:
  146. if int(self._preferredquality) < 10:
  147. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  148. else:
  149. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  150. if self._preferredcodec == 'aac':
  151. more_opts += ['-f', 'adts']
  152. if self._preferredcodec == 'm4a':
  153. more_opts += [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  154. if self._preferredcodec == 'vorbis':
  155. extension = 'ogg'
  156. if self._preferredcodec == 'wav':
  157. extension = 'wav'
  158. more_opts += ['-f', 'wav']
  159. prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
  160. new_path = prefix + sep + extension
  161. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  162. if new_path == path:
  163. self._nopostoverwrites = True
  164. try:
  165. if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
  166. self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
  167. else:
  168. self._downloader.to_screen(u'[' + (self._exes['avconv'] and 'avconv' or 'ffmpeg') + '] Destination: ' + new_path)
  169. self.run_ffmpeg(path, new_path, acodec, more_opts)
  170. except:
  171. etype,e,tb = sys.exc_info()
  172. if isinstance(e, AudioConversionError):
  173. msg = u'audio conversion failed: ' + e.message
  174. else:
  175. msg = u'error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg')
  176. raise PostProcessingError(msg)
  177. # Try to update the date time for extracted audio file.
  178. if information.get('filetime') is not None:
  179. try:
  180. os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
  181. except:
  182. self._downloader.to_stderr(u'WARNING: Cannot update utime of audio file')
  183. information['filepath'] = new_path
  184. return self._nopostoverwrites,information
  185. class FFmpegVideoConvertor(FFmpegPostProcessor):
  186. def __init__(self, downloader=None,preferedformat=None):
  187. super(FFmpegVideoConvertor, self).__init__(downloader)
  188. self._preferedformat=preferedformat
  189. def run(self, information):
  190. path = information['filepath']
  191. prefix, sep, ext = path.rpartition(u'.')
  192. outpath = prefix + sep + self._preferedformat
  193. if information['ext'] == self._preferedformat:
  194. self._downloader.to_screen(u'[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
  195. return True,information
  196. self._downloader.to_screen(u'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) +outpath)
  197. self.run_ffmpeg(path, outpath, [])
  198. information['filepath'] = outpath
  199. information['format'] = self._preferedformat
  200. information['ext'] = self._preferedformat
  201. return False,information