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