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.

198 lines
6.8 KiB

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import subprocess
  5. import sys
  6. import time
  7. from utils import *
  8. class PostProcessor(object):
  9. """Post Processor class.
  10. PostProcessor objects can be added to downloaders with their
  11. add_post_processor() method. When the downloader has finished a
  12. successful download, it will take its internal chain of PostProcessors
  13. and start calling the run() method on each one of them, first with
  14. an initial argument and then with the returned value of the previous
  15. PostProcessor.
  16. The chain will be stopped if one of them ever returns None or the end
  17. of the chain is reached.
  18. PostProcessor objects follow a "mutual registration" process similar
  19. to InfoExtractor objects.
  20. """
  21. _downloader = None
  22. def __init__(self, downloader=None):
  23. self._downloader = downloader
  24. def set_downloader(self, downloader):
  25. """Sets the downloader for this PP."""
  26. self._downloader = downloader
  27. def run(self, information):
  28. """Run the PostProcessor.
  29. The "information" argument is a dictionary like the ones
  30. composed by InfoExtractors. The only difference is that this
  31. one has an extra field called "filepath" that points to the
  32. downloaded file.
  33. When this method returns None, the postprocessing chain is
  34. stopped. However, this method may return an information
  35. dictionary that will be passed to the next postprocessing
  36. object in the chain. It can be the one it received after
  37. changing some fields.
  38. In addition, this method may raise a PostProcessingError
  39. exception that will be taken into account by the downloader
  40. it was called from.
  41. """
  42. return information # by default, do nothing
  43. class AudioConversionError(BaseException):
  44. def __init__(self, message):
  45. self.message = message
  46. class FFmpegExtractAudioPP(PostProcessor):
  47. def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, keepvideo=False):
  48. PostProcessor.__init__(self, downloader)
  49. if preferredcodec is None:
  50. preferredcodec = 'best'
  51. self._preferredcodec = preferredcodec
  52. self._preferredquality = preferredquality
  53. self._keepvideo = keepvideo
  54. self._exes = self.detect_executables()
  55. @staticmethod
  56. def detect_executables():
  57. def executable(exe):
  58. try:
  59. subprocess.check_output([exe, '-version'])
  60. except OSError:
  61. return False
  62. return exe
  63. programs = ['avprobe', 'avconv', 'ffmpeg', 'ffprobe']
  64. return dict((program, executable(program)) for program in programs)
  65. def get_audio_codec(self, path):
  66. if not self._exes['ffprobe'] and not self._exes['avprobe']: return None
  67. try:
  68. cmd = [self._exes['avprobe'] or self._exes['ffprobe'], '-show_streams', '--', encodeFilename(path)]
  69. handle = subprocess.Popen(cmd, stderr=file(os.path.devnull, 'w'), stdout=subprocess.PIPE)
  70. output = handle.communicate()[0]
  71. if handle.wait() != 0:
  72. return None
  73. except (IOError, OSError):
  74. return None
  75. audio_codec = None
  76. for line in output.split('\n'):
  77. if line.startswith('codec_name='):
  78. audio_codec = line.split('=')[1].strip()
  79. elif line.strip() == 'codec_type=audio' and audio_codec is not None:
  80. return audio_codec
  81. return None
  82. def run_ffmpeg(self, path, out_path, codec, more_opts):
  83. if not self._exes['ffmpeg'] and not self._exes['avconv']:
  84. raise AudioConversionError('ffmpeg or avconv not found. Please install one.')
  85. if codec is None:
  86. acodec_opts = []
  87. else:
  88. acodec_opts = ['-acodec', codec]
  89. cmd = ([self._exes['avconv'] or self._exes['ffmpeg'], '-y', '-i', encodeFilename(path), '-vn']
  90. + acodec_opts + more_opts +
  91. ['--', encodeFilename(out_path)])
  92. p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  93. stdout,stderr = p.communicate()
  94. if p.returncode != 0:
  95. msg = stderr.strip().split('\n')[-1]
  96. raise AudioConversionError(msg)
  97. def run(self, information):
  98. path = information['filepath']
  99. filecodec = self.get_audio_codec(path)
  100. if filecodec is None:
  101. self._downloader.to_stderr(u'WARNING: unable to obtain file audio codec with ffprobe')
  102. return None
  103. more_opts = []
  104. if self._preferredcodec == 'best' or self._preferredcodec == filecodec or (self._preferredcodec == 'm4a' and filecodec == 'aac'):
  105. if self._preferredcodec == 'm4a' and filecodec == 'aac':
  106. # Lossless, but in another container
  107. acodec = 'copy'
  108. extension = self._preferredcodec
  109. more_opts = [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  110. elif filecodec in ['aac', 'mp3', 'vorbis']:
  111. # Lossless if possible
  112. acodec = 'copy'
  113. extension = filecodec
  114. if filecodec == 'aac':
  115. more_opts = ['-f', 'adts']
  116. if filecodec == 'vorbis':
  117. extension = 'ogg'
  118. else:
  119. # MP3 otherwise.
  120. acodec = 'libmp3lame'
  121. extension = 'mp3'
  122. more_opts = []
  123. if self._preferredquality is not None:
  124. if int(self._preferredquality) < 10:
  125. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  126. else:
  127. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality]
  128. else:
  129. # We convert the audio (lossy)
  130. acodec = {'mp3': 'libmp3lame', 'aac': 'aac', 'm4a': 'aac', 'vorbis': 'libvorbis', 'wav': None}[self._preferredcodec]
  131. extension = self._preferredcodec
  132. more_opts = []
  133. if self._preferredquality is not None:
  134. if int(self._preferredquality) < 10:
  135. more_opts += [self._exes['avconv'] and '-q:a' or '-aq', self._preferredquality]
  136. else:
  137. more_opts += [self._exes['avconv'] and '-b:a' or '-ab', self._preferredquality]
  138. if self._preferredcodec == 'aac':
  139. more_opts += ['-f', 'adts']
  140. if self._preferredcodec == 'm4a':
  141. more_opts += [self._exes['avconv'] and '-bsf:a' or '-absf', 'aac_adtstoasc']
  142. if self._preferredcodec == 'vorbis':
  143. extension = 'ogg'
  144. if self._preferredcodec == 'wav':
  145. extension = 'wav'
  146. more_opts += ['-f', 'wav']
  147. prefix, sep, ext = path.rpartition(u'.') # not os.path.splitext, since the latter does not work on unicode in all setups
  148. new_path = prefix + sep + extension
  149. self._downloader.to_screen(u'[' + (self._exes['avconv'] and 'avconv' or 'ffmpeg') + '] Destination: ' + new_path)
  150. try:
  151. self.run_ffmpeg(path, new_path, acodec, more_opts)
  152. except:
  153. etype,e,tb = sys.exc_info()
  154. if isinstance(e, AudioConversionError):
  155. self._downloader.to_stderr(u'ERROR: audio conversion failed: ' + e.message)
  156. else:
  157. self._downloader.to_stderr(u'ERROR: error running ' + (self._exes['avconv'] and 'avconv' or 'ffmpeg'))
  158. return None
  159. # Try to update the date time for extracted audio file.
  160. if information.get('filetime') is not None:
  161. try:
  162. os.utime(encodeFilename(new_path), (time.time(), information['filetime']))
  163. except:
  164. self._downloader.to_stderr(u'WARNING: Cannot update utime of audio file')
  165. if not self._keepvideo:
  166. try:
  167. os.remove(encodeFilename(path))
  168. except (IOError, OSError):
  169. self._downloader.to_stderr(u'WARNING: Unable to remove downloaded video file')
  170. return None
  171. information['filepath'] = new_path
  172. return information