python: update python examples to modern python, Gst, and Glib versions
[experiments/gstreamer.git] / python / gst-decoupled-pipelines.py
1 #!/usr/bin/env python3
2
3 import sys
4
5 from math import pi
6
7 import gi
8 gi.require_version('Gst', '1.0')
9 from gi.repository import Gst
10 Gst.init(None)
11
12 from gi.repository import GLib
13
14
15 PIPELINE_SRC = """
16 videotestsrc pattern=18 background-color=4294901760 ! intervideosink
17 """
18
19 #PIPELINE_SRC = """
20 #v4l2src ! video/x-raw,width=320,height=240 ! intervideosink
21 #"""
22
23 PIPELINE_SINK = """
24 intervideosrc timeout=-1 ! videoconvert ! rotate name=rotate ! videoconvert ! autovideosink
25 """
26
27
28 class Player:
29     def __init__(self):
30         self.loop = GLib.MainLoop()
31         self.pipeline_src = Gst.parse_launch(PIPELINE_SRC)
32         self.pipeline_sink = Gst.parse_launch(PIPELINE_SINK)
33
34         self.rotate = self.pipeline_sink.get_by_name('rotate')
35         self.paused = 0
36         self.angle = 0
37
38         bus = self.pipeline_src.get_bus()
39         bus.add_signal_watch()
40         bus.connect('message::eos', self.on_eos)
41         bus.connect('message::error', self.on_error)
42         bus.connect('message::state-changed', self .on_state_changed)
43
44     def run(self):
45         self.pipeline_src.set_state(Gst.State.PLAYING)
46         self.pipeline_sink.set_state(Gst.State.PLAYING)
47         self.loop.run()
48
49     def quit(self):
50         self.pipeline_sink.set_state(Gst.State.NULL)
51         self.pipeline_src.set_state(Gst.State.NULL)
52         self.loop.quit()
53
54     def on_rotate(self):
55         self.angle -= pi / 100
56         self.angle %= 2 * pi
57         self.rotate.set_property("angle", self.angle)
58
59     def on_input(self):
60         print(self.paused)
61         if self.paused:
62             self.pipeline_src.set_state(Gst.State.PLAYING)
63         else:
64             self.pipeline_src.set_state(Gst.State.PAUSED)
65
66         self.paused ^= 1
67
68     def on_eos(self, bus, msg):
69         self.quit()
70
71     def on_error(self, bus, msg):
72         (err, debug) = msg.parse_error()
73         print("Error: %s" % err)
74         self.quit()
75
76     def on_state_changed(self, bus, msg):
77         if msg.src != self.pipeline_src:
78             return
79
80         old_state, new_state, pending = msg.parse_state_changed()
81         print("%s from %s to %s" % (msg.src.get_name(), old_state, new_state))
82
83
84 def main():
85     player = Player()
86
87     def stdin_cb(source, condition):
88         source.readline()
89         player.on_input()
90         return True
91
92     def timeout_cb():
93         player.on_rotate()
94         return True
95
96     GLib.io_add_watch(sys.stdin, GLib.IO_IN, stdin_cb)
97     GLib.timeout_add(100, timeout_cb)
98
99     print("\nPress Enter to freeze the video\n")
100     player.run()
101
102
103 if __name__ == '__main__':
104     sys.exit(main())