#!/usr/bin/env python

import sys, os, mmpython, glob
from stat import *

args = sys.argv[1:len(sys.argv)]

for file in args:
    try:
        position = str(mmpython.parse(file).video[0].length / 2.0)
    except:
        # else arbitrary consider that file is 1Mbps and grab position at 10%
        position = str(os.stat(file)[ST_SIZE]/1024/1024/10.0)
    mplayer_in, mplayer_out, mplayer_err = \
                os.popen3(('mplayer', '-nosound',
                           '-vo', 'png',
                           '-frames', '8',
                           '-ss', position,
                           '-vop', 'scale=240:-2', file))
    mplayer_out.read()
    captures = glob.glob('000000??.png')
    try:
        capture = captures[-1:][0]
        os.rename(capture, os.path.splitext(file)[0] + ".png")
        captures = captures[:-1]
        print file
    except: print "error creating capture for %s" % file
    for capture in captures:
        try: os.remove(capture)
        except: print "error removing temporary captures for %s" % file
