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