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