/
generic.py
293 lines (231 loc) · 10.3 KB
/
generic.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
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008,2009 Fluendo, S.L.
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
#
# This file may be distributed and/or modified under the terms of
# the GNU Lesser General Public License version 2.1 as published by
# the Free Software Foundation.
# This file is distributed without any warranty; without even the implied
# warranty of merchantability or fitness for a particular purpose.
# See "LICENSE.LGPL" in the source distribution for more information.
#
# Headers in this file shall remain intact.
import gst
import gobject
import threading
from flumotion.component import decodercomponent as dc
from flumotion.common import messages, gstreamer
from flumotion.common.i18n import N_, gettexter
T_ = gettexter()
__version__ = "$Rev: 7162 $"
BASIC_AUDIO_CAPS = "audio/x-raw-int;audio/x-raw-float"
BASIC_VIDEO_CAPS = "video/x-raw-yuv;video/x-raw-rgb"
# FIXME: The GstAutoplugSelectResult enum has no bindings in gst-python.
# Replace this when the enum is exposed in the bindings.
GST_AUTOPLUG_SELECT_TRY = 0
GST_AUTOPLUG_SELECT_SKIP = 2
class FeederInfo(object):
def __init__(self, name, caps, linked=False):
self.name = name
self.caps = caps
class SyncKeeper(gst.Element):
__gstdetails__ = ('SyncKeeper', 'Generic',
'Retimestamp the output to be contiguous and maintain '
'the sync', 'Xavier Queralt')
_audiosink = gst.PadTemplate("audio-in",
gst.PAD_SINK,
gst.PAD_ALWAYS,
gst.caps_from_string(BASIC_AUDIO_CAPS))
_videosink = gst.PadTemplate("video-in",
gst.PAD_SINK,
gst.PAD_ALWAYS,
gst.caps_from_string(BASIC_VIDEO_CAPS))
_audiosrc = gst.PadTemplate("audio-out",
gst.PAD_SRC,
gst.PAD_ALWAYS,
gst.caps_from_string(BASIC_AUDIO_CAPS))
_videosrc = gst.PadTemplate("video-out",
gst.PAD_SRC,
gst.PAD_ALWAYS,
gst.caps_from_string(BASIC_VIDEO_CAPS))
def __init__(self):
gst.Element.__init__(self)
# create source pads
self.audiosrc = gst.Pad(self._audiosrc, "audio-out")
self.add_pad(self.audiosrc)
self.videosrc = gst.Pad(self._videosrc, "video-out")
self.add_pad(self.videosrc)
# create the sink pads and set the chain and event function
self.audiosink = gst.Pad(self._audiosink, "audio-in")
self.audiosink.set_chain_function(lambda pad, buffer:
self.chainfunc(pad, buffer, self.audiosrc))
self.audiosink.set_event_function(lambda pad, buffer:
self.eventfunc(pad, buffer, self.audiosrc))
self.add_pad(self.audiosink)
self.videosink = gst.Pad(self._videosink, "video-in")
self.videosink.set_chain_function(lambda pad, buffer:
self.chainfunc(pad, buffer, self.videosrc))
self.videosink.set_event_function(lambda pad, buffer:
self.eventfunc(pad, buffer, self.videosrc))
self.add_pad(self.videosink)
# all this variables need to be protected with a lock!!!
self._lock = threading.Lock()
self._totalTime = 0L
self._syncTimestamp = 0L
self._syncOffset = 0L
self._resetReceived = True
self._sendNewSegment = True
def _send_new_segment(self):
for pad in [self.videosrc, self.audiosrc]:
pad.push_event(
gst.event_new_new_segment(True, 1.0, gst.FORMAT_TIME,
self._syncTimestamp, -1, 0))
self._sendNewSegment = False
def _update_sync_point(self, start, position):
# Only update the sync point if we haven't received any buffer
# (totalTime == 0) or we received a reset
if not self._totalTime and not self._resetReceived:
return
self._syncTimestamp = self._totalTime
if position >= start:
self._syncOffset = start + (position - start)
else:
self._syncOffset = start
self._resetReceived = False
self.info("Update sync point to % r, offset to %r" %
(gst.TIME_ARGS(self._syncTimestamp),
(gst.TIME_ARGS(self._syncOffset))))
def chainfunc(self, pad, buf, srcpad):
self.log("Input %s timestamp: %s, %s" %
(srcpad is self.audiosrc and 'audio' or 'video',
gst.TIME_ARGS(buf.timestamp),
gst.TIME_ARGS(buf.duration)))
if not self._sendNewSegment:
self._send_new_segment()
try:
self._lock.acquire()
# Discard buffers outside the configured segment
if buf.timestamp < self._syncOffset:
self.warning("Could not clip buffer to segment")
return gst.FLOW_OK
if buf.timestamp == gst.CLOCK_TIME_NONE:
return gst.FLOW_OK
# Get the input stream time of the buffer
buf.timestamp -= self._syncOffset
# Set the accumulated stream time
buf.timestamp += self._syncTimestamp
duration = 0
if buf.duration != gst.CLOCK_TIME_NONE:
duration = buf.duration
self._totalTime = max(buf.timestamp + duration, self._totalTime)
self.log("Output %s timestamp: %s, %s" %
(srcpad is self.audiosrc and 'audio' or 'video',
gst.TIME_ARGS(buf.timestamp),
gst.TIME_ARGS(buf.duration)))
finally:
self._lock.release()
srcpad.push(buf)
return gst.FLOW_OK
def eventfunc(self, pad, event, srcpad):
self.debug("Received event %r from %s" % (event, event.src))
try:
self._lock.acquire()
if event.type == gst.EVENT_NEWSEGMENT:
u, r, f, start, s, position = event.parse_new_segment()
self._update_sync_point(start, position)
if gstreamer.event_is_flumotion_reset(event):
self._resetReceived = True
self._send_new_segment = True
finally:
self._lock.release()
# forward all the events except the new segment events
if event.type != gst.EVENT_NEWSEGMENT:
return srcpad.push_event(event)
return True
gobject.type_register(SyncKeeper)
gst.element_register(SyncKeeper, "synckeeper", gst.RANK_MARGINAL)
class GenericDecoder(dc.DecoderComponent):
"""
Generic decoder component using decodebin2.
It listen to the custom gstreamer event flumotion-reset,
and reset the decoding pipeline by removing the old one
and creating a new one.
Sub-classes must override _get_feeders_info() and return
a list of FeederInfo instances that describe the decoder
output.
When reset, if the new decoded pads do not match the
previously negotiated caps, feeder will not be connected,
and the decoder will go sad.
"""
logCategory = "gen-decoder"
feeder_tmpl = ("identity name=%(ename)s single-segment=true "
"silent=true ! %(caps)s ! @feeder:%(pad)s@")
### Public Methods ###
def init(self):
self._feeders_info = None # {FEEDER_NAME: FeederInfo}
def get_pipeline_string(self, properties):
# Retrieve feeder info and build a dict out of it
finfo = self._get_feeders_info()
assert finfo, "No feeder info specified"
self._feeders_info = dict([(i.name, i) for i in finfo])
pipeline_parts = [self._get_base_pipeline_string()]
for i in self._feeders_info.values():
ename = self._get_output_element_name(i.name)
pipeline_parts.append(
self.feeder_tmpl % dict(ename=ename, caps=i.caps, pad=i.name))
pipeline_str = " ".join(pipeline_parts)
self.log("Decoder pipeline: %s", pipeline_str)
self._blacklist = properties.get('blacklist', [])
return pipeline_str
def configure_pipeline(self, pipeline, properties):
dc.DecoderComponent.configure_pipeline(self, pipeline,
properties)
decoder = self.pipeline.get_by_name("decoder")
decoder.connect('autoplug-select', self._autoplug_select_cb)
### Protected Methods ##
def _get_base_pipeline_string(self):
return 'decodebin2 name=decoder'
def _get_feeders_info(self):
"""
Must be overridden to returns a tuple of FeederInfo.
"""
return None
### Private Methods ###
def _get_output_element_name(self, feed_name):
return "%s-output" % feed_name
### Callbacks ###
def _autoplug_select_cb(self, decoder, pad, caps, factory):
if factory.get_name() in self._blacklist:
self.log("Skipping element %s because it's in the blacklist",
factory.get_name())
return GST_AUTOPLUG_SELECT_SKIP
return GST_AUTOPLUG_SELECT_TRY
class SingleGenericDecoder(GenericDecoder):
logCategory = "sgen-decoder"
_caps_lookup = {'audio': BASIC_AUDIO_CAPS,
'video': BASIC_VIDEO_CAPS}
def init(self):
self._media_type = None
def check_properties(self, properties, addMessage):
media_type = properties.get("media-type")
if media_type not in ["audio", "video"]:
msg = 'Property media-type can only be "audio" or "video"'
m = messages.Error(T_(N_(msg)), mid="error-decoder-media-type")
addMessage(m)
else:
self._media_type = media_type
def _get_feeders_info(self):
caps = self._caps_lookup[self._media_type]
return FeederInfo('default', caps),
class AVGenericDecoder(GenericDecoder):
logCategory = "avgen-decoder"
feeder_tmpl = ("identity name=%(ename)s silent=true ! %(caps)s ! "
"sync.%(pad)s-in sync.%(pad)s-out ! @feeder:%(pad)s@")
def _get_feeders_info(self):
return (FeederInfo('audio', BASIC_AUDIO_CAPS),
FeederInfo('video', BASIC_VIDEO_CAPS))
def _get_base_pipeline_string(self):
return 'decodebin2 name=decoder synckeeper name=sync'