#!/usr/bin/python

from gi.repository import Gst, GObject, GLib
from time import sleep

ns_to_s = 1000000000.0
Gst.init(None)

def on_pad_added(element, pad):
    print "new pad!"
    pad.link(convert.get_static_pad("sink"))	


pipe = Gst.Pipeline.new('pipe')
src = Gst.ElementFactory.make('filesrc')
src.set_property('location', '/home/luisbg/colorbars.mpg')
decode = Gst.ElementFactory.make('decodebin')
decode.connect('pad-added', on_pad_added)
convert = Gst.ElementFactory.make('videoconvert')
sink = Gst.ElementFactory.make('xvimagesink')

pipe.add(src)
pipe.add(decode)
pipe.add(convert)
pipe.add(sink)

src.link(decode)
decode.link(convert)
convert.link(sink)

print "pause and sleep for a second"
pipe.set_state(Gst.State.PAUSED)

loop = 1
while loop:
    sleep(1)
    print "do 5 one frame steps\n"
    for x in range(0, 5):
        print 'step'
        sink.send_event(Gst.Event.new_step(Gst.Format.BUFFERS, 1, 1.0, True, False))
        ret, pos_int = pipe.query_position(Gst.Format.TIME)
        print "position " + str(pos_int / ns_to_s)
        sleep(1)

    print "pause"
    sleep(2)

    print "play for half a second"
    pipe.set_state(Gst.State.PLAYING)
    sleep(.5)

    print "pause"
    pipe.set_state(Gst.State.PAUSED)
    ret, pos_int = pipe.query_position(Gst.Format.TIME)
    print "position " + str(pos_int / ns_to_s)
    sleep(1)

    loop = loop + 1
    print 'loop: ' + str(loop)
    if loop > 5:
        exit()
