Move python experiments to a python/ subdir
[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 gobject
9 gobject.threads_init()
10
11 import gst
12
13
14 class Player:
15     def __init__(self, filename, rate):
16         self._filename = filename
17         self._rate = rate
18
19         self._player = gst.element_factory_make("playbin2", "player")
20         self._player.set_property("uri", filename)
21
22         bus = self._player.get_bus()
23         bus.add_signal_watch()
24         bus.connect('message::state-changed', self.on_state_changed)
25
26     def run(self):
27         self._player.set_state(gst.STATE_PLAYING)
28         loop = gobject.MainLoop()
29         loop.run()
30
31     def on_state_changed(self, bus, msg):
32         if msg.src != self._player:
33             return
34
35         print 'on_state_changed'
36         old_state, new_state, pending = msg.parse_state_changed()
37         print "%s -> %s" % (old_state, new_state)
38         if old_state == gst.STATE_READY and new_state == gst.STATE_PAUSED:
39             self.set_rate(self._rate)
40
41     def set_rate(self, rate):
42         self._rate = rate
43         try:
44             position, format = self._player.query_position(gst.FORMAT_TIME)
45         except:
46             position = 0
47
48         # Create the seek event
49         if rate > 0:
50             seek_event = gst.event_new_seek(rate,
51                     gst.FORMAT_TIME,
52                     gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE,
53                     gst.SEEK_TYPE_SET, position,
54                     gst.SEEK_TYPE_NONE, 0)
55         else:
56             seek_event = gst.event_new_seek(rate,
57                     gst.FORMAT_TIME,
58                     gst.SEEK_FLAG_FLUSH | gst.SEEK_FLAG_ACCURATE,
59                     gst.SEEK_TYPE_SET, 0,
60                     gst.SEEK_TYPE_SET, position)
61
62         if seek_event:
63             self._player.send_event(seek_event)
64             gst.info("rate set to %s" % rate)
65         else:
66             gst.warining("change rate failed")
67
68
69 def main(args):
70     def usage():
71         sys.stdout.write("usage: %s <URI-OF-MEDIA-FILE>\n" % args[0])
72
73     if len(args) != 2:
74         usage()
75         sys.exit(1)
76
77     if not gst.uri_is_valid(args[1]):
78         sys.stderr.write("Error: Invalid URI: %s\n" % args[1])
79         sys.exit(1)
80
81     player = Player(args[1], 3.0)
82     player.run()
83
84 if __name__ == '__main__':
85     sys.exit(main(sys.argv))