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;
61 /* BaseAudioSink signals and args */
68 /* we tollerate half a second diff before we start resyncing. This
69 * should be enough to compensate for various rounding errors in the timestamp
70 * and sample offset position.
71 * This is an emergency resync fallback since buffers marked as DISCONT will
72 * always lock to the correct timestamp immediatly and buffers not marked as
73 * DISCONT are contiguous by definition.
75 #define DIFF_TOLERANCE 2
77 /* FIXME: 0.11, store the buffer_time and latency_time in nanoseconds */
78 #define DEFAULT_BUFFER_TIME ((200 * GST_MSECOND) / GST_USECOND)
79 #define DEFAULT_LATENCY_TIME ((10 * GST_MSECOND) / GST_USECOND)
80 #define DEFAULT_PROVIDE_CLOCK TRUE
81 #define DEFAULT_SLAVE_METHOD GST_BASE_AUDIO_SINK_SLAVE_SKEW
93 gst_base_audio_sink_slave_method_get_type (void)
95 static GType slave_method_type = 0;
96 static const GEnumValue slave_method[] = {
97 {GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE, "Resampling slaving", "resample"},
98 {GST_BASE_AUDIO_SINK_SLAVE_SKEW, "Skew slaving", "skew"},
99 {GST_BASE_AUDIO_SINK_SLAVE_NONE, "No slaving", "none"},
103 if (!slave_method_type) {
105 g_enum_register_static ("GstBaseAudioSinkSlaveMethod", slave_method);
107 return slave_method_type;
111 #define _do_init(bla) \
112 GST_DEBUG_CATEGORY_INIT (gst_base_audio_sink_debug, "baseaudiosink", 0, "baseaudiosink element");
114 GST_BOILERPLATE_FULL (GstBaseAudioSink, gst_base_audio_sink, GstBaseSink,
115 GST_TYPE_BASE_SINK, _do_init);
117 static void gst_base_audio_sink_dispose (GObject * object);
119 static void gst_base_audio_sink_set_property (GObject * object, guint prop_id,
120 const GValue * value, GParamSpec * pspec);
121 static void gst_base_audio_sink_get_property (GObject * object, guint prop_id,
122 GValue * value, GParamSpec * pspec);
124 static GstStateChangeReturn gst_base_audio_sink_async_play (GstBaseSink *
126 static GstStateChangeReturn gst_base_audio_sink_change_state (GstElement *
127 element, GstStateChange transition);
128 static gboolean gst_base_audio_sink_activate_pull (GstBaseSink * basesink,
130 static gboolean gst_base_audio_sink_query (GstElement * element, GstQuery *
133 static GstClock *gst_base_audio_sink_provide_clock (GstElement * elem);
134 static GstClockTime gst_base_audio_sink_get_time (GstClock * clock,
135 GstBaseAudioSink * sink);
136 static void gst_base_audio_sink_callback (GstRingBuffer * rbuf, guint8 * data,
137 guint len, gpointer user_data);
139 static GstFlowReturn gst_base_audio_sink_preroll (GstBaseSink * bsink,
141 static GstFlowReturn gst_base_audio_sink_render (GstBaseSink * bsink,
143 static gboolean gst_base_audio_sink_event (GstBaseSink * bsink,
145 static void gst_base_audio_sink_get_times (GstBaseSink * bsink,
146 GstBuffer * buffer, GstClockTime * start, GstClockTime * end);
147 static gboolean gst_base_audio_sink_setcaps (GstBaseSink * bsink,
149 static void gst_base_audio_sink_fixate (GstBaseSink * bsink, GstCaps * caps);
151 static gboolean gst_base_audio_sink_query_pad (GstPad * pad, GstQuery * query);
154 /* static guint gst_base_audio_sink_signals[LAST_SIGNAL] = { 0 }; */
157 gst_base_audio_sink_base_init (gpointer g_class)
162 gst_base_audio_sink_class_init (GstBaseAudioSinkClass * klass)
164 GObjectClass *gobject_class;
165 GstElementClass *gstelement_class;
166 GstBaseSinkClass *gstbasesink_class;
168 gobject_class = (GObjectClass *) klass;
169 gstelement_class = (GstElementClass *) klass;
170 gstbasesink_class = (GstBaseSinkClass *) klass;
172 g_type_class_add_private (klass, sizeof (GstBaseAudioSinkPrivate));
174 gobject_class->set_property =
175 GST_DEBUG_FUNCPTR (gst_base_audio_sink_set_property);
176 gobject_class->get_property =
177 GST_DEBUG_FUNCPTR (gst_base_audio_sink_get_property);
178 gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_base_audio_sink_dispose);
180 g_object_class_install_property (gobject_class, PROP_BUFFER_TIME,
181 g_param_spec_int64 ("buffer-time", "Buffer Time",
182 "Size of audio buffer in microseconds", 1,
183 G_MAXINT64, DEFAULT_BUFFER_TIME,
184 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
186 g_object_class_install_property (gobject_class, PROP_LATENCY_TIME,
187 g_param_spec_int64 ("latency-time", "Latency Time",
188 "Audio latency in microseconds", 1,
189 G_MAXINT64, DEFAULT_LATENCY_TIME,
190 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
192 g_object_class_install_property (gobject_class, PROP_PROVIDE_CLOCK,
193 g_param_spec_boolean ("provide-clock", "Provide Clock",
194 "Provide a clock to be used as the global pipeline clock",
195 DEFAULT_PROVIDE_CLOCK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
197 g_object_class_install_property (gobject_class, PROP_SLAVE_METHOD,
198 g_param_spec_enum ("slave-method", "Slave Method",
199 "Algorithm to use to match the rate of the masterclock",
200 GST_TYPE_BASE_AUDIO_SINK_SLAVE_METHOD, DEFAULT_SLAVE_METHOD,
201 G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
203 gstelement_class->change_state =
204 GST_DEBUG_FUNCPTR (gst_base_audio_sink_change_state);
205 gstelement_class->provide_clock =
206 GST_DEBUG_FUNCPTR (gst_base_audio_sink_provide_clock);
207 gstelement_class->query = GST_DEBUG_FUNCPTR (gst_base_audio_sink_query);
209 gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_base_audio_sink_event);
210 gstbasesink_class->preroll = GST_DEBUG_FUNCPTR (gst_base_audio_sink_preroll);
211 gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_base_audio_sink_render);
212 gstbasesink_class->get_times =
213 GST_DEBUG_FUNCPTR (gst_base_audio_sink_get_times);
214 gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_base_audio_sink_setcaps);
215 gstbasesink_class->fixate = GST_DEBUG_FUNCPTR (gst_base_audio_sink_fixate);
216 gstbasesink_class->async_play =
217 GST_DEBUG_FUNCPTR (gst_base_audio_sink_async_play);
218 gstbasesink_class->activate_pull =
219 GST_DEBUG_FUNCPTR (gst_base_audio_sink_activate_pull);
221 /* ref class from a thread-safe context to work around missing bit of
222 * thread-safety in GObject */
223 g_type_class_ref (GST_TYPE_AUDIO_CLOCK);
224 g_type_class_ref (GST_TYPE_RING_BUFFER);
228 gst_base_audio_sink_init (GstBaseAudioSink * baseaudiosink,
229 GstBaseAudioSinkClass * g_class)
231 baseaudiosink->priv = GST_BASE_AUDIO_SINK_GET_PRIVATE (baseaudiosink);
233 baseaudiosink->buffer_time = DEFAULT_BUFFER_TIME;
234 baseaudiosink->latency_time = DEFAULT_LATENCY_TIME;
235 baseaudiosink->provide_clock = DEFAULT_PROVIDE_CLOCK;
236 baseaudiosink->priv->slave_method = DEFAULT_SLAVE_METHOD;
238 baseaudiosink->provided_clock = gst_audio_clock_new ("GstAudioSinkClock",
239 (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time, baseaudiosink);
241 GST_BASE_SINK (baseaudiosink)->can_activate_push = TRUE;
242 /* FIXME, enable pull mode when segments, latency, state changes, negotiation
243 * and clock slaving are figured out */
244 GST_BASE_SINK (baseaudiosink)->can_activate_pull = FALSE;
246 /* install some custom pad_query functions */
247 gst_pad_set_query_function (GST_BASE_SINK_PAD (baseaudiosink),
248 GST_DEBUG_FUNCPTR (gst_base_audio_sink_query_pad));
252 gst_base_audio_sink_dispose (GObject * object)
254 GstBaseAudioSink *sink;
256 sink = GST_BASE_AUDIO_SINK (object);
258 if (sink->provided_clock)
259 gst_object_unref (sink->provided_clock);
260 sink->provided_clock = NULL;
262 if (sink->ringbuffer) {
263 gst_object_unparent (GST_OBJECT_CAST (sink->ringbuffer));
264 sink->ringbuffer = NULL;
267 G_OBJECT_CLASS (parent_class)->dispose (object);
272 gst_base_audio_sink_provide_clock (GstElement * elem)
274 GstBaseAudioSink *sink;
277 sink = GST_BASE_AUDIO_SINK (elem);
279 /* we have no ringbuffer (must be NULL state) */
280 if (sink->ringbuffer == NULL)
283 if (!gst_ring_buffer_is_acquired (sink->ringbuffer))
286 GST_OBJECT_LOCK (sink);
287 if (!sink->provide_clock)
290 clock = GST_CLOCK_CAST (gst_object_ref (sink->provided_clock));
291 GST_OBJECT_UNLOCK (sink);
298 GST_DEBUG_OBJECT (sink, "ringbuffer not acquired");
303 GST_DEBUG_OBJECT (sink, "clock provide disabled");
304 GST_OBJECT_UNLOCK (sink);
310 gst_base_audio_sink_query_pad (GstPad * pad, GstQuery * query)
312 gboolean res = FALSE;
313 GstBaseAudioSink *basesink;
315 basesink = GST_BASE_AUDIO_SINK (gst_pad_get_parent (pad));
317 switch (GST_QUERY_TYPE (query)) {
318 case GST_QUERY_CONVERT:
320 GstFormat src_fmt, dest_fmt;
321 gint64 src_val, dest_val;
323 GST_LOG_OBJECT (pad, "query convert");
325 if (basesink->ringbuffer) {
326 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, NULL);
327 res = gst_ring_buffer_convert (basesink->ringbuffer, src_fmt, src_val,
328 dest_fmt, &dest_val);
330 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
339 gst_object_unref (basesink);
345 gst_base_audio_sink_query (GstElement * element, GstQuery * query)
347 gboolean res = FALSE;
348 GstBaseAudioSink *basesink;
350 basesink = GST_BASE_AUDIO_SINK (element);
352 switch (GST_QUERY_TYPE (query)) {
353 case GST_QUERY_LATENCY:
355 gboolean live, us_live;
356 GstClockTime min_l, max_l;
358 GST_DEBUG_OBJECT (basesink, "latency query");
360 if (!basesink->ringbuffer || !basesink->ringbuffer->spec.rate) {
361 GST_DEBUG_OBJECT (basesink,
362 "we are not yet negotiated, can't report latency yet");
367 /* ask parent first, it will do an upstream query for us. */
369 gst_base_sink_query_latency (GST_BASE_SINK_CAST (basesink), &live,
370 &us_live, &min_l, &max_l))) {
371 GstClockTime min_latency, max_latency;
373 /* we and upstream are both live, adjust the min_latency */
374 if (live && us_live) {
375 GstRingBufferSpec *spec;
377 spec = &basesink->ringbuffer->spec;
379 basesink->priv->us_latency = min_l;
382 gst_util_uint64_scale_int (spec->seglatency * spec->segsize,
383 GST_SECOND, spec->rate * spec->bytes_per_sample);
385 /* we cannot go lower than the buffer size and the min peer latency */
386 min_latency = min_latency + min_l;
387 /* the max latency is the max of the peer, we can delay an infinite
389 max_latency = min_latency + (max_l == -1 ? 0 : max_l);
391 GST_DEBUG_OBJECT (basesink,
392 "peer min %" GST_TIME_FORMAT ", our min latency: %"
393 GST_TIME_FORMAT, GST_TIME_ARGS (min_l),
394 GST_TIME_ARGS (min_latency));
396 GST_DEBUG_OBJECT (basesink,
397 "peer or we are not live, don't care about latency");
401 gst_query_set_latency (query, live, min_latency, max_latency);
405 case GST_QUERY_CONVERT:
407 GstFormat src_fmt, dest_fmt;
408 gint64 src_val, dest_val;
410 GST_LOG_OBJECT (basesink, "query convert");
412 if (basesink->ringbuffer) {
413 gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, NULL);
414 res = gst_ring_buffer_convert (basesink->ringbuffer, src_fmt, src_val,
415 dest_fmt, &dest_val);
417 gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
423 res = GST_ELEMENT_CLASS (parent_class)->query (element, query);
433 gst_base_audio_sink_get_time (GstClock * clock, GstBaseAudioSink * sink)
435 guint64 raw, samples;
439 if (sink->ringbuffer == NULL || sink->ringbuffer->spec.rate == 0)
440 return GST_CLOCK_TIME_NONE;
442 /* our processed samples are always increasing */
443 raw = samples = gst_ring_buffer_samples_done (sink->ringbuffer);
445 /* the number of samples not yet processed, this is still queued in the
446 * device (not played for playback). */
447 delay = gst_ring_buffer_delay (sink->ringbuffer);
449 if (G_LIKELY (samples >= delay))
454 result = gst_util_uint64_scale_int (samples, GST_SECOND,
455 sink->ringbuffer->spec.rate);
457 GST_DEBUG_OBJECT (sink,
458 "processed samples: raw %llu, delay %u, real %llu, time %"
459 GST_TIME_FORMAT, raw, delay, samples, GST_TIME_ARGS (result));
465 * gst_base_audio_sink_set_provide_clock:
466 * @sink: a #GstBaseAudioSink
467 * @provide: new state
469 * Controls whether @sink will provide a clock or not. If @provide is %TRUE,
470 * gst_element_provide_clock() will return a clock that reflects the datarate
471 * of @sink. If @provide is %FALSE, gst_element_provide_clock() will return NULL.
476 gst_base_audio_sink_set_provide_clock (GstBaseAudioSink * sink,
479 g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
481 GST_OBJECT_LOCK (sink);
482 sink->provide_clock = provide;
483 GST_OBJECT_UNLOCK (sink);
487 * gst_base_audio_sink_get_provide_clock:
488 * @sink: a #GstBaseAudioSink
490 * Queries whether @sink will provide a clock or not. See also
491 * gst_base_audio_sink_set_provide_clock.
493 * Returns: %TRUE if @sink will provide a clock.
498 gst_base_audio_sink_get_provide_clock (GstBaseAudioSink * sink)
502 g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), FALSE);
504 GST_OBJECT_LOCK (sink);
505 result = sink->provide_clock;
506 GST_OBJECT_UNLOCK (sink);
512 * gst_base_audio_sink_set_slave_method:
513 * @sink: a #GstBaseAudioSink
514 * @method: the new slave method
516 * Controls how clock slaving will be performed in @sink.
521 gst_base_audio_sink_set_slave_method (GstBaseAudioSink * sink,
522 GstBaseAudioSinkSlaveMethod method)
524 g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
526 GST_OBJECT_LOCK (sink);
527 sink->priv->slave_method = method;
528 GST_OBJECT_UNLOCK (sink);
532 * gst_base_audio_sink_get_slave_method:
533 * @sink: a #GstBaseAudioSink
535 * Get the current slave method used by @sink.
537 * Returns: The current slave method used by @sink.
541 GstBaseAudioSinkSlaveMethod
542 gst_base_audio_sink_get_slave_method (GstBaseAudioSink * sink)
544 GstBaseAudioSinkSlaveMethod result;
546 g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), -1);
548 GST_OBJECT_LOCK (sink);
549 result = sink->priv->slave_method;
550 GST_OBJECT_UNLOCK (sink);
556 gst_base_audio_sink_set_property (GObject * object, guint prop_id,
557 const GValue * value, GParamSpec * pspec)
559 GstBaseAudioSink *sink;
561 sink = GST_BASE_AUDIO_SINK (object);
564 case PROP_BUFFER_TIME:
565 sink->buffer_time = g_value_get_int64 (value);
567 case PROP_LATENCY_TIME:
568 sink->latency_time = g_value_get_int64 (value);
570 case PROP_PROVIDE_CLOCK:
571 gst_base_audio_sink_set_provide_clock (sink, g_value_get_boolean (value));
573 case PROP_SLAVE_METHOD:
574 gst_base_audio_sink_set_slave_method (sink, g_value_get_enum (value));
577 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
583 gst_base_audio_sink_get_property (GObject * object, guint prop_id,
584 GValue * value, GParamSpec * pspec)
586 GstBaseAudioSink *sink;
588 sink = GST_BASE_AUDIO_SINK (object);
591 case PROP_BUFFER_TIME:
592 g_value_set_int64 (value, sink->buffer_time);
594 case PROP_LATENCY_TIME:
595 g_value_set_int64 (value, sink->latency_time);
597 case PROP_PROVIDE_CLOCK:
598 g_value_set_boolean (value, gst_base_audio_sink_get_provide_clock (sink));
600 case PROP_SLAVE_METHOD:
601 g_value_set_enum (value, gst_base_audio_sink_get_slave_method (sink));
604 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
610 gst_base_audio_sink_setcaps (GstBaseSink * bsink, GstCaps * caps)
612 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
613 GstRingBufferSpec *spec;
615 if (!sink->ringbuffer)
618 spec = &sink->ringbuffer->spec;
620 GST_DEBUG_OBJECT (sink, "release old ringbuffer");
622 /* release old ringbuffer */
623 gst_ring_buffer_pause (sink->ringbuffer);
624 gst_ring_buffer_activate (sink->ringbuffer, FALSE);
625 gst_ring_buffer_release (sink->ringbuffer);
627 GST_DEBUG_OBJECT (sink, "parse caps");
629 spec->buffer_time = sink->buffer_time;
630 spec->latency_time = sink->latency_time;
633 if (!gst_ring_buffer_parse_caps (spec, caps))
636 gst_ring_buffer_debug_spec_buff (spec);
638 GST_DEBUG_OBJECT (sink, "acquire ringbuffer");
639 if (!gst_ring_buffer_acquire (sink->ringbuffer, spec))
642 if (bsink->pad_mode == GST_ACTIVATE_PUSH) {
643 GST_DEBUG_OBJECT (sink, "activate ringbuffer");
644 gst_ring_buffer_activate (sink->ringbuffer, TRUE);
647 /* calculate actual latency and buffer times.
648 * FIXME: In 0.11, store the latency_time internally in ns */
649 spec->latency_time = gst_util_uint64_scale (spec->segsize,
650 (GST_SECOND / GST_USECOND), spec->rate * spec->bytes_per_sample);
652 spec->buffer_time = spec->segtotal * spec->latency_time;
654 gst_ring_buffer_debug_spec_buff (spec);
661 GST_DEBUG_OBJECT (sink, "could not parse caps");
662 GST_ELEMENT_ERROR (sink, STREAM, FORMAT,
663 (NULL), ("cannot parse audio format."));
668 GST_DEBUG_OBJECT (sink, "could not acquire ringbuffer");
674 gst_base_audio_sink_fixate (GstBaseSink * bsink, GstCaps * caps)
679 s = gst_caps_get_structure (caps, 0);
681 /* fields for all formats */
682 gst_structure_fixate_field_nearest_int (s, "rate", 44100);
683 gst_structure_fixate_field_nearest_int (s, "channels", 2);
684 gst_structure_fixate_field_nearest_int (s, "width", 16);
687 if (gst_structure_has_field (s, "depth")) {
688 gst_structure_get_int (s, "width", &width);
689 /* round width to nearest multiple of 8 for the depth */
690 depth = GST_ROUND_UP_8 (width);
691 gst_structure_fixate_field_nearest_int (s, "depth", depth);
693 if (gst_structure_has_field (s, "signed"))
694 gst_structure_fixate_field_boolean (s, "signed", TRUE);
695 if (gst_structure_has_field (s, "endianness"))
696 gst_structure_fixate_field_nearest_int (s, "endianness", G_BYTE_ORDER);
700 gst_base_audio_sink_get_times (GstBaseSink * bsink, GstBuffer * buffer,
701 GstClockTime * start, GstClockTime * end)
703 /* our clock sync is a bit too much for the base class to handle so
704 * we implement it ourselves. */
705 *start = GST_CLOCK_TIME_NONE;
706 *end = GST_CLOCK_TIME_NONE;
709 /* This waits for the drain to happen and can be canceled */
711 gst_base_audio_sink_drain (GstBaseAudioSink * sink)
713 if (!sink->ringbuffer)
715 if (!sink->ringbuffer->spec.rate)
718 /* need to start playback before we can drain, but only when
719 * we have successfully negotiated a format and thus acquired the
721 if (gst_ring_buffer_is_acquired (sink->ringbuffer))
722 gst_ring_buffer_start (sink->ringbuffer);
724 if (sink->priv->eos_time != -1) {
725 GST_DEBUG_OBJECT (sink,
726 "last sample time %" GST_TIME_FORMAT,
727 GST_TIME_ARGS (sink->priv->eos_time));
729 /* wait for the EOS time to be reached, this is the time when the last
730 * sample is played. */
731 gst_base_sink_wait_eos (GST_BASE_SINK (sink), sink->priv->eos_time, NULL);
733 GST_DEBUG_OBJECT (sink, "drained audio");
739 gst_base_audio_sink_event (GstBaseSink * bsink, GstEvent * event)
741 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
743 switch (GST_EVENT_TYPE (event)) {
744 case GST_EVENT_FLUSH_START:
745 if (sink->ringbuffer)
746 gst_ring_buffer_set_flushing (sink->ringbuffer, TRUE);
748 case GST_EVENT_FLUSH_STOP:
749 /* always resync on sample after a flush */
750 sink->priv->avg_skew = -1;
751 sink->next_sample = -1;
752 sink->priv->eos_time = -1;
753 if (sink->ringbuffer)
754 gst_ring_buffer_set_flushing (sink->ringbuffer, FALSE);
757 /* now wait till we played everything */
758 gst_base_audio_sink_drain (sink);
760 case GST_EVENT_NEWSEGMENT:
764 /* we only need the rate */
765 gst_event_parse_new_segment_full (event, NULL, &rate, NULL, NULL,
768 GST_DEBUG_OBJECT (sink, "new segment rate of %f", rate);
778 gst_base_audio_sink_preroll (GstBaseSink * bsink, GstBuffer * buffer)
780 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
782 if (!gst_ring_buffer_is_acquired (sink->ringbuffer))
785 /* we don't really do anything when prerolling. We could make a
786 * property to play this buffer to have some sort of scrubbing
792 GST_DEBUG_OBJECT (sink, "ringbuffer in wrong state");
793 GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("sink not negotiated."));
794 return GST_FLOW_NOT_NEGOTIATED;
799 gst_base_audio_sink_get_offset (GstBaseAudioSink * sink)
802 gint writeseg, segdone, sps;
805 /* assume we can append to the previous sample */
806 sample = sink->next_sample;
807 /* no previous sample, try to insert at position 0 */
811 sps = sink->ringbuffer->samples_per_seg;
813 /* figure out the segment and the offset inside the segment where
814 * the sample should be written. */
815 writeseg = sample / sps;
817 /* get the currently processed segment */
818 segdone = g_atomic_int_get (&sink->ringbuffer->segdone)
819 - sink->ringbuffer->segbase;
821 /* see how far away it is from the write segment */
822 diff = writeseg - segdone;
824 /* sample would be dropped, position to next playable position */
825 sample = (segdone + 1) * sps;
832 clock_convert_external (GstClockTime external, GstClockTime cinternal,
833 GstClockTime cexternal, GstClockTime crate_num, GstClockTime crate_denom)
835 /* adjust for rate and speed */
836 if (external >= cexternal) {
838 gst_util_uint64_scale (external - cexternal, crate_denom, crate_num);
839 external += cinternal;
842 gst_util_uint64_scale (cexternal - external, crate_denom, crate_num);
843 if (cinternal > external)
844 external = cinternal - external;
851 /* algorithm to calculate sample positions that will result in resampling to
852 * match the clock rate of the master */
854 gst_base_audio_sink_resample_slaving (GstBaseAudioSink * sink,
855 GstClockTime render_start, GstClockTime render_stop,
856 GstClockTime * srender_start, GstClockTime * srender_stop)
858 GstClockTime cinternal, cexternal;
859 GstClockTime crate_num, crate_denom;
861 /* FIXME, we can sample and add observations here or use the timeouts on the
862 * clock. No idea which one is better or more stable. The timeout seems more
863 * arbitrary but this one seems more demanding and does not work when there is
864 * no data comming in to the sink. */
866 GstClockTime etime, itime;
869 /* sample clocks and figure out clock skew */
870 etime = gst_clock_get_time (GST_ELEMENT_CLOCK (sink));
871 itime = gst_clock_get_internal_time (sink->provided_clock);
873 /* add new observation */
874 gst_clock_add_observation (sink->provided_clock, itime, etime, &r_squared);
877 /* get calibration parameters to compensate for speed and offset differences
878 * when we are slaved */
879 gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
880 &crate_num, &crate_denom);
882 GST_DEBUG_OBJECT (sink, "internal %" GST_TIME_FORMAT " external %"
883 GST_TIME_FORMAT " %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT " = %f",
884 GST_TIME_ARGS (cinternal), GST_TIME_ARGS (cexternal), crate_num,
885 crate_denom, gst_guint64_to_gdouble (crate_num) /
886 gst_guint64_to_gdouble (crate_denom));
889 crate_denom = crate_num = 1;
891 /* bring external time to internal time */
892 render_start = clock_convert_external (render_start, cinternal, cexternal,
893 crate_num, crate_denom);
894 render_stop = clock_convert_external (render_stop, cinternal, cexternal,
895 crate_num, crate_denom);
897 GST_DEBUG_OBJECT (sink,
898 "after slaving: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
899 GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
901 *srender_start = render_start;
902 *srender_stop = render_stop;
905 /* algorithm to calculate sample positions that will result in changing the
906 * playout pointer to match the clock rate of the master */
908 gst_base_audio_sink_skew_slaving (GstBaseAudioSink * sink,
909 GstClockTime render_start, GstClockTime render_stop,
910 GstClockTime * srender_start, GstClockTime * srender_stop)
912 GstClockTime cinternal, cexternal, crate_num, crate_denom;
913 GstClockTime etime, itime;
914 GstClockTimeDiff skew, segtime, segtime2;
918 /* get calibration parameters to compensate for offsets */
919 gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
920 &crate_num, &crate_denom);
922 /* sample clocks and figure out clock skew */
923 etime = gst_clock_get_time (GST_ELEMENT_CLOCK (sink));
924 itime = gst_clock_get_internal_time (sink->provided_clock);
926 GST_DEBUG_OBJECT (sink,
927 "internal %" GST_TIME_FORMAT " external %" GST_TIME_FORMAT
928 " cinternal %" GST_TIME_FORMAT " cexternal %" GST_TIME_FORMAT,
929 GST_TIME_ARGS (itime), GST_TIME_ARGS (etime),
930 GST_TIME_ARGS (cinternal), GST_TIME_ARGS (cexternal));
932 /* make sure we never go below 0 */
933 etime = etime > cexternal ? etime - cexternal : 0;
934 itime = itime > cinternal ? itime - cinternal : 0;
937 * positive value means external clock goes slower
938 * negative value means external clock goes faster */
939 skew = GST_CLOCK_DIFF (etime, itime);
940 if (sink->priv->avg_skew == -1) {
941 /* first observation */
942 sink->priv->avg_skew = skew;
944 /* next observations use a moving average */
945 sink->priv->avg_skew = (31 * sink->priv->avg_skew + skew) / 32;
948 GST_DEBUG_OBJECT (sink, "internal %" GST_TIME_FORMAT " external %"
949 GST_TIME_FORMAT " skew %" G_GINT64_FORMAT " avg %" G_GINT64_FORMAT,
950 GST_TIME_ARGS (itime), GST_TIME_ARGS (etime), skew, sink->priv->avg_skew);
952 /* the max drift we allow is the length of a segment */
953 segtime = sink->ringbuffer->spec.latency_time * 1000;
954 segtime2 = segtime / 2;
956 /* adjust playout pointer based on skew */
957 if (sink->priv->avg_skew > segtime2) {
958 /* master is running slower, move internal time forward */
959 GST_WARNING_OBJECT (sink,
960 "correct clock skew %" G_GINT64_FORMAT " > %" G_GINT64_FORMAT,
961 sink->priv->avg_skew, segtime2);
962 cexternal = cexternal > segtime ? cexternal - segtime : 0;
963 sink->priv->avg_skew -= segtime;
966 sink->ringbuffer->spec.segsize /
967 sink->ringbuffer->spec.bytes_per_sample;
968 last_align = sink->priv->last_align;
970 /* if we were aligning in the wrong direction or we aligned more than what we
971 * will correct, resync */
972 if (last_align < 0 || last_align > segsamples)
973 sink->next_sample = -1;
975 GST_DEBUG_OBJECT (sink,
976 "last_align %" G_GINT64_FORMAT " segsamples %u, next %"
977 G_GUINT64_FORMAT, last_align, segsamples, sink->next_sample);
979 gst_clock_set_calibration (sink->provided_clock, cinternal, cexternal,
980 crate_num, crate_denom);
981 } else if (sink->priv->avg_skew < -segtime2) {
982 /* master is running faster, move external time forwards */
983 GST_WARNING_OBJECT (sink,
984 "correct clock skew %" G_GINT64_FORMAT " < %" G_GINT64_FORMAT,
985 sink->priv->avg_skew, -segtime2);
986 cexternal += segtime;
987 sink->priv->avg_skew += segtime;
990 sink->ringbuffer->spec.segsize /
991 sink->ringbuffer->spec.bytes_per_sample;
992 last_align = sink->priv->last_align;
994 /* if we were aligning in the wrong direction or we aligned more than what we
995 * will correct, resync */
996 if (last_align > 0 || -last_align > segsamples)
997 sink->next_sample = -1;
999 GST_DEBUG_OBJECT (sink,
1000 "last_align %" G_GINT64_FORMAT " segsamples %u, next %"
1001 G_GUINT64_FORMAT, last_align, segsamples, sink->next_sample);
1003 gst_clock_set_calibration (sink->provided_clock, cinternal, cexternal,
1004 crate_num, crate_denom);
1007 /* convert, ignoring speed */
1008 render_start = clock_convert_external (render_start, cinternal, cexternal,
1009 crate_num, crate_denom);
1010 render_stop = clock_convert_external (render_stop, cinternal, cexternal,
1011 crate_num, crate_denom);
1013 *srender_start = render_start;
1014 *srender_stop = render_stop;
1017 /* apply the clock offset but do no slaving otherwise */
1019 gst_base_audio_sink_none_slaving (GstBaseAudioSink * sink,
1020 GstClockTime render_start, GstClockTime render_stop,
1021 GstClockTime * srender_start, GstClockTime * srender_stop)
1023 GstClockTime cinternal, cexternal, crate_num, crate_denom;
1025 /* get calibration parameters to compensate for offsets */
1026 gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
1027 &crate_num, &crate_denom);
1029 /* convert, ignoring speed */
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 *srender_start = render_start;
1036 *srender_stop = render_stop;
1039 /* converts render_start and render_stop to their slaved values */
1041 gst_base_audio_sink_handle_slaving (GstBaseAudioSink * sink,
1042 GstClockTime render_start, GstClockTime render_stop,
1043 GstClockTime * srender_start, GstClockTime * srender_stop)
1045 switch (sink->priv->slave_method) {
1046 case GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE:
1047 gst_base_audio_sink_resample_slaving (sink, render_start, render_stop,
1048 srender_start, srender_stop);
1050 case GST_BASE_AUDIO_SINK_SLAVE_SKEW:
1051 gst_base_audio_sink_skew_slaving (sink, render_start, render_stop,
1052 srender_start, srender_stop);
1054 case GST_BASE_AUDIO_SINK_SLAVE_NONE:
1055 gst_base_audio_sink_none_slaving (sink, render_start, render_stop,
1056 srender_start, srender_stop);
1059 g_warning ("unknown slaving method %d", sink->priv->slave_method);
1064 /* must be called with LOCK */
1065 static GstFlowReturn
1066 gst_base_audio_sink_sync_latency (GstBaseSink * bsink, GstMiniObject * obj)
1069 GstClockReturn status;
1072 GstBaseAudioSink *sink;
1073 GstClockTime itime, etime;
1074 GstClockTime rate_num, rate_denom;
1075 GstClockTimeDiff jitter;
1077 sink = GST_BASE_AUDIO_SINK (bsink);
1079 clock = GST_ELEMENT_CLOCK (sink);
1080 if (G_UNLIKELY (clock == NULL))
1083 /* we provided the global clock, don't need to do anything special */
1084 if (clock == sink->provided_clock)
1087 GST_OBJECT_UNLOCK (sink);
1090 GST_DEBUG_OBJECT (sink, "checking preroll");
1092 ret = gst_base_sink_do_preroll (bsink, obj);
1093 if (ret != GST_FLOW_OK)
1096 GST_OBJECT_LOCK (sink);
1097 time = sink->priv->us_latency;
1098 GST_OBJECT_UNLOCK (sink);
1100 /* preroll done, we can sync since we are in PLAYING now. */
1101 GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
1102 GST_TIME_FORMAT, GST_TIME_ARGS (time));
1104 /* wait for the clock, this can be interrupted because we got shut down or
1106 status = gst_base_sink_wait_clock (bsink, time, &jitter);
1108 GST_DEBUG_OBJECT (sink, "clock returned %d %" GST_TIME_FORMAT, status,
1109 GST_TIME_ARGS (jitter));
1111 /* invalid time, no clock or sync disabled, just continue then */
1112 if (status == GST_CLOCK_BADTIME)
1115 /* waiting could have been interrupted and we can be flushing now */
1116 if (G_UNLIKELY (bsink->flushing))
1119 /* retry if we got unscheduled, which means we did not reach the timeout
1120 * yet. if some other error occures, we continue. */
1121 } while (status == GST_CLOCK_UNSCHEDULED);
1123 GST_OBJECT_LOCK (sink);
1124 GST_DEBUG_OBJECT (sink, "latency synced");
1126 /* when we prerolled in time, we can accurately set the calibration,
1127 * our internal clock should exactly have been the latency (== the running
1128 * time of the external clock) */
1129 etime = GST_ELEMENT_CAST (sink)->base_time + time;
1130 itime = gst_base_audio_sink_get_time (sink->provided_clock, sink);
1132 if (status == GST_CLOCK_EARLY) {
1133 /* when we prerolled late, we have to take into account the lateness */
1134 GST_DEBUG_OBJECT (sink, "late preroll, adding jitter");
1138 /* start ringbuffer so we can start slaving right away when we need to */
1139 gst_ring_buffer_start (sink->ringbuffer);
1141 GST_DEBUG_OBJECT (sink,
1142 "internal time: %" GST_TIME_FORMAT " external time: %" GST_TIME_FORMAT,
1143 GST_TIME_ARGS (itime), GST_TIME_ARGS (etime));
1145 /* copy the original calibrated rate but update the internal and external
1147 gst_clock_get_calibration (sink->provided_clock, NULL, NULL, &rate_num,
1149 gst_clock_set_calibration (sink->provided_clock, itime, etime,
1150 rate_num, rate_denom);
1152 switch (sink->priv->slave_method) {
1153 case GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE:
1154 /* only set as master when we are resampling */
1155 GST_DEBUG_OBJECT (sink, "Setting clock as master");
1156 gst_clock_set_master (sink->provided_clock, clock);
1158 case GST_BASE_AUDIO_SINK_SLAVE_SKEW:
1159 case GST_BASE_AUDIO_SINK_SLAVE_NONE:
1164 sink->priv->avg_skew = -1;
1165 sink->next_sample = -1;
1166 sink->priv->eos_time = -1;
1173 GST_DEBUG_OBJECT (sink, "we have no clock");
1178 GST_DEBUG_OBJECT (sink, "we are not slaved");
1183 GST_DEBUG_OBJECT (sink, "we are flushing");
1184 GST_OBJECT_LOCK (sink);
1185 return GST_FLOW_WRONG_STATE;
1189 static GstFlowReturn
1190 gst_base_audio_sink_render (GstBaseSink * bsink, GstBuffer * buf)
1193 GstClockTime time, stop, render_start, render_stop, sample_offset;
1194 GstClockTimeDiff sync_offset, ts_offset;
1195 GstBaseAudioSink *sink;
1196 GstRingBuffer *ringbuf;
1197 gint64 diff, align, ctime, cstop;
1200 guint samples, written;
1204 GstClockTime base_time, render_delay, latency;
1206 gboolean sync, slaved, align_next;
1208 GstSegment clip_seg;
1210 sink = GST_BASE_AUDIO_SINK (bsink);
1212 ringbuf = sink->ringbuffer;
1214 /* can't do anything when we don't have the device */
1215 if (G_UNLIKELY (!gst_ring_buffer_is_acquired (ringbuf)))
1218 /* Wait for upstream latency before starting the ringbuffer, we do this so
1219 * that we can align the first sample of the ringbuffer to the base_time +
1221 GST_OBJECT_LOCK (sink);
1222 base_time = GST_ELEMENT_CAST (sink)->base_time;
1223 if (G_UNLIKELY (sink->priv->sync_latency)) {
1224 ret = gst_base_audio_sink_sync_latency (bsink, GST_MINI_OBJECT_CAST (buf));
1225 GST_OBJECT_UNLOCK (sink);
1226 if (G_UNLIKELY (ret != GST_FLOW_OK))
1227 goto sync_latency_failed;
1228 /* only do this once until we are set back to PLAYING */
1229 sink->priv->sync_latency = FALSE;
1231 GST_OBJECT_UNLOCK (sink);
1234 bps = ringbuf->spec.bytes_per_sample;
1236 size = GST_BUFFER_SIZE (buf);
1237 if (G_UNLIKELY (size % bps) != 0)
1240 samples = size / bps;
1241 out_samples = samples;
1243 in_offset = GST_BUFFER_OFFSET (buf);
1244 time = GST_BUFFER_TIMESTAMP (buf);
1246 GST_DEBUG_OBJECT (sink,
1247 "time %" GST_TIME_FORMAT ", offset %llu, start %" GST_TIME_FORMAT
1248 ", samples %u", GST_TIME_ARGS (time), in_offset,
1249 GST_TIME_ARGS (bsink->segment.start), samples);
1251 data = GST_BUFFER_DATA (buf);
1253 /* if not valid timestamp or we can't clip or sync, try to play
1255 if (!GST_CLOCK_TIME_IS_VALID (time)) {
1256 render_start = gst_base_audio_sink_get_offset (sink);
1257 render_stop = render_start + samples;
1258 GST_DEBUG_OBJECT (sink,
1259 "Buffer of size %u has no time. Using render_start=%" G_GUINT64_FORMAT,
1260 GST_BUFFER_SIZE (buf), render_start);
1261 /* we don't have a start so we don't know stop either */
1266 /* let's calc stop based on the number of samples in the buffer instead
1267 * of trusting the DURATION */
1268 stop = time + gst_util_uint64_scale_int (samples, GST_SECOND,
1269 ringbuf->spec.rate);
1271 /* prepare the clipping segment. Since we will be subtracting ts-offset and
1272 * device-delay later we scale the start and stop with those values so that we
1273 * can correctly clip them */
1274 clip_seg.format = GST_FORMAT_TIME;
1275 clip_seg.start = bsink->segment.start;
1276 clip_seg.stop = bsink->segment.stop;
1277 clip_seg.duration = -1;
1279 /* the sync offset is the combination of ts-offset and device-delay */
1280 latency = gst_base_sink_get_latency (bsink);
1281 ts_offset = gst_base_sink_get_ts_offset (bsink);
1282 render_delay = gst_base_sink_get_render_delay (bsink);
1283 sync_offset = ts_offset - render_delay + latency;
1285 GST_DEBUG_OBJECT (sink,
1286 "sync-offset %" G_GINT64_FORMAT ", render-delay %" GST_TIME_FORMAT
1287 ", ts-offset %" G_GINT64_FORMAT, sync_offset,
1288 GST_TIME_ARGS (render_delay), ts_offset);
1290 /* compensate for ts-offset and device-delay when negative we need to
1292 if (sync_offset < 0) {
1293 clip_seg.start += -sync_offset;
1294 if (clip_seg.stop != -1)
1295 clip_seg.stop += -sync_offset;
1298 /* samples should be rendered based on their timestamp. All samples
1299 * arriving before the segment.start or after segment.stop are to be
1300 * thrown away. All samples should also be clipped to the segment
1302 if (!gst_segment_clip (&clip_seg, GST_FORMAT_TIME, time, stop, &ctime,
1304 goto out_of_segment;
1306 /* see if some clipping happened */
1307 diff = ctime - time;
1309 /* bring clipped time to samples */
1310 diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1311 GST_DEBUG_OBJECT (sink, "clipping start to %" GST_TIME_FORMAT " %"
1312 G_GUINT64_FORMAT " samples", GST_TIME_ARGS (ctime), diff);
1317 diff = stop - cstop;
1319 /* bring clipped time to samples */
1320 diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1321 GST_DEBUG_OBJECT (sink, "clipping stop to %" GST_TIME_FORMAT " %"
1322 G_GUINT64_FORMAT " samples", GST_TIME_ARGS (cstop), diff);
1327 /* figure out how to sync */
1328 if ((clock = GST_ELEMENT_CLOCK (bsink)))
1334 /* no sync needed, play sample ASAP */
1335 render_start = gst_base_audio_sink_get_offset (sink);
1336 render_stop = render_start + samples;
1337 GST_DEBUG_OBJECT (sink,
1338 "no sync needed. Using render_start=%" G_GUINT64_FORMAT, render_start);
1342 /* bring buffer start and stop times to running time */
1344 gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, time);
1346 gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, stop);
1348 GST_DEBUG_OBJECT (sink,
1349 "running: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1350 GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1352 /* store the time of the last sample, we'll use this to perform sync on the
1353 * last sample when draining the buffer */
1354 if (bsink->segment.rate >= 0.0) {
1355 sink->priv->eos_time = render_stop;
1357 sink->priv->eos_time = render_start;
1360 /* compensate for ts-offset and delay we know this will not underflow because we
1362 GST_DEBUG_OBJECT (sink,
1363 "compensating for sync-offset %" GST_TIME_FORMAT,
1364 GST_TIME_ARGS (sync_offset));
1365 render_start += sync_offset;
1366 render_stop += sync_offset;
1368 GST_DEBUG_OBJECT (sink, "adding base_time %" GST_TIME_FORMAT,
1369 GST_TIME_ARGS (base_time));
1371 /* add base time to sync against the clock */
1372 render_start += base_time;
1373 render_stop += base_time;
1375 GST_DEBUG_OBJECT (sink,
1376 "after compensation: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1377 GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1379 if ((slaved = clock != sink->provided_clock)) {
1380 /* handle clock slaving */
1381 gst_base_audio_sink_handle_slaving (sink, render_start, render_stop,
1382 &render_start, &render_stop);
1384 /* no slaving needed but we need to adapt to the clock calibration
1386 gst_base_audio_sink_none_slaving (sink, render_start, render_stop,
1387 &render_start, &render_stop);
1390 /* and bring the time to the rate corrected offset in the buffer */
1391 render_start = gst_util_uint64_scale_int (render_start,
1392 ringbuf->spec.rate, GST_SECOND);
1393 render_stop = gst_util_uint64_scale_int (render_stop,
1394 ringbuf->spec.rate, GST_SECOND);
1396 /* positive playback rate, first sample is render_start, negative rate, first
1397 * sample is render_stop. When no rate conversion is active, render exactly
1398 * the amount of input samples to avoid aligning to rounding errors. */
1399 if (bsink->segment.rate >= 0.0) {
1400 sample_offset = render_start;
1401 if (bsink->segment.rate == 1.0)
1402 render_stop = sample_offset + samples;
1404 sample_offset = render_stop;
1405 if (bsink->segment.rate == -1.0)
1406 render_start = sample_offset + samples;
1409 /* always resync after a discont */
1410 if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT))) {
1411 GST_DEBUG_OBJECT (sink, "resync after discont");
1415 /* resync when we don't know what to align the sample with */
1416 if (G_UNLIKELY (sink->next_sample == -1)) {
1417 GST_DEBUG_OBJECT (sink,
1418 "no align possible: no previous sample position known");
1422 /* now try to align the sample to the previous one, first see how big the
1424 if (sample_offset >= sink->next_sample)
1425 diff = sample_offset - sink->next_sample;
1427 diff = sink->next_sample - sample_offset;
1429 /* we tollerate half a second diff before we start resyncing. This
1430 * should be enough to compensate for various rounding errors in the timestamp
1431 * and sample offset position. We always resync if we got a discont anyway and
1432 * non-discont should be aligned by definition. */
1433 if (G_LIKELY (diff < ringbuf->spec.rate / DIFF_TOLERANCE)) {
1434 /* calc align with previous sample */
1435 align = sink->next_sample - sample_offset;
1436 GST_DEBUG_OBJECT (sink,
1437 "align with prev sample, ABS (%" G_GINT64_FORMAT ") < %d", align,
1438 ringbuf->spec.rate / DIFF_TOLERANCE);
1440 /* bring sample diff to seconds for error message */
1441 diff = gst_util_uint64_scale_int (diff, GST_SECOND, ringbuf->spec.rate);
1442 /* timestamps drifted apart from previous samples too much, we need to
1443 * resync. We log this as an element warning. */
1444 GST_ELEMENT_WARNING (sink, CORE, CLOCK,
1445 ("Compensating for audio synchronisation problems"),
1446 ("Unexpected discontinuity in audio timestamps of more "
1447 "than half a second (%" GST_TIME_FORMAT "), resyncing",
1448 GST_TIME_ARGS (diff)));
1451 sink->priv->last_align = align;
1453 /* apply alignment */
1454 render_start += align;
1456 /* only align stop if we are not slaved to resample */
1457 if (slaved && sink->priv->slave_method == GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE) {
1458 GST_DEBUG_OBJECT (sink, "no stop time align needed: we are slaved");
1461 render_stop += align;
1464 /* number of target samples is difference between start and stop */
1465 out_samples = render_stop - render_start;
1468 /* we render the first or last sample first, depending on the rate */
1469 if (bsink->segment.rate >= 0.0)
1470 sample_offset = render_start;
1472 sample_offset = render_stop;
1474 GST_DEBUG_OBJECT (sink, "rendering at %" G_GUINT64_FORMAT " %d/%d",
1475 sample_offset, samples, out_samples);
1477 /* we need to accumulate over different runs for when we get interrupted */
1482 gst_ring_buffer_commit_full (ringbuf, &sample_offset, data, samples,
1483 out_samples, &accum);
1485 GST_DEBUG_OBJECT (sink, "wrote %u of %u", written, samples);
1486 /* if we wrote all, we're done */
1487 if (written == samples)
1490 /* else something interrupted us and we wait for preroll. */
1491 if (gst_base_sink_wait_preroll (bsink) != GST_FLOW_OK)
1494 /* if we got interrupted, we cannot assume that the next sample should
1495 * be aligned to this one */
1499 data += written * bps;
1503 sink->next_sample = sample_offset;
1505 sink->next_sample = -1;
1507 GST_DEBUG_OBJECT (sink, "next sample expected at %" G_GUINT64_FORMAT,
1510 if (GST_CLOCK_TIME_IS_VALID (stop) && stop >= bsink->segment.stop) {
1511 GST_DEBUG_OBJECT (sink,
1512 "start playback because we are at the end of segment");
1513 gst_ring_buffer_start (ringbuf);
1521 GST_DEBUG_OBJECT (sink,
1522 "dropping sample out of segment time %" GST_TIME_FORMAT ", start %"
1523 GST_TIME_FORMAT, GST_TIME_ARGS (time),
1524 GST_TIME_ARGS (bsink->segment.start));
1530 GST_DEBUG_OBJECT (sink, "ringbuffer not negotiated");
1531 GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("sink not negotiated."));
1532 return GST_FLOW_NOT_NEGOTIATED;
1536 GST_DEBUG_OBJECT (sink, "wrong size");
1537 GST_ELEMENT_ERROR (sink, STREAM, WRONG_TYPE,
1538 (NULL), ("sink received buffer of wrong size."));
1539 return GST_FLOW_ERROR;
1543 GST_DEBUG_OBJECT (sink, "ringbuffer is stopping");
1544 return GST_FLOW_WRONG_STATE;
1546 sync_latency_failed:
1548 GST_DEBUG_OBJECT (sink, "failed waiting for latency");
1554 * gst_base_audio_sink_create_ringbuffer:
1555 * @sink: a #GstBaseAudioSink.
1557 * Create and return the #GstRingBuffer for @sink. This function will call the
1558 * ::create_ringbuffer vmethod and will set @sink as the parent of the returned
1559 * buffer (see gst_object_set_parent()).
1561 * Returns: The new ringbuffer of @sink.
1564 gst_base_audio_sink_create_ringbuffer (GstBaseAudioSink * sink)
1566 GstBaseAudioSinkClass *bclass;
1567 GstRingBuffer *buffer = NULL;
1569 bclass = GST_BASE_AUDIO_SINK_GET_CLASS (sink);
1570 if (bclass->create_ringbuffer)
1571 buffer = bclass->create_ringbuffer (sink);
1574 gst_object_set_parent (GST_OBJECT (buffer), GST_OBJECT (sink));
1580 gst_base_audio_sink_callback (GstRingBuffer * rbuf, guint8 * data, guint len,
1583 GstBaseSink *basesink;
1584 GstBaseAudioSink *sink;
1588 basesink = GST_BASE_SINK (user_data);
1589 sink = GST_BASE_AUDIO_SINK (user_data);
1591 GST_PAD_STREAM_LOCK (basesink->sinkpad);
1593 /* would be nice to arrange for pad_alloc_buffer to return data -- as it is we
1594 will copy twice, once into data, once into DMA */
1595 GST_LOG_OBJECT (basesink, "pulling %d bytes offset %" G_GUINT64_FORMAT
1596 " to fill audio buffer", len, basesink->offset);
1598 gst_pad_pull_range (basesink->sinkpad, basesink->segment.last_stop, len,
1601 if (ret != GST_FLOW_OK) {
1602 if (ret == GST_FLOW_UNEXPECTED)
1608 GST_PAD_PREROLL_LOCK (basesink->sinkpad);
1609 if (basesink->flushing)
1612 /* complete preroll and wait for PLAYING */
1613 ret = gst_base_sink_do_preroll (basesink, GST_MINI_OBJECT_CAST (buf));
1614 if (ret != GST_FLOW_OK)
1617 if (len != GST_BUFFER_SIZE (buf)) {
1618 GST_INFO_OBJECT (basesink,
1619 "got different size than requested from sink pad: %u != %u", len,
1620 GST_BUFFER_SIZE (buf));
1621 len = MIN (GST_BUFFER_SIZE (buf), len);
1624 basesink->segment.last_stop += len;
1626 memcpy (data, GST_BUFFER_DATA (buf), len);
1627 GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
1629 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1635 GST_WARNING_OBJECT (basesink, "Got flow '%s' but can't return it: %d",
1636 gst_flow_get_name (ret), ret);
1637 gst_ring_buffer_pause (rbuf);
1638 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1643 /* FIXME: this is not quite correct; we'll be called endlessly until
1644 * the sink gets shut down; maybe we should set a flag somewhere, or
1645 * set segment.stop and segment.duration to the last sample or so */
1646 GST_DEBUG_OBJECT (sink, "EOS");
1647 gst_base_audio_sink_drain (sink);
1648 gst_ring_buffer_pause (rbuf);
1649 gst_element_post_message (GST_ELEMENT_CAST (sink),
1650 gst_message_new_eos (GST_OBJECT_CAST (sink)));
1651 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1655 GST_DEBUG_OBJECT (sink, "we are flushing");
1656 gst_ring_buffer_pause (rbuf);
1657 GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
1658 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1663 GST_DEBUG_OBJECT (sink, "error %s", gst_flow_get_name (ret));
1664 gst_ring_buffer_pause (rbuf);
1665 GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
1666 GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1672 gst_base_audio_sink_activate_pull (GstBaseSink * basesink, gboolean active)
1675 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (basesink);
1678 GST_DEBUG_OBJECT (basesink, "activating pull");
1680 gst_ring_buffer_set_callback (sink->ringbuffer,
1681 gst_base_audio_sink_callback, sink);
1683 ret = gst_ring_buffer_activate (sink->ringbuffer, TRUE);
1685 GST_DEBUG_OBJECT (basesink, "deactivating pull");
1686 gst_ring_buffer_set_callback (sink->ringbuffer, NULL, NULL);
1687 ret = gst_ring_buffer_activate (sink->ringbuffer, FALSE);
1693 /* should be called with the LOCK */
1694 static GstStateChangeReturn
1695 gst_base_audio_sink_async_play (GstBaseSink * basesink)
1697 GstBaseAudioSink *sink;
1699 sink = GST_BASE_AUDIO_SINK (basesink);
1701 GST_DEBUG_OBJECT (sink, "ringbuffer may start now");
1702 sink->priv->sync_latency = TRUE;
1703 gst_ring_buffer_may_start (sink->ringbuffer, TRUE);
1704 if (basesink->pad_mode == GST_ACTIVATE_PULL) {
1705 /* we always start the ringbuffer in pull mode immediatly */
1706 gst_ring_buffer_start (sink->ringbuffer);
1709 return GST_STATE_CHANGE_SUCCESS;
1712 static GstStateChangeReturn
1713 gst_base_audio_sink_do_play (GstBaseAudioSink * sink)
1715 GstStateChangeReturn ret;
1717 GST_OBJECT_LOCK (sink);
1718 ret = gst_base_audio_sink_async_play (GST_BASE_SINK_CAST (sink));
1719 GST_OBJECT_UNLOCK (sink);
1724 static GstStateChangeReturn
1725 gst_base_audio_sink_change_state (GstElement * element,
1726 GstStateChange transition)
1728 GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1729 GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (element);
1731 switch (transition) {
1732 case GST_STATE_CHANGE_NULL_TO_READY:
1733 if (sink->ringbuffer == NULL) {
1734 gst_audio_clock_reset (GST_AUDIO_CLOCK (sink->provided_clock), 0);
1735 sink->ringbuffer = gst_base_audio_sink_create_ringbuffer (sink);
1737 if (!gst_ring_buffer_open_device (sink->ringbuffer))
1740 case GST_STATE_CHANGE_READY_TO_PAUSED:
1741 sink->next_sample = -1;
1742 sink->priv->last_align = -1;
1743 sink->priv->eos_time = -1;
1744 gst_ring_buffer_set_flushing (sink->ringbuffer, FALSE);
1745 gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
1747 case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1748 gst_base_audio_sink_do_play (sink);
1750 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1751 /* need to take the lock so we don't interfere with an
1753 GST_OBJECT_LOCK (sink);
1754 /* ringbuffer cannot start anymore */
1755 gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
1756 gst_ring_buffer_pause (sink->ringbuffer);
1757 sink->priv->sync_latency = FALSE;
1758 GST_OBJECT_UNLOCK (sink);
1760 case GST_STATE_CHANGE_PAUSED_TO_READY:
1761 /* make sure we unblock before calling the parent state change
1762 * so it can grab the STREAM_LOCK */
1763 gst_ring_buffer_set_flushing (sink->ringbuffer, TRUE);
1769 ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1771 switch (transition) {
1772 case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1773 /* stop slaving ourselves to the master, if any */
1774 gst_clock_set_master (sink->provided_clock, NULL);
1776 case GST_STATE_CHANGE_PAUSED_TO_READY:
1777 gst_ring_buffer_activate (sink->ringbuffer, FALSE);
1778 gst_ring_buffer_release (sink->ringbuffer);
1780 case GST_STATE_CHANGE_READY_TO_NULL:
1781 /* we release again here because the aqcuire happens when setting the
1782 * caps, which happens before we commit the state to PAUSED and thus the
1783 * PAUSED->READY state change (see above, where we release the ringbuffer)
1784 * might not be called when we get here. */
1785 gst_ring_buffer_activate (sink->ringbuffer, FALSE);
1786 gst_ring_buffer_release (sink->ringbuffer);
1787 gst_ring_buffer_close_device (sink->ringbuffer);
1798 /* subclass must post a meaningfull error message */
1799 GST_DEBUG_OBJECT (sink, "open failed");
1800 return GST_STATE_CHANGE_FAILURE;