Merge branch 'master' into 0.11
[platform/upstream/gstreamer.git] / gst-libs / gst / audio / gstbaseaudiosink.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2005 Wim Taymans <wim@fluendo.com>
4  *
5  * gstbaseaudiosink.c:
6  *
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.
11  *
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.
16  *
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.
21  */
22
23 /**
24  * SECTION:gstbaseaudiosink
25  * @short_description: Base class for audio sinks
26  * @see_also: #GstAudioSink, #GstRingBuffer.
27  *
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.
31  *
32  * Last reviewed on 2006-09-27 (0.10.12)
33  */
34
35 #include <string.h>
36
37 #include "gstbaseaudiosink.h"
38
39 GST_DEBUG_CATEGORY_STATIC (gst_base_audio_sink_debug);
40 #define GST_CAT_DEFAULT gst_base_audio_sink_debug
41
42 #define GST_BASE_AUDIO_SINK_GET_PRIVATE(obj)  \
43    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_BASE_AUDIO_SINK, GstBaseAudioSinkPrivate))
44
45 struct _GstBaseAudioSinkPrivate
46 {
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 */
54   gint64 last_align;
55
56   gboolean sync_latency;
57
58   GstClockTime eos_time;
59
60   /* number of microseconds we alow timestamps or clock slaving to drift
61    * before resyncing */
62   guint64 drift_tolerance;
63 };
64
65 /* BaseAudioSink signals and args */
66 enum
67 {
68   /* FILL ME */
69   LAST_SIGNAL
70 };
71
72 /* FIXME: 0.11, store the buffer_time and latency_time in nanoseconds */
73 #define DEFAULT_BUFFER_TIME     ((200 * GST_MSECOND) / GST_USECOND)
74 #define DEFAULT_LATENCY_TIME    ((10 * GST_MSECOND) / GST_USECOND)
75 #define DEFAULT_PROVIDE_CLOCK   TRUE
76 #define DEFAULT_SLAVE_METHOD    GST_BASE_AUDIO_SINK_SLAVE_SKEW
77
78 /* FIXME, enable pull mode when clock slaving and trick modes are figured out */
79 #define DEFAULT_CAN_ACTIVATE_PULL FALSE
80
81 /* when timestamps or clock slaving drift for more than 40ms we resync. This is
82  * a reasonable default */
83 #define DEFAULT_DRIFT_TOLERANCE   ((40 * GST_MSECOND) / GST_USECOND)
84
85 enum
86 {
87   PROP_0,
88
89   PROP_BUFFER_TIME,
90   PROP_LATENCY_TIME,
91   PROP_PROVIDE_CLOCK,
92   PROP_SLAVE_METHOD,
93   PROP_CAN_ACTIVATE_PULL,
94   PROP_DRIFT_TOLERANCE,
95
96   PROP_LAST
97 };
98
99 GType
100 gst_base_audio_sink_slave_method_get_type (void)
101 {
102   static volatile gsize slave_method_type = 0;
103   static const GEnumValue slave_method[] = {
104     {GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE, "GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE",
105         "resample"},
106     {GST_BASE_AUDIO_SINK_SLAVE_SKEW, "GST_BASE_AUDIO_SINK_SLAVE_SKEW", "skew"},
107     {GST_BASE_AUDIO_SINK_SLAVE_NONE, "GST_BASE_AUDIO_SINK_SLAVE_NONE", "none"},
108     {0, NULL, NULL},
109   };
110
111   if (g_once_init_enter (&slave_method_type)) {
112     GType tmp =
113         g_enum_register_static ("GstBaseAudioSinkSlaveMethod", slave_method);
114     g_once_init_leave (&slave_method_type, tmp);
115   }
116
117   return (GType) slave_method_type;
118 }
119
120
121 #define _do_init \
122     GST_DEBUG_CATEGORY_INIT (gst_base_audio_sink_debug, "baseaudiosink", 0, "baseaudiosink element");
123 #define gst_base_audio_sink_parent_class parent_class
124 G_DEFINE_TYPE_WITH_CODE (GstBaseAudioSink, gst_base_audio_sink,
125     GST_TYPE_BASE_SINK, _do_init);
126
127 static void gst_base_audio_sink_dispose (GObject * object);
128
129 static void gst_base_audio_sink_set_property (GObject * object, guint prop_id,
130     const GValue * value, GParamSpec * pspec);
131 static void gst_base_audio_sink_get_property (GObject * object, guint prop_id,
132     GValue * value, GParamSpec * pspec);
133
134 #if 0
135 static GstStateChangeReturn gst_base_audio_sink_async_play (GstBaseSink *
136     basesink);
137 #endif
138 static GstStateChangeReturn gst_base_audio_sink_change_state (GstElement *
139     element, GstStateChange transition);
140 static gboolean gst_base_audio_sink_activate_pull (GstBaseSink * basesink,
141     gboolean active);
142 static gboolean gst_base_audio_sink_query (GstElement * element, GstQuery *
143     query);
144
145 static GstClock *gst_base_audio_sink_provide_clock (GstElement * elem);
146 static GstClockTime gst_base_audio_sink_get_time (GstClock * clock,
147     GstBaseAudioSink * sink);
148 static void gst_base_audio_sink_callback (GstRingBuffer * rbuf, guint8 * data,
149     guint len, gpointer user_data);
150
151 static GstFlowReturn gst_base_audio_sink_preroll (GstBaseSink * bsink,
152     GstBuffer * buffer);
153 static GstFlowReturn gst_base_audio_sink_render (GstBaseSink * bsink,
154     GstBuffer * buffer);
155 static gboolean gst_base_audio_sink_event (GstBaseSink * bsink,
156     GstEvent * event);
157 static void gst_base_audio_sink_get_times (GstBaseSink * bsink,
158     GstBuffer * buffer, GstClockTime * start, GstClockTime * end);
159 static gboolean gst_base_audio_sink_setcaps (GstBaseSink * bsink,
160     GstCaps * caps);
161 static void gst_base_audio_sink_fixate (GstBaseSink * bsink, GstCaps * caps);
162
163 static gboolean gst_base_audio_sink_query_pad (GstPad * pad, GstQuery * query);
164
165
166 /* static guint gst_base_audio_sink_signals[LAST_SIGNAL] = { 0 }; */
167
168 static void
169 gst_base_audio_sink_class_init (GstBaseAudioSinkClass * klass)
170 {
171   GObjectClass *gobject_class;
172   GstElementClass *gstelement_class;
173   GstBaseSinkClass *gstbasesink_class;
174
175   gobject_class = (GObjectClass *) klass;
176   gstelement_class = (GstElementClass *) klass;
177   gstbasesink_class = (GstBaseSinkClass *) klass;
178
179   g_type_class_add_private (klass, sizeof (GstBaseAudioSinkPrivate));
180
181   gobject_class->set_property = gst_base_audio_sink_set_property;
182   gobject_class->get_property = gst_base_audio_sink_get_property;
183   gobject_class->dispose = gst_base_audio_sink_dispose;
184
185   g_object_class_install_property (gobject_class, PROP_BUFFER_TIME,
186       g_param_spec_int64 ("buffer-time", "Buffer Time",
187           "Size of audio buffer in microseconds", 1,
188           G_MAXINT64, DEFAULT_BUFFER_TIME,
189           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
190
191   g_object_class_install_property (gobject_class, PROP_LATENCY_TIME,
192       g_param_spec_int64 ("latency-time", "Latency Time",
193           "Audio latency in microseconds", 1,
194           G_MAXINT64, DEFAULT_LATENCY_TIME,
195           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
196
197   g_object_class_install_property (gobject_class, PROP_PROVIDE_CLOCK,
198       g_param_spec_boolean ("provide-clock", "Provide Clock",
199           "Provide a clock to be used as the global pipeline clock",
200           DEFAULT_PROVIDE_CLOCK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
201
202   g_object_class_install_property (gobject_class, PROP_SLAVE_METHOD,
203       g_param_spec_enum ("slave-method", "Slave Method",
204           "Algorithm to use to match the rate of the masterclock",
205           GST_TYPE_BASE_AUDIO_SINK_SLAVE_METHOD, DEFAULT_SLAVE_METHOD,
206           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
207
208   g_object_class_install_property (gobject_class, PROP_CAN_ACTIVATE_PULL,
209       g_param_spec_boolean ("can-activate-pull", "Allow Pull Scheduling",
210           "Allow pull-based scheduling", DEFAULT_CAN_ACTIVATE_PULL,
211           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
212   /**
213    * GstBaseAudioSink:drift-tolerance
214    *
215    * Controls the amount of time in milliseconds that timestamps or clocks are allowed
216    * to drift before resynchronisation happens.
217    *
218    * Since: 0.10.26
219    */
220   g_object_class_install_property (gobject_class, PROP_DRIFT_TOLERANCE,
221       g_param_spec_int64 ("drift-tolerance", "Drift Tolerance",
222           "Tolerance for timestamp and clock drift in microseconds", 1,
223           G_MAXINT64, DEFAULT_DRIFT_TOLERANCE,
224           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
225
226   gstelement_class->change_state =
227       GST_DEBUG_FUNCPTR (gst_base_audio_sink_change_state);
228   gstelement_class->provide_clock =
229       GST_DEBUG_FUNCPTR (gst_base_audio_sink_provide_clock);
230   gstelement_class->query = GST_DEBUG_FUNCPTR (gst_base_audio_sink_query);
231
232   gstbasesink_class->event = GST_DEBUG_FUNCPTR (gst_base_audio_sink_event);
233   gstbasesink_class->preroll = GST_DEBUG_FUNCPTR (gst_base_audio_sink_preroll);
234   gstbasesink_class->render = GST_DEBUG_FUNCPTR (gst_base_audio_sink_render);
235   gstbasesink_class->get_times =
236       GST_DEBUG_FUNCPTR (gst_base_audio_sink_get_times);
237   gstbasesink_class->set_caps = GST_DEBUG_FUNCPTR (gst_base_audio_sink_setcaps);
238   gstbasesink_class->fixate = GST_DEBUG_FUNCPTR (gst_base_audio_sink_fixate);
239 #if 0
240   gstbasesink_class->async_play =
241       GST_DEBUG_FUNCPTR (gst_base_audio_sink_async_play);
242 #endif
243   gstbasesink_class->activate_pull =
244       GST_DEBUG_FUNCPTR (gst_base_audio_sink_activate_pull);
245
246   /* ref class from a thread-safe context to work around missing bit of
247    * thread-safety in GObject */
248   g_type_class_ref (GST_TYPE_AUDIO_CLOCK);
249   g_type_class_ref (GST_TYPE_RING_BUFFER);
250
251 }
252
253 static void
254 gst_base_audio_sink_init (GstBaseAudioSink * baseaudiosink)
255 {
256   GstBaseSink *basesink;
257
258   baseaudiosink->priv = GST_BASE_AUDIO_SINK_GET_PRIVATE (baseaudiosink);
259
260   baseaudiosink->buffer_time = DEFAULT_BUFFER_TIME;
261   baseaudiosink->latency_time = DEFAULT_LATENCY_TIME;
262   baseaudiosink->provide_clock = DEFAULT_PROVIDE_CLOCK;
263   baseaudiosink->priv->slave_method = DEFAULT_SLAVE_METHOD;
264   baseaudiosink->priv->drift_tolerance = DEFAULT_DRIFT_TOLERANCE;
265
266   baseaudiosink->provided_clock = gst_audio_clock_new ("GstAudioSinkClock",
267       (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time, baseaudiosink);
268
269   basesink = GST_BASE_SINK_CAST (baseaudiosink);
270   basesink->can_activate_push = TRUE;
271   basesink->can_activate_pull = DEFAULT_CAN_ACTIVATE_PULL;
272
273   gst_base_sink_set_last_buffer_enabled (basesink, FALSE);
274
275   /* install some custom pad_query functions */
276   gst_pad_set_query_function (GST_BASE_SINK_PAD (baseaudiosink),
277       GST_DEBUG_FUNCPTR (gst_base_audio_sink_query_pad));
278 }
279
280 static void
281 gst_base_audio_sink_dispose (GObject * object)
282 {
283   GstBaseAudioSink *sink;
284
285   sink = GST_BASE_AUDIO_SINK (object);
286
287   if (sink->provided_clock) {
288     gst_audio_clock_invalidate (sink->provided_clock);
289     gst_object_unref (sink->provided_clock);
290     sink->provided_clock = NULL;
291   }
292
293   if (sink->ringbuffer) {
294     gst_object_unparent (GST_OBJECT_CAST (sink->ringbuffer));
295     sink->ringbuffer = NULL;
296   }
297
298   G_OBJECT_CLASS (parent_class)->dispose (object);
299 }
300
301
302 static GstClock *
303 gst_base_audio_sink_provide_clock (GstElement * elem)
304 {
305   GstBaseAudioSink *sink;
306   GstClock *clock;
307
308   sink = GST_BASE_AUDIO_SINK (elem);
309
310   /* we have no ringbuffer (must be NULL state) */
311   if (sink->ringbuffer == NULL)
312     goto wrong_state;
313
314   if (!gst_ring_buffer_is_acquired (sink->ringbuffer))
315     goto wrong_state;
316
317   GST_OBJECT_LOCK (sink);
318   if (!sink->provide_clock)
319     goto clock_disabled;
320
321   clock = GST_CLOCK_CAST (gst_object_ref (sink->provided_clock));
322   GST_OBJECT_UNLOCK (sink);
323
324   return clock;
325
326   /* ERRORS */
327 wrong_state:
328   {
329     GST_DEBUG_OBJECT (sink, "ringbuffer not acquired");
330     return NULL;
331   }
332 clock_disabled:
333   {
334     GST_DEBUG_OBJECT (sink, "clock provide disabled");
335     GST_OBJECT_UNLOCK (sink);
336     return NULL;
337   }
338 }
339
340 static gboolean
341 gst_base_audio_sink_query_pad (GstPad * pad, GstQuery * query)
342 {
343   gboolean res = FALSE;
344   GstBaseAudioSink *basesink;
345
346   basesink = GST_BASE_AUDIO_SINK (gst_pad_get_parent (pad));
347
348   switch (GST_QUERY_TYPE (query)) {
349     case GST_QUERY_CONVERT:
350     {
351       GstFormat src_fmt, dest_fmt;
352       gint64 src_val, dest_val;
353
354       GST_LOG_OBJECT (pad, "query convert");
355
356       if (basesink->ringbuffer) {
357         gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, NULL);
358         res = gst_ring_buffer_convert (basesink->ringbuffer, src_fmt, src_val,
359             dest_fmt, &dest_val);
360         if (res) {
361           gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
362         }
363       }
364       break;
365     }
366     default:
367       break;
368   }
369
370   gst_object_unref (basesink);
371
372   return res;
373 }
374
375 static gboolean
376 gst_base_audio_sink_query (GstElement * element, GstQuery * query)
377 {
378   gboolean res = FALSE;
379   GstBaseAudioSink *basesink;
380
381   basesink = GST_BASE_AUDIO_SINK (element);
382
383   switch (GST_QUERY_TYPE (query)) {
384     case GST_QUERY_LATENCY:
385     {
386       gboolean live, us_live;
387       GstClockTime min_l, max_l;
388
389       GST_DEBUG_OBJECT (basesink, "latency query");
390
391       /* ask parent first, it will do an upstream query for us. */
392       if ((res =
393               gst_base_sink_query_latency (GST_BASE_SINK_CAST (basesink), &live,
394                   &us_live, &min_l, &max_l))) {
395         GstClockTime min_latency, max_latency;
396
397         /* we and upstream are both live, adjust the min_latency */
398         if (live && us_live) {
399           GstRingBufferSpec *spec;
400
401           GST_OBJECT_LOCK (basesink);
402           if (!basesink->ringbuffer || !basesink->ringbuffer->spec.rate) {
403             GST_OBJECT_UNLOCK (basesink);
404
405             GST_DEBUG_OBJECT (basesink,
406                 "we are not yet negotiated, can't report latency yet");
407             res = FALSE;
408             goto done;
409           }
410           spec = &basesink->ringbuffer->spec;
411
412           basesink->priv->us_latency = min_l;
413
414           min_latency =
415               gst_util_uint64_scale_int (spec->seglatency * spec->segsize,
416               GST_SECOND, spec->rate * spec->bytes_per_sample);
417           GST_OBJECT_UNLOCK (basesink);
418
419           /* we cannot go lower than the buffer size and the min peer latency */
420           min_latency = min_latency + min_l;
421           /* the max latency is the max of the peer, we can delay an infinite
422            * amount of time. */
423           max_latency = min_latency + (max_l == -1 ? 0 : max_l);
424
425           GST_DEBUG_OBJECT (basesink,
426               "peer min %" GST_TIME_FORMAT ", our min latency: %"
427               GST_TIME_FORMAT, GST_TIME_ARGS (min_l),
428               GST_TIME_ARGS (min_latency));
429         } else {
430           GST_DEBUG_OBJECT (basesink,
431               "peer or we are not live, don't care about latency");
432           min_latency = min_l;
433           max_latency = max_l;
434         }
435         gst_query_set_latency (query, live, min_latency, max_latency);
436       }
437       break;
438     }
439     case GST_QUERY_CONVERT:
440     {
441       GstFormat src_fmt, dest_fmt;
442       gint64 src_val, dest_val;
443
444       GST_LOG_OBJECT (basesink, "query convert");
445
446       if (basesink->ringbuffer) {
447         gst_query_parse_convert (query, &src_fmt, &src_val, &dest_fmt, NULL);
448         res = gst_ring_buffer_convert (basesink->ringbuffer, src_fmt, src_val,
449             dest_fmt, &dest_val);
450         if (res) {
451           gst_query_set_convert (query, src_fmt, src_val, dest_fmt, dest_val);
452         }
453       }
454       break;
455     }
456     default:
457       res = GST_ELEMENT_CLASS (parent_class)->query (element, query);
458       break;
459   }
460
461 done:
462   return res;
463 }
464
465
466 static GstClockTime
467 gst_base_audio_sink_get_time (GstClock * clock, GstBaseAudioSink * sink)
468 {
469   guint64 raw, samples;
470   guint delay;
471   GstClockTime result;
472
473   if (sink->ringbuffer == NULL || sink->ringbuffer->spec.rate == 0)
474     return GST_CLOCK_TIME_NONE;
475
476   /* our processed samples are always increasing */
477   raw = samples = gst_ring_buffer_samples_done (sink->ringbuffer);
478
479   /* the number of samples not yet processed, this is still queued in the
480    * device (not played for playback). */
481   delay = gst_ring_buffer_delay (sink->ringbuffer);
482
483   if (G_LIKELY (samples >= delay))
484     samples -= delay;
485   else
486     samples = 0;
487
488   result = gst_util_uint64_scale_int (samples, GST_SECOND,
489       sink->ringbuffer->spec.rate);
490
491   GST_DEBUG_OBJECT (sink,
492       "processed samples: raw %" G_GUINT64_FORMAT ", delay %u, real %"
493       G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT,
494       raw, delay, samples, GST_TIME_ARGS (result));
495
496   return result;
497 }
498
499 /**
500  * gst_base_audio_sink_set_provide_clock:
501  * @sink: a #GstBaseAudioSink
502  * @provide: new state
503  *
504  * Controls whether @sink will provide a clock or not. If @provide is %TRUE,
505  * gst_element_provide_clock() will return a clock that reflects the datarate
506  * of @sink. If @provide is %FALSE, gst_element_provide_clock() will return NULL.
507  *
508  * Since: 0.10.16
509  */
510 void
511 gst_base_audio_sink_set_provide_clock (GstBaseAudioSink * sink,
512     gboolean provide)
513 {
514   g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
515
516   GST_OBJECT_LOCK (sink);
517   sink->provide_clock = provide;
518   GST_OBJECT_UNLOCK (sink);
519 }
520
521 /**
522  * gst_base_audio_sink_get_provide_clock:
523  * @sink: a #GstBaseAudioSink
524  *
525  * Queries whether @sink will provide a clock or not. See also
526  * gst_base_audio_sink_set_provide_clock.
527  *
528  * Returns: %TRUE if @sink will provide a clock.
529  *
530  * Since: 0.10.16
531  */
532 gboolean
533 gst_base_audio_sink_get_provide_clock (GstBaseAudioSink * sink)
534 {
535   gboolean result;
536
537   g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), FALSE);
538
539   GST_OBJECT_LOCK (sink);
540   result = sink->provide_clock;
541   GST_OBJECT_UNLOCK (sink);
542
543   return result;
544 }
545
546 /**
547  * gst_base_audio_sink_set_slave_method:
548  * @sink: a #GstBaseAudioSink
549  * @method: the new slave method
550  *
551  * Controls how clock slaving will be performed in @sink.
552  *
553  * Since: 0.10.16
554  */
555 void
556 gst_base_audio_sink_set_slave_method (GstBaseAudioSink * sink,
557     GstBaseAudioSinkSlaveMethod method)
558 {
559   g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
560
561   GST_OBJECT_LOCK (sink);
562   sink->priv->slave_method = method;
563   GST_OBJECT_UNLOCK (sink);
564 }
565
566 /**
567  * gst_base_audio_sink_get_slave_method:
568  * @sink: a #GstBaseAudioSink
569  *
570  * Get the current slave method used by @sink.
571  *
572  * Returns: The current slave method used by @sink.
573  *
574  * Since: 0.10.16
575  */
576 GstBaseAudioSinkSlaveMethod
577 gst_base_audio_sink_get_slave_method (GstBaseAudioSink * sink)
578 {
579   GstBaseAudioSinkSlaveMethod result;
580
581   g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), -1);
582
583   GST_OBJECT_LOCK (sink);
584   result = sink->priv->slave_method;
585   GST_OBJECT_UNLOCK (sink);
586
587   return result;
588 }
589
590
591 /**
592  * gst_base_audio_sink_set_drift_tolerance:
593  * @sink: a #GstBaseAudioSink
594  * @drift_tolerance: the new drift tolerance in microseconds
595  *
596  * Controls the sink's drift tolerance.
597  *
598  * Since: 0.10.31
599  */
600 void
601 gst_base_audio_sink_set_drift_tolerance (GstBaseAudioSink * sink,
602     gint64 drift_tolerance)
603 {
604   g_return_if_fail (GST_IS_BASE_AUDIO_SINK (sink));
605
606   GST_OBJECT_LOCK (sink);
607   sink->priv->drift_tolerance = drift_tolerance;
608   GST_OBJECT_UNLOCK (sink);
609 }
610
611 /**
612  * gst_base_audio_sink_get_drift_tolerance
613  * @sink: a #GstBaseAudioSink
614  *
615  * Get the current drift tolerance, in microseconds, used by @sink.
616  *
617  * Returns: The current drift tolerance used by @sink.
618  *
619  * Since: 0.10.31
620  */
621 gint64
622 gst_base_audio_sink_get_drift_tolerance (GstBaseAudioSink * sink)
623 {
624   gint64 result;
625
626   g_return_val_if_fail (GST_IS_BASE_AUDIO_SINK (sink), -1);
627
628   GST_OBJECT_LOCK (sink);
629   result = sink->priv->drift_tolerance;
630   GST_OBJECT_UNLOCK (sink);
631
632   return result;
633 }
634
635 static void
636 gst_base_audio_sink_set_property (GObject * object, guint prop_id,
637     const GValue * value, GParamSpec * pspec)
638 {
639   GstBaseAudioSink *sink;
640
641   sink = GST_BASE_AUDIO_SINK (object);
642
643   switch (prop_id) {
644     case PROP_BUFFER_TIME:
645       sink->buffer_time = g_value_get_int64 (value);
646       break;
647     case PROP_LATENCY_TIME:
648       sink->latency_time = g_value_get_int64 (value);
649       break;
650     case PROP_PROVIDE_CLOCK:
651       gst_base_audio_sink_set_provide_clock (sink, g_value_get_boolean (value));
652       break;
653     case PROP_SLAVE_METHOD:
654       gst_base_audio_sink_set_slave_method (sink, g_value_get_enum (value));
655       break;
656     case PROP_CAN_ACTIVATE_PULL:
657       GST_BASE_SINK (sink)->can_activate_pull = g_value_get_boolean (value);
658       break;
659     case PROP_DRIFT_TOLERANCE:
660       gst_base_audio_sink_set_drift_tolerance (sink, g_value_get_int64 (value));
661       break;
662     default:
663       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
664       break;
665   }
666 }
667
668 static void
669 gst_base_audio_sink_get_property (GObject * object, guint prop_id,
670     GValue * value, GParamSpec * pspec)
671 {
672   GstBaseAudioSink *sink;
673
674   sink = GST_BASE_AUDIO_SINK (object);
675
676   switch (prop_id) {
677     case PROP_BUFFER_TIME:
678       g_value_set_int64 (value, sink->buffer_time);
679       break;
680     case PROP_LATENCY_TIME:
681       g_value_set_int64 (value, sink->latency_time);
682       break;
683     case PROP_PROVIDE_CLOCK:
684       g_value_set_boolean (value, gst_base_audio_sink_get_provide_clock (sink));
685       break;
686     case PROP_SLAVE_METHOD:
687       g_value_set_enum (value, gst_base_audio_sink_get_slave_method (sink));
688       break;
689     case PROP_CAN_ACTIVATE_PULL:
690       g_value_set_boolean (value, GST_BASE_SINK (sink)->can_activate_pull);
691       break;
692     case PROP_DRIFT_TOLERANCE:
693       g_value_set_int64 (value, gst_base_audio_sink_get_drift_tolerance (sink));
694       break;
695     default:
696       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
697       break;
698   }
699 }
700
701 static gboolean
702 gst_base_audio_sink_setcaps (GstBaseSink * bsink, GstCaps * caps)
703 {
704   GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
705   GstRingBufferSpec *spec;
706   GstClockTime now;
707   GstClockTime crate_num, crate_denom;
708
709   if (!sink->ringbuffer)
710     return FALSE;
711
712   spec = &sink->ringbuffer->spec;
713
714   GST_DEBUG_OBJECT (sink, "release old ringbuffer");
715
716   /* get current time, updates the last_time. When the subclass has a clock that
717    * restarts from 0 when a new format is negotiated, it will call
718    * gst_audio_clock_reset() which will use this last_time to create an offset
719    * so that time from the clock keeps on increasing monotonically. */
720   now = gst_clock_get_time (sink->provided_clock);
721
722   GST_DEBUG_OBJECT (sink, "time was %" GST_TIME_FORMAT, GST_TIME_ARGS (now));
723
724   /* release old ringbuffer */
725   gst_ring_buffer_pause (sink->ringbuffer);
726   gst_ring_buffer_activate (sink->ringbuffer, FALSE);
727   gst_ring_buffer_release (sink->ringbuffer);
728
729   GST_DEBUG_OBJECT (sink, "parse caps");
730
731   spec->buffer_time = sink->buffer_time;
732   spec->latency_time = sink->latency_time;
733
734   /* parse new caps */
735   if (!gst_ring_buffer_parse_caps (spec, caps))
736     goto parse_error;
737
738   gst_ring_buffer_debug_spec_buff (spec);
739
740   GST_DEBUG_OBJECT (sink, "acquire ringbuffer");
741   if (!gst_ring_buffer_acquire (sink->ringbuffer, spec))
742     goto acquire_error;
743
744   if (bsink->pad_mode == GST_ACTIVATE_PUSH) {
745     GST_DEBUG_OBJECT (sink, "activate ringbuffer");
746     gst_ring_buffer_activate (sink->ringbuffer, TRUE);
747   }
748
749   /* due to possible changes in the spec file we should recalibrate the clock */
750   gst_clock_get_calibration (sink->provided_clock, NULL, NULL,
751       &crate_num, &crate_denom);
752   gst_clock_set_calibration (sink->provided_clock,
753       gst_clock_get_internal_time (sink->provided_clock), now, crate_num,
754       crate_denom);
755
756   /* calculate actual latency and buffer times.
757    * FIXME: In 0.11, store the latency_time internally in ns */
758   spec->latency_time = gst_util_uint64_scale (spec->segsize,
759       (GST_SECOND / GST_USECOND), spec->rate * spec->bytes_per_sample);
760
761   spec->buffer_time = spec->segtotal * spec->latency_time;
762
763   gst_ring_buffer_debug_spec_buff (spec);
764
765   return TRUE;
766
767   /* ERRORS */
768 parse_error:
769   {
770     GST_DEBUG_OBJECT (sink, "could not parse caps");
771     GST_ELEMENT_ERROR (sink, STREAM, FORMAT,
772         (NULL), ("cannot parse audio format."));
773     return FALSE;
774   }
775 acquire_error:
776   {
777     GST_DEBUG_OBJECT (sink, "could not acquire ringbuffer");
778     return FALSE;
779   }
780 }
781
782 static void
783 gst_base_audio_sink_fixate (GstBaseSink * bsink, GstCaps * caps)
784 {
785   GstStructure *s;
786   gint width, depth;
787
788   s = gst_caps_get_structure (caps, 0);
789
790   /* fields for all formats */
791   gst_structure_fixate_field_nearest_int (s, "rate", 44100);
792   gst_structure_fixate_field_nearest_int (s, "channels", 2);
793   gst_structure_fixate_field_nearest_int (s, "width", 16);
794
795   /* fields for int */
796   if (gst_structure_has_field (s, "depth")) {
797     gst_structure_get_int (s, "width", &width);
798     /* round width to nearest multiple of 8 for the depth */
799     depth = GST_ROUND_UP_8 (width);
800     gst_structure_fixate_field_nearest_int (s, "depth", depth);
801   }
802   if (gst_structure_has_field (s, "signed"))
803     gst_structure_fixate_field_boolean (s, "signed", TRUE);
804   if (gst_structure_has_field (s, "endianness"))
805     gst_structure_fixate_field_nearest_int (s, "endianness", G_BYTE_ORDER);
806 }
807
808 static void
809 gst_base_audio_sink_get_times (GstBaseSink * bsink, GstBuffer * buffer,
810     GstClockTime * start, GstClockTime * end)
811 {
812   /* our clock sync is a bit too much for the base class to handle so
813    * we implement it ourselves. */
814   *start = GST_CLOCK_TIME_NONE;
815   *end = GST_CLOCK_TIME_NONE;
816 }
817
818 /* This waits for the drain to happen and can be canceled */
819 static gboolean
820 gst_base_audio_sink_drain (GstBaseAudioSink * sink)
821 {
822   if (!sink->ringbuffer)
823     return TRUE;
824   if (!sink->ringbuffer->spec.rate)
825     return TRUE;
826
827   /* if PLAYING is interrupted,
828    * arrange to have clock running when going to PLAYING again */
829   g_atomic_int_set (&sink->abidata.ABI.eos_rendering, 1);
830
831   /* need to start playback before we can drain, but only when
832    * we have successfully negotiated a format and thus acquired the
833    * ringbuffer. */
834   if (gst_ring_buffer_is_acquired (sink->ringbuffer))
835     gst_ring_buffer_start (sink->ringbuffer);
836
837   if (sink->priv->eos_time != -1) {
838     GST_DEBUG_OBJECT (sink,
839         "last sample time %" GST_TIME_FORMAT,
840         GST_TIME_ARGS (sink->priv->eos_time));
841
842     /* wait for the EOS time to be reached, this is the time when the last
843      * sample is played. */
844     gst_base_sink_wait_eos (GST_BASE_SINK (sink), sink->priv->eos_time, NULL);
845
846     GST_DEBUG_OBJECT (sink, "drained audio");
847   }
848   g_atomic_int_set (&sink->abidata.ABI.eos_rendering, 0);
849   return TRUE;
850 }
851
852 static gboolean
853 gst_base_audio_sink_event (GstBaseSink * bsink, GstEvent * event)
854 {
855   GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
856
857   switch (GST_EVENT_TYPE (event)) {
858     case GST_EVENT_FLUSH_START:
859       if (sink->ringbuffer)
860         gst_ring_buffer_set_flushing (sink->ringbuffer, TRUE);
861       break;
862     case GST_EVENT_FLUSH_STOP:
863       /* always resync on sample after a flush */
864       sink->priv->avg_skew = -1;
865       sink->next_sample = -1;
866       sink->priv->eos_time = -1;
867       if (sink->ringbuffer)
868         gst_ring_buffer_set_flushing (sink->ringbuffer, FALSE);
869       break;
870     case GST_EVENT_EOS:
871       /* now wait till we played everything */
872       gst_base_audio_sink_drain (sink);
873       break;
874     default:
875       break;
876   }
877   return TRUE;
878 }
879
880 static GstFlowReturn
881 gst_base_audio_sink_preroll (GstBaseSink * bsink, GstBuffer * buffer)
882 {
883   GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (bsink);
884
885   if (!gst_ring_buffer_is_acquired (sink->ringbuffer))
886     goto wrong_state;
887
888   /* we don't really do anything when prerolling. We could make a
889    * property to play this buffer to have some sort of scrubbing
890    * support. */
891   return GST_FLOW_OK;
892
893 wrong_state:
894   {
895     GST_DEBUG_OBJECT (sink, "ringbuffer in wrong state");
896     GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("sink not negotiated."));
897     return GST_FLOW_NOT_NEGOTIATED;
898   }
899 }
900
901 static guint64
902 gst_base_audio_sink_get_offset (GstBaseAudioSink * sink)
903 {
904   guint64 sample;
905   gint writeseg, segdone, sps;
906   gint diff;
907
908   /* assume we can append to the previous sample */
909   sample = sink->next_sample;
910   /* no previous sample, try to insert at position 0 */
911   if (sample == -1)
912     sample = 0;
913
914   sps = sink->ringbuffer->samples_per_seg;
915
916   /* figure out the segment and the offset inside the segment where
917    * the sample should be written. */
918   writeseg = sample / sps;
919
920   /* get the currently processed segment */
921   segdone = g_atomic_int_get (&sink->ringbuffer->segdone)
922       - sink->ringbuffer->segbase;
923
924   /* see how far away it is from the write segment */
925   diff = writeseg - segdone;
926   if (diff < 0) {
927     /* sample would be dropped, position to next playable position */
928     sample = (segdone + 1) * sps;
929   }
930
931   return sample;
932 }
933
934 static GstClockTime
935 clock_convert_external (GstClockTime external, GstClockTime cinternal,
936     GstClockTime cexternal, GstClockTime crate_num, GstClockTime crate_denom)
937 {
938   /* adjust for rate and speed */
939   if (external >= cexternal) {
940     external =
941         gst_util_uint64_scale (external - cexternal, crate_denom, crate_num);
942     external += cinternal;
943   } else {
944     external =
945         gst_util_uint64_scale (cexternal - external, crate_denom, crate_num);
946     if (cinternal > external)
947       external = cinternal - external;
948     else
949       external = 0;
950   }
951   return external;
952 }
953
954 /* algorithm to calculate sample positions that will result in resampling to
955  * match the clock rate of the master */
956 static void
957 gst_base_audio_sink_resample_slaving (GstBaseAudioSink * sink,
958     GstClockTime render_start, GstClockTime render_stop,
959     GstClockTime * srender_start, GstClockTime * srender_stop)
960 {
961   GstClockTime cinternal, cexternal;
962   GstClockTime crate_num, crate_denom;
963
964   /* FIXME, we can sample and add observations here or use the timeouts on the
965    * clock. No idea which one is better or more stable. The timeout seems more
966    * arbitrary but this one seems more demanding and does not work when there is
967    * no data comming in to the sink. */
968 #if 0
969   GstClockTime etime, itime;
970   gdouble r_squared;
971
972   /* sample clocks and figure out clock skew */
973   etime = gst_clock_get_time (GST_ELEMENT_CLOCK (sink));
974   itime = gst_audio_clock_get_time (sink->provided_clock);
975
976   /* add new observation */
977   gst_clock_add_observation (sink->provided_clock, itime, etime, &r_squared);
978 #endif
979
980   /* get calibration parameters to compensate for speed and offset differences
981    * when we are slaved */
982   gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
983       &crate_num, &crate_denom);
984
985   GST_DEBUG_OBJECT (sink, "internal %" GST_TIME_FORMAT " external %"
986       GST_TIME_FORMAT " %" G_GUINT64_FORMAT "/%" G_GUINT64_FORMAT " = %f",
987       GST_TIME_ARGS (cinternal), GST_TIME_ARGS (cexternal), crate_num,
988       crate_denom, gst_guint64_to_gdouble (crate_num) /
989       gst_guint64_to_gdouble (crate_denom));
990
991   if (crate_num == 0)
992     crate_denom = crate_num = 1;
993
994   /* bring external time to internal time */
995   render_start = clock_convert_external (render_start, cinternal, cexternal,
996       crate_num, crate_denom);
997   render_stop = clock_convert_external (render_stop, cinternal, cexternal,
998       crate_num, crate_denom);
999
1000   GST_DEBUG_OBJECT (sink,
1001       "after slaving: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1002       GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1003
1004   *srender_start = render_start;
1005   *srender_stop = render_stop;
1006 }
1007
1008 /* algorithm to calculate sample positions that will result in changing the
1009  * playout pointer to match the clock rate of the master */
1010 static void
1011 gst_base_audio_sink_skew_slaving (GstBaseAudioSink * sink,
1012     GstClockTime render_start, GstClockTime render_stop,
1013     GstClockTime * srender_start, GstClockTime * srender_stop)
1014 {
1015   GstClockTime cinternal, cexternal, crate_num, crate_denom;
1016   GstClockTime etime, itime;
1017   GstClockTimeDiff skew, mdrift, mdrift2;
1018   gint driftsamples;
1019   gint64 last_align;
1020
1021   /* get calibration parameters to compensate for offsets */
1022   gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
1023       &crate_num, &crate_denom);
1024
1025   /* sample clocks and figure out clock skew */
1026   etime = gst_clock_get_time (GST_ELEMENT_CLOCK (sink));
1027   itime = gst_audio_clock_get_time (sink->provided_clock);
1028   itime = gst_audio_clock_adjust (sink->provided_clock, itime);
1029
1030   GST_DEBUG_OBJECT (sink,
1031       "internal %" GST_TIME_FORMAT " external %" GST_TIME_FORMAT
1032       " cinternal %" GST_TIME_FORMAT " cexternal %" GST_TIME_FORMAT,
1033       GST_TIME_ARGS (itime), GST_TIME_ARGS (etime),
1034       GST_TIME_ARGS (cinternal), GST_TIME_ARGS (cexternal));
1035
1036   /* make sure we never go below 0 */
1037   etime = etime > cexternal ? etime - cexternal : 0;
1038   itime = itime > cinternal ? itime - cinternal : 0;
1039
1040   /* do itime - etime.
1041    * positive value means external clock goes slower
1042    * negative value means external clock goes faster */
1043   skew = GST_CLOCK_DIFF (etime, itime);
1044   if (sink->priv->avg_skew == -1) {
1045     /* first observation */
1046     sink->priv->avg_skew = skew;
1047   } else {
1048     /* next observations use a moving average */
1049     sink->priv->avg_skew = (31 * sink->priv->avg_skew + skew) / 32;
1050   }
1051
1052   GST_DEBUG_OBJECT (sink, "internal %" GST_TIME_FORMAT " external %"
1053       GST_TIME_FORMAT " skew %" G_GINT64_FORMAT " avg %" G_GINT64_FORMAT,
1054       GST_TIME_ARGS (itime), GST_TIME_ARGS (etime), skew, sink->priv->avg_skew);
1055
1056   /* the max drift we allow */
1057   mdrift = sink->priv->drift_tolerance * 1000;
1058   mdrift2 = mdrift / 2;
1059
1060   /* adjust playout pointer based on skew */
1061   if (sink->priv->avg_skew > mdrift2) {
1062     /* master is running slower, move internal time forward */
1063     GST_WARNING_OBJECT (sink,
1064         "correct clock skew %" G_GINT64_FORMAT " > %" G_GINT64_FORMAT,
1065         sink->priv->avg_skew, mdrift2);
1066     cexternal = cexternal > mdrift ? cexternal - mdrift : 0;
1067     sink->priv->avg_skew -= mdrift;
1068
1069     driftsamples = (sink->ringbuffer->spec.rate * mdrift) / GST_SECOND;
1070     last_align = sink->priv->last_align;
1071
1072     /* if we were aligning in the wrong direction or we aligned more than what we
1073      * will correct, resync */
1074     if (last_align < 0 || last_align > driftsamples)
1075       sink->next_sample = -1;
1076
1077     GST_DEBUG_OBJECT (sink,
1078         "last_align %" G_GINT64_FORMAT " driftsamples %u, next %"
1079         G_GUINT64_FORMAT, last_align, driftsamples, sink->next_sample);
1080
1081     gst_clock_set_calibration (sink->provided_clock, cinternal, cexternal,
1082         crate_num, crate_denom);
1083   } else if (sink->priv->avg_skew < -mdrift2) {
1084     /* master is running faster, move external time forwards */
1085     GST_WARNING_OBJECT (sink,
1086         "correct clock skew %" G_GINT64_FORMAT " < %" G_GINT64_FORMAT,
1087         sink->priv->avg_skew, -mdrift2);
1088     cexternal += mdrift;
1089     sink->priv->avg_skew += mdrift;
1090
1091     driftsamples = (sink->ringbuffer->spec.rate * mdrift) / GST_SECOND;
1092     last_align = sink->priv->last_align;
1093
1094     /* if we were aligning in the wrong direction or we aligned more than what we
1095      * will correct, resync */
1096     if (last_align > 0 || -last_align > driftsamples)
1097       sink->next_sample = -1;
1098
1099     GST_DEBUG_OBJECT (sink,
1100         "last_align %" G_GINT64_FORMAT " driftsamples %u, next %"
1101         G_GUINT64_FORMAT, last_align, driftsamples, sink->next_sample);
1102
1103     gst_clock_set_calibration (sink->provided_clock, cinternal, cexternal,
1104         crate_num, crate_denom);
1105   }
1106
1107   /* convert, ignoring speed */
1108   render_start = clock_convert_external (render_start, cinternal, cexternal,
1109       crate_num, crate_denom);
1110   render_stop = clock_convert_external (render_stop, cinternal, cexternal,
1111       crate_num, crate_denom);
1112
1113   *srender_start = render_start;
1114   *srender_stop = render_stop;
1115 }
1116
1117 /* apply the clock offset but do no slaving otherwise */
1118 static void
1119 gst_base_audio_sink_none_slaving (GstBaseAudioSink * sink,
1120     GstClockTime render_start, GstClockTime render_stop,
1121     GstClockTime * srender_start, GstClockTime * srender_stop)
1122 {
1123   GstClockTime cinternal, cexternal, crate_num, crate_denom;
1124
1125   /* get calibration parameters to compensate for offsets */
1126   gst_clock_get_calibration (sink->provided_clock, &cinternal, &cexternal,
1127       &crate_num, &crate_denom);
1128
1129   /* convert, ignoring speed */
1130   render_start = clock_convert_external (render_start, cinternal, cexternal,
1131       crate_num, crate_denom);
1132   render_stop = clock_convert_external (render_stop, cinternal, cexternal,
1133       crate_num, crate_denom);
1134
1135   *srender_start = render_start;
1136   *srender_stop = render_stop;
1137 }
1138
1139 /* converts render_start and render_stop to their slaved values */
1140 static void
1141 gst_base_audio_sink_handle_slaving (GstBaseAudioSink * sink,
1142     GstClockTime render_start, GstClockTime render_stop,
1143     GstClockTime * srender_start, GstClockTime * srender_stop)
1144 {
1145   switch (sink->priv->slave_method) {
1146     case GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE:
1147       gst_base_audio_sink_resample_slaving (sink, render_start, render_stop,
1148           srender_start, srender_stop);
1149       break;
1150     case GST_BASE_AUDIO_SINK_SLAVE_SKEW:
1151       gst_base_audio_sink_skew_slaving (sink, render_start, render_stop,
1152           srender_start, srender_stop);
1153       break;
1154     case GST_BASE_AUDIO_SINK_SLAVE_NONE:
1155       gst_base_audio_sink_none_slaving (sink, render_start, render_stop,
1156           srender_start, srender_stop);
1157       break;
1158     default:
1159       g_warning ("unknown slaving method %d", sink->priv->slave_method);
1160       break;
1161   }
1162 }
1163
1164 /* must be called with LOCK */
1165 static GstFlowReturn
1166 gst_base_audio_sink_sync_latency (GstBaseSink * bsink, GstMiniObject * obj)
1167 {
1168   GstClock *clock;
1169   GstClockReturn status;
1170   GstClockTime time, render_delay;
1171   GstFlowReturn ret;
1172   GstBaseAudioSink *sink;
1173   GstClockTime itime, etime;
1174   GstClockTime rate_num, rate_denom;
1175   GstClockTimeDiff jitter;
1176
1177   sink = GST_BASE_AUDIO_SINK (bsink);
1178
1179   clock = GST_ELEMENT_CLOCK (sink);
1180   if (G_UNLIKELY (clock == NULL))
1181     goto no_clock;
1182
1183   /* we provided the global clock, don't need to do anything special */
1184   if (clock == sink->provided_clock)
1185     goto no_slaving;
1186
1187   GST_OBJECT_UNLOCK (sink);
1188
1189   do {
1190     GST_DEBUG_OBJECT (sink, "checking preroll");
1191
1192     ret = gst_base_sink_do_preroll (bsink, obj);
1193     if (ret != GST_FLOW_OK)
1194       goto flushing;
1195
1196     GST_OBJECT_LOCK (sink);
1197     time = sink->priv->us_latency;
1198     GST_OBJECT_UNLOCK (sink);
1199
1200     /* Renderdelay is added onto our own latency, and needs
1201      * to be subtracted as well */
1202     render_delay = gst_base_sink_get_render_delay (bsink);
1203
1204     if (G_LIKELY (time > render_delay))
1205       time -= render_delay;
1206     else
1207       time = 0;
1208
1209     /* preroll done, we can sync since we are in PLAYING now. */
1210     GST_DEBUG_OBJECT (sink, "possibly waiting for clock to reach %"
1211         GST_TIME_FORMAT, GST_TIME_ARGS (time));
1212
1213     /* wait for the clock, this can be interrupted because we got shut down or
1214      * we PAUSED. */
1215     status = gst_base_sink_wait_clock (bsink, time, &jitter);
1216
1217     GST_DEBUG_OBJECT (sink, "clock returned %d %" GST_TIME_FORMAT, status,
1218         GST_TIME_ARGS (jitter));
1219
1220     /* invalid time, no clock or sync disabled, just continue then */
1221     if (status == GST_CLOCK_BADTIME)
1222       break;
1223
1224     /* waiting could have been interrupted and we can be flushing now */
1225     if (G_UNLIKELY (bsink->flushing))
1226       goto flushing;
1227
1228     /* retry if we got unscheduled, which means we did not reach the timeout
1229      * yet. if some other error occures, we continue. */
1230   } while (status == GST_CLOCK_UNSCHEDULED);
1231
1232   GST_OBJECT_LOCK (sink);
1233   GST_DEBUG_OBJECT (sink, "latency synced");
1234
1235   /* when we prerolled in time, we can accurately set the calibration,
1236    * our internal clock should exactly have been the latency (== the running
1237    * time of the external clock) */
1238   etime = GST_ELEMENT_CAST (sink)->base_time + time;
1239   itime = gst_audio_clock_get_time (sink->provided_clock);
1240   itime = gst_audio_clock_adjust (sink->provided_clock, itime);
1241
1242   if (status == GST_CLOCK_EARLY) {
1243     /* when we prerolled late, we have to take into account the lateness */
1244     GST_DEBUG_OBJECT (sink, "late preroll, adding jitter");
1245     etime += jitter;
1246   }
1247
1248   /* start ringbuffer so we can start slaving right away when we need to */
1249   gst_ring_buffer_start (sink->ringbuffer);
1250
1251   GST_DEBUG_OBJECT (sink,
1252       "internal time: %" GST_TIME_FORMAT " external time: %" GST_TIME_FORMAT,
1253       GST_TIME_ARGS (itime), GST_TIME_ARGS (etime));
1254
1255   /* copy the original calibrated rate but update the internal and external
1256    * times. */
1257   gst_clock_get_calibration (sink->provided_clock, NULL, NULL, &rate_num,
1258       &rate_denom);
1259   gst_clock_set_calibration (sink->provided_clock, itime, etime,
1260       rate_num, rate_denom);
1261
1262   switch (sink->priv->slave_method) {
1263     case GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE:
1264       /* only set as master when we are resampling */
1265       GST_DEBUG_OBJECT (sink, "Setting clock as master");
1266       gst_clock_set_master (sink->provided_clock, clock);
1267       break;
1268     case GST_BASE_AUDIO_SINK_SLAVE_SKEW:
1269     case GST_BASE_AUDIO_SINK_SLAVE_NONE:
1270     default:
1271       break;
1272   }
1273
1274   sink->priv->avg_skew = -1;
1275   sink->next_sample = -1;
1276   sink->priv->eos_time = -1;
1277
1278   return GST_FLOW_OK;
1279
1280   /* ERRORS */
1281 no_clock:
1282   {
1283     GST_DEBUG_OBJECT (sink, "we have no clock");
1284     return GST_FLOW_OK;
1285   }
1286 no_slaving:
1287   {
1288     GST_DEBUG_OBJECT (sink, "we are not slaved");
1289     return GST_FLOW_OK;
1290   }
1291 flushing:
1292   {
1293     GST_DEBUG_OBJECT (sink, "we are flushing");
1294     GST_OBJECT_LOCK (sink);
1295     return GST_FLOW_WRONG_STATE;
1296   }
1297 }
1298
1299 static gint64
1300 gst_base_audio_sink_get_alignment (GstBaseAudioSink * sink,
1301     GstClockTime sample_offset)
1302 {
1303   GstRingBuffer *ringbuf = sink->ringbuffer;
1304   gint64 align;
1305   gint64 diff;
1306   gint64 maxdrift;
1307   gint segdone = g_atomic_int_get (&ringbuf->segdone) - ringbuf->segbase;
1308   gint64 samples_done = segdone * ringbuf->samples_per_seg;
1309   gint64 headroom = sample_offset - samples_done;
1310   gboolean allow_align = TRUE;
1311
1312   /* now try to align the sample to the previous one, first see how big the
1313    * difference is. */
1314   if (sample_offset >= sink->next_sample)
1315     diff = sample_offset - sink->next_sample;
1316   else
1317     diff = sink->next_sample - sample_offset;
1318
1319   /* calculate the max allowed drift in units of samples. By default this is
1320    * 20ms and should be anough to compensate for timestamp rounding errors. */
1321   maxdrift = (ringbuf->spec.rate * sink->priv->drift_tolerance) / GST_MSECOND;
1322
1323   /* calc align with previous sample */
1324   align = sink->next_sample - sample_offset;
1325
1326   /* don't align if it means writing behind the read-segment */
1327   if (diff > headroom && align < 0)
1328     allow_align = FALSE;
1329
1330   if (G_LIKELY (diff < maxdrift && allow_align)) {
1331     GST_DEBUG_OBJECT (sink,
1332         "align with prev sample, ABS (%" G_GINT64_FORMAT ") < %"
1333         G_GINT64_FORMAT, align, maxdrift);
1334   } else {
1335     /* calculate sample diff in seconds for error message */
1336     gint64 diff_s =
1337         gst_util_uint64_scale_int (diff, GST_SECOND, ringbuf->spec.rate);
1338     /* timestamps drifted apart from previous samples too much, we need to
1339      * resync. We log this as an element warning. */
1340     GST_WARNING_OBJECT (sink,
1341         "Unexpected discontinuity in audio timestamps of "
1342         "%s%" GST_TIME_FORMAT ", resyncing",
1343         sample_offset > sink->next_sample ? "+" : "-", GST_TIME_ARGS (diff_s));
1344     align = 0;
1345   }
1346
1347   return align;
1348 }
1349
1350 static GstFlowReturn
1351 gst_base_audio_sink_render (GstBaseSink * bsink, GstBuffer * buf)
1352 {
1353   guint64 in_offset;
1354   GstClockTime time, stop, render_start, render_stop, sample_offset;
1355   GstClockTimeDiff sync_offset, ts_offset;
1356   GstBaseAudioSinkClass *bclass;
1357   GstBaseAudioSink *sink;
1358   GstRingBuffer *ringbuf;
1359   gint64 diff, align;
1360   guint64 ctime, cstop;
1361   gsize offset;
1362   guint8 *data;
1363   gsize size;
1364   guint samples, written;
1365   gint bps;
1366   gint accum;
1367   gint out_samples;
1368   GstClockTime base_time, render_delay, latency;
1369   GstClock *clock;
1370   gboolean sync, slaved, align_next;
1371   GstFlowReturn ret;
1372   GstSegment clip_seg;
1373   gint64 time_offset;
1374   GstBuffer *out = NULL;
1375
1376   sink = GST_BASE_AUDIO_SINK (bsink);
1377   bclass = GST_BASE_AUDIO_SINK_GET_CLASS (sink);
1378
1379   ringbuf = sink->ringbuffer;
1380
1381   /* can't do anything when we don't have the device */
1382   if (G_UNLIKELY (!gst_ring_buffer_is_acquired (ringbuf)))
1383     goto wrong_state;
1384
1385   /* Wait for upstream latency before starting the ringbuffer, we do this so
1386    * that we can align the first sample of the ringbuffer to the base_time +
1387    * latency. */
1388   GST_OBJECT_LOCK (sink);
1389   base_time = GST_ELEMENT_CAST (sink)->base_time;
1390   if (G_UNLIKELY (sink->priv->sync_latency)) {
1391     ret = gst_base_audio_sink_sync_latency (bsink, GST_MINI_OBJECT_CAST (buf));
1392     GST_OBJECT_UNLOCK (sink);
1393     if (G_UNLIKELY (ret != GST_FLOW_OK))
1394       goto sync_latency_failed;
1395     /* only do this once until we are set back to PLAYING */
1396     sink->priv->sync_latency = FALSE;
1397   } else {
1398     GST_OBJECT_UNLOCK (sink);
1399   }
1400
1401   /* Before we go on, let's see if we need to payload the data. If yes, we also
1402    * need to unref the output buffer before leaving. */
1403   if (bclass->payload) {
1404     out = bclass->payload (sink, buf);
1405
1406     if (!out)
1407       goto payload_failed;
1408
1409     buf = out;
1410   }
1411
1412   bps = ringbuf->spec.bytes_per_sample;
1413
1414   size = gst_buffer_get_size (buf);
1415   if (G_UNLIKELY (size % bps) != 0)
1416     goto wrong_size;
1417
1418   samples = size / bps;
1419   out_samples = samples;
1420
1421   in_offset = GST_BUFFER_OFFSET (buf);
1422   time = GST_BUFFER_TIMESTAMP (buf);
1423
1424   GST_DEBUG_OBJECT (sink,
1425       "time %" GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT ", start %"
1426       GST_TIME_FORMAT ", samples %u", GST_TIME_ARGS (time), in_offset,
1427       GST_TIME_ARGS (bsink->segment.start), samples);
1428
1429   offset = 0;
1430
1431   /* if not valid timestamp or we can't clip or sync, try to play
1432    * sample ASAP */
1433   if (!GST_CLOCK_TIME_IS_VALID (time)) {
1434     render_start = gst_base_audio_sink_get_offset (sink);
1435     render_stop = render_start + samples;
1436     GST_DEBUG_OBJECT (sink,
1437         "Buffer of size %u has no time. Using render_start=%" G_GUINT64_FORMAT,
1438         size, render_start);
1439     /* we don't have a start so we don't know stop either */
1440     stop = -1;
1441     goto no_sync;
1442   }
1443
1444   /* let's calc stop based on the number of samples in the buffer instead
1445    * of trusting the DURATION */
1446   stop = time + gst_util_uint64_scale_int (samples, GST_SECOND,
1447       ringbuf->spec.rate);
1448
1449   /* prepare the clipping segment. Since we will be subtracting ts-offset and
1450    * device-delay later we scale the start and stop with those values so that we
1451    * can correctly clip them */
1452   clip_seg.format = GST_FORMAT_TIME;
1453   clip_seg.start = bsink->segment.start;
1454   clip_seg.stop = bsink->segment.stop;
1455   clip_seg.duration = -1;
1456
1457   /* the sync offset is the combination of ts-offset and device-delay */
1458   latency = gst_base_sink_get_latency (bsink);
1459   ts_offset = gst_base_sink_get_ts_offset (bsink);
1460   render_delay = gst_base_sink_get_render_delay (bsink);
1461   sync_offset = ts_offset - render_delay + latency;
1462
1463   GST_DEBUG_OBJECT (sink,
1464       "sync-offset %" G_GINT64_FORMAT ", render-delay %" GST_TIME_FORMAT
1465       ", ts-offset %" G_GINT64_FORMAT, sync_offset,
1466       GST_TIME_ARGS (render_delay), ts_offset);
1467
1468   /* compensate for ts-offset and device-delay when negative we need to
1469    * clip. */
1470   if (sync_offset < 0) {
1471     clip_seg.start += -sync_offset;
1472     if (clip_seg.stop != -1)
1473       clip_seg.stop += -sync_offset;
1474   }
1475
1476   /* samples should be rendered based on their timestamp. All samples
1477    * arriving before the segment.start or after segment.stop are to be
1478    * thrown away. All samples should also be clipped to the segment
1479    * boundaries */
1480   if (!gst_segment_clip (&clip_seg, GST_FORMAT_TIME, time, stop, &ctime,
1481           &cstop))
1482     goto out_of_segment;
1483
1484   /* see if some clipping happened */
1485   diff = ctime - time;
1486   if (diff > 0) {
1487     /* bring clipped time to samples */
1488     diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1489     GST_DEBUG_OBJECT (sink, "clipping start to %" GST_TIME_FORMAT " %"
1490         G_GUINT64_FORMAT " samples", GST_TIME_ARGS (ctime), diff);
1491     samples -= diff;
1492     offset += diff * bps;
1493     time = ctime;
1494   }
1495   diff = stop - cstop;
1496   if (diff > 0) {
1497     /* bring clipped time to samples */
1498     diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1499     GST_DEBUG_OBJECT (sink, "clipping stop to %" GST_TIME_FORMAT " %"
1500         G_GUINT64_FORMAT " samples", GST_TIME_ARGS (cstop), diff);
1501     samples -= diff;
1502     stop = cstop;
1503   }
1504
1505   /* figure out how to sync */
1506   if ((clock = GST_ELEMENT_CLOCK (bsink)))
1507     sync = bsink->sync;
1508   else
1509     sync = FALSE;
1510
1511   if (!sync) {
1512     /* no sync needed, play sample ASAP */
1513     render_start = gst_base_audio_sink_get_offset (sink);
1514     render_stop = render_start + samples;
1515     GST_DEBUG_OBJECT (sink,
1516         "no sync needed. Using render_start=%" G_GUINT64_FORMAT, render_start);
1517     goto no_sync;
1518   }
1519
1520   /* bring buffer start and stop times to running time */
1521   render_start =
1522       gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, time);
1523   render_stop =
1524       gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, stop);
1525
1526   GST_DEBUG_OBJECT (sink,
1527       "running: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1528       GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1529
1530   /* store the time of the last sample, we'll use this to perform sync on the
1531    * last sample when draining the buffer */
1532   if (bsink->segment.rate >= 0.0) {
1533     sink->priv->eos_time = render_stop;
1534   } else {
1535     sink->priv->eos_time = render_start;
1536   }
1537
1538   /* compensate for ts-offset and delay we know this will not underflow because we
1539    * clipped above. */
1540   GST_DEBUG_OBJECT (sink,
1541       "compensating for sync-offset %" GST_TIME_FORMAT,
1542       GST_TIME_ARGS (sync_offset));
1543   render_start += sync_offset;
1544   render_stop += sync_offset;
1545
1546   GST_DEBUG_OBJECT (sink, "adding base_time %" GST_TIME_FORMAT,
1547       GST_TIME_ARGS (base_time));
1548
1549   /* add base time to sync against the clock */
1550   render_start += base_time;
1551   render_stop += base_time;
1552
1553   GST_DEBUG_OBJECT (sink,
1554       "after compensation: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1555       GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1556
1557   if ((slaved = clock != sink->provided_clock)) {
1558     /* handle clock slaving */
1559     gst_base_audio_sink_handle_slaving (sink, render_start, render_stop,
1560         &render_start, &render_stop);
1561   } else {
1562     /* no slaving needed but we need to adapt to the clock calibration
1563      * parameters */
1564     gst_base_audio_sink_none_slaving (sink, render_start, render_stop,
1565         &render_start, &render_stop);
1566   }
1567
1568   GST_DEBUG_OBJECT (sink,
1569       "final timestamps: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1570       GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1571
1572   /* bring to position in the ringbuffer */
1573   time_offset =
1574       GST_AUDIO_CLOCK_CAST (sink->provided_clock)->abidata.ABI.time_offset;
1575   GST_DEBUG_OBJECT (sink,
1576       "time offset %" GST_TIME_FORMAT, GST_TIME_ARGS (time_offset));
1577   if (render_start > time_offset)
1578     render_start -= time_offset;
1579   else
1580     render_start = 0;
1581   if (render_stop > time_offset)
1582     render_stop -= time_offset;
1583   else
1584     render_stop = 0;
1585
1586   /* and bring the time to the rate corrected offset in the buffer */
1587   render_start = gst_util_uint64_scale_int (render_start,
1588       ringbuf->spec.rate, GST_SECOND);
1589   render_stop = gst_util_uint64_scale_int (render_stop,
1590       ringbuf->spec.rate, GST_SECOND);
1591
1592   /* positive playback rate, first sample is render_start, negative rate, first
1593    * sample is render_stop. When no rate conversion is active, render exactly
1594    * the amount of input samples to avoid aligning to rounding errors. */
1595   if (bsink->segment.rate >= 0.0) {
1596     sample_offset = render_start;
1597     if (bsink->segment.rate == 1.0)
1598       render_stop = sample_offset + samples;
1599   } else {
1600     sample_offset = render_stop;
1601     if (bsink->segment.rate == -1.0)
1602       render_start = sample_offset + samples;
1603   }
1604
1605   /* always resync after a discont */
1606   if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT))) {
1607     GST_DEBUG_OBJECT (sink, "resync after discont");
1608     goto no_align;
1609   }
1610
1611   /* resync when we don't know what to align the sample with */
1612   if (G_UNLIKELY (sink->next_sample == -1)) {
1613     GST_DEBUG_OBJECT (sink,
1614         "no align possible: no previous sample position known");
1615     goto no_align;
1616   }
1617
1618   align = gst_base_audio_sink_get_alignment (sink, sample_offset);
1619   sink->priv->last_align = align;
1620
1621   /* apply alignment */
1622   render_start += align;
1623
1624   /* only align stop if we are not slaved to resample */
1625   if (slaved && sink->priv->slave_method == GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE) {
1626     GST_DEBUG_OBJECT (sink, "no stop time align needed: we are slaved");
1627     goto no_align;
1628   }
1629   render_stop += align;
1630
1631 no_align:
1632   /* number of target samples is difference between start and stop */
1633   out_samples = render_stop - render_start;
1634
1635 no_sync:
1636   /* we render the first or last sample first, depending on the rate */
1637   if (bsink->segment.rate >= 0.0)
1638     sample_offset = render_start;
1639   else
1640     sample_offset = render_stop;
1641
1642   GST_DEBUG_OBJECT (sink, "rendering at %" G_GUINT64_FORMAT " %d/%d",
1643       sample_offset, samples, out_samples);
1644
1645   /* we need to accumulate over different runs for when we get interrupted */
1646   accum = 0;
1647   align_next = TRUE;
1648   data = gst_buffer_map (buf, &size, NULL, GST_MAP_READ);
1649   do {
1650     written =
1651         gst_ring_buffer_commit_full (ringbuf, &sample_offset, data + offset,
1652         samples, out_samples, &accum);
1653
1654     GST_DEBUG_OBJECT (sink, "wrote %u of %u", written, samples);
1655     /* if we wrote all, we're done */
1656     if (written == samples)
1657       break;
1658
1659     /* else something interrupted us and we wait for preroll. */
1660     if ((ret = gst_base_sink_wait_preroll (bsink)) != GST_FLOW_OK)
1661       goto stopping;
1662
1663     /* if we got interrupted, we cannot assume that the next sample should
1664      * be aligned to this one */
1665     align_next = FALSE;
1666
1667     /* update the output samples. FIXME, this will just skip them when pausing
1668      * during trick mode */
1669     if (out_samples > written) {
1670       out_samples -= written;
1671       accum = 0;
1672     } else
1673       break;
1674
1675     samples -= written;
1676     offset += written * bps;
1677   } while (TRUE);
1678   gst_buffer_unmap (buf, data, size);
1679
1680   if (align_next)
1681     sink->next_sample = sample_offset;
1682   else
1683     sink->next_sample = -1;
1684
1685   GST_DEBUG_OBJECT (sink, "next sample expected at %" G_GUINT64_FORMAT,
1686       sink->next_sample);
1687
1688   if (GST_CLOCK_TIME_IS_VALID (stop) && stop >= bsink->segment.stop) {
1689     GST_DEBUG_OBJECT (sink,
1690         "start playback because we are at the end of segment");
1691     gst_ring_buffer_start (ringbuf);
1692   }
1693
1694   ret = GST_FLOW_OK;
1695
1696 done:
1697   if (out)
1698     gst_buffer_unref (out);
1699
1700   return ret;
1701
1702   /* SPECIAL cases */
1703 out_of_segment:
1704   {
1705     GST_DEBUG_OBJECT (sink,
1706         "dropping sample out of segment time %" GST_TIME_FORMAT ", start %"
1707         GST_TIME_FORMAT, GST_TIME_ARGS (time),
1708         GST_TIME_ARGS (bsink->segment.start));
1709     ret = GST_FLOW_OK;
1710     goto done;
1711   }
1712   /* ERRORS */
1713 payload_failed:
1714   {
1715     GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("failed to payload."));
1716     ret = GST_FLOW_ERROR;
1717     goto done;
1718   }
1719 wrong_state:
1720   {
1721     GST_DEBUG_OBJECT (sink, "ringbuffer not negotiated");
1722     GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("sink not negotiated."));
1723     ret = GST_FLOW_NOT_NEGOTIATED;
1724     goto done;
1725   }
1726 wrong_size:
1727   {
1728     GST_DEBUG_OBJECT (sink, "wrong size");
1729     GST_ELEMENT_ERROR (sink, STREAM, WRONG_TYPE,
1730         (NULL), ("sink received buffer of wrong size."));
1731     ret = GST_FLOW_ERROR;
1732     goto done;
1733   }
1734 stopping:
1735   {
1736     GST_DEBUG_OBJECT (sink, "preroll got interrupted: %d (%s)", ret,
1737         gst_flow_get_name (ret));
1738     gst_buffer_unmap (buf, data, size);
1739     goto done;
1740   }
1741 sync_latency_failed:
1742   {
1743     GST_DEBUG_OBJECT (sink, "failed waiting for latency");
1744     goto done;
1745   }
1746 }
1747
1748 /**
1749  * gst_base_audio_sink_create_ringbuffer:
1750  * @sink: a #GstBaseAudioSink.
1751  *
1752  * Create and return the #GstRingBuffer for @sink. This function will call the
1753  * ::create_ringbuffer vmethod and will set @sink as the parent of the returned
1754  * buffer (see gst_object_set_parent()).
1755  *
1756  * Returns: The new ringbuffer of @sink.
1757  */
1758 GstRingBuffer *
1759 gst_base_audio_sink_create_ringbuffer (GstBaseAudioSink * sink)
1760 {
1761   GstBaseAudioSinkClass *bclass;
1762   GstRingBuffer *buffer = NULL;
1763
1764   bclass = GST_BASE_AUDIO_SINK_GET_CLASS (sink);
1765   if (bclass->create_ringbuffer)
1766     buffer = bclass->create_ringbuffer (sink);
1767
1768   if (buffer)
1769     gst_object_set_parent (GST_OBJECT (buffer), GST_OBJECT (sink));
1770
1771   return buffer;
1772 }
1773
1774 static void
1775 gst_base_audio_sink_callback (GstRingBuffer * rbuf, guint8 * data, guint len,
1776     gpointer user_data)
1777 {
1778   GstBaseSink *basesink;
1779   GstBaseAudioSink *sink;
1780   GstBuffer *buf;
1781   GstFlowReturn ret;
1782   gsize size;
1783
1784   basesink = GST_BASE_SINK (user_data);
1785   sink = GST_BASE_AUDIO_SINK (user_data);
1786
1787   GST_PAD_STREAM_LOCK (basesink->sinkpad);
1788
1789   /* would be nice to arrange for pad_alloc_buffer to return data -- as it is we
1790      will copy twice, once into data, once into DMA */
1791   GST_LOG_OBJECT (basesink, "pulling %d bytes offset %" G_GUINT64_FORMAT
1792       " to fill audio buffer", len, basesink->offset);
1793   ret =
1794       gst_pad_pull_range (basesink->sinkpad, basesink->segment.position, len,
1795       &buf);
1796
1797   if (ret != GST_FLOW_OK) {
1798     if (ret == GST_FLOW_UNEXPECTED)
1799       goto eos;
1800     else
1801       goto error;
1802   }
1803
1804   GST_BASE_SINK_PREROLL_LOCK (basesink);
1805   if (basesink->flushing)
1806     goto flushing;
1807
1808   /* complete preroll and wait for PLAYING */
1809   ret = gst_base_sink_do_preroll (basesink, GST_MINI_OBJECT_CAST (buf));
1810   if (ret != GST_FLOW_OK)
1811     goto preroll_error;
1812
1813   size = gst_buffer_get_size (buf);
1814
1815   if (len != size) {
1816     GST_INFO_OBJECT (basesink,
1817         "got different size than requested from sink pad: %u != %u", len, size);
1818     len = MIN (size, len);
1819   }
1820
1821   basesink->segment.position += len;
1822
1823   gst_buffer_extract (buf, 0, data, len);
1824   GST_BASE_SINK_PREROLL_UNLOCK (basesink);
1825
1826   GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1827
1828   return;
1829
1830 error:
1831   {
1832     GST_WARNING_OBJECT (basesink, "Got flow '%s' but can't return it: %d",
1833         gst_flow_get_name (ret), ret);
1834     gst_ring_buffer_pause (rbuf);
1835     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1836     return;
1837   }
1838 eos:
1839   {
1840     /* FIXME: this is not quite correct; we'll be called endlessly until
1841      * the sink gets shut down; maybe we should set a flag somewhere, or
1842      * set segment.stop and segment.duration to the last sample or so */
1843     GST_DEBUG_OBJECT (sink, "EOS");
1844     gst_base_audio_sink_drain (sink);
1845     gst_ring_buffer_pause (rbuf);
1846     gst_element_post_message (GST_ELEMENT_CAST (sink),
1847         gst_message_new_eos (GST_OBJECT_CAST (sink)));
1848     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1849   }
1850 flushing:
1851   {
1852     GST_DEBUG_OBJECT (sink, "we are flushing");
1853     gst_ring_buffer_pause (rbuf);
1854     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
1855     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1856     return;
1857   }
1858 preroll_error:
1859   {
1860     GST_DEBUG_OBJECT (sink, "error %s", gst_flow_get_name (ret));
1861     gst_ring_buffer_pause (rbuf);
1862     GST_BASE_SINK_PREROLL_UNLOCK (basesink);
1863     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
1864     return;
1865   }
1866 }
1867
1868 static gboolean
1869 gst_base_audio_sink_activate_pull (GstBaseSink * basesink, gboolean active)
1870 {
1871   gboolean ret;
1872   GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (basesink);
1873
1874   if (active) {
1875     GST_DEBUG_OBJECT (basesink, "activating pull");
1876
1877     gst_ring_buffer_set_callback (sink->ringbuffer,
1878         gst_base_audio_sink_callback, sink);
1879
1880     ret = gst_ring_buffer_activate (sink->ringbuffer, TRUE);
1881   } else {
1882     GST_DEBUG_OBJECT (basesink, "deactivating pull");
1883     gst_ring_buffer_set_callback (sink->ringbuffer, NULL, NULL);
1884     ret = gst_ring_buffer_activate (sink->ringbuffer, FALSE);
1885   }
1886
1887   return ret;
1888 }
1889
1890 #if 0
1891 /* should be called with the LOCK */
1892 static GstStateChangeReturn
1893 gst_base_audio_sink_async_play (GstBaseSink * basesink)
1894 {
1895   GstBaseAudioSink *sink;
1896
1897   sink = GST_BASE_AUDIO_SINK (basesink);
1898
1899   GST_DEBUG_OBJECT (sink, "ringbuffer may start now");
1900   sink->priv->sync_latency = TRUE;
1901   gst_ring_buffer_may_start (sink->ringbuffer, TRUE);
1902   if (basesink->pad_mode == GST_ACTIVATE_PULL) {
1903     /* we always start the ringbuffer in pull mode immediatly */
1904     gst_ring_buffer_start (sink->ringbuffer);
1905   }
1906
1907   return GST_STATE_CHANGE_SUCCESS;
1908 }
1909 #endif
1910
1911 static GstStateChangeReturn
1912 gst_base_audio_sink_change_state (GstElement * element,
1913     GstStateChange transition)
1914 {
1915   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1916   GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (element);
1917
1918   switch (transition) {
1919     case GST_STATE_CHANGE_NULL_TO_READY:
1920       if (sink->ringbuffer == NULL) {
1921         gst_audio_clock_reset (GST_AUDIO_CLOCK (sink->provided_clock), 0);
1922         sink->ringbuffer = gst_base_audio_sink_create_ringbuffer (sink);
1923       }
1924       if (!gst_ring_buffer_open_device (sink->ringbuffer))
1925         goto open_failed;
1926       break;
1927     case GST_STATE_CHANGE_READY_TO_PAUSED:
1928       sink->next_sample = -1;
1929       sink->priv->last_align = -1;
1930       sink->priv->eos_time = -1;
1931       gst_ring_buffer_set_flushing (sink->ringbuffer, FALSE);
1932       gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
1933
1934       /* Only post clock-provide messages if this is the clock that
1935        * we've created. If the subclass has overriden it the subclass
1936        * should post this messages whenever necessary */
1937       if (sink->provided_clock && GST_IS_AUDIO_CLOCK (sink->provided_clock) &&
1938           GST_AUDIO_CLOCK_CAST (sink->provided_clock)->func ==
1939           (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time)
1940         gst_element_post_message (element,
1941             gst_message_new_clock_provide (GST_OBJECT_CAST (element),
1942                 sink->provided_clock, TRUE));
1943       break;
1944     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1945     {
1946       gboolean eos;
1947
1948       GST_OBJECT_LOCK (sink);
1949       GST_DEBUG_OBJECT (sink, "ringbuffer may start now");
1950       sink->priv->sync_latency = TRUE;
1951       eos = GST_BASE_SINK (sink)->eos;
1952       GST_OBJECT_UNLOCK (sink);
1953
1954       gst_ring_buffer_may_start (sink->ringbuffer, TRUE);
1955       if (GST_BASE_SINK_CAST (sink)->pad_mode == GST_ACTIVATE_PULL ||
1956           g_atomic_int_get (&sink->abidata.ABI.eos_rendering) || eos) {
1957         /* we always start the ringbuffer in pull mode immediatly */
1958         /* sync rendering on eos needs running clock,
1959          * and others need running clock when finished rendering eos */
1960         gst_ring_buffer_start (sink->ringbuffer);
1961       }
1962       break;
1963     }
1964     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1965       /* ringbuffer cannot start anymore */
1966       gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
1967       gst_ring_buffer_pause (sink->ringbuffer);
1968
1969       GST_OBJECT_LOCK (sink);
1970       sink->priv->sync_latency = FALSE;
1971       GST_OBJECT_UNLOCK (sink);
1972       break;
1973     case GST_STATE_CHANGE_PAUSED_TO_READY:
1974       /* Only post clock-lost messages if this is the clock that
1975        * we've created. If the subclass has overriden it the subclass
1976        * should post this messages whenever necessary */
1977       if (sink->provided_clock && GST_IS_AUDIO_CLOCK (sink->provided_clock) &&
1978           GST_AUDIO_CLOCK_CAST (sink->provided_clock)->func ==
1979           (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time)
1980         gst_element_post_message (element,
1981             gst_message_new_clock_lost (GST_OBJECT_CAST (element),
1982                 sink->provided_clock));
1983
1984       /* make sure we unblock before calling the parent state change
1985        * so it can grab the STREAM_LOCK */
1986       gst_ring_buffer_set_flushing (sink->ringbuffer, TRUE);
1987       break;
1988     default:
1989       break;
1990   }
1991
1992   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1993
1994   switch (transition) {
1995     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1996       /* stop slaving ourselves to the master, if any */
1997       gst_clock_set_master (sink->provided_clock, NULL);
1998       break;
1999     case GST_STATE_CHANGE_PAUSED_TO_READY:
2000       gst_ring_buffer_activate (sink->ringbuffer, FALSE);
2001       gst_ring_buffer_release (sink->ringbuffer);
2002       break;
2003     case GST_STATE_CHANGE_READY_TO_NULL:
2004       /* we release again here because the aqcuire happens when setting the
2005        * caps, which happens before we commit the state to PAUSED and thus the
2006        * PAUSED->READY state change (see above, where we release the ringbuffer)
2007        * might not be called when we get here. */
2008       gst_ring_buffer_activate (sink->ringbuffer, FALSE);
2009       gst_ring_buffer_release (sink->ringbuffer);
2010       gst_ring_buffer_close_device (sink->ringbuffer);
2011       GST_OBJECT_LOCK (sink);
2012       gst_object_unparent (GST_OBJECT_CAST (sink->ringbuffer));
2013       sink->ringbuffer = NULL;
2014       GST_OBJECT_UNLOCK (sink);
2015       break;
2016     default:
2017       break;
2018   }
2019
2020   return ret;
2021
2022   /* ERRORS */
2023 open_failed:
2024   {
2025     /* subclass must post a meaningfull error message */
2026     GST_DEBUG_OBJECT (sink, "open failed");
2027     return GST_STATE_CHANGE_FAILURE;
2028   }
2029 }