import subprocess, tempfile, threading decoders = {} encoders = {} class DecoderMeta(type): def __init__(cls, name, bases, dict): if not name in ('Decoder', 'Codec'): decoders[cls.decoder_name] = cls class Decoder(object): __metaclass__ = DecoderMeta class EncoderMeta(type): def __init__(cls, name, bases, dict): if not name in ('Encoder', 'Codec'): encoders[cls.encoder_name] = cls class Encoder(object): __metaclass__ = EncoderMeta class CodecMeta(DecoderMeta, EncoderMeta): def __init__(cls, name, bases, dict): DecoderMeta.__init__(cls, name, bases, dict) EncoderMeta.__init__(cls, name, bases, dict) class Codec(object): __metaclass__ = CodecMeta # end of metastuff class FFmpeg(Codec): decoder_name = 'ffmpeg' encoder_name = 'ffmpeg' def decode(self, source, dest, *args): ret = subprocess.call((x.format(infile = source, outfile = dest) for x in 'ffmpeg -loglevel quiet -i {infile} -y {outfile}'.split())) print 'decoding returned', ret def encode(self, source, dest, *args): ret = subprocess.call((x.format(infile = source, outfile = dest) for x in 'ffmpeg -loglevel quiet -i {infile} -y {outfile}'.split())) print 'encoding returned', ret def recode(self, source, dest, *args): ret = subprocess.call((x.format(infile = source, outfile = dest) for x in 'ffmpeg -loglevel quiet -i {infile} -y {outfile}'.split())) print 'recoding returned', ret class Recoder(object): def __init__(self, decoder, encoder): self.decoder = decoder self.encoder = encoder def recode(self, source, dest): if self.decoder.__class__ == self.encoder.__class__ and hasattr(self.decoder, 'recode'): print 'recoding' print self.decoder self.decoder.recode(source, dest) else: temp = tempfile.NamedTemporaryFile(mode = 'wb', prefix = 'foo', suffix = os.path.splitext(dest)[1], delete = True) print 'decoding' self.decoder.decode(source, temp.name) print 'encoding' self.encoder.encode(temp.name, dest) temp.close() class RecodeThread(threading.Thread): lock = threading.Lock() queue = [] running = False def get_job(self): return self.queue.pop(0) if len(self.queue) else None def run(self): self.lock.acquire() job = self.get_job() while job: self.lock.release() func, decoder, encoder, sessionid = job func(decoder, encoder, sessionid) self.lock.acquire() job = self.get_job() RecodeThread.running = False self.lock.release() @classmethod def add(cls, job): cls.lock.acquire() cls.queue.append(job) if not cls.running: cls.running = True RecodeThread().start() cls.lock.release() if __name__ == '__main__': import sys ffmpeg = FFmpeg() print ffmpeg r = Recoder(ffmpeg, ffmpeg) r.recode(sys.argv[1], sys.argv[2])