#!bin/python

# <input video> <output.webm>
# this tool writes to a side file first so you won't see an in-progress output.
# It also makes an output mp4 for ios.

import sys, subprocess, os, random, string, logging
sys.path.append("/my/site/photo")
from dims import fitSize, videoSize, avprobe
logging.basicConfig()
log = logging.getLogger()

def _avconvArgs(inPath, outSize, probe, tmpOut):
    convArgs = ['-y', '-i', inPath, '-s', '%sx%s' % outSize]
    if '11025 Hz' in probe or '11024 Hz' in probe:
        # see http://ffmpeg-users.933282.n4.nabble.com/ffmpeg-fails-to-create-webm-content-if-audio-bitrate-is-less-than-44K-td2303313.html
        # '11024' is from some canon cam
        convArgs.extend(['-ar', '44100'])
    if '24000 Hz' in probe:
        # another camera
        convArgs.extend(['-ar', '48000'])
    if tmpOut.endswith('.mp4'):
        convArgs.extend([
            '-qcomp', '0.6',
            '-qmin', '10',
            '-qmax', '63',
            '-qdiff', '4',
            '-trellis', '2',
            '-strict', 'experimental',
            '-acodec', 'aac',
            '-vcodec', 'libx264',
            '-b:v', '500k',
        ])
    else:
        # webm
        convArgs.extend([
            '-b:v', '500k',
            ])
    convArgs.append(tmpOut)
    return convArgs

def run(inPath, outPath):
    tmpSuffix = ".tmp" + ''.join([random.choice(string.letters) for c in range(5)])
    tmpOut = outPath + tmpSuffix + os.path.splitext(outPath)[1]

    try:
        probe = avprobe(inPath)
    except subprocess.CalledProcessError as e:
        log.warn(e.output)
        raise
    w,h = videoSize(inPath, probe=probe)
    outSize = fitSize(w, h, 320, 320)

    convArgs = _avconvArgs(inPath, outSize, probe, tmpOut)
        
    try:
        subprocess.check_call(['/usr/bin/ffmpeg'] + convArgs)
        os.rename(tmpOut, outPath)
    except Exception as e:
        try:
            os.unlink(tmpOut)
        except OSError:
            pass
        raise e

inPath, outPath = sys.argv[1:]
run(inPath, outPath)
run(inPath, outPath.replace('.webm', '.mp4'))
