#!/usr/bin/python
# -*- coding: utf-8 -*-
# vi:si:et:sw=4:sts=4:ts=4
# GPL 2008

import os
import sys
from optparse import OptionParser

import pygst
pygst.require("0.10")
import gst
import Image

root = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
if os.path.exists(os.path.join(root, 'oxgst')):
    sys.path.insert(0, root)

from oxgst import Video


if __name__ == '__main__':
    width = None
    height = None
    size = None
    parser = OptionParser()
    parser.add_option('-x', '--size', dest='size', help='scale image to size')
    parser.add_option('-p', '--pos', dest='pos', help='frame position in seconds, float')
    parser.add_option('-i', '--input', dest='input', help='video input')
    parser.add_option('-o', '--output', dest='output', help='path to save frame to, jpg, png supported')
    (opts, args) = parser.parse_args()
    if None in (opts.input, opts.output, opts.pos):
        parser.print_help()
        sys.exit()
    video = Video(opts.input)
    timestamp = int(float(opts.pos) * gst.SECOND)

    frame = video.frame(timestamp)
    if frame:
        width = frame.size[0]
        height = frame.size[1]
        if opts.size:
            if width > height:
                width = int(int(opts.size) * (float(width) / height))
                height = int(opts.size)
                width = width - width % 2
                ox = abs(height - width) / 2
                oy = 0
            else:
                height = int(int(opts.size) * (float(height) / width))
                width = int(opts.size)
                height = height - height % 2
                ox = 0
                oy = abs(height - width) / 2
            frame = frame.resize((width, height), Image.ANTIALIAS)
    
        frame = frame.crop((ox, oy, int(opts.size) + ox, oy + int(opts.size)))
        frame.save(opts.output)