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.

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