Add gst-input-selector-switch.py
authorAntonio Ospite <ao2@ao2.it>
Fri, 2 Dec 2016 11:56:33 +0000 (12:56 +0100)
committerAntonio Ospite <ao2@ao2.it>
Fri, 2 Dec 2016 11:56:33 +0000 (12:56 +0100)
python/gst-input-selector-switch.py [new file with mode: 0755]

diff --git a/python/gst-input-selector-switch.py b/python/gst-input-selector-switch.py
new file mode 100755 (executable)
index 0000000..f653dfa
--- /dev/null
@@ -0,0 +1,89 @@
+#!/usr/bin/env python3
+
+import sys
+
+import gi
+gi.require_version('Gst', '1.0')
+from gi.repository import Gst
+Gst.init(None)
+
+from gi.repository import GObject
+GObject.threads_init()
+
+
+# The following pipeline works
+PIPELINE = """
+videotestsrc pattern=0 ! selector.
+videotestsrc pattern=13 ! selector.
+input-selector name=selector ! autovideosink
+"""
+
+
+class Player:
+    def __init__(self):
+        self.loop = GObject.MainLoop()
+        self.pipeline = Gst.parse_launch(PIPELINE)
+        self.selector = self.pipeline.get_by_name('selector')
+
+        pad = self.selector.get_static_pad("sink_0")
+        self.selector.set_property("active-pad", pad)
+        print("n-pads: %d" % self.selector.get_property("n-pads"))
+
+        bus = self.pipeline.get_bus()
+        bus.add_signal_watch()
+        bus.connect('message::eos', self.on_eos)
+        bus.connect('message::error', self.on_error)
+        bus.connect('message::state-changed', self.on_state_changed)
+
+    def run(self):
+        self.pipeline.set_state(Gst.State.PLAYING)
+        self.loop.run()
+
+    def quit(self):
+        self.pipeline.set_state(Gst.State.NULL)
+        self.loop.quit()
+
+    def switch(self):
+        active_pad = self.selector.get_property("active-pad")
+        if active_pad.get_name() == "sink_0":
+            new_pad = self.selector.get_static_pad("sink_1")
+        else:
+            new_pad = self.selector.get_static_pad("sink_0")
+
+        print("switching from %s to %s" % (active_pad.get_name(),
+                                           new_pad.get_name()))
+
+        self.selector.set_property("active-pad", new_pad)
+
+    def on_eos(self, bus, msg):
+        self.quit()
+
+    def on_error(self, bus, msg):
+        (err, debug) = msg.parse_error()
+        print("Error: %s" % err)
+        self.quit()
+
+    def on_state_changed(self, bus, msg):
+        if msg.src != self.pipeline:
+            return
+
+        old_state, new_state, pending = msg.parse_state_changed()
+        print("%s from %s to %s" % (msg.src.get_name(), old_state, new_state))
+
+
+def main():
+    player = Player()
+
+    def stdin_cb(source, condition):
+        source.readline()
+        player.switch()
+        return True
+
+    GObject.io_add_watch(sys.stdin, GObject.IO_IN, stdin_cb)
+
+    print("\nPress Enter to switch the source\n")
+    player.run()
+
+
+if __name__ == '__main__':
+    sys.exit(main())