# call me with an URI as parameter.

import sys
import gi
gi.require_version('Gst', '1.0')
from gi.repository import Gst, GObject

Gst.init([])

loop = GObject.MainLoop()
pipeline = Gst.ElementFactory.make("playbin", "play")
pipeline.props.uri = sys.argv[1]

started = False

def quit():
    pipeline.set_state(Gst.State.NULL)
    loop.quit()

def seek_back():
    event = Gst.Event.new_seek(-1.0, Gst.Format.TIME, Gst.SeekFlags.FLUSH,
                               Gst.SeekType.SET, 0,
                               Gst.SeekType.SET, 0.3 * Gst.SECOND)

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

def on_message(bus, message):
    t = message.type
    if t == Gst.MessageType.ERROR:
        err, debug = message.parse_error()
        print "Error: %s" % err, debug
        quit()
    elif t == Gst.MessageType.ASYNC_DONE:
        global started
        if started:
            return
        started = True
        pipeline.set_state(Gst.State.PLAYING)
        print "start forward playback"
        event = Gst.Event.new_seek(1.0, Gst.Format.TIME, Gst.SeekFlags.FLUSH,
                               Gst.SeekType.SET, 3 * Gst.SECOND,
                               Gst.SeekType.SET, 5 * Gst.SECOND)

        pipeline.send_event(event)
        GObject.timeout_add(1000, seek_back)
    elif t == Gst.MessageType.EOS:
        print "EOS"
        ret, pos = pipeline.query_position(Gst.Format.TIME)
        print "Position: ", pos
        quit()

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

pipeline.set_state(Gst.State.PAUSED)

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