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