Source

makeiso / mkiso / videotypes.py

#!/usr/bin/python
"""
This file contains classes of possible video types and each class is
responsible for defining how it converts it's filetype to a MPEG2 compaitable
format.
"""
import re

from utils import run_cmd


class InvalidVideoFormatError(Exception):

    def __str__(self):
        return "%s is not a valid video format." % (self.args[0], )


class VideoFile(object):

    def __init__(self, filename):
        self.filename = filename
        self.mpg_file = ".".join(filename.split('.')[:-1]) + ".mpg"

    def get_convert_cmd(self):
        pass

    def convert(self):
        return run_cmd(self.get_convert_cmd())


class MkvFile(VideoFile):

    STREAM_RE = re.compile(
        "Stream\s\#(?P<stream>0\.[01]{1})(\(eng\))?\:\s(?P<type>[a-zA-Z]+)\:")

    def get_convert_cmd(self):
        vstream, astream = self.get_streams()
        return "ffmpeg -threads 2 -v 1 -i %s -r ntsc -target dvd -b 4771k -s 720x480 -acodec copy -copyts -aspect 16:9 %s -map %s -map %s" % (
            self.filename, self.mpg_file, vstream, astream)

    def get_streams(self):
        cmd = "ffmpeg -i %s" % (self.filename, )
        info = run_cmd(cmd, show_output=True)
        matches = self.STREAM_RE.findall(info)
        if matches[0][-1] == 'Audio':
            audio = matches[0][0]
            video = matches[1][0]
        else:
            audio = matches[1][0]
            video = matches[0][0]
        return (video, audio)


class AviFile(VideoFile):

    def get_convert_cmd(self):
        return "ffmpeg -i %s -target ntsc-dvd -aspect 16:9 -sameq %s" % (
            self.filename, self.mpg_file)


class Mp4File(VideoFile):

    def get_convert_cmd(self):
        return "ffmpeg -i %s -target ntsc-dvd -aspect 16:9 -s 720x480 %s" % (
            self.filename, self.mpg_file)