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.

237 lines
10 KiB

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