#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# $Date: 2013-03-07 11:05:02 +0100 $
#
# To the extent possible under law, Roland Smith has waived all
# copyright and related or neighboring rights to avi2mkv.py. This work
# is published from the Netherlands. See
# http://creativecommons.org/publicdomain/zero/1.0/

"""Convert all AVI files given on the command line to Theora/Vorbis
   streams in a Matroska container."""

import base64
import os
import sys
import subprocess
from multiprocessing import Pool, Lock

globallock = Lock()

def output(txt):
    """Print while holding a global lock."""
    globallock.acquire()
    print txt
    globallock.release()        
   
def process(fname):
    """Use ffmpeg2theora and mkvmerge to convert an AVI file to Theora/Vorbis
    streams in a Matroska container.

    Arguments:
    fname -- name of the file to convert
    """
    if fname.endswith(('.avi', '.AVI')):
        basename = fname[:-4]
    else:
        basename = fname
    ogv = basename + '.ogv'
    args = ['ffmpeg2theora', '--no-oshash', '--nosubtitles', '--nometadata', 
            '-o', ogv, '-v', '8', fname]
    args2 = ['mkvmerge', '-q', '-o', basename + '.mkv', ogv]
    bitbucket = open(os.devnull, 'w')
    try:
        output("Converting {} to {}.".format(fname, ogv))
        subprocess.check_call(args, stdout=bitbucket, stderr=bitbucket)
        output("Starting merge for {}.".format(ogv))
        subprocess.check_call(args2, stdout=bitbucket, stderr=bitbucket)
        os.remove(ogv)
        output("Conversion of {} completed.".format(fname))
    except:
        output("ERROR: Converting {} failed.".format(fname))
    bitbucket.close()

def main(argv):
    """Main program.

    Arguments:
    argv -- command line arguments
    """
    if len(argv) == 1:
        binary = os.path.basename(argv[0])
        print "Usage: {} [file ...]".format(binary)
        sys.exit(0)
    avis = argv[1:]
    p = Pool()
    p.map(process, avis)
    p.close()

if __name__ == '__main__':
    main(sys.argv)
