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.

204 lines
8.5 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 AudioConversionError(BaseException):
  45. def __init__(self, message):
  46. self.message = message
  47. class FFmpegExtractAudioPP(PostProcessor):
  48. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, keepvideo=False, nopostoverwrites=False):
  49. PostProcessor.__init__(self, downloader)
  50. if preferredcodec is None:
  51. preferredcodec = 'best'
  52. self._preferredcodec = preferredcodec
  53. self._preferredquality = preferredquality
  54. self._keepvideo = keepvideo
  55. self._nopostoverwrites = nopostoverwrites
  56. self._exes = self.detect_executables()
  57. @staticmethod
  58. def detect_executables():
  59. def executable(exe):
  60. try:
  61. subprocess.Popen([exe, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
  62. except OSError:
  63. return False
  64. return exe
  65. programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
  66. return dict((program, executable(program)) for program in programs)
  67. def get_audio_codec(self, path):
  68. if not self._exes['ffprobe'] and not self._exes['avprobe']: return None
  69. try:
  70. cmd = [self._exes['avprobe'] or self._exes['ffprobe'], '-show_streams', '--', encodeFilename(path)]
  71. handle = subprocess.Popen(cmd, stderr=compat_subprocess_get_DEVNULL(), stdout=subprocess.PIPE)
  72. output = handle.communicate()[0]
  73. if handle.wait() != 0:
  74. return None
  75. except (IOError, OSError):
  76. return None
  77. audio_codec = None
  78. for line in output.decode('ascii', 'ignore').split('\n'):
  79. if line.startswith('codec_name='):
  80. audio_codec = line.split('=')[1].strip()
  81. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  82. return audio_codec
  83. return None
  84. def run_ffmpeg(self, path, out_path, codec, more_opts):
  85. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  86. raise AudioConversionError('ffmpeg or avconv not found. Please install one.')
  87. if codec is None:
  88. acodec_opts = []
  89. else:
  90. acodec_opts = ['-acodec', codec]
  91. cmd = ([self._exes['avconv'] or self._exes['ffmpeg'], '-y', '-i', encodeFilename(path), '-vn']
  92. + acodec_opts + more_opts +
  93. ['--', encodeFilename(out_path)])
  94. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  95. stdout,stderr = p.communicate()
  96. if p.returncode != 0:
  97. msg = stderr.strip().split('\n')[-1]
  98. raise AudioConversionError(msg)
  99. def run(self, information):
  100. path = information['filepath']
  101. filecodec = self.get_audio_codec(path)
  102. if filecodec is None:
  103. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  104. return None
  105. more_opts = []
  106. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  107. if self._preferredcodec == 'm4a' and filecodec == 'aac':
  108. # Lossless, but in another container
  109. acodec = 'copy'
  110. extension = self._preferredcodec
  111. more_opts = [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  112. elif filecodec in ['aac', 'mp3', 'vorbis']:
  113. # Lossless if possible
  114. acodec = 'copy'
  115. extension = filecodec
  116. if filecodec == 'aac':
  117. more_opts = ['-f', 'adts']
  118. if filecodec == 'vorbis':
  119. extension = 'ogg'
  120. else:
  121. # MP3 otherwise.
  122. acodec = 'libmp3lame'
  123. extension = 'mp3'
  124. more_opts = []
  125. if self._preferredquality is not None:
  126. if int(self._preferredquality) < 10:
  127. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  128. else:
  129. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality + 'k']
  130. else:
  131. # We convert the audio (lossy)
  132. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  133. extension = self._preferredcodec
  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. if self._preferredcodec == 'aac':
  141. more_opts += ['-f', 'adts']
  142. if self._preferredcodec == 'm4a':
  143. more_opts += [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  144. if self._preferredcodec == 'vorbis':
  145. extension = 'ogg'
  146. if self._preferredcodec == 'wav':
  147. extension = 'wav'
  148. more_opts += ['-f', 'wav']
  149. prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
  150. new_path = prefix + sep + extension
  151. try:
  152. if self._nopostoverwrites and os.path.exists(encodeFilename(new_path)):
  153. self._downloader.to_screen(u'[youtube] Post-process file %s exists, skipping' % new_path)
  154. else:
  155. self._downloader.to_screen(u'[' + (self._exes['avconv'] and 'avconv' or 'ffmpeg') + '] Destination: ' + new_path)
  156. self.run_ffmpeg(path, new_path, acodec, more_opts)
  157. except:
  158. etype,e,tb = sys.exc_info()
  159. if isinstance(e, AudioConversionError):
  160. self._downloader.to_stderr(u'ERROR: audio conversion failed: ' + e.message)
  161. else:
  162. self._downloader.to_stderr(u'ERROR: error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg'))
  163. return None
  164. # Try to update the date time for extracted audio file.
  165. if information.get('filetime') is not None:
  166. try:
  167. os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
  168. except:
  169. self._downloader.to_stderr(u'WARNING: Cannot update utime of audio file')
  170. if not self._keepvideo:
  171. try:
  172. os.remove(encodeFilename(path))
  173. except (IOError, OSError):
  174. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  175. return None
  176. information['filepath'] = new_path
  177. return information