#!/usr/bin/env python3
import argparse
import gi
import sys

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


Gst.init(sys.argv)


class PlaybinAdderExample(object):
    def __init__(self, uri, use_adder):
        self.pipeline = Gst.ElementFactory.make("playbin", None)
        self.pipeline.set_property("uri", uri)
        
        if use_adder:
            adder = Gst.ElementFactory.make("adder", None)
            self.pipeline.set_property("audio-stream-combiner", adder)
        
        # xvimagesink is broken on my VM
        videosink = Gst.ElementFactory.make("fakesink", None)
        self.pipeline.set_property("video-sink", videosink)
        
        self.bus = self.pipeline.get_bus()
        self.bus.add_signal_watch()
        self.bus.connect("message::error", self.on_error)
        
        self.main_loop = GObject.MainLoop()
        GObject.timeout_add_seconds(1, self.on_tick)
        
    def on_error(self, bus, message):
        print(message.parse_error())
        self.quit()
    
    def on_tick(self):
        print("Tick")
        self.pipeline.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH, 0)
        print("Tock")
        return True
    
    def quit(self):
        self.pipeline.set_state(Gst.State.NULL)
        self.main_loop.quit()
    
    def run(self):
        self.pipeline.set_state(Gst.State.PAUSED)
        self.main_loop.run()


def main():
    parser = argparse.ArgumentParser(description="Example of adder causing lockups when seeking in paused state")
    parser.add_argument("uri",
                        help="The URI to play, passed directly to playbin")
    parser.add_argument("--use-adder", action="store_true",
                        help="Use an adder for audio instead of the default input-selector")
    result = parser.parse_args()
    
    PlaybinAdderExample(result.uri, result.use_adder).run()


if __name__ == "__main__":
    sys.exit(main())
