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.

234 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']:
  83. raise PostProcessingError(u'ffprobe or avprobe not found. Please install one.')
  84. try:
  85. cmd = [self._exes['avprobe'] or self._exes['ffprobe'], '-show_streams', encodeFilename(self._ffmpeg_filename_argument(path))]
  86. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
  87. output = handle.communicate()[0]
  88. if handle.wait() != 0:
  89. return None
  90. except (IOError, OSError):
  91. return None
  92. audio_codec = None
  93. for line in output.decode('ascii', 'ignore').split('\n'):
  94. if line.startswith('codec_name='):
  95. audio_codec = line.split('=')[1].strip()
  96. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  97. return audio_codec
  98. return None
  99. def run_ffmpeg(self, path, out_path, codec, more_opts):
  100. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  101. raise AudioConversionError('ffmpeg or avconv not found. Please install one.')
  102. if codec is None:
  103. acodec_opts = []
  104. else:
  105. acodec_opts = ['-acodec', codec]
  106. opts = ['-vn'] + acodec_opts + more_opts
  107. try:
  108. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  109. except FFmpegPostProcessorError as err:
  110. raise AudioConversionError(err.message)
  111. def run(self, information):
  112. path = information['filepath']
  113. filecodec = self.get_audio_codec(path)
  114. if filecodec is None:
  115. raise PostProcessingError(u'WARNING: unable to obtain file audio codec with ffprobe')
  116. more_opts = []
  117. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  118. if filecodec == 'aac' and self._preferredcodec in ['m4a', 'best']:
  119. # Lossless, but in another container
  120. acodec = 'copy'
  121. extension = 'm4a'
  122. more_opts = [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  123. elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
  124. # Lossless if possible
  125. acodec = 'copy'
  126. extension = filecodec
  127. if filecodec == 'aac':
  128. more_opts = ['-f', 'adts']
  129. if filecodec == 'vorbis':
  130. extension = 'ogg'
  131. else:
  132. # MP3 otherwise.
  133. acodec = 'libmp3lame'
  134. extension = 'mp3'
  135. more_opts = []
  136. if self._preferredquality is not None:
  137. if int(self._preferredquality) < 10:
  138. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  139. else:
  140. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  141. else:
  142. # We convert the audio (lossy)
  143. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  144. extension = self._preferredcodec
  145. more_opts = []
  146. if self._preferredquality is not None:
  147. if int(self._preferredquality) < 10:
  148. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  149. else:
  150. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  151. if self._preferredcodec == 'aac':
  152. more_opts += ['-f', 'adts']
  153. if self._preferredcodec == 'm4a':
  154. more_opts += [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  155. if self._preferredcodec == 'vorbis':
  156. extension = 'ogg'
  157. if self._preferredcodec == 'wav':
  158. extension = 'wav'
  159. more_opts += ['-f', 'wav']
  160. prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
  161. new_path = prefix + sep + extension
  162. # If we download foo.mp3 and convert it to... foo.mp3, then don't delete foo.mp3, silly.
  163. if new_path == path:
  164. self._nopostoverwrites = True
  165. try:
  166. if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
  167. self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
  168. else:
  169. self._downloader.to_screen(u'[' + (self._exes['avconv'] and 'avconv' or 'ffmpeg') + '] Destination: ' + new_path)
  170. self.run_ffmpeg(path, new_path, acodec, more_opts)
  171. except:
  172. etype,e,tb = sys.exc_info()
  173. if isinstance(e, AudioConversionError):
  174. msg = u'audio conversion failed: ' + e.message
  175. else:
  176. msg = u'error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg')
  177. raise PostProcessingError(msg)
  178. # Try to update the date time for extracted audio file.
  179. if information.get('filetime') is not None:
  180. try:
  181. os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
  182. except:
  183. self._downloader.report_warning(u'Cannot update utime of audio file')
  184. information['filepath'] = new_path
  185. return self._nopostoverwrites,information
  186. class FFmpegVideoConvertor(FFmpegPostProcessor):
  187. def __init__(self, downloader=None,preferedformat=None):
  188. super(FFmpegVideoConvertor, self).__init__(downloader)
  189. self._preferedformat=preferedformat
  190. def run(self, information):
  191. path = information['filepath']
  192. prefix, sep, ext = path.rpartition(u'.')
  193. outpath = prefix + sep + self._preferedformat
  194. if information['ext'] == self._preferedformat:
  195. self._downloader.to_screen(u'[ffmpeg] Not converting video file %s - already is in target format %s' % (path, self._preferedformat))
  196. return True,information
  197. self._downloader.to_screen(u'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information['ext'], self._preferedformat) +outpath)
  198. self.run_ffmpeg(path, outpath, [])
  199. information['filepath'] = outpath
  200. information['format'] = self._preferedformat
  201. information['ext'] = self._preferedformat
  202. return False,information