#!/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 Example(object):
    def __init__(self, uri, use_funnel):
        self.pipeline = Gst.ElementFactory.make("playbin", None)
        self.pipeline.set_property("uri", uri)
        
        if use_funnel:
            funnel = Gst.ElementFactory.make("funnel", None)
            self.pipeline.set_property("text-stream-combiner", funnel)
        
        bus = self.pipeline.get_bus()
        bus.add_signal_watch()
        bus.connect("message::error", self.on_error)
        bus.connect("message::eos", self.on_eos)
        
        self.main_loop = GObject.MainLoop()

    def on_eos(self, bus, message):
        print("EOS")
        self.quit()

    def on_error(self, bus, message):
        print(message.parse_error())
        self.quit()

    def quit(self):
        self.pipeline.set_state(Gst.State.NULL)
        self.main_loop.quit()

    def run(self):
        self.pipeline.set_state(Gst.State.PLAYING)
        self.main_loop.run()


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("uri")
    parser.add_argument("--use-funnel", action="store_true")
    args = parser.parse_args()

    Example(args.uri, args.use_funnel).run()


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