# call me with an URI as parameter.

import gobject
import gst
import sys

loop = gobject.MainLoop()
pipeline = gst.element_factory_make("playbin2")
pipeline.props.uri = sys.argv[1]
#pipeline.props.audio_sink = gst.element_factory_make("fakesink")

def quit():
    pipeline.set_state(gst.STATE_NULL)
    loop.quit()

def on_message(bus, message):
    t = message.type
    if t == gst.MESSAGE_ERROR:
        err, debug = message.parse_error()
        print "Error: %s" % err, debug
        quit()
    elif t == gst.MESSAGE_EOS:
        print "EOS"
        start()

bus = pipeline.get_bus()
bus.add_signal_watch()
bus.connect('message', on_message)

def seek_back():
    event = gst.event_new_seek(-1.0, gst.FORMAT_TIME,
                               gst.SEEK_FLAG_FLUSH,
                               gst.SEEK_TYPE_SET, 0,
                               gst.SEEK_TYPE_SET, 0.3 * gst.SECOND)

    pipeline.send_event(event)
    print "start reverse playback"
    return False

def start():
    print "start forward playback"
    pipeline.set_state(gst.STATE_READY)
    pipeline.set_state(gst.STATE_PLAYING)
    event = gst.event_new_seek(1.0, gst.FORMAT_TIME,
                               gst.SEEK_FLAG_FLUSH,
                               gst.SEEK_TYPE_SET, 3 * gst.SECOND,
                               gst.SEEK_TYPE_NONE, 5 * gst.SECOND)

    pipeline.send_event(event)
    gobject.timeout_add(1000, seek_back)

start()
try:
    loop.run()
except KeyboardInterrupt:
    quit()
