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.

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