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.

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