2b2fb5cdb9ecd8341d08ed74627d741e7ca521dc
[platform/upstream/gstreamer.git] / examples / dynamic_src.py
1 #!/usr/bin/env python3
2
3 '''
4 Simple example to demonstrate dynamically adding and removing source elements
5 to a playing pipeline.
6 '''
7
8 import sys
9 import random
10
11 import gi
12 gi.require_version('Gst', '1.0')
13 gi.require_version('GLib', '2.0')
14 gi.require_version('GObject', '2.0')
15 from gi.repository import GLib, GObject, Gst
16
17 class ProbeData:
18     def __init__(self, pipe, src):
19         self.pipe = pipe
20         self.src = src
21
22 def bus_call(bus, message, loop):
23     t = message.type
24     if t == Gst.MessageType.EOS:
25         sys.stdout.write("End-of-stream\n")
26         loop.quit()
27     elif t == Gst.MessageType.ERROR:
28         err, debug = message.parse_error()
29         sys.stderr.write("Error: %s: %s\n" % (err, debug))
30         loop.quit()
31     return True
32
33 def dispose_src_cb(src):
34     src.set_state(Gst.State.NULL)
35
36 def probe_cb(pad, info, pdata):
37     peer = pad.get_peer()
38     pad.unlink(peer)
39     pdata.pipe.remove(pdata.src)
40     # Can't set the state of the src to NULL from its streaming thread
41     GLib.idle_add(dispose_src_cb, pdata.src)
42
43     pdata.src = Gst.ElementFactory.make('videotestsrc')
44     pdata.src.props.pattern = random.randint(0, 24)
45     pdata.pipe.add(pdata.src)
46     srcpad = pdata.src.get_static_pad ("src")
47     srcpad.link(peer)
48     pdata.src.sync_state_with_parent()
49
50     GLib.timeout_add_seconds(1, timeout_cb, pdata)
51
52     return Gst.PadProbeReturn.REMOVE
53
54 def timeout_cb(pdata):
55     srcpad = pdata.src.get_static_pad('src')
56     srcpad.add_probe(Gst.PadProbeType.IDLE, probe_cb, pdata)
57     return GLib.SOURCE_REMOVE
58
59 def main(args):
60     GObject.threads_init()
61     Gst.init(None)
62
63     pipe = Gst.Pipeline.new('dynamic')
64     src = Gst.ElementFactory.make('videotestsrc')
65     sink = Gst.ElementFactory.make('autovideosink')
66     pipe.add(src, sink)
67     src.link(sink)
68
69     pdata = ProbeData(pipe, src)
70
71     loop = GObject.MainLoop()
72
73     GLib.timeout_add_seconds(1, timeout_cb, pdata)
74
75     bus = pipe.get_bus()
76     bus.add_signal_watch()
77     bus.connect ("message", bus_call, loop)
78     
79     # start play back and listen to events
80     pipe.set_state(Gst.State.PLAYING)
81     try:
82       loop.run()
83     except:
84       pass
85     
86     # cleanup
87     pipe.set_state(Gst.State.NULL)
88
89 if __name__ == '__main__':
90     sys.exit(main(sys.argv))