a01daba094e923905c58ad07f62e8ace61e876a4
[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, filename, rate):
21         self._filename = filename
22         self._rate = rate
23
24         self._player = Gst.ElementFactory.make("playbin", "player")
25         self._player.set_property("uri", filename)
26
27         bus = self._player.get_bus()
28         bus.add_signal_watch()
29         bus.connect('message::state-changed', self.on_state_changed)
30
31     def run(self):
32         self._player.set_state(Gst.State.PLAYING)
33         loop = GObject.MainLoop()
34         loop.run()
35
36     def on_state_changed(self, bus, msg):
37         if msg.src != self._player:
38             return
39
40         print 'on_state_changed'
41         old_state, new_state, pending = msg.parse_state_changed()
42         print "%s -> %s" % (old_state, new_state)
43         if old_state == Gst.State.READY and new_state == Gst.State.PAUSED:
44             self.set_rate(self._rate)
45
46     def set_rate(self, rate):
47         self._rate = rate
48         try:
49             position, fmt = self._player.query_position(Gst.Format.TIME)
50         except:
51             position = 0
52
53         # Create the seek event
54         if rate > 0:
55             seek_event = Gst.Event.new_seek(rate,
56                     Gst.Format.TIME,
57                     Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE,
58                     Gst.SeekType.SET, position,
59                     Gst.SeekType.NONE, 0)
60         else:
61             seek_event = Gst.Event.new_seek(rate,
62                     Gst.Format.TIME,
63                     Gst.SeekFlags.FLUSH | Gst.SeekFlags.ACCURATE,
64                     Gst.SeekType.SET, 0,
65                     Gst.SeekType.SET, position)
66
67         if seek_event:
68             self._player.send_event(seek_event)
69             Gst.info("rate set to %s" % rate)
70         else:
71             Gst.warining("change rate failed")
72
73
74 def main(args):
75     def usage():
76         sys.stdout.write("usage: %s <URI-OF-MEDIA-FILE>\n" % args[0])
77
78     if len(args) != 2:
79         usage()
80         sys.exit(1)
81
82     if not Gst.uri_is_valid(args[1]):
83         sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
84         sys.exit(1)
85
86     player = Player(args[1], 3.0)
87     player.run()
88
89 if __name__ == '__main__':
90     sys.exit(main(sys.argv))