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