gst-trick-mode.py: pass the speed rate as a command line argument
[experiments/gstreamer.git] / python / gst-trick-mode.py
1 #!/usr/bin/env python
2 #
3 # A simple "trick-mode" player to play a file at a given speed rate.
4 #
5 # Get a test sample with:
6 # youtube-dl -t http://www.youtube.com/watch?v=yWa-YXiSk2Y
7
8 import sys
9
10 import gi
11 gi.require_version('Gst', '1.0')
12 from gi.repository import Gst
13 Gst.init(None)
14
15 from gi.repository import GObject
16 GObject.threads_init()
17
18
19 class Player:
20     def __init__(self, uri, rate):
21         self._rate = rate
22
23         self._player = Gst.ElementFactory.make("playbin", "player")
24         self._player.set_property("uri", uri)
25
26         bus = self._player.get_bus()
27         bus.add_signal_watch()
28         bus.connect('message::state-changed', self.on_state_changed)
29
30     def run(self):
31         self._player.set_state(Gst.State.PLAYING)
32         loop = GObject.MainLoop()
33         loop.run()
34
35     def on_state_changed(self, bus, msg):
36         if msg.src != self._player:
37             return
38
39         print 'on_state_changed'
40         old_state, new_state, pending = msg.parse_state_changed()
41         print "%s -> %s" % (old_state, new_state)
42         if old_state == Gst.State.READY and new_state == Gst.State.PAUSED:
43             self.set_rate(self._rate)
44
45     def set_rate(self, rate):
46         self._rate = rate
47         try:
48             position, fmt = self._player.query_position(Gst.Format.TIME)
49         except:
50             position = 0
51
52         # Create the seek event
53         if rate > 0:
54             seek_event = Gst.Event.new_seek(rate,
55                     Gst.Format.TIME,
56                     Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE,
57                     Gst.SeekType.SET, position,
58                     Gst.SeekType.NONE, 0)
59         else:
60             seek_event = Gst.Event.new_seek(rate,
61                     Gst.Format.TIME,
62                     Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE,
63                     Gst.SeekType.SET, 0,
64                     Gst.SeekType.SET, position)
65
66         if seek_event:
67             self._player.send_event(seek_event)
68             Gst.info("rate set to %s" % rate)
69         else:
70             Gst.warining("change rate failed")
71
72
73 def main(args):
74     def usage():
75         sys.stdout.write("usage: %s <filename> <speedrate>\n" % args[0])
76
77     if len(args) != 3:
78         usage()
79         sys.exit(1)
80
81     uri = Gst.filename_to_uri(args[1])
82     rate = float(args[2])
83
84     player = Player(uri, rate)
85     player.run()
86
87 if __name__ == '__main__':
88     sys.exit(main(sys.argv))