#!/usr/bin/env python # -*- coding: utf-8 -*- import os import subprocess import sys import time from utils import * class PostProcessor(object): """Post Processor class. PostProcessor objects can be added to downloaders with their add_post_processor() method. When the downloader has finished a successful download, it will take its internal chain of PostProcessors and start calling the run() method on each one of them, first with an initial argument and then with the returned value of the previous PostProcessor. The chain will be stopped if one of them ever returns None or the end of the chain is reached. PostProcessor objects follow a "mutual registration" process similar to InfoExtractor objects. """ _downloader = None def __init__(self, downloader=None): self._downloader = downloader def set_downloader(self, downloader): """Sets the downloader for this PP.""" self._downloader = downloader def run(self, information): """Run the PostProcessor. The "information" argument is a dictionary like the ones composed by InfoExtractors. The only difference is that this one has an extra field called "filepath" that points to the downloaded file. When this method returns None, the postprocessing chain is stopped. However, this method may return an information dictionary that will be passed to the next postprocessing object in the chain. It can be the one it received after changing some fields. In addition, this method may raise a PostProcessingError exception that will be taken into account by the downloader it was called from. """ return information # by default, do nothing class AudioConversionError(BaseException): def __init__(self, message): self.message = message class FFmpegExtractAudioPP(PostProcessor): def __init__(self, downloader=None, preferredcodec=None, preferredquality=None, keepvideo=False): PostProcessor.__init__(self, downloader) if preferredcodec is None: preferredcodec = 'best' self._preferredcodec = preferredcodec self._preferredquality = preferredquality self._keepvideo = keepvideo self._exes = self.detect_executables() @staticmethod def detect_executables(): available = {'avprobe' : False, 'avconv' : False, 'ffmpeg' : False, 'ffprobe' : False} for path in os.environ["PATH"].split(os.pathsep): for program in available.keys(): exe_file = os.path.join(path, program) if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK): available[program] = exe_file return available def get_audio_codec(self, path): if not self._exes['ffprobe'] and not self._exes['avprobe']: return None try: cmd = [self._exes['avprobe'] or self._exes['ffprobe'], '-show_streams', '--', encodeFilename(path)] handle = subprocess.Popen(cmd, stderr=file(os.path.devnull, 'w'), stdout=subprocess.PIPE) output = handle.communicate()[0] if handle.wait() != 0: return None except (IOError, OSError): return None codec = None duration = None for line in output.split('\n'): if line.startswith('codec_name='): codec = line.split('=')[1].strip() elif line.startswith('duration='): duration = line.split('=')[1].strip() try: duration = float(duration) except: duration = None elif line.strip() == '[/STREAM]' and codec is not None: break return { 'codec': codec, 'duration': duration } def run_ffmpeg(self, path, out_path, codec, more_opts, duration): if not self._exes['ffmpeg'] and not self._exes['avconv']: raise AudioConversionError('ffmpeg or avconv not found. Please install one.') if codec is None: acodec_opts = [] else: acodec_opts = ['-acodec', codec] cmd = ([self._exes['avconv'] or self._exes['ffmpeg'], '-y', '-i', encodeFilename(path), '-vn'] + acodec_opts + more_opts + ['--', encodeFilename(out_path)]) start = time.time() # open process redirecting stderr to stdout p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True) import fcntl import errno import select # entire captured output p_output = '' # size= 765kB time=243.67 bitrate= 25.7kbits/s reo = re.compile("""size=\s*(?P\S+) # size \stime=(?P