-
Notifications
You must be signed in to change notification settings - Fork 0
/
pipeline.py
435 lines (367 loc) · 14.3 KB
/
pipeline.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python2
#
# pipeline.py
#
# Copyright (C) 2012 Thibault Saunier <[email protected]>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
"""
High-level pipelines
"""
from loggable import Loggable
from signallable import Signallable
from misc import print_ns
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gst
# FIXME : define/document a proper hierarchy
class PipelineError(Exception):
pass
class Seeker(Signallable, Loggable):
"""
The Seeker is a singleton helper class to do various seeking
operations in the pipeline.
"""
_instance = None
__signals__ = {
'seek': ['position', 'format'],
'seek-relative': ['time'],
}
def __new__(cls, *args, **kwargs):
"""
Override the new method to return the singleton instance if available.
Otherwise, create one.
"""
if not cls._instance:
cls._instance = super(Seeker, cls).__new__(cls, *args, **kwargs)
return cls._instance
def __init__(self, timeout=80):
"""
@param timeout (optional): the amount of miliseconds for a seek attempt
"""
Signallable.__init__(self)
Loggable.__init__(self)
self.timeout = timeout
self.pending_seek_id = None
self.position = None
self.format = None
self._time = None
def seek(self, position, format=Gst.Format.TIME, on_idle=False):
self.format = format
self.position = position
if self.pending_seek_id is None:
if on_idle:
GLib.idle_add(self._seekTimeoutCb)
else:
self._seekTimeoutCb()
self.pending_seek_id = self._scheduleSeek(self.timeout, self._seekTimeoutCb)
def seekRelative(self, time, on_idle=False):
if self.pending_seek_id is None:
self._time = time
if on_idle:
GLib.idle_add(self._seekTimeoutCb, True)
else:
self._seekTimeoutCb()
self.pending_seek_id = self._scheduleSeek(self.timeout, self._seekTimeoutCb, True)
def flush(self, on_idle=False):
self.seekRelative(0, on_idle)
def _scheduleSeek(self, timeout, callback, relative=False):
return GLib.timeout_add(timeout, callback, relative)
def _seekTimeoutCb(self, relative=False):
self.pending_seek_id = None
if relative:
try:
self.emit('seek-relative', self._time)
except PipelineError:
self.error("Error while seeking %s relative", self._time)
# if an exception happened while seeking, properly
# reset ourselves
return False
self._time = None
elif self.position is not None and self.format is not None:
position, self.position = self.position, None
format, self.format = self.format, None
try:
self.emit('seek', position, format)
except PipelineError as e:
self.error("Error while seeking to position:%s format: %r, reason: %s",
print_ns(position), format, e)
# if an exception happened while seeking, properly
# reset ourselves
return False
return False
class SimplePipeline(Signallable, Loggable):
"""
The Pipeline is only responsible for:
- State changes
- Position seeking
- Position Querying
- Along with an periodic callback (optional)
Signals:
- C{state-change} : The state of the pipeline changed.
- C{position} : The current position of the pipeline changed.
- C{eos} : The Pipeline has finished playing.
- C{error} : An error happened.
"""
__signals__ = {
"state-change": ["state"],
"position": ["position"],
"duration-changed": ["duration"],
"eos": [],
"error": ["message", "details"]
}
def __init__(self, pipeline, video_overlay):
Loggable.__init__(self)
Signallable.__init__(self)
self._pipeline = pipeline
self._bus = self._pipeline.get_bus()
self._bus.add_signal_watch()
self._bus.connect("message", self._busMessageCb)
self._listening = False # for the position handler
self._listeningInterval = 300 # default 300ms
self._listeningSigId = 0
self._duration = Gst.CLOCK_TIME_NONE
self.video_overlay = video_overlay
def release(self):
"""
Release the L{Pipeline} and all used L{ObjectFactory} and
L{Action}s.
Call this method when the L{Pipeline} is no longer used. Forgetting to do
so will result in memory loss.
@postcondition: The L{Pipeline} will no longer be usable.
"""
self.deactivatePositionListener()
self._bus.disconnect_by_func(self._busMessageCb)
self._bus.remove_signal_watch()
self._pipeline.set_state(Gst.State.NULL)
self._bus = None
def flushSeek(self):
self.pause()
try:
self.seekRelative(0)
except PipelineError:
pass
def setState(self, state):
"""
Set the L{Pipeline} to the given state.
@raises PipelineError: If the C{Gst.Pipeline} could not be changed to
the requested state.
"""
self.debug("state:%r" % state)
res = self._pipeline.set_state(state)
if res == Gst.StateChangeReturn.FAILURE:
# reset to NULL
self._pipeline.set_state(Gst.State.NULL)
raise PipelineError("Failure changing state of the Gst.Pipeline to %r, currently reset to NULL" % state)
def getState(self):
"""
Query the L{Pipeline} for the current state.
@see: L{setState}
This will do an actual query to the underlying GStreamer Pipeline.
@return: The current state.
@rtype: C{State}
"""
change, state, pending = self._pipeline.get_state(0)
self.debug("change:%r, state:%r, pending:%r" % (change, state, pending))
return state
def play(self):
"""
Sets the L{Pipeline} to PLAYING
"""
self.setState(Gst.State.PLAYING)
def pause(self):
"""
Sets the L{Pipeline} to PAUSED
"""
self.setState(Gst.State.PAUSED)
# When the pipeline has been paused we need to update the
# timeline/playhead position, as the 'position' signal
# is only emitted every 300ms and the playhead jumps
# during the playback.
try:
self.emit("position", self.getPosition())
except PipelineError:
# Getting the position failed
pass
def stop(self):
"""
Sets the L{Pipeline} to READY
"""
self.setState(Gst.State.READY)
def togglePlayback(self):
if self.getState() == Gst.State.PLAYING:
self.pause()
else:
self.play()
#{ Position and Seeking methods
def getPosition(self, format=Gst.Format.TIME):
"""
Get the current position of the L{Pipeline}.
@param format: The format to return the current position in
@type format: C{Gst.Format}
@return: The current position or Gst.CLOCK_TIME_NONE
@rtype: L{long}
@raise PipelineError: If the position couldn't be obtained.
"""
self.log("format %r" % format)
try:
res, cur = self._pipeline.query_position(format)
except Exception, e:
self.handleException(e)
raise PipelineError("Couldn't get position")
if not res:
raise PipelineError("Couldn't get position")
self.log("Got position %s" % print_ns(cur))
return cur
def getDuration(self, format=Gst.Format.TIME):
"""
Get the duration of the C{Pipeline}.
"""
self.log("format %r" % format)
dur = self._getDuration(format)
if dur is None:
self.error("Invalid duration: None")
else:
self.log("Got duration %s" % print_ns(dur))
if self._duration != dur:
self.emit("duration-changed", dur)
self._duration = dur
return dur
def activatePositionListener(self, interval=30):
"""
Activate the position listener.
When activated, the Pipeline will emit the 'position' signal at the
specified interval when it is the PLAYING or PAUSED state.
@see: L{deactivatePositionListener}
@param interval: Interval between position queries in milliseconds
@type interval: L{int} milliseconds
@return: Whether the position listener was activated or not
@rtype: L{bool}
"""
if self._listening:
return True
self._listening = True
self._listeningInterval = interval
# if we're in paused or playing, switch it on
self._listenToPosition(self.getState() == Gst.State.PLAYING)
return True
def deactivatePositionListener(self):
"""
De-activates the position listener.
@see: L{activatePositionListener}
"""
self._listenToPosition(False)
self._listening = False
def _positionListenerCb(self):
try:
cur = self.getPosition()
if cur != Gst.CLOCK_TIME_NONE:
self.emit('position', cur)
finally:
return True
def _listenToPosition(self, listen=True):
# stupid and dumm method, not many checks done
# i.e. it does NOT check for current state
if listen:
if self._listening and self._listeningSigId == 0:
self._listeningSigId = GLib.timeout_add(self._listeningInterval,
self._positionListenerCb)
elif self._listeningSigId != 0:
GLib.source_remove(self._listeningSigId)
self._listeningSigId = 0
def simple_seek(self, position, format=Gst.Format.TIME):
"""
Seeks in the L{Pipeline} to the given position.
@param position: Position to seek to
@type position: L{long}
@param format: The C{Format} of the seek position
@type format: C{Gst.Format}
@raise PipelineError: If seek failed
"""
if format == Gst.Format.TIME:
self.debug("position : %s" % print_ns(position))
else:
self.debug("position : %d , format:%d" % (position, format))
# clamp between [0, duration]
if format == Gst.Format.TIME:
position = max(0, min(position, self.getDuration()) - 1)
res = self._pipeline.seek(1.0, format, Gst.SeekFlags.FLUSH,
Gst.SeekType.SET, position,
Gst.SeekType.NONE, -1)
if not res:
self.debug("seeking failed")
raise PipelineError("seek failed")
self.debug("seeking successful")
self.emit('position', position)
def seekRelative(self, time):
if not time:
self.error("Trying to seek to an invalid time: %s", time)
return
seekvalue = max(0, min(self.getPosition() + time, self.getDuration()))
self.simple_seek(seekvalue)
#}
## Private methods
def _busMessageCb(self, unused_bus, message):
if message.type == Gst.MessageType.EOS:
self.pause()
self.emit('eos')
elif message.type == Gst.MessageType.STATE_CHANGED:
prev, new, pending = message.parse_state_changed()
if message.src == self._pipeline:
self.debug("Pipeline change state prev:%r, new:%r, pending:%r" % (prev, new, pending))
emit_state_change = pending == Gst.State.VOID_PENDING
if prev == Gst.State.READY and new == Gst.State.PAUSED:
# trigger duration-changed
try:
self.getDuration()
except PipelineError:
# no sinks??
pass
elif prev == Gst.State.PAUSED and new == Gst.State.PLAYING:
self._listenToPosition(True)
elif prev == Gst.State.PLAYING and new == Gst.State.PAUSED:
self._listenToPosition(False)
if emit_state_change:
self.emit('state-change', new)
elif message.type == Gst.MessageType.ERROR:
error, detail = message.parse_error()
self._handleErrorMessage(error, detail, message.src)
elif message.type == Gst.MessageType.DURATION_CHANGED:
self.debug("Duration might have changed, querying it")
GLib.idle_add(self._queryDurationAsync)
else:
self.log("%s [%r]" % (message.type, message.src))
def _queryDurationAsync(self, *args, **kwargs):
try:
self.getDuration()
except:
self.log("Duration failed... but we don't care")
return False
def _handleErrorMessage(self, error, detail, source):
self.error("error from %s: %s (%s)" % (source, error, detail))
self.emit('error', error.message, detail)
def _getDuration(self, format=Gst.Format.TIME):
try:
res, dur = self._pipeline.query_duration(format)
except Exception, e:
self.handleException(e)
raise PipelineError("Couldn't get duration: %s" % e)
if not res:
raise PipelineError("Couldn't get duration: Returned None")