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.

244 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. When this method returns None, the postprocessing chain is
  35. stopped. However, this method may return an information
  36. dictionary that will be passed to the next postprocessing
  37. object in the chain. It can be the one it received after
  38. changing some fields.
  39. In addition, this method may raise a PostProcessingError
  40. exception that will be taken into account by the downloader
  41. it was called from.
  42. """
  43. return information # by default, do nothing
  44. class FFmpegPostProcessorError(BaseException):
  45. def __init__(self, message):
  46. self.message = message
  47. class AudioConversionError(BaseException):
  48. def __init__(self, message):
  49. self.message = message
  50. class FFmpegPostProcessor(PostProcessor):
  51. def __init__(self,downloader=None):
  52. PostProcessor.__init__(self, downloader)
  53. self._exes = self.detect_executables()
  54. @staticmethod
  55. def detect_executables():
  56. def executable(exe):
  57. try:
  58. subprocess.Popen([exe, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  59. except OSError:
  60. return False
  61. return exe
  62. programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
  63. return dict((program, executable(program)) for program in programs)
  64. def run_ffmpeg(self, path, out_path, opts):
  65. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  66. raise FFmpegPostProcessorError('ffmpeg or avconv not found. Please install one.')
  67. cmd = ([self._exes['avconv'] or self._exes['ffmpeg'], '-y', '-i', encodeFilename(path)]
  68. + opts +
  69. [encodeFilename(self._ffmpeg_filename_argument(out_path))])
  70. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  71. stdout,stderr = p.communicate()
  72. if p.returncode != 0:
  73. msg = stderr.strip().split('\n')[-1]
  74. raise FFmpegPostProcessorError(msg)
  75. def _ffmpeg_filename_argument(self, fn):
  76. # ffmpeg broke --, see https://ffmpeg.org/trac/ffmpeg/ticket/2127 for details
  77. if fn.startswith(u'-'):
  78. return u'./' + fn
  79. return fn
  80. class FFmpegExtractAudioPP(FFmpegPostProcessor):
  81. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, keepvideo=False, nopostoverwrites=False):
  82. FFmpegPostProcessor.__init__(self, downloader)
  83. if preferredcodec is None:
  84. preferredcodec = 'best'
  85. self._preferredcodec = preferredcodec
  86. self._preferredquality = preferredquality
  87. self._keepvideo = keepvideo
  88. self._nopostoverwrites = nopostoverwrites
  89. def get_audio_codec(self, path):
  90. if not self._exes['ffprobe'] and not self._exes['avprobe']: return None
  91. try:
  92. cmd = [self._exes['avprobe'] or self._exes['ffprobe'], '-show_streams', encodeFilename(self._ffmpeg_filename_argument(path))]
  93. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
  94. output = handle.communicate()[0]
  95. if handle.wait() != 0:
  96. return None
  97. except (IOError, OSError):
  98. return None
  99. audio_codec = None
  100. for line in output.decode('ascii', 'ignore').split('\n'):
  101. if line.startswith('codec_name='):
  102. audio_codec = line.split('=')[1].strip()
  103. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  104. return audio_codec
  105. return None
  106. def run_ffmpeg(self, path, out_path, codec, more_opts):
  107. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  108. raise AudioConversionError('ffmpeg or avconv not found. Please install one.')
  109. if codec is None:
  110. acodec_opts = []
  111. else:
  112. acodec_opts = ['-acodec', codec]
  113. opts = ['-vn'] + acodec_opts + more_opts
  114. try:
  115. FFmpegPostProcessor.run_ffmpeg(self, path, out_path, opts)
  116. except FFmpegPostProcessorError as err:
  117. raise AudioConversionError(err.message)
  118. def run(self, information):
  119. path = information['filepath']
  120. filecodec = self.get_audio_codec(path)
  121. if filecodec is None:
  122. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  123. return None
  124. more_opts = []
  125. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  126. if self._preferredcodec == 'm4a' and filecodec == 'aac':
  127. # Lossless, but in another container
  128. acodec = 'copy'
  129. extension = self._preferredcodec
  130. more_opts = [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  131. elif filecodec in ['aac', 'mp3', 'vorbis', 'opus']:
  132. # Lossless if possible
  133. acodec = 'copy'
  134. extension = filecodec
  135. if filecodec == 'aac':
  136. more_opts = ['-f', 'adts']
  137. if filecodec == 'vorbis':
  138. extension = 'ogg'
  139. else:
  140. # MP3 otherwise.
  141. acodec = 'libmp3lame'
  142. extension = 'mp3'
  143. more_opts = []
  144. if self._preferredquality is not None:
  145. if int(self._preferredquality) < 10:
  146. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  147. else:
  148. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  149. else:
  150. # We convert the audio (lossy)
  151. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'opus': 'opus', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  152. extension = self._preferredcodec
  153. more_opts = []
  154. if self._preferredquality is not None:
  155. if int(self._preferredquality) < 10:
  156. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  157. else:
  158. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  159. if self._preferredcodec == 'aac':
  160. more_opts += ['-f', 'adts']
  161. if self._preferredcodec == 'm4a':
  162. more_opts += [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  163. if self._preferredcodec == 'vorbis':
  164. extension = 'ogg'
  165. if self._preferredcodec == 'wav':
  166. extension = 'wav'
  167. more_opts += ['-f', 'wav']
  168. prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
  169. new_path = prefix + sep + extension
  170. try:
  171. if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
  172. self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
  173. else:
  174. self._downloader.to_screen(u'[' + (self._exes['avconv'] and 'avconv' or 'ffmpeg') + '] Destination: ' + new_path)
  175. self.run_ffmpeg(path, new_path, acodec, more_opts)
  176. except:
  177. etype,e,tb = sys.exc_info()
  178. if isinstance(e, AudioConversionError):
  179. self._downloader.to_stderr(u'ERROR: audio conversion failed: ' + e.message)
  180. else:
  181. self._downloader.to_stderr(u'ERROR: error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg'))
  182. return None
  183. # Try to update the date time for extracted audio file.
  184. if information.get('filetime') is not None:
  185. try:
  186. os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
  187. except:
  188. self._downloader.to_stderr(u'WARNING: Cannot update utime of audio file')
  189. if not self._keepvideo:
  190. try:
  191. os.remove(encodeFilename(path))
  192. except (IOError, OSError):
  193. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  194. return None
  195. information['filepath'] = new_path
  196. return information
  197. class FFmpegVideoConvertor(FFmpegPostProcessor):
  198. def __init__(self, downloader=None,preferedformat=None):
  199. FFmpegPostProcessor.__init__(self,downloader)
  200. self._preferedformat=preferedformat
  201. def run(self, information):
  202. path = information['filepath']
  203. prefix, sep, ext = path.rpartition(u'.')
  204. outpath = prefix + sep + self._preferedformat
  205. if not self._preferedformat or information['format'] == self._preferedformat:
  206. return information
  207. self._downloader.to_screen(u'['+'ffmpeg'+'] Converting video from %s to %s, Destination: ' % (information['format'], self._preferedformat) +outpath)
  208. self.run_ffmpeg(path, outpath, [])
  209. information['filepath'] = outpath
  210. information['format'] = self._preferedformat
  211. return information