tizen 2.3.1 release
[framework/multimedia/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   if (sink->priv->slave_method != GST_BASE_AUDIO_SINK_SLAVE_NONE)
1442     gst_ring_buffer_start (sink->ringbuffer);
1443
1444   GST_DEBUG_OBJECT (sink,
1445       "internal time: %" GST_TIME_FORMAT " external time: %" GST_TIME_FORMAT,
1446       GST_TIME_ARGS (itime), GST_TIME_ARGS (etime));
1447
1448   /* copy the original calibrated rate but update the internal and external
1449    * times. */
1450   gst_clock_get_calibration (sink->provided_clock, NULL, NULL, &rate_num,
1451       &rate_denom);
1452   gst_clock_set_calibration (sink->provided_clock, itime, etime,
1453       rate_num, rate_denom);
1454
1455   switch (sink->priv->slave_method) {
1456     case GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE:
1457       /* only set as master when we are resampling */
1458       GST_DEBUG_OBJECT (sink, "Setting clock as master");
1459       gst_clock_set_master (sink->provided_clock, clock);
1460       break;
1461     case GST_BASE_AUDIO_SINK_SLAVE_SKEW:
1462     case GST_BASE_AUDIO_SINK_SLAVE_NONE:
1463     default:
1464       break;
1465   }
1466
1467   sink->priv->avg_skew = -1;
1468   sink->next_sample = -1;
1469   sink->priv->eos_time = -1;
1470   sink->priv->discont_time = -1;
1471
1472   return GST_FLOW_OK;
1473
1474   /* ERRORS */
1475 no_clock:
1476   {
1477     GST_DEBUG_OBJECT (sink, "we have no clock");
1478     return GST_FLOW_OK;
1479   }
1480 no_slaving:
1481   {
1482     GST_DEBUG_OBJECT (sink, "we are not slaved");
1483     return GST_FLOW_OK;
1484   }
1485 flushing:
1486   {
1487     GST_DEBUG_OBJECT (sink, "we are flushing");
1488     GST_OBJECT_LOCK (sink);
1489     return GST_FLOW_WRONG_STATE;
1490   }
1491 }
1492
1493 static gint64
1494 gst_base_audio_sink_get_alignment (GstBaseAudioSink * sink,
1495     GstClockTime sample_offset)
1496 {
1497   GstRingBuffer *ringbuf = sink->ringbuffer;
1498   gint64 align;
1499   gint64 sample_diff;
1500   gint64 max_sample_diff;
1501   gint segdone = g_atomic_int_get (&ringbuf->segdone) - ringbuf->segbase;
1502   gint64 samples_done = segdone * ringbuf->samples_per_seg;
1503   gint64 headroom = sample_offset - samples_done;
1504   gboolean allow_align = TRUE;
1505   gboolean discont = FALSE;
1506
1507   /* now try to align the sample to the previous one, first see how big the
1508    * difference is. */
1509   if (sample_offset >= sink->next_sample)
1510     sample_diff = sample_offset - sink->next_sample;
1511   else
1512     sample_diff = sink->next_sample - sample_offset;
1513
1514   /* calculate the max allowed drift in units of samples. */
1515   max_sample_diff = gst_util_uint64_scale_int (sink->priv->alignment_threshold,
1516       ringbuf->spec.rate, GST_SECOND);
1517
1518   /* calc align with previous sample */
1519   align = sink->next_sample - sample_offset;
1520
1521   /* don't align if it means writing behind the read-segment */
1522   if (sample_diff > headroom && align < 0)
1523     allow_align = FALSE;
1524
1525   if (G_UNLIKELY (sample_diff >= max_sample_diff)) {
1526     /* wait before deciding to make a discontinuity */
1527     if (sink->priv->discont_wait > 0) {
1528       GstClockTime time = gst_util_uint64_scale_int (sample_offset,
1529           GST_SECOND, ringbuf->spec.rate);
1530       if (sink->priv->discont_time == -1) {
1531         /* discont candidate */
1532         sink->priv->discont_time = time;
1533       } else if (time - sink->priv->discont_time >= sink->priv->discont_wait) {
1534         /* discont_wait expired, discontinuity detected */
1535         discont = TRUE;
1536         sink->priv->discont_time = -1;
1537       }
1538     } else {
1539       discont = TRUE;
1540     }
1541   } else if (G_UNLIKELY (sink->priv->discont_time != -1)) {
1542     /* we have had a discont, but are now back on track! */
1543     sink->priv->discont_time = -1;
1544   }
1545
1546   if (G_LIKELY (!discont && allow_align)) {
1547     GST_DEBUG_OBJECT (sink,
1548         "align with prev sample, ABS (%" G_GINT64_FORMAT ") < %"
1549         G_GINT64_FORMAT, align, max_sample_diff);
1550   } else {
1551     gint64 diff_s G_GNUC_UNUSED;
1552
1553     /* calculate sample diff in seconds for error message */
1554     diff_s =
1555         gst_util_uint64_scale_int (sample_diff, GST_SECOND, ringbuf->spec.rate);
1556
1557     /* timestamps drifted apart from previous samples too much, we need to
1558      * resync. We log this as an element warning. */
1559     GST_WARNING_OBJECT (sink,
1560         "Unexpected discontinuity in audio timestamps of "
1561         "%s%" GST_TIME_FORMAT ", resyncing",
1562         sample_offset > sink->next_sample ? "+" : "-", GST_TIME_ARGS (diff_s));
1563     align = 0;
1564   }
1565
1566   return align;
1567 }
1568
1569 static GstFlowReturn
1570 gst_base_audio_sink_render (GstBaseSink * bsink, GstBuffer * buf)
1571 {
1572   guint64 in_offset;
1573   GstClockTime time, stop, render_start, render_stop, sample_offset;
1574   GstClockTimeDiff sync_offset, ts_offset;
1575   GstBaseAudioSinkClass *bclass;
1576   GstBaseAudioSink *sink;
1577   GstRingBuffer *ringbuf;
1578   gint64 diff, align, ctime, cstop;
1579   guint8 *data;
1580   guint size;
1581   guint samples, written;
1582   gint bps;
1583   gint accum;
1584   gint out_samples;
1585   GstClockTime base_time, render_delay, latency;
1586   GstClock *clock;
1587   gboolean sync, slaved, align_next;
1588   GstFlowReturn ret;
1589   GstSegment clip_seg;
1590   gint64 time_offset;
1591   GstBuffer *out = NULL;
1592
1593   sink = GST_BASE_AUDIO_SINK (bsink);
1594   bclass = GST_BASE_AUDIO_SINK_GET_CLASS (sink);
1595
1596   ringbuf = sink->ringbuffer;
1597
1598   /* can't do anything when we don't have the device */
1599   if (G_UNLIKELY (!gst_ring_buffer_is_acquired (ringbuf)))
1600     goto wrong_state;
1601
1602   /* Wait for upstream latency before starting the ringbuffer, we do this so
1603    * that we can align the first sample of the ringbuffer to the base_time +
1604    * latency. */
1605   GST_OBJECT_LOCK (sink);
1606   base_time = GST_ELEMENT_CAST (sink)->base_time;
1607   if (G_UNLIKELY (sink->priv->sync_latency)) {
1608     ret = gst_base_audio_sink_sync_latency (bsink, GST_MINI_OBJECT_CAST (buf));
1609     GST_OBJECT_UNLOCK (sink);
1610     if (G_UNLIKELY (ret != GST_FLOW_OK))
1611       goto sync_latency_failed;
1612     /* only do this once until we are set back to PLAYING */
1613     sink->priv->sync_latency = FALSE;
1614   } else {
1615     GST_OBJECT_UNLOCK (sink);
1616   }
1617
1618   /* Before we go on, let's see if we need to payload the data. If yes, we also
1619    * need to unref the output buffer before leaving. */
1620   if (bclass->payload) {
1621     out = bclass->payload (sink, buf);
1622
1623     if (!out)
1624       goto payload_failed;
1625
1626     buf = out;
1627   }
1628
1629   bps = ringbuf->spec.bytes_per_sample;
1630
1631   size = GST_BUFFER_SIZE (buf);
1632   if (G_UNLIKELY (size % bps) != 0)
1633     goto wrong_size;
1634
1635   samples = size / bps;
1636   out_samples = samples;
1637
1638   in_offset = GST_BUFFER_OFFSET (buf);
1639   time = GST_BUFFER_TIMESTAMP (buf);
1640
1641   GST_DEBUG_OBJECT (sink,
1642       "time %" GST_TIME_FORMAT ", offset %" G_GUINT64_FORMAT ", start %"
1643       GST_TIME_FORMAT ", samples %u", GST_TIME_ARGS (time), in_offset,
1644       GST_TIME_ARGS (bsink->segment.start), samples);
1645
1646   data = GST_BUFFER_DATA (buf);
1647
1648   /* if not valid timestamp or we can't clip or sync, try to play
1649    * sample ASAP */
1650   if (!GST_CLOCK_TIME_IS_VALID (time)) {
1651     render_start = gst_base_audio_sink_get_offset (sink);
1652     render_stop = render_start + samples;
1653     GST_DEBUG_OBJECT (sink,
1654         "Buffer of size %u has no time. Using render_start=%" G_GUINT64_FORMAT,
1655         GST_BUFFER_SIZE (buf), render_start);
1656     /* we don't have a start so we don't know stop either */
1657     stop = -1;
1658     goto no_sync;
1659   }
1660
1661   /* let's calc stop based on the number of samples in the buffer instead
1662    * of trusting the DURATION */
1663   stop = time + gst_util_uint64_scale_int (samples, GST_SECOND,
1664       ringbuf->spec.rate);
1665
1666   /* prepare the clipping segment. Since we will be subtracting ts-offset and
1667    * device-delay later we scale the start and stop with those values so that we
1668    * can correctly clip them */
1669   clip_seg.format = GST_FORMAT_TIME;
1670   clip_seg.start = bsink->segment.start;
1671   clip_seg.stop = bsink->segment.stop;
1672   clip_seg.duration = -1;
1673
1674   /* the sync offset is the combination of ts-offset and device-delay */
1675   latency = gst_base_sink_get_latency (bsink);
1676   ts_offset = gst_base_sink_get_ts_offset (bsink);
1677   render_delay = gst_base_sink_get_render_delay (bsink);
1678   sync_offset = ts_offset - render_delay + latency;
1679
1680   GST_DEBUG_OBJECT (sink,
1681       "sync-offset %" G_GINT64_FORMAT ", render-delay %" GST_TIME_FORMAT
1682       ", ts-offset %" G_GINT64_FORMAT, sync_offset,
1683       GST_TIME_ARGS (render_delay), ts_offset);
1684
1685   /* compensate for ts-offset and device-delay when negative we need to
1686    * clip. */
1687   if (sync_offset < 0) {
1688     clip_seg.start += -sync_offset;
1689     if (clip_seg.stop != -1)
1690       clip_seg.stop += -sync_offset;
1691   }
1692
1693   /* samples should be rendered based on their timestamp. All samples
1694    * arriving before the segment.start or after segment.stop are to be
1695    * thrown away. All samples should also be clipped to the segment
1696    * boundaries */
1697   if (!gst_segment_clip (&clip_seg, GST_FORMAT_TIME, time, stop, &ctime,
1698           &cstop))
1699     goto out_of_segment;
1700
1701   /* see if some clipping happened */
1702   diff = ctime - time;
1703   if (diff > 0) {
1704     /* bring clipped time to samples */
1705     diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1706     GST_DEBUG_OBJECT (sink, "clipping start to %" GST_TIME_FORMAT " %"
1707         G_GUINT64_FORMAT " samples", GST_TIME_ARGS (ctime), diff);
1708     samples -= diff;
1709     data += diff * bps;
1710     time = ctime;
1711   }
1712   diff = stop - cstop;
1713   if (diff > 0) {
1714     /* bring clipped time to samples */
1715     diff = gst_util_uint64_scale_int (diff, ringbuf->spec.rate, GST_SECOND);
1716     GST_DEBUG_OBJECT (sink, "clipping stop to %" GST_TIME_FORMAT " %"
1717         G_GUINT64_FORMAT " samples", GST_TIME_ARGS (cstop), diff);
1718     samples -= diff;
1719     stop = cstop;
1720   }
1721
1722   /* figure out how to sync */
1723   if ((clock = GST_ELEMENT_CLOCK (bsink)))
1724     sync = bsink->sync;
1725   else
1726     sync = FALSE;
1727
1728   if (!sync) {
1729     /* no sync needed, play sample ASAP */
1730     render_start = gst_base_audio_sink_get_offset (sink);
1731     render_stop = render_start + samples;
1732     GST_DEBUG_OBJECT (sink,
1733         "no sync needed. Using render_start=%" G_GUINT64_FORMAT, render_start);
1734     goto no_sync;
1735   }
1736
1737   /* bring buffer start and stop times to running time */
1738   render_start =
1739       gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, time);
1740   render_stop =
1741       gst_segment_to_running_time (&bsink->segment, GST_FORMAT_TIME, stop);
1742
1743   GST_DEBUG_OBJECT (sink,
1744       "running: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1745       GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1746
1747   /* store the time of the last sample, we'll use this to perform sync on the
1748    * last sample when draining the buffer */
1749   if (bsink->segment.rate >= 0.0) {
1750     sink->priv->eos_time = render_stop;
1751   } else {
1752     sink->priv->eos_time = render_start;
1753   }
1754
1755   /* compensate for ts-offset and delay we know this will not underflow because we
1756    * clipped above. */
1757   GST_DEBUG_OBJECT (sink,
1758       "compensating for sync-offset %" GST_TIME_FORMAT,
1759       GST_TIME_ARGS (sync_offset));
1760   render_start += sync_offset;
1761   render_stop += sync_offset;
1762
1763   GST_DEBUG_OBJECT (sink, "adding base_time %" GST_TIME_FORMAT,
1764       GST_TIME_ARGS (base_time));
1765
1766   /* add base time to sync against the clock */
1767   render_start += base_time;
1768   render_stop += base_time;
1769
1770   GST_DEBUG_OBJECT (sink,
1771       "after compensation: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1772       GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1773
1774   if ((slaved = clock != sink->provided_clock)) {
1775     /* handle clock slaving */
1776     gst_base_audio_sink_handle_slaving (sink, render_start, render_stop,
1777         &render_start, &render_stop);
1778   } else {
1779     /* no slaving needed but we need to adapt to the clock calibration
1780      * parameters */
1781     gst_base_audio_sink_none_slaving (sink, render_start, render_stop,
1782         &render_start, &render_stop);
1783   }
1784
1785   GST_DEBUG_OBJECT (sink,
1786       "final timestamps: start %" GST_TIME_FORMAT " - stop %" GST_TIME_FORMAT,
1787       GST_TIME_ARGS (render_start), GST_TIME_ARGS (render_stop));
1788
1789   /* bring to position in the ringbuffer */
1790   if (sink->priv->do_time_offset) {
1791     time_offset =
1792         GST_AUDIO_CLOCK_CAST (sink->provided_clock)->abidata.ABI.time_offset;
1793     GST_DEBUG_OBJECT (sink,
1794         "time offset %" GST_TIME_FORMAT, GST_TIME_ARGS (time_offset));
1795     if (render_start > time_offset)
1796       render_start -= time_offset;
1797     else
1798       render_start = 0;
1799     if (render_stop > time_offset)
1800       render_stop -= time_offset;
1801     else
1802       render_stop = 0;
1803   }
1804
1805   /* in some clock slaving cases, all late samples end up at 0 first,
1806    * and subsequent ones align with that until threshold exceeded,
1807    * and then sync back to 0 and so on, so avoid that altogether */
1808   if (G_UNLIKELY (render_start == 0 && render_stop == 0))
1809     goto too_late;
1810
1811   /* and bring the time to the rate corrected offset in the buffer */
1812   render_start = gst_util_uint64_scale_int (render_start,
1813       ringbuf->spec.rate, GST_SECOND);
1814   render_stop = gst_util_uint64_scale_int (render_stop,
1815       ringbuf->spec.rate, GST_SECOND);
1816
1817   /* positive playback rate, first sample is render_start, negative rate, first
1818    * sample is render_stop. When no rate conversion is active, render exactly
1819    * the amount of input samples to avoid aligning to rounding errors. */
1820   if (bsink->segment.rate >= 0.0) {
1821     sample_offset = render_start;
1822     if (bsink->segment.rate == 1.0)
1823       render_stop = sample_offset + samples;
1824   } else {
1825     sample_offset = render_stop;
1826     if (bsink->segment.rate == -1.0)
1827       render_start = sample_offset + samples;
1828   }
1829
1830   /* always resync after a discont */
1831   if (G_UNLIKELY (GST_BUFFER_FLAG_IS_SET (buf, GST_BUFFER_FLAG_DISCONT))) {
1832     GST_DEBUG_OBJECT (sink, "resync after discont");
1833     goto no_align;
1834   }
1835
1836   /* resync when we don't know what to align the sample with */
1837   if (G_UNLIKELY (sink->next_sample == -1)) {
1838     GST_DEBUG_OBJECT (sink,
1839         "no align possible: no previous sample position known");
1840     goto no_align;
1841   }
1842
1843   align = gst_base_audio_sink_get_alignment (sink, sample_offset);
1844   sink->priv->last_align = align;
1845
1846   /* apply alignment */
1847   render_start += align;
1848
1849   /* only align stop if we are not slaved to resample */
1850   if (slaved && sink->priv->slave_method == GST_BASE_AUDIO_SINK_SLAVE_RESAMPLE) {
1851     GST_DEBUG_OBJECT (sink, "no stop time align needed: we are slaved");
1852     goto no_align;
1853   }
1854   render_stop += align;
1855
1856 no_align:
1857   /* number of target samples is difference between start and stop */
1858   out_samples = render_stop - render_start;
1859
1860 no_sync:
1861   /* we render the first or last sample first, depending on the rate */
1862   if (bsink->segment.rate >= 0.0)
1863     sample_offset = render_start;
1864   else
1865     sample_offset = render_stop;
1866
1867   GST_DEBUG_OBJECT (sink, "rendering at %" G_GUINT64_FORMAT " %d/%d",
1868       sample_offset, samples, out_samples);
1869
1870   /* we need to accumulate over different runs for when we get interrupted */
1871   accum = 0;
1872   align_next = TRUE;
1873   do {
1874     written =
1875         gst_ring_buffer_commit_full (ringbuf, &sample_offset, data, samples,
1876         out_samples, &accum);
1877
1878     GST_DEBUG_OBJECT (sink, "wrote %u of %u", written, samples);
1879     /* if we wrote all, we're done */
1880     if (written == samples)
1881       break;
1882
1883     /* else something interrupted us and we wait for preroll. */
1884     if ((ret = gst_base_sink_wait_preroll (bsink)) != GST_FLOW_OK)
1885       goto stopping;
1886
1887     /* if we got interrupted, we cannot assume that the next sample should
1888      * be aligned to this one */
1889     align_next = FALSE;
1890
1891     /* update the output samples. FIXME, this will just skip them when pausing
1892      * during trick mode */
1893     if (out_samples > written) {
1894       out_samples -= written;
1895       accum = 0;
1896     } else
1897       break;
1898
1899     samples -= written;
1900     data += written * bps;
1901   } while (TRUE);
1902
1903   if (align_next)
1904     sink->next_sample = sample_offset;
1905   else
1906     sink->next_sample = -1;
1907
1908   GST_DEBUG_OBJECT (sink, "next sample expected at %" G_GUINT64_FORMAT,
1909       sink->next_sample);
1910
1911   if (GST_CLOCK_TIME_IS_VALID (stop) && stop >= bsink->segment.stop) {
1912     GST_DEBUG_OBJECT (sink,
1913         "start playback because we are at the end of segment");
1914     gst_ring_buffer_start (ringbuf);
1915   }
1916
1917   ret = GST_FLOW_OK;
1918
1919 done:
1920   if (out)
1921     gst_buffer_unref (out);
1922
1923   return ret;
1924
1925   /* SPECIAL cases */
1926 out_of_segment:
1927   {
1928     GST_DEBUG_OBJECT (sink,
1929         "dropping sample out of segment time %" GST_TIME_FORMAT ", start %"
1930         GST_TIME_FORMAT, GST_TIME_ARGS (time),
1931         GST_TIME_ARGS (bsink->segment.start));
1932     ret = GST_FLOW_OK;
1933     goto done;
1934   }
1935 too_late:
1936   {
1937     GST_DEBUG_OBJECT (sink, "dropping late sample");
1938     ret = GST_FLOW_OK;
1939     goto done;
1940   }
1941   /* ERRORS */
1942 payload_failed:
1943   {
1944     GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("failed to payload."));
1945     ret = GST_FLOW_ERROR;
1946     goto done;
1947   }
1948 wrong_state:
1949   {
1950     GST_DEBUG_OBJECT (sink, "ringbuffer not negotiated");
1951     GST_ELEMENT_ERROR (sink, STREAM, FORMAT, (NULL), ("sink not negotiated."));
1952     ret = GST_FLOW_NOT_NEGOTIATED;
1953     goto done;
1954   }
1955 wrong_size:
1956   {
1957     GST_DEBUG_OBJECT (sink, "wrong size");
1958     GST_ELEMENT_ERROR (sink, STREAM, WRONG_TYPE,
1959         (NULL), ("sink received buffer of wrong size."));
1960     ret = GST_FLOW_ERROR;
1961     goto done;
1962   }
1963 stopping:
1964   {
1965     GST_DEBUG_OBJECT (sink, "preroll got interrupted: %d (%s)", ret,
1966         gst_flow_get_name (ret));
1967     goto done;
1968   }
1969 sync_latency_failed:
1970   {
1971     GST_DEBUG_OBJECT (sink, "failed waiting for latency");
1972     goto done;
1973   }
1974 }
1975
1976 /**
1977  * gst_base_audio_sink_create_ringbuffer:
1978  * @sink: a #GstBaseAudioSink.
1979  *
1980  * Create and return the #GstRingBuffer for @sink. This function will call the
1981  * ::create_ringbuffer vmethod and will set @sink as the parent of the returned
1982  * buffer (see gst_object_set_parent()).
1983  *
1984  * Returns: The new ringbuffer of @sink.
1985  */
1986 GstRingBuffer *
1987 gst_base_audio_sink_create_ringbuffer (GstBaseAudioSink * sink)
1988 {
1989   GstBaseAudioSinkClass *bclass;
1990   GstRingBuffer *buffer = NULL;
1991
1992   bclass = GST_BASE_AUDIO_SINK_GET_CLASS (sink);
1993   if (bclass->create_ringbuffer)
1994     buffer = bclass->create_ringbuffer (sink);
1995
1996   if (buffer)
1997     gst_object_set_parent (GST_OBJECT (buffer), GST_OBJECT (sink));
1998
1999   return buffer;
2000 }
2001
2002 static void
2003 gst_base_audio_sink_callback (GstRingBuffer * rbuf, guint8 * data, guint len,
2004     gpointer user_data)
2005 {
2006   GstBaseSink *basesink;
2007   GstBaseAudioSink *sink;
2008   GstBuffer *buf;
2009   GstFlowReturn ret;
2010
2011   basesink = GST_BASE_SINK (user_data);
2012   sink = GST_BASE_AUDIO_SINK (user_data);
2013
2014   GST_PAD_STREAM_LOCK (basesink->sinkpad);
2015
2016   /* would be nice to arrange for pad_alloc_buffer to return data -- as it is we
2017      will copy twice, once into data, once into DMA */
2018   GST_LOG_OBJECT (basesink, "pulling %d bytes offset %" G_GUINT64_FORMAT
2019       " to fill audio buffer", len, basesink->offset);
2020   ret =
2021       gst_pad_pull_range (basesink->sinkpad, basesink->segment.last_stop, len,
2022       &buf);
2023
2024   if (ret != GST_FLOW_OK) {
2025     if (ret == GST_FLOW_UNEXPECTED)
2026       goto eos;
2027     else
2028       goto error;
2029   }
2030
2031   GST_PAD_PREROLL_LOCK (basesink->sinkpad);
2032   if (basesink->flushing)
2033     goto flushing;
2034
2035   /* complete preroll and wait for PLAYING */
2036   ret = gst_base_sink_do_preroll (basesink, GST_MINI_OBJECT_CAST (buf));
2037   if (ret != GST_FLOW_OK)
2038     goto preroll_error;
2039
2040   if (len != GST_BUFFER_SIZE (buf)) {
2041     GST_INFO_OBJECT (basesink,
2042         "got different size than requested from sink pad: %u != %u", len,
2043         GST_BUFFER_SIZE (buf));
2044     len = MIN (GST_BUFFER_SIZE (buf), len);
2045   }
2046
2047   basesink->segment.last_stop += len;
2048
2049   memcpy (data, GST_BUFFER_DATA (buf), len);
2050   GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
2051
2052   GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
2053
2054   return;
2055
2056 error:
2057   {
2058     GST_WARNING_OBJECT (basesink, "Got flow '%s' but can't return it: %d",
2059         gst_flow_get_name (ret), ret);
2060     gst_ring_buffer_pause (rbuf);
2061     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
2062     return;
2063   }
2064 eos:
2065   {
2066     /* FIXME: this is not quite correct; we'll be called endlessly until
2067      * the sink gets shut down; maybe we should set a flag somewhere, or
2068      * set segment.stop and segment.duration to the last sample or so */
2069     GST_DEBUG_OBJECT (sink, "EOS");
2070     gst_base_audio_sink_drain (sink);
2071     gst_ring_buffer_pause (rbuf);
2072     gst_element_post_message (GST_ELEMENT_CAST (sink),
2073         gst_message_new_eos (GST_OBJECT_CAST (sink)));
2074     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
2075   }
2076 flushing:
2077   {
2078     GST_DEBUG_OBJECT (sink, "we are flushing");
2079     gst_ring_buffer_pause (rbuf);
2080     GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
2081     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
2082     return;
2083   }
2084 preroll_error:
2085   {
2086     GST_DEBUG_OBJECT (sink, "error %s", gst_flow_get_name (ret));
2087     gst_ring_buffer_pause (rbuf);
2088     GST_PAD_PREROLL_UNLOCK (basesink->sinkpad);
2089     GST_PAD_STREAM_UNLOCK (basesink->sinkpad);
2090     return;
2091   }
2092 }
2093
2094 static gboolean
2095 gst_base_audio_sink_activate_pull (GstBaseSink * basesink, gboolean active)
2096 {
2097   gboolean ret;
2098   GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (basesink);
2099
2100   if (active) {
2101     GST_DEBUG_OBJECT (basesink, "activating pull");
2102
2103     gst_ring_buffer_set_callback (sink->ringbuffer,
2104         gst_base_audio_sink_callback, sink);
2105
2106     ret = gst_ring_buffer_activate (sink->ringbuffer, TRUE);
2107   } else {
2108     GST_DEBUG_OBJECT (basesink, "deactivating pull");
2109     gst_ring_buffer_set_callback (sink->ringbuffer, NULL, NULL);
2110     ret = gst_ring_buffer_activate (sink->ringbuffer, FALSE);
2111   }
2112
2113   return ret;
2114 }
2115
2116 /* should be called with the LOCK */
2117 static GstStateChangeReturn
2118 gst_base_audio_sink_async_play (GstBaseSink * basesink)
2119 {
2120   GstBaseAudioSink *sink;
2121
2122   sink = GST_BASE_AUDIO_SINK (basesink);
2123
2124   GST_DEBUG_OBJECT (sink, "ringbuffer may start now");
2125   sink->priv->sync_latency = TRUE;
2126   gst_ring_buffer_may_start (sink->ringbuffer, TRUE);
2127   if (basesink->pad_mode == GST_ACTIVATE_PULL) {
2128     /* we always start the ringbuffer in pull mode immediately */
2129     gst_ring_buffer_start (sink->ringbuffer);
2130   }
2131
2132   return GST_STATE_CHANGE_SUCCESS;
2133 }
2134
2135 static GstStateChangeReturn
2136 gst_base_audio_sink_change_state (GstElement * element,
2137     GstStateChange transition)
2138 {
2139   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
2140   GstBaseAudioSink *sink = GST_BASE_AUDIO_SINK (element);
2141
2142   switch (transition) {
2143     case GST_STATE_CHANGE_NULL_TO_READY:
2144       if (sink->ringbuffer == NULL) {
2145         gst_audio_clock_reset (GST_AUDIO_CLOCK (sink->provided_clock), 0);
2146         sink->ringbuffer = gst_base_audio_sink_create_ringbuffer (sink);
2147       }
2148       if (!gst_ring_buffer_open_device (sink->ringbuffer))
2149         goto open_failed;
2150       break;
2151     case GST_STATE_CHANGE_READY_TO_PAUSED:
2152       sink->next_sample = -1;
2153       sink->priv->last_align = -1;
2154       sink->priv->eos_time = -1;
2155       sink->priv->discont_time = -1;
2156       gst_ring_buffer_set_flushing (sink->ringbuffer, FALSE);
2157       gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
2158
2159       /* Only post clock-provide messages if this is the clock that
2160        * we've created. If the subclass has overriden it the subclass
2161        * should post this messages whenever necessary */
2162       if (sink->provided_clock && GST_IS_AUDIO_CLOCK (sink->provided_clock) &&
2163           GST_AUDIO_CLOCK_CAST (sink->provided_clock)->func ==
2164           (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time)
2165         gst_element_post_message (element,
2166             gst_message_new_clock_provide (GST_OBJECT_CAST (element),
2167                 sink->provided_clock, TRUE));
2168       break;
2169     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
2170     {
2171       gboolean eos;
2172
2173       GST_OBJECT_LOCK (sink);
2174       GST_DEBUG_OBJECT (sink, "ringbuffer may start now");
2175       sink->priv->sync_latency = TRUE;
2176       eos = GST_BASE_SINK (sink)->eos;
2177       GST_OBJECT_UNLOCK (sink);
2178
2179       gst_ring_buffer_may_start (sink->ringbuffer, TRUE);
2180       if (GST_BASE_SINK_CAST (sink)->pad_mode == GST_ACTIVATE_PULL ||
2181           g_atomic_int_get (&sink->abidata.ABI.eos_rendering) || eos) {
2182         /* we always start the ringbuffer in pull mode immediately */
2183         /* sync rendering on eos needs running clock,
2184          * and others need running clock when finished rendering eos */
2185         gst_ring_buffer_start (sink->ringbuffer);
2186       }
2187       break;
2188     }
2189     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2190       /* ringbuffer cannot start anymore */
2191       gst_ring_buffer_may_start (sink->ringbuffer, FALSE);
2192       gst_ring_buffer_pause (sink->ringbuffer);
2193
2194       GST_OBJECT_LOCK (sink);
2195       sink->priv->sync_latency = FALSE;
2196       GST_OBJECT_UNLOCK (sink);
2197       break;
2198     case GST_STATE_CHANGE_PAUSED_TO_READY:
2199       /* Only post clock-lost messages if this is the clock that
2200        * we've created. If the subclass has overriden it the subclass
2201        * should post this messages whenever necessary */
2202       if (sink->provided_clock && GST_IS_AUDIO_CLOCK (sink->provided_clock) &&
2203           GST_AUDIO_CLOCK_CAST (sink->provided_clock)->func ==
2204           (GstAudioClockGetTimeFunc) gst_base_audio_sink_get_time)
2205         gst_element_post_message (element,
2206             gst_message_new_clock_lost (GST_OBJECT_CAST (element),
2207                 sink->provided_clock));
2208
2209       /* make sure we unblock before calling the parent state change
2210        * so it can grab the STREAM_LOCK */
2211       gst_ring_buffer_set_flushing (sink->ringbuffer, TRUE);
2212       break;
2213     default:
2214       break;
2215   }
2216
2217   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
2218
2219   switch (transition) {
2220     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
2221       /* stop slaving ourselves to the master, if any */
2222       gst_clock_set_master (sink->provided_clock, NULL);
2223       break;
2224     case GST_STATE_CHANGE_PAUSED_TO_READY:
2225       gst_ring_buffer_activate (sink->ringbuffer, FALSE);
2226       gst_ring_buffer_release (sink->ringbuffer);
2227       break;
2228     case GST_STATE_CHANGE_READY_TO_NULL:
2229       /* we release again here because the aqcuire happens when setting the
2230        * caps, which happens before we commit the state to PAUSED and thus the
2231        * PAUSED->READY state change (see above, where we release the ringbuffer)
2232        * might not be called when we get here. */
2233       gst_ring_buffer_activate (sink->ringbuffer, FALSE);
2234       gst_ring_buffer_release (sink->ringbuffer);
2235       gst_ring_buffer_close_device (sink->ringbuffer);
2236       GST_OBJECT_LOCK (sink);
2237       gst_object_unparent (GST_OBJECT_CAST (sink->ringbuffer));
2238       sink->ringbuffer = NULL;
2239       GST_OBJECT_UNLOCK (sink);
2240       break;
2241     default:
2242       break;
2243   }
2244
2245   return ret;
2246
2247   /* ERRORS */
2248 open_failed:
2249   {
2250     /* subclass must post a meaningful error message */
2251     GST_DEBUG_OBJECT (sink, "open failed");
2252     return GST_STATE_CHANGE_FAILURE;
2253   }
2254 }