python: update python examples to modern python, Gst, and Glib versions
[experiments/gstreamer.git] / python / gst-input-selector-switch.py
1 #!/usr/bin/env python3
2
3 import sys
4
5 import gi
6 gi.require_version('Gst', '1.0')
7 from gi.repository import Gst
8 Gst.init(None)
9
10 from gi.repository import GLib
11
12
13 # The following pipeline works
14 PIPELINE = """
15 videotestsrc pattern=0 ! selector.
16 videotestsrc pattern=18 background-color=4294901760 ! selector.
17 input-selector name=selector ! autovideosink
18 """
19
20
21 class Player:
22     def __init__(self):
23         self.loop = GLib.MainLoop()
24         self.pipeline = Gst.parse_launch(PIPELINE)
25         self.selector = self.pipeline.get_by_name('selector')
26
27         pad = self.selector.get_static_pad("sink_0")
28         self.selector.set_property("active-pad", pad)
29         print("n-pads: %d" % self.selector.get_property("n-pads"))
30
31         bus = self.pipeline.get_bus()
32         bus.add_signal_watch()
33         bus.connect('message::eos', self.on_eos)
34         bus.connect('message::error', self.on_error)
35         bus.connect('message::state-changed', self.on_state_changed)
36
37     def run(self):
38         self.pipeline.set_state(Gst.State.PLAYING)
39         self.loop.run()
40
41     def quit(self):
42         self.pipeline.set_state(Gst.State.NULL)
43         self.loop.quit()
44
45     def on_switch(self):
46         active_pad = self.selector.get_property("active-pad")
47         if active_pad.get_name() == "sink_0":
48             new_pad = self.selector.get_static_pad("sink_1")
49         else:
50             new_pad = self.selector.get_static_pad("sink_0")
51
52         print("switching from %s to %s" % (active_pad.get_name(),
53                                            new_pad.get_name()))
54
55         self.selector.set_property("active-pad", new_pad)
56
57     def on_eos(self, bus, msg):
58         self.quit()
59
60     def on_error(self, bus, msg):
61         (err, debug) = msg.parse_error()
62         print("Error: %s" % err)
63         self.quit()
64
65     def on_state_changed(self, bus, msg):
66         if msg.src != self.pipeline:
67             return
68
69         old_state, new_state, pending = msg.parse_state_changed()
70         print("%s from %s to %s" % (msg.src.get_name(), old_state, new_state))
71
72
73 def main():
74     player = Player()
75
76     def stdin_cb(source, condition):
77         source.readline()
78         player.on_switch()
79         return True
80
81     GLib.io_add_watch(sys.stdin, GLib.IO_IN, stdin_cb)
82
83     print("\nPress Enter to switch the source\n")
84     player.run()
85
86
87 if __name__ == '__main__':
88     sys.exit(main())