2 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3 * 2005 Wim Taymans <wim@fluendo.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Library General Public
9 * License as published by the Free Software Foundation; either
10 * version 2 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Library General Public License for more details.
17 * You should have received a copy of the GNU Library General Public
18 * License along with this library; if not, write to the
19 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 * Boston, MA 02111-1307, USA.
24 * SECTION:gstbaseaudiosink
25 * @short_description: Base class for audio sinks
26 * @see_also: #GstAudioSink, #GstRingBuffer.
28 * This is the base class for audio sinks. Subclasses need to implement the
29 * ::create_ringbuffer vmethod. This base class will then take care of
30 * writing samples to the ringbuffer, synchronisation, clipping and flushing.
32 * Last reviewed on 2006-09-27 (0.10.12)
37 #include "gstbaseaudiosink.h"
39 GST_DEBUG_CATEGORY_STATIC (gst_base_audio_sink_debug);
40 #define GST_CAT_DEFAULT gst_base_audio_sink_debug
42 #define GST_BASE_AUDIO_SINK_GET_PRIVATE(obj) \
43 (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_AUDIO_SINK, GstBaseAudioSinkPrivate))
45 struct _GstBaseAudioSinkPrivate
47 /* upstream latency */
48 GstClockTime us_latency;
49 /* the clock slaving algorithm in use */
50 GstBaseAudioSinkSlaveMethod slave_method;
51 /* running average of clock skew */
52 GstClockTimeDiff avg_skew;
53 /* the number of samples we aligned last time */
56 gboolean sync_latency;
58 GstClockTime eos_time;
60 gboolean do_time_offset;
61 /* number of microseconds we alow timestamps or clock slaving to drift
63 guint64 drift_tolerance;
66 /* BaseAudioSink signals and args */
73 /* FIXME: 0.11, store the buffer_time and latency_time in nanoseconds */
74 #define DEFAULT_BUFFER_TIME ((200 * GST_MSECOND) / GST_USECOND)
75 #define DEFAULT_LATENCY_TIME ((10 * GST_MSECOND) / GST_USECOND)
76 #define DEFAULT_PROVIDE_CLOCK TRUE
77 #define DEFAULT_SLAVE_METHOD GST_BASE_AUDIO_SINK_SLAVE_SKEW
79 /* FIXME, enable pull mode when clock slaving and trick modes are figured out */
80 #define DEFAULT_CAN_ACTIVATE_PULL FALSE
82 /* when timestamps or clock slaving drift for more than 40ms we resync. This is
83 * a reasonable default */
84 #define DEFAULT_DRIFT_TOLERANCE ((40 * GST_MSECOND) / GST_USECOND)
94 PROP_CAN_ACTIVATE_PULL,
101 gst_base_audio_sink_slave_method_get_type (void)
103 static volatile gsize slave_method_type = 0;
104 static const GEnumValue slave_method[] = {
105 {GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE, "GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE",
107 {GST_BASE_AUDIO_SINK_SLAVE_SKEW, "GST_BASE_AUDIO_SINK_SLAVE_SKEW", "skew"},
108 {GST_BASE_AUDIO_SINK_SLAVE_NONE, "GST_BASE_AUDIO_SINK_SLAVE_NONE", "none"},
112 if (g_once_init_enter (&slave_method_type)) {
114 g_enum_register_static ("GstBaseAudioSinkSlaveMethod", slave_method);
115 g_once_init_leave (&slave_method_type, tmp);
118 return (GType) slave_method_type;
122 #define _do_init(bla) \
123 GST_DEBUG_CATEGORY_INIT (gst_base_audio_sink_debug, "baseaudiosink", 0, "baseaudiosink element");
125 GST_BOILERPLATE_FULL (GstBaseAudioSink, gst_base_audio_sink, GstBaseSink,
126 GST_TYPE_BASE_SINK, _do_init);
128 static void gst_base_audio_sink_dispose (GObject * object);
130 static void gst_base_audio_sink_set_property (GObject * object, guint prop_id,
131 const GValue * value, GParamSpec * pspec);
132 static void gst_base_audio_sink_get_property (GObject * object, guint prop_id,
133 GValue * value, GParamSpec * pspec);
135 static GstStateChangeReturn gst_base_audio_sink_async_play (GstBaseSink *
137 static GstStateChangeReturn gst_base_audio_sink_change_state (GstElement *
138 element, GstStateChange transition);
139 static gboolean gst_base_audio_sink_activate_pull (GstBaseSink * basesink,
141 static gboolean gst_base_audio_sink_query (GstElement * element, GstQuery *
144 static GstClock *gst_base_audio_sink_provide_clock (GstElement * elem);
145 static GstClockTime gst_base_audio_sink_get_time (GstClock * clock,
146 GstBaseAudioSink * sink);
147 static void gst_base_audio_sink_callback (GstRingBuffer * rbuf, guint8 * data,
148 guint len, gpointer user_data);
150 static GstFlowReturn gst_base_audio_sink_preroll (GstBaseSink * bsink,
152 static GstFlowReturn gst_base_audio_sink_render (GstBaseSink * bsink,
154 static gboolean gst_base_audio_sink_event (GstBaseSink * bsink,
156 static void gst_base_audio_sink_get_times (GstBaseSink * bsink,
157 GstBuffer * buffer, GstClockTime * start, GstClockTime * end);
158 static gboolean gst_base_audio_sink_setcaps (GstBaseSink * bsink,
160 static void gst_base_audio_sink_fixate (GstBaseSink * bsink, GstCaps * caps);
162 static gboolean gst_base_audio_sink_query_pad (GstPad * pad, GstQuery * query);
165 /* static guint gst_base_audio_sink_signals[LAST_SIGNAL] = { 0 }; */
168 gst_base_audio_sink_base_init (gpointer g_class)
173 gst_base_audio_sink_class_init (GstBaseAudioSinkClass * klass)
175 GObjectClass *gobject_class;
176 GstElementClass *gstelement_class;
177 GstBaseSinkClass *gstbasesink_class;
179 gobject_class = (GObjectClass *) klass;
180 gstelement_class = (GstElementClass *) klass;
181 gstbasesink_class = (GstBaseSinkClass *) klass;
183 g_type_class_add_private (klass, sizeof (GstBaseAudioSinkPrivate));
185 gobject_class->set_property = gst_base_audio_sink_set_property;
186 gobject_class->get_property = gst_base_audio_sink_get_property;
187 gobject_class->dispose = gst_base_audio_sink_dispose;
189 g_object_class_install_property (gobject_class, PROP_BUFFER_TIME,
190 g_param_spec_int64 ("buffer-time", "Buffer Time",
191 "Size of audio buffer in microseconds", 1,
192 G_MAXINT64, DEFAULT_BUFFER_TIME,
193 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
195 g_object_class_install_property (gobject_class, PROP_LATENCY_TIME,
196 g_param_spec_int64 ("latency-time", "Latency Time",
197 "Audio latency in microseconds", 1,
198 G_MAXINT64, DEFAULT_LATENCY_TIME,
199 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
201 g_object_class_install_property (gobject_class, PROP_PROVIDE_CLOCK,
202 g_param_spec_boolean ("provide-clock", "Provide Clock",
203 "Provide a clock to be used as the global pipeline clock",
204 DEFAULT_PROVIDE_CLOCK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
206 g_object_class_install_property (gobject_class, PROP_SLAVE_METHOD,
207 g_param_spec_enum ("slave-method", "Slave Method",
208 "Algorithm to use to match the rate of the masterclock",
209 GST_TYPE_BASE_AUDIO_SINK_SLAVE_METHOD, DEFAULT_SLAVE_METHOD,
210 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
212 g_object_class_install_property (gobject_class, PROP_CAN_ACTIVATE_PULL,
213 g_param_spec_boolean ("can-activate-pull", "Allow Pull Scheduling",
214 "Allow pull-based scheduling", DEFAULT_CAN_ACTIVATE_PULL,
215 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
217 * GstBaseAudioSink:drift-tolerance
219 * Controls the amount of time in milliseconds that timestamps or clocks are allowed
220 * to drift before resynchronisation happens.
224 g_object_class_install_property (gobject_class, PROP_DRIFT_TOLERANCE,
225 g_param_spec_int64 ("drift-tolerance", "Drift Tolerance",
226 "Tolerance for timestamp and clock drift in microseconds", 1,
227 G_MAXINT64, DEFAULT_DRIFT_TOLERANCE,
228 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
230 gstelement_class->change_state =
231 GST_DEBUG_FUNCPTR (gst_base_audio_sink_change_state);
232 gstelement_class->provide_clock =
233 GST_DEBUG_FUNCPTR (gst_base_audio_sink_provide_clock);
234 gstelement_class->query = GST_DEBUG_FUNCPTR (gst_base_audio_sink_query);
236 gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_base_audio_sink_event);
237 gstbasesink_class->preroll = GST_DEBUG_FUNCPTR (gst_base_audio_sink_preroll);
238 gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_base_audio_sink_render);
239 gstbasesink_class->get_times =
240 GST_DEBUG_FUNCPTR (gst_base_audio_sink_get_times);
241 gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_base_audio_sink_setcaps);
242 gstbasesink_class->fixate = GST_DEBUG_FUNCPTR (gst_base_audio_sink_fixate);
243 gstbasesink_class->async_play =
244 GST_DEBUG_FUNCPTR (gst_base_audio_sink_async_play);
245 gstbasesink_class->activate_pull =
246 GST_DEBUG_FUNCPTR (gst_base_audio_sink_activate_pull);
248 /* ref class from a thread-safe context to work around missing bit of
249 * thread-safety in GObject */
250 g_type_class_ref (GST_TYPE_AUDIO_CLOCK);
251 g_type_class_ref (GST_TYPE_RING_BUFFER);
256 gst_base_audio_sink_init (GstBaseAudioSink * baseaudiosink,
257 GstBaseAudioSinkClass * g_class)
259 GstPluginFeature *feature;
260 GstBaseSink *basesink;
262 baseaudiosink->priv = GST_BASE_AUDIO_SINK_GET_PRIVATE (baseaudiosink);
264 baseaudiosink->buffer_time = DEFAULT_BUFFER_TIME;
265 baseaudiosink->latency_time = DEFAULT_LATENCY_TIME;
266 baseaudiosink->provide_clock = DEFAULT_PROVIDE_CLOCK;
267 baseaudiosink->priv->slave_method = DEFAULT_SLAVE_METHOD;
268 baseaudiosink->priv->drift_tolerance = DEFAULT_DRIFT_TOLERANCE;
270 baseaudiosink->provided_clock = gst_audio_clock_new ("GstAudioSinkClock",
271 (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time, baseaudiosink);
273 basesink = GST_BASE_SINK_CAST (baseaudiosink);
274 basesink->can_activate_push = TRUE;
275 basesink->can_activate_pull = DEFAULT_CAN_ACTIVATE_PULL;
277 gst_base_sink_set_last_buffer_enabled (basesink, FALSE);
279 /* install some custom pad_query functions */
280 gst_pad_set_query_function (GST_BASE_SINK_PAD (baseaudiosink),
281 GST_DEBUG_FUNCPTR (gst_base_audio_sink_query_pad));
283 baseaudiosink->priv->do_time_offset = TRUE;
285 /* check the factory, pulsesink < 0.10.17 does the timestamp offset itself so
286 * we should not do ourselves */
288 GST_PLUGIN_FEATURE_CAST (GST_ELEMENT_CLASS (g_class)->elementfactory);
289 GST_DEBUG ("created from factory %p", feature);
291 /* HACK for old pulsesink that did the time_offset themselves */
293 if (strcmp (gst_plugin_feature_get_name (feature), "pulsesink") == 0) {
294 if (!gst_plugin_feature_check_version (feature, 0, 10, 17)) {
295 /* we're dealing with an old pulsesink, we need to disable time corection */
296 GST_DEBUG ("disable time offset");
297 baseaudiosink->priv->do_time_offset = FALSE;
304 gst_base_audio_sink_dispose (GObject * object)
306 GstBaseAudioSink *sink;
308 sink = GST_BASE_AUDIO_SINK (object);
310 if (sink->provided_clock) {
311 gst_audio_clock_invalidate (sink->provided_clock);
312 gst_object_unref (sink->provided_clock);
313 sink->provided_clock = NULL;
316 if (sink->ringbuffer) {
317 gst_object_unparent (GST_OBJECT_CAST (sink->ringbuffer));
318 sink->ringbuffer = NULL;
321 G_OBJECT_CLASS (parent_class)->dispose (object);
326 gst_base_audio_sink_provide_clock (GstElement * elem)
328 GstBaseAudioSink *sink;
331 sink = GST_BASE_AUDIO_SINK (elem);
333 /* we have no ringbuffer (must be NULL state) */
334 if (sink->ringbuffer == NULL)
337 if (!gst_ring_buffer_is_acquired (sink->ringbuffer))
340 GST_OBJECT_LOCK (sink);
341 if (!sink->provide_clock)
344 clock = GST_CLOCK_CAST (gst_object_ref (sink->provided_clock));
345 GST_OBJECT_UNLOCK (sink);
352 GST_DEBUG_OBJECT (sink, "ringbuffer not acquired");
357 GST_DEBUG_OBJECT (sink, "clock provide disabled");
358 GST_OBJECT_UNLOCK (sink);
364 gst_base_audio_sink_query_pad (GstPad * pad, GstQuery * query)
366 gboolean res = FALSE;
367 GstBaseAudioSink *basesink;
369 basesink = GST_BASE_AUDIO_SINK (gst_pad_get_parent (pad));
371 switch (GST_QUERY_TYPE (query)) {
372 case GST_QUERY_CONVERT:
374 GstFormat src_fmt, dest_fmt;
375 gint64 src_val, dest_val;
377 GST_LOG_OBJECT (pad, "query convert");
379 if (basesink->ringbuffer) {
380 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, NULL);
381 res = gst_ring_buffer_convert (basesink->ringbuffer, src_fmt, src_val,
382 dest_fmt, &dest_val);
384 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
393 gst_object_unref (basesink);
399 gst_base_audio_sink_query (GstElement * element, GstQuery * query)
401 gboolean res = FALSE;
402 GstBaseAudioSink *basesink;
404 basesink = GST_BASE_AUDIO_SINK (element);
406 switch (GST_QUERY_TYPE (query)) {
407 case GST_QUERY_LATENCY:
409 gboolean live, us_live;
410 GstClockTime min_l, max_l;
412 GST_DEBUG_OBJECT (basesink, "latency query");
414 /* ask parent first, it will do an upstream query for us. */
416 gst_base_sink_query_latency (GST_BASE_SINK_CAST (basesink), &live,
417 &us_live, &min_l, &max_l))) {
418 GstClockTime base_latency, min_latency, max_latency;
420 /* we and upstream are both live, adjust the min_latency */
421 if (live && us_live) {
422 GstRingBufferSpec *spec;
424 GST_OBJECT_LOCK (basesink);
425 if (!basesink->ringbuffer || !basesink->ringbuffer->spec.rate) {
426 GST_OBJECT_UNLOCK (basesink);
428 GST_DEBUG_OBJECT (basesink,
429 "we are not yet negotiated, can't report latency yet");
433 spec = &basesink->ringbuffer->spec;
435 basesink->priv->us_latency = min_l;
438 gst_util_uint64_scale_int (spec->seglatency * spec->segsize,
439 GST_SECOND, spec->rate * spec->bytes_per_sample);
440 GST_OBJECT_UNLOCK (basesink);
442 /* we cannot go lower than the buffer size and the min peer latency */
443 min_latency = base_latency + min_l;
444 /* the max latency is the max of the peer, we can delay an infinite
446 max_latency = (max_l == -1) ? -1 : (base_latency + max_l);
448 GST_DEBUG_OBJECT (basesink,
449 "peer min %" GST_TIME_FORMAT ", our min latency: %"
450 GST_TIME_FORMAT, GST_TIME_ARGS (min_l),
451 GST_TIME_ARGS (min_latency));
452 GST_DEBUG_OBJECT (basesink,
453 "peer max %" GST_TIME_FORMAT ", our max latency: %"
454 GST_TIME_FORMAT, GST_TIME_ARGS (max_l),
455 GST_TIME_ARGS (max_latency));
457 GST_DEBUG_OBJECT (basesink,
458 "peer or we are not live, don't care about latency");
462 gst_query_set_latency (query, live, min_latency, max_latency);
466 case GST_QUERY_CONVERT:
468 GstFormat src_fmt, dest_fmt;
469 gint64 src_val, dest_val;
471 GST_LOG_OBJECT (basesink, "query convert");
473 if (basesink->ringbuffer) {
474 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, NULL);
475 res = gst_ring_buffer_convert (basesink->ringbuffer, src_fmt, src_val,
476 dest_fmt, &dest_val);
478 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
484 res = GST_ELEMENT_CLASS (parent_class)->query (element, query);
494 gst_base_audio_sink_get_time (GstClock * clock, GstBaseAudioSink * sink)
496 guint64 raw, samples;
500 if (sink->ringbuffer == NULL || sink->ringbuffer->spec.rate == 0)
501 return GST_CLOCK_TIME_NONE;
503 /* our processed samples are always increasing */
504 raw = samples = gst_ring_buffer_samples_done (sink->ringbuffer);
506 /* the number of samples not yet processed, this is still queued in the
507 * device (not played for playback). */
508 delay = gst_ring_buffer_delay (sink->ringbuffer);
510 if (G_LIKELY (samples >= delay))
515 result = gst_util_uint64_scale_int (samples, GST_SECOND,
516 sink->ringbuffer->spec.rate);
518 GST_DEBUG_OBJECT (sink,
519 "processed samples: raw %" G_GUINT64_FORMAT ", delay %u, real %"
520 G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT,
521 raw, delay, samples, GST_TIME_ARGS (result));
527 * gst_base_audio_sink_set_provide_clock:
528 * @sink: a #GstBaseAudioSink
529 * @provide: new state
531 * Controls whether @sink will provide a clock or not. If @provide is %TRUE,
532 * gst_element_provide_clock() will return a clock that reflects the datarate
533 * of @sink. If @provide is %FALSE, gst_element_provide_clock() will return NULL.
538 gst_base_audio_sink_set_provide_clock (GstBaseAudioSink * sink,
541 g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
543 GST_OBJECT_LOCK (sink);
544 sink->provide_clock = provide;
545 GST_OBJECT_UNLOCK (sink);
549 * gst_base_audio_sink_get_provide_clock:
550 * @sink: a #GstBaseAudioSink
552 * Queries whether @sink will provide a clock or not. See also
553 * gst_base_audio_sink_set_provide_clock.
555 * Returns: %TRUE if @sink will provide a clock.
560 gst_base_audio_sink_get_provide_clock (GstBaseAudioSink * sink)
564 g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), FALSE);
566 GST_OBJECT_LOCK (sink);
567 result = sink->provide_clock;
568 GST_OBJECT_UNLOCK (sink);
574 * gst_base_audio_sink_set_slave_method:
575 * @sink: a #GstBaseAudioSink
576 * @method: the new slave method
578 * Controls how clock slaving will be performed in @sink.
583 gst_base_audio_sink_set_slave_method (GstBaseAudioSink * sink,
584 GstBaseAudioSinkSlaveMethod method)
586 g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
588 GST_OBJECT_LOCK (sink);
589 sink->priv->slave_method = method;
590 GST_OBJECT_UNLOCK (sink);
594 * gst_base_audio_sink_get_slave_method:
595 * @sink: a #GstBaseAudioSink
597 * Get the current slave method used by @sink.
599 * Returns: The current slave method used by @sink.
603 GstBaseAudioSinkSlaveMethod
604 gst_base_audio_sink_get_slave_method (GstBaseAudioSink * sink)
606 GstBaseAudioSinkSlaveMethod result;
608 g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), -1);
610 GST_OBJECT_LOCK (sink);
611 result = sink->priv->slave_method;
612 GST_OBJECT_UNLOCK (sink);
619 * gst_base_audio_sink_set_drift_tolerance:
620 * @sink: a #GstBaseAudioSink
621 * @drift_tolerance: the new drift tolerance in microseconds
623 * Controls the sink's drift tolerance.
628 gst_base_audio_sink_set_drift_tolerance (GstBaseAudioSink * sink,
629 gint64 drift_tolerance)
631 g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
633 GST_OBJECT_LOCK (sink);
634 sink->priv->drift_tolerance = drift_tolerance;
635 GST_OBJECT_UNLOCK (sink);
639 * gst_base_audio_sink_get_drift_tolerance
640 * @sink: a #GstBaseAudioSink
642 * Get the current drift tolerance, in microseconds, used by @sink.
644 * Returns: The current drift tolerance used by @sink.
649 gst_base_audio_sink_get_drift_tolerance (GstBaseAudioSink * sink)
653 g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), -1);
655 GST_OBJECT_LOCK (sink);
656 result = sink->priv->drift_tolerance;
657 GST_OBJECT_UNLOCK (sink);
663 gst_base_audio_sink_set_property (GObject * object, guint prop_id,
664 const GValue * value, GParamSpec * pspec)
666 GstBaseAudioSink *sink;
668 sink = GST_BASE_AUDIO_SINK (object);
671 case PROP_BUFFER_TIME:
672 sink->buffer_time = g_value_get_int64 (value);
674 case PROP_LATENCY_TIME:
675 sink->latency_time = g_value_get_int64 (value);
677 case PROP_PROVIDE_CLOCK:
678 gst_base_audio_sink_set_provide_clock (sink, g_value_get_boolean (value));
680 case PROP_SLAVE_METHOD:
681 gst_base_audio_sink_set_slave_method (sink, g_value_get_enum (value));
683 case PROP_CAN_ACTIVATE_PULL:
684 GST_BASE_SINK (sink)->can_activate_pull = g_value_get_boolean (value);
686 case PROP_DRIFT_TOLERANCE:
687 gst_base_audio_sink_set_drift_tolerance (sink, g_value_get_int64 (value));
690 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
696 gst_base_audio_sink_get_property (GObject * object, guint prop_id,
697 GValue * value, GParamSpec * pspec)
699 GstBaseAudioSink *sink;
701 sink = GST_BASE_AUDIO_SINK (object);
704 case PROP_BUFFER_TIME:
705 g_value_set_int64 (value, sink->buffer_time);
707 case PROP_LATENCY_TIME:
708 g_value_set_int64 (value, sink->latency_time);
710 case PROP_PROVIDE_CLOCK:
711 g_value_set_boolean (value, gst_base_audio_sink_get_provide_clock (sink));
713 case PROP_SLAVE_METHOD:
714 g_value_set_enum (value, gst_base_audio_sink_get_slave_method (sink));
716 case PROP_CAN_ACTIVATE_PULL:
717 g_value_set_boolean (value, GST_BASE_SINK (sink)->can_activate_pull);
719 case PROP_DRIFT_TOLERANCE:
720 g_value_set_int64 (value, gst_base_audio_sink_get_drift_tolerance (sink));
723 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
729 gst_base_audio_sink_setcaps (GstBaseSink * bsink, GstCaps * caps)
731 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
732 GstRingBufferSpec *spec;
734 GstClockTime crate_num, crate_denom;
736 if (!sink->ringbuffer)
739 spec = &sink->ringbuffer->spec;
741 GST_DEBUG_OBJECT (sink, "release old ringbuffer");
743 /* get current time, updates the last_time */
744 now = gst_clock_get_time (sink->provided_clock);
746 GST_DEBUG_OBJECT (sink, "time was %" GST_TIME_FORMAT, GST_TIME_ARGS (now));
748 /* release old ringbuffer */
749 gst_ring_buffer_pause (sink->ringbuffer);
750 gst_ring_buffer_activate (sink->ringbuffer, FALSE);
751 gst_ring_buffer_release (sink->ringbuffer);
753 GST_DEBUG_OBJECT (sink, "parse caps");
755 spec->buffer_time = sink->buffer_time;
756 spec->latency_time = sink->latency_time;
759 if (!gst_ring_buffer_parse_caps (spec, caps))
762 gst_ring_buffer_debug_spec_buff (spec);
764 GST_DEBUG_OBJECT (sink, "acquire ringbuffer");
765 if (!gst_ring_buffer_acquire (sink->ringbuffer, spec))
768 if (bsink->pad_mode == GST_ACTIVATE_PUSH) {
769 GST_DEBUG_OBJECT (sink, "activate ringbuffer");
770 gst_ring_buffer_activate (sink->ringbuffer, TRUE);
773 /* due to possible changes in the spec file we should recalibrate the clock */
774 gst_clock_get_calibration (sink->provided_clock, NULL, NULL,
775 &crate_num, &crate_denom);
776 gst_clock_set_calibration (sink->provided_clock,
777 gst_clock_get_internal_time (sink->provided_clock), now, crate_num,
780 /* calculate actual latency and buffer times.
781 * FIXME: In 0.11, store the latency_time internally in ns */
782 spec->latency_time = gst_util_uint64_scale (spec->segsize,
783 (GST_SECOND / GST_USECOND), spec->rate * spec->bytes_per_sample);
785 spec->buffer_time = spec->segtotal * spec->latency_time;
787 gst_ring_buffer_debug_spec_buff (spec);
794 GST_DEBUG_OBJECT (sink, "could not parse caps");
795 GST_ELEMENT_ERROR (sink, STREAM, FORMAT,
796 (NULL), ("cannot parse audio format."));
801 GST_DEBUG_OBJECT (sink, "could not acquire ringbuffer");
807 gst_base_audio_sink_fixate (GstBaseSink * bsink, GstCaps * caps)
812 s = gst_caps_get_structure (caps, 0);
814 /* fields for all formats */
815 gst_structure_fixate_field_nearest_int (s, "rate", 44100);
816 gst_structure_fixate_field_nearest_int (s, "channels", 2);
817 gst_structure_fixate_field_nearest_int (s, "width", 16);
820 if (gst_structure_has_field (s, "depth")) {
821 gst_structure_get_int (s, "width", &width);
822 /* round width to nearest multiple of 8 for the depth */
823 depth = GST_ROUND_UP_8 (width);
824 gst_structure_fixate_field_nearest_int (s, "depth", depth);
826 if (gst_structure_has_field (s, "signed"))
827 gst_structure_fixate_field_boolean (s, "signed", TRUE);
828 if (gst_structure_has_field (s, "endianness"))
829 gst_structure_fixate_field_nearest_int (s, "endianness", G_BYTE_ORDER);
833 gst_base_audio_sink_get_times (GstBaseSink * bsink, GstBuffer * buffer,
834 GstClockTime * start, GstClockTime * end)
836 /* our clock sync is a bit too much for the base class to handle so
837 * we implement it ourselves. */
838 *start = GST_CLOCK_TIME_NONE;
839 *end = GST_CLOCK_TIME_NONE;
842 /* This waits for the drain to happen and can be canceled */
844 gst_base_audio_sink_drain (GstBaseAudioSink * sink)
846 if (!sink->ringbuffer)
848 if (!sink->ringbuffer->spec.rate)
851 /* if PLAYING is interrupted,
852 * arrange to have clock running when going to PLAYING again */
853 g_atomic_int_set (&sink->abidata.ABI.eos_rendering, 1);
855 /* need to start playback before we can drain, but only when
856 * we have successfully negotiated a format and thus acquired the
858 if (gst_ring_buffer_is_acquired (sink->ringbuffer))
859 gst_ring_buffer_start (sink->ringbuffer);
861 if (sink->priv->eos_time != -1) {
862 GST_DEBUG_OBJECT (sink,
863 "last sample time %" GST_TIME_FORMAT,
864 GST_TIME_ARGS (sink->priv->eos_time));
866 /* wait for the EOS time to be reached, this is the time when the last
867 * sample is played. */
868 gst_base_sink_wait_eos (GST_BASE_SINK (sink), sink->priv->eos_time, NULL);
870 GST_DEBUG_OBJECT (sink, "drained audio");
872 g_atomic_int_set (&sink->abidata.ABI.eos_rendering, 0);
877 gst_base_audio_sink_event (GstBaseSink * bsink, GstEvent * event)
879 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
881 switch (GST_EVENT_TYPE (event)) {
882 case GST_EVENT_FLUSH_START:
883 if (sink->ringbuffer)
884 gst_ring_buffer_set_flushing (sink->ringbuffer, TRUE);
886 case GST_EVENT_FLUSH_STOP:
887 /* always resync on sample after a flush */
888 sink->priv->avg_skew = -1;
889 sink->next_sample = -1;
890 sink->priv->eos_time = -1;
891 if (sink->ringbuffer)
892 gst_ring_buffer_set_flushing (sink->ringbuffer, FALSE);
895 /* now wait till we played everything */
896 gst_base_audio_sink_drain (sink);
898 case GST_EVENT_NEWSEGMENT:
902 /* we only need the rate */
903 gst_event_parse_new_segment_full (event, NULL, &rate, NULL, NULL,
906 GST_DEBUG_OBJECT (sink, "new segment rate of %f", rate);
916 gst_base_audio_sink_preroll (GstBaseSink * bsink, GstBuffer * buffer)
918 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
920 if (!gst_ring_buffer_is_acquired (sink->ringbuffer))
923 /* we don't really do anything when prerolling. We could make a
924 * property to play this buffer to have some sort of scrubbing
930 GST_DEBUG_OBJECT (sink, "ringbuffer in wrong state");
931 GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("sink not negotiated."));
932 return GST_FLOW_NOT_NEGOTIATED;
937 gst_base_audio_sink_get_offset (GstBaseAudioSink * sink)
940 gint writeseg, segdone, sps;
943 /* assume we can append to the previous sample */
944 sample = sink->next_sample;
945 /* no previous sample, try to insert at position 0 */
949 sps = sink->ringbuffer->samples_per_seg;
951 /* figure out the segment and the offset inside the segment where
952 * the sample should be written. */
953 writeseg = sample / sps;
955 /* get the currently processed segment */
956 segdone = g_atomic_int_get (&sink->ringbuffer->segdone)
957 - sink->ringbuffer->segbase;
959 /* see how far away it is from the write segment */
960 diff = writeseg - segdone;
962 /* sample would be dropped, position to next playable position */
963 sample = (segdone + 1) * sps;
970 clock_convert_external (GstClockTime external, GstClockTime cinternal,
971 GstClockTime cexternal, GstClockTime crate_num, GstClockTime crate_denom)
973 /* adjust for rate and speed */
974 if (external >= cexternal) {
976 gst_util_uint64_scale (external - cexternal, crate_denom, crate_num);
977 external += cinternal;
980 gst_util_uint64_scale (cexternal - external, crate_denom, crate_num);
981 if (cinternal > external)
982 external = cinternal - external;
989 /* algorithm to calculate sample positions that will result in resampling to
990 * match the clock rate of the master */
992 gst_base_audio_sink_resample_slaving (GstBaseAudioSink * sink,
993 GstClockTime render_start, GstClockTime render_stop,
994 GstClockTime * srender_start, GstClockTime * srender_stop)
996 GstClockTime cinternal, cexternal;
997 GstClockTime crate_num, crate_denom;
999 /* FIXME, we can sample and add observations here or use the timeouts on the
1000 * clock. No idea which one is better or more stable. The timeout seems more
1001 * arbitrary but this one seems more demanding and does not work when there is
1002 * no data comming in to the sink. */
1004 GstClockTime etime, itime;
1007 /* sample clocks and figure out clock skew */
1008 etime = gst_clock_get_time (GST_ELEMENT_CLOCK (sink));
1009 itime = gst_audio_clock_get_time (sink->provided_clock);
1011 /* add new observation */
1012 gst_clock_add_observation (sink->provided_clock, itime, etime, &r_squared);
1015 /* get calibration parameters to compensate for speed and offset differences
1016 * when we are slaved */
1017 gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
1018 &crate_num, &crate_denom);
1020 GST_DEBUG_OBJECT (sink, "internal %" GST_TIME_FORMAT " external %"
1021 GST_TIME_FORMAT " %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT " = %f",
1022 GST_TIME_ARGS (cinternal), GST_TIME_ARGS (cexternal), crate_num,
1023 crate_denom, gst_guint64_to_gdouble (crate_num) /
1024 gst_guint64_to_gdouble (crate_denom));
1027 crate_denom = crate_num = 1;
1029 /* bring external time to internal time */
1030 render_start = clock_convert_external (render_start, cinternal, cexternal,
1031 crate_num, crate_denom);
1032 render_stop = clock_convert_external (render_stop, cinternal, cexternal,
1033 crate_num, crate_denom);
1035 GST_DEBUG_OBJECT (sink,
1036 "after slaving: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1037 GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1039 *srender_start = render_start;
1040 *srender_stop = render_stop;
1043 /* algorithm to calculate sample positions that will result in changing the
1044 * playout pointer to match the clock rate of the master */
1046 gst_base_audio_sink_skew_slaving (GstBaseAudioSink * sink,
1047 GstClockTime render_start, GstClockTime render_stop,
1048 GstClockTime * srender_start, GstClockTime * srender_stop)
1050 GstClockTime cinternal, cexternal, crate_num, crate_denom;
1051 GstClockTime etime, itime;
1052 GstClockTimeDiff skew, mdrift, mdrift2;
1056 /* get calibration parameters to compensate for offsets */
1057 gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
1058 &crate_num, &crate_denom);
1060 /* sample clocks and figure out clock skew */
1061 etime = gst_clock_get_time (GST_ELEMENT_CLOCK (sink));
1062 itime = gst_audio_clock_get_time (sink->provided_clock);
1063 itime = gst_audio_clock_adjust (sink->provided_clock, itime);
1065 GST_DEBUG_OBJECT (sink,
1066 "internal %" GST_TIME_FORMAT " external %" GST_TIME_FORMAT
1067 " cinternal %" GST_TIME_FORMAT " cexternal %" GST_TIME_FORMAT,
1068 GST_TIME_ARGS (itime), GST_TIME_ARGS (etime),
1069 GST_TIME_ARGS (cinternal), GST_TIME_ARGS (cexternal));
1071 /* make sure we never go below 0 */
1072 etime = etime > cexternal ? etime - cexternal : 0;
1073 itime = itime > cinternal ? itime - cinternal : 0;
1075 /* do itime - etime.
1076 * positive value means external clock goes slower
1077 * negative value means external clock goes faster */
1078 skew = GST_CLOCK_DIFF (etime, itime);
1079 if (sink->priv->avg_skew == -1) {
1080 /* first observation */
1081 sink->priv->avg_skew = skew;
1083 /* next observations use a moving average */
1084 sink->priv->avg_skew = (31 * sink->priv->avg_skew + skew) / 32;
1087 GST_DEBUG_OBJECT (sink, "internal %" GST_TIME_FORMAT " external %"
1088 GST_TIME_FORMAT " skew %" G_GINT64_FORMAT " avg %" G_GINT64_FORMAT,
1089 GST_TIME_ARGS (itime), GST_TIME_ARGS (etime), skew, sink->priv->avg_skew);
1091 /* the max drift we allow */
1092 mdrift = sink->priv->drift_tolerance * 1000;
1093 mdrift2 = mdrift / 2;
1095 /* adjust playout pointer based on skew */
1096 if (sink->priv->avg_skew > mdrift2) {
1097 /* master is running slower, move internal time forward */
1098 GST_WARNING_OBJECT (sink,
1099 "correct clock skew %" G_GINT64_FORMAT " > %" G_GINT64_FORMAT,
1100 sink->priv->avg_skew, mdrift2);
1101 cexternal = cexternal > mdrift ? cexternal - mdrift : 0;
1102 sink->priv->avg_skew -= mdrift;
1104 driftsamples = (sink->ringbuffer->spec.rate * mdrift) / GST_SECOND;
1105 last_align = sink->priv->last_align;
1107 /* if we were aligning in the wrong direction or we aligned more than what we
1108 * will correct, resync */
1109 if (last_align < 0 || last_align > driftsamples)
1110 sink->next_sample = -1;
1112 GST_DEBUG_OBJECT (sink,
1113 "last_align %" G_GINT64_FORMAT " driftsamples %u, next %"
1114 G_GUINT64_FORMAT, last_align, driftsamples, sink->next_sample);
1116 gst_clock_set_calibration (sink->provided_clock, cinternal, cexternal,
1117 crate_num, crate_denom);
1118 } else if (sink->priv->avg_skew < -mdrift2) {
1119 /* master is running faster, move external time forwards */
1120 GST_WARNING_OBJECT (sink,
1121 "correct clock skew %" G_GINT64_FORMAT " < %" G_GINT64_FORMAT,
1122 sink->priv->avg_skew, -mdrift2);
1123 cexternal += mdrift;
1124 sink->priv->avg_skew += mdrift;
1126 driftsamples = (sink->ringbuffer->spec.rate * mdrift) / GST_SECOND;
1127 last_align = sink->priv->last_align;
1129 /* if we were aligning in the wrong direction or we aligned more than what we
1130 * will correct, resync */
1131 if (last_align > 0 || -last_align > driftsamples)
1132 sink->next_sample = -1;
1134 GST_DEBUG_OBJECT (sink,
1135 "last_align %" G_GINT64_FORMAT " driftsamples %u, next %"
1136 G_GUINT64_FORMAT, last_align, driftsamples, sink->next_sample);
1138 gst_clock_set_calibration (sink->provided_clock, cinternal, cexternal,
1139 crate_num, crate_denom);
1142 /* convert, ignoring speed */
1143 render_start = clock_convert_external (render_start, cinternal, cexternal,
1144 crate_num, crate_denom);
1145 render_stop = clock_convert_external (render_stop, cinternal, cexternal,
1146 crate_num, crate_denom);
1148 *srender_start = render_start;
1149 *srender_stop = render_stop;
1152 /* apply the clock offset but do no slaving otherwise */
1154 gst_base_audio_sink_none_slaving (GstBaseAudioSink * sink,
1155 GstClockTime render_start, GstClockTime render_stop,
1156 GstClockTime * srender_start, GstClockTime * srender_stop)
1158 GstClockTime cinternal, cexternal, crate_num, crate_denom;
1160 /* get calibration parameters to compensate for offsets */
1161 gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
1162 &crate_num, &crate_denom);
1164 /* convert, ignoring speed */
1165 render_start = clock_convert_external (render_start, cinternal, cexternal,
1166 crate_num, crate_denom);
1167 render_stop = clock_convert_external (render_stop, cinternal, cexternal,
1168 crate_num, crate_denom);
1170 *srender_start = render_start;
1171 *srender_stop = render_stop;
1174 /* converts render_start and render_stop to their slaved values */
1176 gst_base_audio_sink_handle_slaving (GstBaseAudioSink * sink,
1177 GstClockTime render_start, GstClockTime render_stop,
1178 GstClockTime * srender_start, GstClockTime * srender_stop)
1180 switch (sink->priv->slave_method) {
1181 case GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE:
1182 gst_base_audio_sink_resample_slaving (sink, render_start, render_stop,
1183 srender_start, srender_stop);
1185 case GST_BASE_AUDIO_SINK_SLAVE_SKEW:
1186 gst_base_audio_sink_skew_slaving (sink, render_start, render_stop,
1187 srender_start, srender_stop);
1189 case GST_BASE_AUDIO_SINK_SLAVE_NONE:
1190 gst_base_audio_sink_none_slaving (sink, render_start, render_stop,
1191 srender_start, srender_stop);
1194 g_warning ("unknown slaving method %d", sink->priv->slave_method);
1199 /* must be called with LOCK */
1200 static GstFlowReturn
1201 gst_base_audio_sink_sync_latency (GstBaseSink * bsink, GstMiniObject * obj)
1204 GstClockReturn status;
1205 GstClockTime time, render_delay;
1207 GstBaseAudioSink *sink;
1208 GstClockTime itime, etime;
1209 GstClockTime rate_num, rate_denom;
1210 GstClockTimeDiff jitter;
1212 sink = GST_BASE_AUDIO_SINK (bsink);
1214 clock = GST_ELEMENT_CLOCK (sink);
1215 if (G_UNLIKELY (clock == NULL))
1218 /* we provided the global clock, don't need to do anything special */
1219 if (clock == sink->provided_clock)
1222 GST_OBJECT_UNLOCK (sink);
1225 GST_DEBUG_OBJECT (sink, "checking preroll");
1227 ret = gst_base_sink_do_preroll (bsink, obj);
1228 if (ret != GST_FLOW_OK)
1231 GST_OBJECT_LOCK (sink);
1232 time = sink->priv->us_latency;
1233 GST_OBJECT_UNLOCK (sink);
1235 /* Renderdelay is added onto our own latency, and needs
1236 * to be subtracted as well */
1237 render_delay = gst_base_sink_get_render_delay (bsink);
1239 if (G_LIKELY (time > render_delay))
1240 time -= render_delay;
1244 /* preroll done, we can sync since we are in PLAYING now. */
1245 GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
1246 GST_TIME_FORMAT, GST_TIME_ARGS (time));
1248 /* wait for the clock, this can be interrupted because we got shut down or
1250 status = gst_base_sink_wait_clock (bsink, time, &jitter);
1252 GST_DEBUG_OBJECT (sink, "clock returned %d %" GST_TIME_FORMAT, status,
1253 GST_TIME_ARGS (jitter));
1255 /* invalid time, no clock or sync disabled, just continue then */
1256 if (status == GST_CLOCK_BADTIME)
1259 /* waiting could have been interrupted and we can be flushing now */
1260 if (G_UNLIKELY (bsink->flushing))
1263 /* retry if we got unscheduled, which means we did not reach the timeout
1264 * yet. if some other error occures, we continue. */
1265 } while (status == GST_CLOCK_UNSCHEDULED);
1267 GST_OBJECT_LOCK (sink);
1268 GST_DEBUG_OBJECT (sink, "latency synced");
1270 /* when we prerolled in time, we can accurately set the calibration,
1271 * our internal clock should exactly have been the latency (== the running
1272 * time of the external clock) */
1273 etime = GST_ELEMENT_CAST (sink)->base_time + time;
1274 itime = gst_audio_clock_get_time (sink->provided_clock);
1275 itime = gst_audio_clock_adjust (sink->provided_clock, itime);
1277 if (status == GST_CLOCK_EARLY) {
1278 /* when we prerolled late, we have to take into account the lateness */
1279 GST_DEBUG_OBJECT (sink, "late preroll, adding jitter");
1283 /* start ringbuffer so we can start slaving right away when we need to */
1284 gst_ring_buffer_start (sink->ringbuffer);
1286 GST_DEBUG_OBJECT (sink,
1287 "internal time: %" GST_TIME_FORMAT " external time: %" GST_TIME_FORMAT,
1288 GST_TIME_ARGS (itime), GST_TIME_ARGS (etime));
1290 /* copy the original calibrated rate but update the internal and external
1292 gst_clock_get_calibration (sink->provided_clock, NULL, NULL, &rate_num,
1294 gst_clock_set_calibration (sink->provided_clock, itime, etime,
1295 rate_num, rate_denom);
1297 switch (sink->priv->slave_method) {
1298 case GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE:
1299 /* only set as master when we are resampling */
1300 GST_DEBUG_OBJECT (sink, "Setting clock as master");
1301 gst_clock_set_master (sink->provided_clock, clock);
1303 case GST_BASE_AUDIO_SINK_SLAVE_SKEW:
1304 case GST_BASE_AUDIO_SINK_SLAVE_NONE:
1309 sink->priv->avg_skew = -1;
1310 sink->next_sample = -1;
1311 sink->priv->eos_time = -1;
1318 GST_DEBUG_OBJECT (sink, "we have no clock");
1323 GST_DEBUG_OBJECT (sink, "we are not slaved");
1328 GST_DEBUG_OBJECT (sink, "we are flushing");
1329 GST_OBJECT_LOCK (sink);
1330 return GST_FLOW_WRONG_STATE;
1335 gst_base_audio_sink_get_alignment (GstBaseAudioSink * sink,
1336 GstClockTime sample_offset)
1338 GstRingBuffer *ringbuf = sink->ringbuffer;
1342 gint segdone = g_atomic_int_get (&ringbuf->segdone) - ringbuf->segbase;
1343 gint64 samples_done = segdone * ringbuf->samples_per_seg;
1344 gint64 headroom = sample_offset - samples_done;
1345 gboolean allow_align = TRUE;
1347 /* now try to align the sample to the previous one, first see how big the
1349 if (sample_offset >= sink->next_sample)
1350 diff = sample_offset - sink->next_sample;
1352 diff = sink->next_sample - sample_offset;
1354 /* calculate the max allowed drift in units of samples. By default this is
1355 * 20ms and should be anough to compensate for timestamp rounding errors. */
1356 maxdrift = (ringbuf->spec.rate * sink->priv->drift_tolerance) / GST_MSECOND;
1358 /* calc align with previous sample */
1359 align = sink->next_sample - sample_offset;
1361 /* don't align if it means writing behind the read-segment */
1362 if (diff > headroom && align < 0)
1363 allow_align = FALSE;
1365 if (G_LIKELY (diff < maxdrift && allow_align)) {
1366 GST_DEBUG_OBJECT (sink,
1367 "align with prev sample, ABS (%" G_GINT64_FORMAT ") < %"
1368 G_GINT64_FORMAT, align, maxdrift);
1370 /* calculate sample diff in seconds for error message */
1371 gint64 diff_s = gst_util_uint64_scale_int (diff, GST_SECOND,
1372 ringbuf->spec.rate);
1373 /* timestamps drifted apart from previous samples too much, we need to
1374 * resync. We log this as an element warning. */
1375 GST_WARNING_OBJECT (sink,
1376 "Unexpected discontinuity in audio timestamps of "
1377 "%s%" GST_TIME_FORMAT ", resyncing",
1378 sample_offset > sink->next_sample ? "+" : "-", GST_TIME_ARGS (diff_s));
1385 static GstFlowReturn
1386 gst_base_audio_sink_render (GstBaseSink * bsink, GstBuffer * buf)
1389 GstClockTime time, stop, render_start, render_stop, sample_offset;
1390 GstClockTimeDiff sync_offset, ts_offset;
1391 GstBaseAudioSinkClass *bclass;
1392 GstBaseAudioSink *sink;
1393 GstRingBuffer *ringbuf;
1394 gint64 diff, align, ctime, cstop;
1397 guint samples, written;
1401 GstClockTime base_time, render_delay, latency;
1403 gboolean sync, slaved, align_next;
1405 GstSegment clip_seg;
1407 GstBuffer *out = NULL;
1409 sink = GST_BASE_AUDIO_SINK (bsink);
1410 bclass = GST_BASE_AUDIO_SINK_GET_CLASS (sink);
1412 ringbuf = sink->ringbuffer;
1414 /* can't do anything when we don't have the device */
1415 if (G_UNLIKELY (!gst_ring_buffer_is_acquired (ringbuf)))
1418 /* Wait for upstream latency before starting the ringbuffer, we do this so
1419 * that we can align the first sample of the ringbuffer to the base_time +
1421 GST_OBJECT_LOCK (sink);
1422 base_time = GST_ELEMENT_CAST (sink)->base_time;
1423 if (G_UNLIKELY (sink->priv->sync_latency)) {
1424 ret = gst_base_audio_sink_sync_latency (bsink, GST_MINI_OBJECT_CAST (buf));
1425 GST_OBJECT_UNLOCK (sink);
1426 if (G_UNLIKELY (ret != GST_FLOW_OK))
1427 goto sync_latency_failed;
1428 /* only do this once until we are set back to PLAYING */
1429 sink->priv->sync_latency = FALSE;
1431 GST_OBJECT_UNLOCK (sink);
1434 /* Before we go on, let's see if we need to payload the data. If yes, we also
1435 * need to unref the output buffer before leaving. */
1436 if (bclass->payload) {
1437 out = bclass->payload (sink, buf);
1440 goto payload_failed;
1445 bps = ringbuf->spec.bytes_per_sample;
1447 size = GST_BUFFER_SIZE (buf);
1448 if (G_UNLIKELY (size % bps) != 0)
1451 samples = size / bps;
1452 out_samples = samples;
1454 in_offset = GST_BUFFER_OFFSET (buf);
1455 time = GST_BUFFER_TIMESTAMP (buf);
1457 GST_DEBUG_OBJECT (sink,
1458 "time %" GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT ", start %"
1459 GST_TIME_FORMAT ", samples %u", GST_TIME_ARGS (time), in_offset,
1460 GST_TIME_ARGS (bsink->segment.start), samples);
1462 data = GST_BUFFER_DATA (buf);
1464 /* if not valid timestamp or we can't clip or sync, try to play
1466 if (!GST_CLOCK_TIME_IS_VALID (time)) {
1467 render_start = gst_base_audio_sink_get_offset (sink);
1468 render_stop = render_start + samples;
1469 GST_DEBUG_OBJECT (sink,
1470 "Buffer of size %u has no time. Using render_start=%" G_GUINT64_FORMAT,
1471 GST_BUFFER_SIZE (buf), render_start);
1472 /* we don't have a start so we don't know stop either */
1477 /* let's calc stop based on the number of samples in the buffer instead
1478 * of trusting the DURATION */
1479 stop = time + gst_util_uint64_scale_int (samples, GST_SECOND,
1480 ringbuf->spec.rate);
1482 /* prepare the clipping segment. Since we will be subtracting ts-offset and
1483 * device-delay later we scale the start and stop with those values so that we
1484 * can correctly clip them */
1485 clip_seg.format = GST_FORMAT_TIME;
1486 clip_seg.start = bsink->segment.start;
1487 clip_seg.stop = bsink->segment.stop;
1488 clip_seg.duration = -1;
1490 /* the sync offset is the combination of ts-offset and device-delay */
1491 latency = gst_base_sink_get_latency (bsink);
1492 ts_offset = gst_base_sink_get_ts_offset (bsink);
1493 render_delay = gst_base_sink_get_render_delay (bsink);
1494 sync_offset = ts_offset - render_delay + latency;
1496 GST_DEBUG_OBJECT (sink,
1497 "sync-offset %" G_GINT64_FORMAT ", render-delay %" GST_TIME_FORMAT
1498 ", ts-offset %" G_GINT64_FORMAT, sync_offset,
1499 GST_TIME_ARGS (render_delay), ts_offset);
1501 /* compensate for ts-offset and device-delay when negative we need to
1503 if (sync_offset < 0) {
1504 clip_seg.start += -sync_offset;
1505 if (clip_seg.stop != -1)
1506 clip_seg.stop += -sync_offset;
1509 /* samples should be rendered based on their timestamp. All samples
1510 * arriving before the segment.start or after segment.stop are to be
1511 * thrown away. All samples should also be clipped to the segment
1513 if (!gst_segment_clip (&clip_seg, GST_FORMAT_TIME, time, stop, &ctime,
1515 goto out_of_segment;
1517 /* see if some clipping happened */
1518 diff = ctime - time;
1520 /* bring clipped time to samples */
1521 diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1522 GST_DEBUG_OBJECT (sink, "clipping start to %" GST_TIME_FORMAT " %"
1523 G_GUINT64_FORMAT " samples", GST_TIME_ARGS (ctime), diff);
1528 diff = stop - cstop;
1530 /* bring clipped time to samples */
1531 diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1532 GST_DEBUG_OBJECT (sink, "clipping stop to %" GST_TIME_FORMAT " %"
1533 G_GUINT64_FORMAT " samples", GST_TIME_ARGS (cstop), diff);
1538 /* figure out how to sync */
1539 if ((clock = GST_ELEMENT_CLOCK (bsink)))
1545 /* no sync needed, play sample ASAP */
1546 render_start = gst_base_audio_sink_get_offset (sink);
1547 render_stop = render_start + samples;
1548 GST_DEBUG_OBJECT (sink,
1549 "no sync needed. Using render_start=%" G_GUINT64_FORMAT, render_start);
1553 /* bring buffer start and stop times to running time */
1555 gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, time);
1557 gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, stop);
1559 GST_DEBUG_OBJECT (sink,
1560 "running: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1561 GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1563 /* store the time of the last sample, we'll use this to perform sync on the
1564 * last sample when draining the buffer */
1565 if (bsink->segment.rate >= 0.0) {
1566 sink->priv->eos_time = render_stop;
1568 sink->priv->eos_time = render_start;
1571 /* compensate for ts-offset and delay we know this will not underflow because we
1573 GST_DEBUG_OBJECT (sink,
1574 "compensating for sync-offset %" GST_TIME_FORMAT,
1575 GST_TIME_ARGS (sync_offset));
1576 render_start += sync_offset;
1577 render_stop += sync_offset;
1579 GST_DEBUG_OBJECT (sink, "adding base_time %" GST_TIME_FORMAT,
1580 GST_TIME_ARGS (base_time));
1582 /* add base time to sync against the clock */
1583 render_start += base_time;
1584 render_stop += base_time;
1586 GST_DEBUG_OBJECT (sink,
1587 "after compensation: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1588 GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1590 if ((slaved = clock != sink->provided_clock)) {
1591 /* handle clock slaving */
1592 gst_base_audio_sink_handle_slaving (sink, render_start, render_stop,
1593 &render_start, &render_stop);
1595 /* no slaving needed but we need to adapt to the clock calibration
1597 gst_base_audio_sink_none_slaving (sink, render_start, render_stop,
1598 &render_start, &render_stop);
1601 GST_DEBUG_OBJECT (sink,
1602 "final timestamps: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1603 GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1605 /* bring to position in the ringbuffer */
1606 if (sink->priv->do_time_offset) {
1608 GST_AUDIO_CLOCK_CAST (sink->provided_clock)->abidata.ABI.time_offset;
1609 GST_DEBUG_OBJECT (sink,
1610 "time offset %" GST_TIME_FORMAT, GST_TIME_ARGS (time_offset));
1611 if (render_start > time_offset)
1612 render_start -= time_offset;
1615 if (render_stop > time_offset)
1616 render_stop -= time_offset;
1621 /* in some clock slaving cases, all late samples end up at 0 first,
1622 * and subsequent ones align with that until threshold exceeded,
1623 * and then sync back to 0 and so on, so avoid that altogether */
1624 if (G_UNLIKELY (render_start == 0 && render_stop == 0))
1627 /* and bring the time to the rate corrected offset in the buffer */
1628 render_start = gst_util_uint64_scale_int (render_start,
1629 ringbuf->spec.rate, GST_SECOND);
1630 render_stop = gst_util_uint64_scale_int (render_stop,
1631 ringbuf->spec.rate, GST_SECOND);
1633 /* positive playback rate, first sample is render_start, negative rate, first
1634 * sample is render_stop. When no rate conversion is active, render exactly
1635 * the amount of input samples to avoid aligning to rounding errors. */
1636 if (bsink->segment.rate >= 0.0) {
1637 sample_offset = render_start;
1638 if (bsink->segment.rate == 1.0)
1639 render_stop = sample_offset + samples;
1641 sample_offset = render_stop;
1642 if (bsink->segment.rate == -1.0)
1643 render_start = sample_offset + samples;
1646 /* always resync after a discont */
1647 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT))) {
1648 GST_DEBUG_OBJECT (sink, "resync after discont");
1652 /* resync when we don't know what to align the sample with */
1653 if (G_UNLIKELY (sink->next_sample == -1)) {
1654 GST_DEBUG_OBJECT (sink,
1655 "no align possible: no previous sample position known");
1659 align = gst_base_audio_sink_get_alignment (sink, sample_offset);
1660 sink->priv->last_align = align;
1662 /* apply alignment */
1663 render_start += align;
1665 /* only align stop if we are not slaved to resample */
1666 if (slaved && sink->priv->slave_method == GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE) {
1667 GST_DEBUG_OBJECT (sink, "no stop time align needed: we are slaved");
1670 render_stop += align;
1673 /* number of target samples is difference between start and stop */
1674 out_samples = render_stop - render_start;
1677 /* we render the first or last sample first, depending on the rate */
1678 if (bsink->segment.rate >= 0.0)
1679 sample_offset = render_start;
1681 sample_offset = render_stop;
1683 GST_DEBUG_OBJECT (sink, "rendering at %" G_GUINT64_FORMAT " %d/%d",
1684 sample_offset, samples, out_samples);
1686 /* we need to accumulate over different runs for when we get interrupted */
1691 gst_ring_buffer_commit_full (ringbuf, &sample_offset, data, samples,
1692 out_samples, &accum);
1694 GST_DEBUG_OBJECT (sink, "wrote %u of %u", written, samples);
1695 /* if we wrote all, we're done */
1696 if (written == samples)
1699 /* else something interrupted us and we wait for preroll. */
1700 if ((ret = gst_base_sink_wait_preroll (bsink)) != GST_FLOW_OK)
1703 /* if we got interrupted, we cannot assume that the next sample should
1704 * be aligned to this one */
1707 /* update the output samples. FIXME, this will just skip them when pausing
1708 * during trick mode */
1709 if (out_samples > written) {
1710 out_samples -= written;
1716 data += written * bps;
1720 sink->next_sample = sample_offset;
1722 sink->next_sample = -1;
1724 GST_DEBUG_OBJECT (sink, "next sample expected at %" G_GUINT64_FORMAT,
1727 if (GST_CLOCK_TIME_IS_VALID (stop) && stop >= bsink->segment.stop) {
1728 GST_DEBUG_OBJECT (sink,
1729 "start playback because we are at the end of segment");
1730 gst_ring_buffer_start (ringbuf);
1737 gst_buffer_unref (out);
1744 GST_DEBUG_OBJECT (sink,
1745 "dropping sample out of segment time %" GST_TIME_FORMAT ", start %"
1746 GST_TIME_FORMAT, GST_TIME_ARGS (time),
1747 GST_TIME_ARGS (bsink->segment.start));
1753 GST_DEBUG_OBJECT (sink, "dropping late sample");
1759 GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("failed to payload."));
1760 ret = GST_FLOW_ERROR;
1765 GST_DEBUG_OBJECT (sink, "ringbuffer not negotiated");
1766 GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("sink not negotiated."));
1767 ret = GST_FLOW_NOT_NEGOTIATED;
1772 GST_DEBUG_OBJECT (sink, "wrong size");
1773 GST_ELEMENT_ERROR (sink, STREAM, WRONG_TYPE,
1774 (NULL), ("sink received buffer of wrong size."));
1775 ret = GST_FLOW_ERROR;
1780 GST_DEBUG_OBJECT (sink, "preroll got interrupted: %d (%s)", ret,
1781 gst_flow_get_name (ret));
1784 sync_latency_failed:
1786 GST_DEBUG_OBJECT (sink, "failed waiting for latency");
1792 * gst_base_audio_sink_create_ringbuffer:
1793 * @sink: a #GstBaseAudioSink.
1795 * Create and return the #GstRingBuffer for @sink. This function will call the
1796 * ::create_ringbuffer vmethod and will set @sink as the parent of the returned
1797 * buffer (see gst_object_set_parent()).
1799 * Returns: The new ringbuffer of @sink.
1802 gst_base_audio_sink_create_ringbuffer (GstBaseAudioSink * sink)
1804 GstBaseAudioSinkClass *bclass;
1805 GstRingBuffer *buffer = NULL;
1807 bclass = GST_BASE_AUDIO_SINK_GET_CLASS (sink);
1808 if (bclass->create_ringbuffer)
1809 buffer = bclass->create_ringbuffer (sink);
1812 gst_object_set_parent (GST_OBJECT (buffer), GST_OBJECT (sink));
1818 gst_base_audio_sink_callback (GstRingBuffer * rbuf, guint8 * data, guint len,
1821 GstBaseSink *basesink;
1822 GstBaseAudioSink *sink;
1826 basesink = GST_BASE_SINK (user_data);
1827 sink = GST_BASE_AUDIO_SINK (user_data);
1829 GST_PAD_STREAM_LOCK (basesink->sinkpad);
1831 /* would be nice to arrange for pad_alloc_buffer to return data -- as it is we
1832 will copy twice, once into data, once into DMA */
1833 GST_LOG_OBJECT (basesink, "pulling %d bytes offset %" G_GUINT64_FORMAT
1834 " to fill audio buffer", len, basesink->offset);
1836 gst_pad_pull_range (basesink->sinkpad, basesink->segment.last_stop, len,
1839 if (ret != GST_FLOW_OK) {
1840 if (ret == GST_FLOW_UNEXPECTED)
1846 GST_PAD_PREROLL_LOCK (basesink->sinkpad);
1847 if (basesink->flushing)
1850 /* complete preroll and wait for PLAYING */
1851 ret = gst_base_sink_do_preroll (basesink, GST_MINI_OBJECT_CAST (buf));
1852 if (ret != GST_FLOW_OK)
1855 if (len != GST_BUFFER_SIZE (buf)) {
1856 GST_INFO_OBJECT (basesink,
1857 "got different size than requested from sink pad: %u != %u", len,
1858 GST_BUFFER_SIZE (buf));
1859 len = MIN (GST_BUFFER_SIZE (buf), len);
1862 basesink->segment.last_stop += len;
1864 memcpy (data, GST_BUFFER_DATA (buf), len);
1865 GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
1867 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1873 GST_WARNING_OBJECT (basesink, "Got flow '%s' but can't return it: %d",
1874 gst_flow_get_name (ret), ret);
1875 gst_ring_buffer_pause (rbuf);
1876 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1881 /* FIXME: this is not quite correct; we'll be called endlessly until
1882 * the sink gets shut down; maybe we should set a flag somewhere, or
1883 * set segment.stop and segment.duration to the last sample or so */
1884 GST_DEBUG_OBJECT (sink, "EOS");
1885 gst_base_audio_sink_drain (sink);
1886 gst_ring_buffer_pause (rbuf);
1887 gst_element_post_message (GST_ELEMENT_CAST (sink),
1888 gst_message_new_eos (GST_OBJECT_CAST (sink)));
1889 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1893 GST_DEBUG_OBJECT (sink, "we are flushing");
1894 gst_ring_buffer_pause (rbuf);
1895 GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
1896 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1901 GST_DEBUG_OBJECT (sink, "error %s", gst_flow_get_name (ret));
1902 gst_ring_buffer_pause (rbuf);
1903 GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
1904 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1910 gst_base_audio_sink_activate_pull (GstBaseSink * basesink, gboolean active)
1913 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (basesink);
1916 GST_DEBUG_OBJECT (basesink, "activating pull");
1918 gst_ring_buffer_set_callback (sink->ringbuffer,
1919 gst_base_audio_sink_callback, sink);
1921 ret = gst_ring_buffer_activate (sink->ringbuffer, TRUE);
1923 GST_DEBUG_OBJECT (basesink, "deactivating pull");
1924 gst_ring_buffer_set_callback (sink->ringbuffer, NULL, NULL);
1925 ret = gst_ring_buffer_activate (sink->ringbuffer, FALSE);
1931 /* should be called with the LOCK */
1932 static GstStateChangeReturn
1933 gst_base_audio_sink_async_play (GstBaseSink * basesink)
1935 GstBaseAudioSink *sink;
1937 sink = GST_BASE_AUDIO_SINK (basesink);
1939 GST_DEBUG_OBJECT (sink, "ringbuffer may start now");
1940 sink->priv->sync_latency = TRUE;
1941 gst_ring_buffer_may_start (sink->ringbuffer, TRUE);
1942 if (basesink->pad_mode == GST_ACTIVATE_PULL) {
1943 /* we always start the ringbuffer in pull mode immediatly */
1944 gst_ring_buffer_start (sink->ringbuffer);
1947 return GST_STATE_CHANGE_SUCCESS;
1950 static GstStateChangeReturn
1951 gst_base_audio_sink_change_state (GstElement * element,
1952 GstStateChange transition)
1954 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1955 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (element);
1957 switch (transition) {
1958 case GST_STATE_CHANGE_NULL_TO_READY:
1959 if (sink->ringbuffer == NULL) {
1960 gst_audio_clock_reset (GST_AUDIO_CLOCK (sink->provided_clock), 0);
1961 sink->ringbuffer = gst_base_audio_sink_create_ringbuffer (sink);
1963 if (!gst_ring_buffer_open_device (sink->ringbuffer))
1966 case GST_STATE_CHANGE_READY_TO_PAUSED:
1967 sink->next_sample = -1;
1968 sink->priv->last_align = -1;
1969 sink->priv->eos_time = -1;
1970 gst_ring_buffer_set_flushing (sink->ringbuffer, FALSE);
1971 gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
1973 /* Only post clock-provide messages if this is the clock that
1974 * we've created. If the subclass has overriden it the subclass
1975 * should post this messages whenever necessary */
1976 if (sink->provided_clock && GST_IS_AUDIO_CLOCK (sink->provided_clock) &&
1977 GST_AUDIO_CLOCK_CAST (sink->provided_clock)->func ==
1978 (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time)
1979 gst_element_post_message (element,
1980 gst_message_new_clock_provide (GST_OBJECT_CAST (element),
1981 sink->provided_clock, TRUE));
1983 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1987 GST_OBJECT_LOCK (sink);
1988 GST_DEBUG_OBJECT (sink, "ringbuffer may start now");
1989 sink->priv->sync_latency = TRUE;
1990 eos = GST_BASE_SINK (sink)->eos;
1991 GST_OBJECT_UNLOCK (sink);
1993 gst_ring_buffer_may_start (sink->ringbuffer, TRUE);
1994 if (GST_BASE_SINK_CAST (sink)->pad_mode == GST_ACTIVATE_PULL ||
1995 g_atomic_int_get (&sink->abidata.ABI.eos_rendering) || eos) {
1996 /* we always start the ringbuffer in pull mode immediatly */
1997 /* sync rendering on eos needs running clock,
1998 * and others need running clock when finished rendering eos */
1999 gst_ring_buffer_start (sink->ringbuffer);
2003 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2004 /* ringbuffer cannot start anymore */
2005 gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
2006 gst_ring_buffer_pause (sink->ringbuffer);
2008 GST_OBJECT_LOCK (sink);
2009 sink->priv->sync_latency = FALSE;
2010 GST_OBJECT_UNLOCK (sink);
2012 case GST_STATE_CHANGE_PAUSED_TO_READY:
2013 /* Only post clock-lost messages if this is the clock that
2014 * we've created. If the subclass has overriden it the subclass
2015 * should post this messages whenever necessary */
2016 if (sink->provided_clock && GST_IS_AUDIO_CLOCK (sink->provided_clock) &&
2017 GST_AUDIO_CLOCK_CAST (sink->provided_clock)->func ==
2018 (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time)
2019 gst_element_post_message (element,
2020 gst_message_new_clock_lost (GST_OBJECT_CAST (element),
2021 sink->provided_clock));
2023 /* make sure we unblock before calling the parent state change
2024 * so it can grab the STREAM_LOCK */
2025 gst_ring_buffer_set_flushing (sink->ringbuffer, TRUE);
2031 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2033 switch (transition) {
2034 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2035 /* stop slaving ourselves to the master, if any */
2036 gst_clock_set_master (sink->provided_clock, NULL);
2038 case GST_STATE_CHANGE_PAUSED_TO_READY:
2039 gst_ring_buffer_activate (sink->ringbuffer, FALSE);
2040 gst_ring_buffer_release (sink->ringbuffer);
2042 case GST_STATE_CHANGE_READY_TO_NULL:
2043 /* we release again here because the aqcuire happens when setting the
2044 * caps, which happens before we commit the state to PAUSED and thus the
2045 * PAUSED->READY state change (see above, where we release the ringbuffer)
2046 * might not be called when we get here. */
2047 gst_ring_buffer_activate (sink->ringbuffer, FALSE);
2048 gst_ring_buffer_release (sink->ringbuffer);
2049 gst_ring_buffer_close_device (sink->ringbuffer);
2050 GST_OBJECT_LOCK (sink);
2051 gst_object_unparent (GST_OBJECT_CAST (sink->ringbuffer));
2052 sink->ringbuffer = NULL;
2053 GST_OBJECT_UNLOCK (sink);
2064 /* subclass must post a meaningfull error message */
2065 GST_DEBUG_OBJECT (sink, "open failed");
2066 return GST_STATE_CHANGE_FAILURE;