#!/usr/bin/env python

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

m = GLib.MainLoop()

using_fakesink = True

def got_message(bus, message):
  global using_fakesink

  # print "Got message of type", message.type
  if message.type == Gst.MessageType.STATE_CHANGED:
    (old, new, pend) = message.parse_state_changed()
    if new == Gst.State.PAUSED and using_fakesink:
      print "Clearing fakesink video sink from playbin"
      p.set_state (Gst.State.READY)
      # Flush messages off the bus
      p.get_bus().set_flushing(True)
      p.get_bus().set_flushing(False)
      using_fakesink = False
      p.set_property("video-sink", None)   
      p.set_state (Gst.State.PLAYING)
      return
  elif message.type == Gst.MessageType.ERROR:
    (err, dbg) = message.parse_error()

    print "Got error", err, dbg
    m.quit()
    return
  elif message.type == Gst.MessageType.EOS:
    if not using_fakesink:
      m.quit()
    return

uri = sys.argv[1]

Gst.init(None)

p = Gst.ElementFactory.make('playbin', None)
f = Gst.ElementFactory.make('fakesink', None)
p.set_property("uri", uri)
p.set_property("video-sink", f)

bus = p.get_bus()
bus.add_signal_watch()
bus.connect('message', got_message)

p.set_state (Gst.State.PAUSED)

m.run()

p.set_state (Gst.State.NULL)
