Fix FSF address
[platform/upstream/gstreamer.git] / gst-libs / gst / audio / gstaudiobasesrc.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2005 Wim Taymans <wim@fluendo.com>
4  *
5  * gstaudiobasesrc.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., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:gstaudiobasesrc
25  * @short_description: Base class for audio sources
26  * @see_also: #GstAudioSrc, #GstAudioRingBuffer.
27  *
28  * This is the base class for audio sources. Subclasses need to implement the
29  * ::create_ringbuffer vmethod. This base class will then take care of
30  * reading samples from the ringbuffer, synchronisation and flushing.
31  *
32  * Last reviewed on 2006-09-27 (0.10.12)
33  */
34
35 #ifdef HAVE_CONFIG_H
36 #  include "config.h"
37 #endif
38
39 #include <string.h>
40
41 #include "gstaudiobasesrc.h"
42
43 #include "gst/gst-i18n-plugin.h"
44
45 GST_DEBUG_CATEGORY_STATIC (gst_audio_base_src_debug);
46 #define GST_CAT_DEFAULT gst_audio_base_src_debug
47
48 GType
49 gst_audio_base_src_slave_method_get_type (void)
50 {
51   static volatile gsize slave_method_type = 0;
52   /* FIXME 0.11: nick should be "retimestamp" not "re-timestamp" */
53   static const GEnumValue slave_method[] = {
54     {GST_AUDIO_BASE_SRC_SLAVE_RESAMPLE,
55         "GST_AUDIO_BASE_SRC_SLAVE_RESAMPLE", "resample"},
56     {GST_AUDIO_BASE_SRC_SLAVE_RETIMESTAMP,
57         "GST_AUDIO_BASE_SRC_SLAVE_RETIMESTAMP", "re-timestamp"},
58     {GST_AUDIO_BASE_SRC_SLAVE_SKEW, "GST_AUDIO_BASE_SRC_SLAVE_SKEW", "skew"},
59     {GST_AUDIO_BASE_SRC_SLAVE_NONE, "GST_AUDIO_BASE_SRC_SLAVE_NONE", "none"},
60     {0, NULL, NULL},
61   };
62
63   if (g_once_init_enter (&slave_method_type)) {
64     GType tmp =
65         g_enum_register_static ("GstAudioBaseSrcSlaveMethod", slave_method);
66     g_once_init_leave (&slave_method_type, tmp);
67   }
68   return (GType) slave_method_type;
69 }
70
71 #define GST_AUDIO_BASE_SRC_GET_PRIVATE(obj)  \
72    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_AUDIO_BASE_SRC, GstAudioBaseSrcPrivate))
73
74 struct _GstAudioBaseSrcPrivate
75 {
76   /* the clock slaving algorithm in use */
77   GstAudioBaseSrcSlaveMethod slave_method;
78 };
79
80 /* BaseAudioSrc signals and args */
81 enum
82 {
83   /* FILL ME */
84   LAST_SIGNAL
85 };
86
87 #define DEFAULT_BUFFER_TIME     ((200 * GST_MSECOND) / GST_USECOND)
88 #define DEFAULT_LATENCY_TIME    ((10 * GST_MSECOND) / GST_USECOND)
89 #define DEFAULT_ACTUAL_BUFFER_TIME     -1
90 #define DEFAULT_ACTUAL_LATENCY_TIME    -1
91 #define DEFAULT_PROVIDE_CLOCK   TRUE
92 #define DEFAULT_SLAVE_METHOD    GST_AUDIO_BASE_SRC_SLAVE_SKEW
93
94 enum
95 {
96   PROP_0,
97   PROP_BUFFER_TIME,
98   PROP_LATENCY_TIME,
99   PROP_ACTUAL_BUFFER_TIME,
100   PROP_ACTUAL_LATENCY_TIME,
101   PROP_PROVIDE_CLOCK,
102   PROP_SLAVE_METHOD,
103   PROP_LAST
104 };
105
106 static void
107 _do_init (GType type)
108 {
109   GST_DEBUG_CATEGORY_INIT (gst_audio_base_src_debug, "audiobasesrc", 0,
110       "audiobasesrc element");
111
112 #ifdef ENABLE_NLS
113   GST_DEBUG ("binding text domain %s to locale dir %s", GETTEXT_PACKAGE,
114       LOCALEDIR);
115   bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
116   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
117 #endif /* ENABLE_NLS */
118 }
119
120 #define gst_audio_base_src_parent_class parent_class
121 G_DEFINE_TYPE_WITH_CODE (GstAudioBaseSrc, gst_audio_base_src, GST_TYPE_PUSH_SRC,
122     _do_init (g_define_type_id));
123
124 static void gst_audio_base_src_set_property (GObject * object, guint prop_id,
125     const GValue * value, GParamSpec * pspec);
126 static void gst_audio_base_src_get_property (GObject * object, guint prop_id,
127     GValue * value, GParamSpec * pspec);
128 static void gst_audio_base_src_dispose (GObject * object);
129
130 static GstStateChangeReturn gst_audio_base_src_change_state (GstElement *
131     element, GstStateChange transition);
132
133 static GstClock *gst_audio_base_src_provide_clock (GstElement * elem);
134 static GstClockTime gst_audio_base_src_get_time (GstClock * clock,
135     GstAudioBaseSrc * src);
136
137 static GstFlowReturn gst_audio_base_src_create (GstBaseSrc * bsrc,
138     guint64 offset, guint length, GstBuffer ** buf);
139
140 static gboolean gst_audio_base_src_event (GstBaseSrc * bsrc, GstEvent * event);
141 static void gst_audio_base_src_get_times (GstBaseSrc * bsrc,
142     GstBuffer * buffer, GstClockTime * start, GstClockTime * end);
143 static gboolean gst_audio_base_src_setcaps (GstBaseSrc * bsrc, GstCaps * caps);
144 static gboolean gst_audio_base_src_query (GstBaseSrc * bsrc, GstQuery * query);
145 static GstCaps *gst_audio_base_src_fixate (GstBaseSrc * bsrc, GstCaps * caps);
146
147 /* static guint gst_audio_base_src_signals[LAST_SIGNAL] = { 0 }; */
148
149 static void
150 gst_audio_base_src_class_init (GstAudioBaseSrcClass * klass)
151 {
152   GObjectClass *gobject_class;
153   GstElementClass *gstelement_class;
154   GstBaseSrcClass *gstbasesrc_class;
155
156   gobject_class = (GObjectClass *) klass;
157   gstelement_class = (GstElementClass *) klass;
158   gstbasesrc_class = (GstBaseSrcClass *) klass;
159
160   g_type_class_add_private (klass, sizeof (GstAudioBaseSrcPrivate));
161
162   gobject_class->set_property = gst_audio_base_src_set_property;
163   gobject_class->get_property = gst_audio_base_src_get_property;
164   gobject_class->dispose = gst_audio_base_src_dispose;
165
166   g_object_class_install_property (gobject_class, PROP_BUFFER_TIME,
167       g_param_spec_int64 ("buffer-time", "Buffer Time",
168           "Size of audio buffer in microseconds, this is the maximum amount "
169           "of data that is buffered in the device and the maximum latency that "
170           "the source reports", 1, G_MAXINT64, DEFAULT_BUFFER_TIME,
171           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
172
173   g_object_class_install_property (gobject_class, PROP_LATENCY_TIME,
174       g_param_spec_int64 ("latency-time", "Latency Time",
175           "The minimum amount of data to read in each iteration in microseconds, "
176           "this is the minimum latency that the source reports", 1,
177           G_MAXINT64, DEFAULT_LATENCY_TIME,
178           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
179
180   /**
181    * GstAudioBaseSrc:actual-buffer-time:
182    *
183    * Actual configured size of audio buffer in microseconds.
184    **/
185   g_object_class_install_property (gobject_class, PROP_ACTUAL_BUFFER_TIME,
186       g_param_spec_int64 ("actual-buffer-time", "Actual Buffer Time",
187           "Actual configured size of audio buffer in microseconds",
188           DEFAULT_ACTUAL_BUFFER_TIME, G_MAXINT64, DEFAULT_ACTUAL_BUFFER_TIME,
189           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
190
191   /**
192    * GstAudioBaseSrc:actual-latency-time:
193    *
194    * Actual configured audio latency in microseconds.
195    **/
196   g_object_class_install_property (gobject_class, PROP_ACTUAL_LATENCY_TIME,
197       g_param_spec_int64 ("actual-latency-time", "Actual Latency Time",
198           "Actual configured audio latency in microseconds",
199           DEFAULT_ACTUAL_LATENCY_TIME, G_MAXINT64, DEFAULT_ACTUAL_LATENCY_TIME,
200           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
201
202   g_object_class_install_property (gobject_class, PROP_PROVIDE_CLOCK,
203       g_param_spec_boolean ("provide-clock", "Provide Clock",
204           "Provide a clock to be used as the global pipeline clock",
205           DEFAULT_PROVIDE_CLOCK, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
206
207   g_object_class_install_property (gobject_class, PROP_SLAVE_METHOD,
208       g_param_spec_enum ("slave-method", "Slave Method",
209           "Algorithm to use to match the rate of the masterclock",
210           GST_TYPE_AUDIO_BASE_SRC_SLAVE_METHOD, DEFAULT_SLAVE_METHOD,
211           G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
212
213   gstelement_class->change_state =
214       GST_DEBUG_FUNCPTR (gst_audio_base_src_change_state);
215   gstelement_class->provide_clock =
216       GST_DEBUG_FUNCPTR (gst_audio_base_src_provide_clock);
217
218   gstbasesrc_class->set_caps = GST_DEBUG_FUNCPTR (gst_audio_base_src_setcaps);
219   gstbasesrc_class->event = GST_DEBUG_FUNCPTR (gst_audio_base_src_event);
220   gstbasesrc_class->query = GST_DEBUG_FUNCPTR (gst_audio_base_src_query);
221   gstbasesrc_class->get_times =
222       GST_DEBUG_FUNCPTR (gst_audio_base_src_get_times);
223   gstbasesrc_class->create = GST_DEBUG_FUNCPTR (gst_audio_base_src_create);
224   gstbasesrc_class->fixate = GST_DEBUG_FUNCPTR (gst_audio_base_src_fixate);
225
226   /* ref class from a thread-safe context to work around missing bit of
227    * thread-safety in GObject */
228   g_type_class_ref (GST_TYPE_AUDIO_CLOCK);
229   g_type_class_ref (GST_TYPE_AUDIO_RING_BUFFER);
230 }
231
232 static void
233 gst_audio_base_src_init (GstAudioBaseSrc * audiobasesrc)
234 {
235   audiobasesrc->priv = GST_AUDIO_BASE_SRC_GET_PRIVATE (audiobasesrc);
236
237   audiobasesrc->buffer_time = DEFAULT_BUFFER_TIME;
238   audiobasesrc->latency_time = DEFAULT_LATENCY_TIME;
239   if (DEFAULT_PROVIDE_CLOCK)
240     GST_OBJECT_FLAG_SET (audiobasesrc, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
241   else
242     GST_OBJECT_FLAG_UNSET (audiobasesrc, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
243   audiobasesrc->priv->slave_method = DEFAULT_SLAVE_METHOD;
244   /* reset blocksize we use latency time to calculate a more useful 
245    * value based on negotiated format. */
246   GST_BASE_SRC (audiobasesrc)->blocksize = 0;
247
248   audiobasesrc->clock = gst_audio_clock_new ("GstAudioSrcClock",
249       (GstAudioClockGetTimeFunc) gst_audio_base_src_get_time, audiobasesrc,
250       NULL);
251
252
253   /* we are always a live source */
254   gst_base_src_set_live (GST_BASE_SRC (audiobasesrc), TRUE);
255   /* we operate in time */
256   gst_base_src_set_format (GST_BASE_SRC (audiobasesrc), GST_FORMAT_TIME);
257 }
258
259 static void
260 gst_audio_base_src_dispose (GObject * object)
261 {
262   GstAudioBaseSrc *src;
263
264   src = GST_AUDIO_BASE_SRC (object);
265
266   GST_OBJECT_LOCK (src);
267   if (src->clock) {
268     gst_audio_clock_invalidate (src->clock);
269     gst_object_unref (src->clock);
270     src->clock = NULL;
271   }
272
273   if (src->ringbuffer) {
274     gst_object_unparent (GST_OBJECT_CAST (src->ringbuffer));
275     src->ringbuffer = NULL;
276   }
277   GST_OBJECT_UNLOCK (src);
278
279   G_OBJECT_CLASS (parent_class)->dispose (object);
280 }
281
282 static GstClock *
283 gst_audio_base_src_provide_clock (GstElement * elem)
284 {
285   GstAudioBaseSrc *src;
286   GstClock *clock;
287
288   src = GST_AUDIO_BASE_SRC (elem);
289
290   /* we have no ringbuffer (must be NULL state) */
291   if (src->ringbuffer == NULL)
292     goto wrong_state;
293
294   if (gst_audio_ring_buffer_is_flushing (src->ringbuffer))
295     goto wrong_state;
296
297   GST_OBJECT_LOCK (src);
298
299   if (!GST_OBJECT_FLAG_IS_SET (src, GST_ELEMENT_FLAG_PROVIDE_CLOCK))
300     goto clock_disabled;
301
302   clock = GST_CLOCK_CAST (gst_object_ref (src->clock));
303   GST_OBJECT_UNLOCK (src);
304
305   return clock;
306
307   /* ERRORS */
308 wrong_state:
309   {
310     GST_DEBUG_OBJECT (src, "ringbuffer is flushing");
311     return NULL;
312   }
313 clock_disabled:
314   {
315     GST_DEBUG_OBJECT (src, "clock provide disabled");
316     GST_OBJECT_UNLOCK (src);
317     return NULL;
318   }
319 }
320
321 static GstClockTime
322 gst_audio_base_src_get_time (GstClock * clock, GstAudioBaseSrc * src)
323 {
324   guint64 raw, samples;
325   guint delay;
326   GstClockTime result;
327
328   if (G_UNLIKELY (src->ringbuffer == NULL
329           || src->ringbuffer->spec.info.rate == 0))
330     return GST_CLOCK_TIME_NONE;
331
332   raw = samples = gst_audio_ring_buffer_samples_done (src->ringbuffer);
333
334   /* the number of samples not yet processed, this is still queued in the
335    * device (not yet read for capture). */
336   delay = gst_audio_ring_buffer_delay (src->ringbuffer);
337
338   samples += delay;
339
340   result = gst_util_uint64_scale_int (samples, GST_SECOND,
341       src->ringbuffer->spec.info.rate);
342
343   GST_DEBUG_OBJECT (src,
344       "processed samples: raw %" G_GUINT64_FORMAT ", delay %u, real %"
345       G_GUINT64_FORMAT ", time %" GST_TIME_FORMAT, raw, delay, samples,
346       GST_TIME_ARGS (result));
347
348   return result;
349 }
350
351 /**
352  * gst_audio_base_src_set_provide_clock:
353  * @src: a #GstAudioBaseSrc
354  * @provide: new state
355  *
356  * Controls whether @src will provide a clock or not. If @provide is %TRUE, 
357  * gst_element_provide_clock() will return a clock that reflects the datarate
358  * of @src. If @provide is %FALSE, gst_element_provide_clock() will return NULL.
359  */
360 void
361 gst_audio_base_src_set_provide_clock (GstAudioBaseSrc * src, gboolean provide)
362 {
363   g_return_if_fail (GST_IS_AUDIO_BASE_SRC (src));
364
365   GST_OBJECT_LOCK (src);
366   if (provide)
367     GST_OBJECT_FLAG_SET (src, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
368   else
369     GST_OBJECT_FLAG_UNSET (src, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
370   GST_OBJECT_UNLOCK (src);
371 }
372
373 /**
374  * gst_audio_base_src_get_provide_clock:
375  * @src: a #GstAudioBaseSrc
376  *
377  * Queries whether @src will provide a clock or not. See also
378  * gst_audio_base_src_set_provide_clock.
379  *
380  * Returns: %TRUE if @src will provide a clock.
381  */
382 gboolean
383 gst_audio_base_src_get_provide_clock (GstAudioBaseSrc * src)
384 {
385   gboolean result;
386
387   g_return_val_if_fail (GST_IS_AUDIO_BASE_SRC (src), FALSE);
388
389   GST_OBJECT_LOCK (src);
390   result = GST_OBJECT_FLAG_IS_SET (src, GST_ELEMENT_FLAG_PROVIDE_CLOCK);
391   GST_OBJECT_UNLOCK (src);
392
393   return result;
394 }
395
396 /**
397  * gst_audio_base_src_set_slave_method:
398  * @src: a #GstAudioBaseSrc
399  * @method: the new slave method
400  *
401  * Controls how clock slaving will be performed in @src.
402  */
403 void
404 gst_audio_base_src_set_slave_method (GstAudioBaseSrc * src,
405     GstAudioBaseSrcSlaveMethod method)
406 {
407   g_return_if_fail (GST_IS_AUDIO_BASE_SRC (src));
408
409   GST_OBJECT_LOCK (src);
410   src->priv->slave_method = method;
411   GST_OBJECT_UNLOCK (src);
412 }
413
414 /**
415  * gst_audio_base_src_get_slave_method:
416  * @src: a #GstAudioBaseSrc
417  *
418  * Get the current slave method used by @src.
419  *
420  * Returns: The current slave method used by @src.
421  */
422 GstAudioBaseSrcSlaveMethod
423 gst_audio_base_src_get_slave_method (GstAudioBaseSrc * src)
424 {
425   GstAudioBaseSrcSlaveMethod result;
426
427   g_return_val_if_fail (GST_IS_AUDIO_BASE_SRC (src), -1);
428
429   GST_OBJECT_LOCK (src);
430   result = src->priv->slave_method;
431   GST_OBJECT_UNLOCK (src);
432
433   return result;
434 }
435
436 static void
437 gst_audio_base_src_set_property (GObject * object, guint prop_id,
438     const GValue * value, GParamSpec * pspec)
439 {
440   GstAudioBaseSrc *src;
441
442   src = GST_AUDIO_BASE_SRC (object);
443
444   switch (prop_id) {
445     case PROP_BUFFER_TIME:
446       src->buffer_time = g_value_get_int64 (value);
447       break;
448     case PROP_LATENCY_TIME:
449       src->latency_time = g_value_get_int64 (value);
450       break;
451     case PROP_PROVIDE_CLOCK:
452       gst_audio_base_src_set_provide_clock (src, g_value_get_boolean (value));
453       break;
454     case PROP_SLAVE_METHOD:
455       gst_audio_base_src_set_slave_method (src, g_value_get_enum (value));
456       break;
457     default:
458       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
459       break;
460   }
461 }
462
463 static void
464 gst_audio_base_src_get_property (GObject * object, guint prop_id,
465     GValue * value, GParamSpec * pspec)
466 {
467   GstAudioBaseSrc *src;
468
469   src = GST_AUDIO_BASE_SRC (object);
470
471   switch (prop_id) {
472     case PROP_BUFFER_TIME:
473       g_value_set_int64 (value, src->buffer_time);
474       break;
475     case PROP_LATENCY_TIME:
476       g_value_set_int64 (value, src->latency_time);
477       break;
478     case PROP_ACTUAL_BUFFER_TIME:
479       GST_OBJECT_LOCK (src);
480       if (src->ringbuffer && src->ringbuffer->acquired)
481         g_value_set_int64 (value, src->ringbuffer->spec.buffer_time);
482       else
483         g_value_set_int64 (value, DEFAULT_ACTUAL_BUFFER_TIME);
484       GST_OBJECT_UNLOCK (src);
485       break;
486     case PROP_ACTUAL_LATENCY_TIME:
487       GST_OBJECT_LOCK (src);
488       if (src->ringbuffer && src->ringbuffer->acquired)
489         g_value_set_int64 (value, src->ringbuffer->spec.latency_time);
490       else
491         g_value_set_int64 (value, DEFAULT_ACTUAL_LATENCY_TIME);
492       GST_OBJECT_UNLOCK (src);
493       break;
494     case PROP_PROVIDE_CLOCK:
495       g_value_set_boolean (value, gst_audio_base_src_get_provide_clock (src));
496       break;
497     case PROP_SLAVE_METHOD:
498       g_value_set_enum (value, gst_audio_base_src_get_slave_method (src));
499       break;
500     default:
501       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
502       break;
503   }
504 }
505
506 static GstCaps *
507 gst_audio_base_src_fixate (GstBaseSrc * bsrc, GstCaps * caps)
508 {
509   GstStructure *s;
510
511   caps = gst_caps_make_writable (caps);
512
513   s = gst_caps_get_structure (caps, 0);
514
515   /* fields for all formats */
516   gst_structure_fixate_field_nearest_int (s, "rate", GST_AUDIO_DEF_RATE);
517   gst_structure_fixate_field_nearest_int (s, "channels",
518       GST_AUDIO_DEF_CHANNELS);
519   gst_structure_fixate_field_string (s, "format", GST_AUDIO_DEF_FORMAT);
520
521   caps = GST_BASE_SRC_CLASS (parent_class)->fixate (bsrc, caps);
522
523   return caps;
524 }
525
526 static gboolean
527 gst_audio_base_src_setcaps (GstBaseSrc * bsrc, GstCaps * caps)
528 {
529   GstAudioBaseSrc *src = GST_AUDIO_BASE_SRC (bsrc);
530   GstAudioRingBufferSpec *spec;
531   gint bpf, rate;
532
533   spec = &src->ringbuffer->spec;
534
535   spec->buffer_time = src->buffer_time;
536   spec->latency_time = src->latency_time;
537
538   GST_OBJECT_LOCK (src);
539   if (!gst_audio_ring_buffer_parse_caps (spec, caps)) {
540     GST_OBJECT_UNLOCK (src);
541     goto parse_error;
542   }
543
544   bpf = GST_AUDIO_INFO_BPF (&spec->info);
545   rate = GST_AUDIO_INFO_RATE (&spec->info);
546
547   /* calculate suggested segsize and segtotal */
548   spec->segsize = rate * bpf * spec->latency_time / GST_MSECOND;
549   spec->segtotal = spec->buffer_time / spec->latency_time;
550
551   GST_OBJECT_UNLOCK (src);
552
553   GST_DEBUG ("release old ringbuffer");
554
555   gst_audio_ring_buffer_release (src->ringbuffer);
556
557   gst_audio_ring_buffer_debug_spec_buff (spec);
558
559   GST_DEBUG ("acquire new ringbuffer");
560
561   if (!gst_audio_ring_buffer_acquire (src->ringbuffer, spec))
562     goto acquire_error;
563
564   /* calculate actual latency and buffer times */
565   spec->latency_time = spec->segsize * GST_MSECOND / (rate * bpf);
566   spec->buffer_time =
567       spec->segtotal * spec->segsize * GST_MSECOND / (rate * bpf);
568
569   gst_audio_ring_buffer_debug_spec_buff (spec);
570
571   g_object_notify (G_OBJECT (src), "actual-buffer-time");
572   g_object_notify (G_OBJECT (src), "actual-latency-time");
573
574   return TRUE;
575
576   /* ERRORS */
577 parse_error:
578   {
579     GST_DEBUG ("could not parse caps");
580     return FALSE;
581   }
582 acquire_error:
583   {
584     GST_DEBUG ("could not acquire ringbuffer");
585     return FALSE;
586   }
587 }
588
589 static void
590 gst_audio_base_src_get_times (GstBaseSrc * bsrc, GstBuffer * buffer,
591     GstClockTime * start, GstClockTime * end)
592 {
593   /* no need to sync to a clock here, we schedule the samples based
594    * on our own clock for the moment. */
595   *start = GST_CLOCK_TIME_NONE;
596   *end = GST_CLOCK_TIME_NONE;
597 }
598
599 static gboolean
600 gst_audio_base_src_query (GstBaseSrc * bsrc, GstQuery * query)
601 {
602   GstAudioBaseSrc *src = GST_AUDIO_BASE_SRC (bsrc);
603   gboolean res = FALSE;
604
605   switch (GST_QUERY_TYPE (query)) {
606     case GST_QUERY_LATENCY:
607     {
608       GstClockTime min_latency, max_latency;
609       GstAudioRingBufferSpec *spec;
610       gint bpf, rate;
611
612       GST_OBJECT_LOCK (src);
613       if (G_UNLIKELY (src->ringbuffer == NULL
614               || src->ringbuffer->spec.info.rate == 0)) {
615         GST_OBJECT_UNLOCK (src);
616         goto done;
617       }
618
619       spec = &src->ringbuffer->spec;
620       rate = GST_AUDIO_INFO_RATE (&spec->info);
621       bpf = GST_AUDIO_INFO_BPF (&spec->info);
622
623       /* we have at least 1 segment of latency */
624       min_latency =
625           gst_util_uint64_scale_int (spec->segsize, GST_SECOND, rate * bpf);
626       /* we cannot delay more than the buffersize else we lose data */
627       max_latency =
628           gst_util_uint64_scale_int (spec->segtotal * spec->segsize, GST_SECOND,
629           rate * bpf);
630       GST_OBJECT_UNLOCK (src);
631
632       GST_DEBUG_OBJECT (src,
633           "report latency min %" GST_TIME_FORMAT " max %" GST_TIME_FORMAT,
634           GST_TIME_ARGS (min_latency), GST_TIME_ARGS (max_latency));
635
636       /* we are always live, the min latency is 1 segment and the max latency is
637        * the complete buffer of segments. */
638       gst_query_set_latency (query, TRUE, min_latency, max_latency);
639
640       res = TRUE;
641       break;
642     }
643     case GST_QUERY_SCHEDULING:
644     {
645       /* We allow limited pull base operation. Basically pulling can be
646        * done on any number of bytes as long as the offset is -1 or
647        * sequentially increasing. */
648       gst_query_set_scheduling (query, GST_SCHEDULING_FLAG_SEQUENTIAL, 1, -1,
649           0);
650       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PULL);
651       gst_query_add_scheduling_mode (query, GST_PAD_MODE_PUSH);
652
653       res = TRUE;
654       break;
655     }
656     default:
657       res = GST_BASE_SRC_CLASS (parent_class)->query (bsrc, query);
658       break;
659   }
660 done:
661   return res;
662 }
663
664 static gboolean
665 gst_audio_base_src_event (GstBaseSrc * bsrc, GstEvent * event)
666 {
667   GstAudioBaseSrc *src = GST_AUDIO_BASE_SRC (bsrc);
668   gboolean res, forward;
669
670   res = FALSE;
671   forward = TRUE;
672
673   switch (GST_EVENT_TYPE (event)) {
674     case GST_EVENT_FLUSH_START:
675       GST_DEBUG_OBJECT (bsrc, "flush-start");
676       gst_audio_ring_buffer_pause (src->ringbuffer);
677       gst_audio_ring_buffer_clear_all (src->ringbuffer);
678       break;
679     case GST_EVENT_FLUSH_STOP:
680       GST_DEBUG_OBJECT (bsrc, "flush-stop");
681       /* always resync on sample after a flush */
682       src->next_sample = -1;
683       gst_audio_ring_buffer_clear_all (src->ringbuffer);
684       break;
685     case GST_EVENT_SEEK:
686       GST_DEBUG_OBJECT (bsrc, "refuse to seek");
687       forward = FALSE;
688       break;
689     default:
690       GST_DEBUG_OBJECT (bsrc, "forward event %p", event);
691       break;
692   }
693   if (forward)
694     res = GST_BASE_SRC_CLASS (parent_class)->event (bsrc, event);
695
696   return res;
697 }
698
699 /* get the next offset in the ringbuffer for reading samples.
700  * If the next sample is too far away, this function will position itself to the
701  * next most recent sample, creating discontinuity */
702 static guint64
703 gst_audio_base_src_get_offset (GstAudioBaseSrc * src)
704 {
705   guint64 sample;
706   gint readseg, segdone, segtotal, sps;
707   gint diff;
708
709   /* assume we can append to the previous sample */
710   sample = src->next_sample;
711
712   sps = src->ringbuffer->samples_per_seg;
713   segtotal = src->ringbuffer->spec.segtotal;
714
715   /* get the currently processed segment */
716   segdone = g_atomic_int_get (&src->ringbuffer->segdone)
717       - src->ringbuffer->segbase;
718
719   if (sample != -1) {
720     GST_DEBUG_OBJECT (src, "at segment %d and sample %" G_GUINT64_FORMAT,
721         segdone, sample);
722     /* figure out the segment and the offset inside the segment where
723      * the sample should be read from. */
724     readseg = sample / sps;
725
726     /* see how far away it is from the read segment, normally segdone (where new
727      * data is written in the ringbuffer) is bigger than readseg (where we are
728      * reading). */
729     diff = segdone - readseg;
730     if (diff >= segtotal) {
731       GST_DEBUG_OBJECT (src, "dropped, align to segment %d", segdone);
732       /* sample would be dropped, position to next playable position */
733       sample = ((guint64) (segdone)) * sps;
734     }
735   } else {
736     /* no previous sample, go to the current position */
737     GST_DEBUG_OBJECT (src, "first sample, align to current %d", segdone);
738     sample = ((guint64) (segdone)) * sps;
739     readseg = segdone;
740   }
741
742   GST_DEBUG_OBJECT (src,
743       "reading from %d, we are at %d, sample %" G_GUINT64_FORMAT, readseg,
744       segdone, sample);
745
746   return sample;
747 }
748
749 static GstFlowReturn
750 gst_audio_base_src_create (GstBaseSrc * bsrc, guint64 offset, guint length,
751     GstBuffer ** outbuf)
752 {
753   GstFlowReturn ret;
754   GstAudioBaseSrc *src = GST_AUDIO_BASE_SRC (bsrc);
755   GstBuffer *buf;
756   GstMapInfo info;
757   guint8 *ptr;
758   guint samples, total_samples;
759   guint64 sample;
760   gint bpf, rate;
761   GstAudioRingBuffer *ringbuffer;
762   GstAudioRingBufferSpec *spec;
763   guint read;
764   GstClockTime timestamp, duration;
765   GstClockTime rb_timestamp = GST_CLOCK_TIME_NONE;
766   GstClock *clock;
767   gboolean first;
768
769   ringbuffer = src->ringbuffer;
770   spec = &ringbuffer->spec;
771
772   if (G_UNLIKELY (!gst_audio_ring_buffer_is_acquired (ringbuffer)))
773     goto wrong_state;
774
775   bpf = GST_AUDIO_INFO_BPF (&spec->info);
776   rate = GST_AUDIO_INFO_RATE (&spec->info);
777
778   if ((length == 0 && bsrc->blocksize == 0) || length == -1)
779     /* no length given, use the default segment size */
780     length = spec->segsize;
781   else
782     /* make sure we round down to an integral number of samples */
783     length -= length % bpf;
784
785   /* figure out the offset in the ringbuffer */
786   if (G_UNLIKELY (offset != -1)) {
787     sample = offset / bpf;
788     /* if a specific offset was given it must be the next sequential
789      * offset we expect or we fail for now. */
790     if (src->next_sample != -1 && sample != src->next_sample)
791       goto wrong_offset;
792   } else {
793     /* calculate the sequentially next sample we need to read. This can jump and
794      * create a DISCONT. */
795     sample = gst_audio_base_src_get_offset (src);
796   }
797
798   GST_DEBUG_OBJECT (src, "reading from sample %" G_GUINT64_FORMAT " length %u",
799       sample, length);
800
801   /* get the number of samples to read */
802   total_samples = samples = length / bpf;
803
804   /* use the basesrc allocation code to use bufferpools or custom allocators */
805   ret = GST_BASE_SRC_CLASS (parent_class)->alloc (bsrc, offset, length, &buf);
806   if (G_UNLIKELY (ret != GST_FLOW_OK))
807     goto alloc_failed;
808
809   gst_buffer_map (buf, &info, GST_MAP_WRITE);
810   ptr = info.data;
811   first = TRUE;
812   do {
813     GstClockTime tmp_ts;
814
815     read =
816         gst_audio_ring_buffer_read (ringbuffer, sample, ptr, samples, &tmp_ts);
817     if (first && GST_CLOCK_TIME_IS_VALID (tmp_ts)) {
818       first = FALSE;
819       rb_timestamp = tmp_ts;
820     }
821     GST_DEBUG_OBJECT (src, "read %u of %u", read, samples);
822     /* if we read all, we're done */
823     if (read == samples)
824       break;
825
826     /* else something interrupted us and we wait for playing again. */
827     GST_DEBUG_OBJECT (src, "wait playing");
828     if (gst_base_src_wait_playing (bsrc) != GST_FLOW_OK)
829       goto stopped;
830
831     GST_DEBUG_OBJECT (src, "continue playing");
832
833     /* read next samples */
834     sample += read;
835     samples -= read;
836     ptr += read * bpf;
837   } while (TRUE);
838   gst_buffer_unmap (buf, &info);
839
840   /* mark discontinuity if needed */
841   if (G_UNLIKELY (sample != src->next_sample) && src->next_sample != -1) {
842     GST_WARNING_OBJECT (src,
843         "create DISCONT of %" G_GUINT64_FORMAT " samples at sample %"
844         G_GUINT64_FORMAT, sample - src->next_sample, sample);
845     GST_ELEMENT_WARNING (src, CORE, CLOCK,
846         (_("Can't record audio fast enough")),
847         ("Dropped %" G_GUINT64_FORMAT " samples. This is most likely because "
848             "downstream can't keep up and is consuming samples too slowly.",
849             sample - src->next_sample));
850     GST_BUFFER_FLAG_SET (buf, GST_BUFFER_FLAG_DISCONT);
851   }
852
853   src->next_sample = sample + samples;
854
855   /* get the normal timestamp to get the duration. */
856   timestamp = gst_util_uint64_scale_int (sample, GST_SECOND, rate);
857   duration = gst_util_uint64_scale_int (src->next_sample, GST_SECOND,
858       rate) - timestamp;
859
860   GST_OBJECT_LOCK (src);
861   if (!(clock = GST_ELEMENT_CLOCK (src)))
862     goto no_sync;
863
864   if (clock != src->clock) {
865     /* we are slaved, check how to handle this */
866     switch (src->priv->slave_method) {
867       case GST_AUDIO_BASE_SRC_SLAVE_RESAMPLE:
868         /* not implemented, use skew algorithm. This algorithm should
869          * work on the readout pointer and produces more or less samples based
870          * on the clock drift */
871       case GST_AUDIO_BASE_SRC_SLAVE_SKEW:
872       {
873         GstClockTime running_time;
874         GstClockTime base_time;
875         GstClockTime current_time;
876         guint64 running_time_sample;
877         gint running_time_segment;
878         gint last_read_segment;
879         gint segment_skew;
880         gint sps;
881         gint segments_written;
882         gint last_written_segment;
883
884         /* get the amount of segments written from the device by now */
885         segments_written = g_atomic_int_get (&ringbuffer->segdone);
886
887         /* subtract the base to segments_written to get the number of the
888            last written segment in the ringbuffer (one segment written = segment 0) */
889         last_written_segment = segments_written - ringbuffer->segbase - 1;
890
891         /* samples per segment */
892         sps = ringbuffer->samples_per_seg;
893
894         /* get the current time */
895         current_time = gst_clock_get_time (clock);
896
897         /* get the basetime */
898         base_time = GST_ELEMENT_CAST (src)->base_time;
899
900         /* get the running_time */
901         running_time = current_time - base_time;
902
903         /* the running_time converted to a sample (relative to the ringbuffer) */
904         running_time_sample =
905             gst_util_uint64_scale_int (running_time, rate, GST_SECOND);
906
907         /* the segmentnr corresponding to running_time, round down */
908         running_time_segment = running_time_sample / sps;
909
910         /* the segment currently read from the ringbuffer */
911         last_read_segment = sample / sps;
912
913         /* the skew we have between running_time and the ringbuffertime (last written to) */
914         segment_skew = running_time_segment - last_written_segment;
915
916         GST_DEBUG_OBJECT (bsrc,
917             "\n running_time                                              = %"
918             GST_TIME_FORMAT
919             "\n timestamp                                                  = %"
920             GST_TIME_FORMAT
921             "\n running_time_segment                                       = %d"
922             "\n last_written_segment                                       = %d"
923             "\n segment_skew (running time segment - last_written_segment) = %d"
924             "\n last_read_segment                                          = %d",
925             GST_TIME_ARGS (running_time), GST_TIME_ARGS (timestamp),
926             running_time_segment, last_written_segment, segment_skew,
927             last_read_segment);
928
929         /* Resync the ringbuffer if:
930          *
931          * 1. We are more than the length of the ringbuffer behind.
932          *    The length of the ringbuffer then gets to dictate
933          *    the threshold for what is considered "too late"
934          *
935          * 2. If this is our first buffer.
936          *    We know that we should catch up to running_time
937          *    the first time we are ran.
938          */
939         if ((segment_skew >= ringbuffer->spec.segtotal) ||
940             (last_read_segment == 0)) {
941           gint new_read_segment;
942           gint segment_diff;
943           guint64 new_sample;
944
945           /* the difference between running_time and the last written segment */
946           segment_diff = running_time_segment - last_written_segment;
947
948           /* advance the ringbuffer */
949           gst_audio_ring_buffer_advance (ringbuffer, segment_diff);
950
951           /* we move the  new read segment to the last known written segment */
952           new_read_segment =
953               g_atomic_int_get (&ringbuffer->segdone) - ringbuffer->segbase;
954
955           /* we calculate the new sample value */
956           new_sample = ((guint64) new_read_segment) * sps;
957
958           /* and get the relative time to this -> our new timestamp */
959           timestamp = gst_util_uint64_scale_int (new_sample, GST_SECOND, rate);
960
961           /* we update the next sample accordingly */
962           src->next_sample = new_sample + samples;
963
964           GST_DEBUG_OBJECT (bsrc,
965               "Timeshifted the ringbuffer with %d segments: "
966               "Updating the timestamp to %" GST_TIME_FORMAT ", "
967               "and src->next_sample to %" G_GUINT64_FORMAT, segment_diff,
968               GST_TIME_ARGS (timestamp), src->next_sample);
969         }
970         break;
971       }
972       case GST_AUDIO_BASE_SRC_SLAVE_RETIMESTAMP:
973       {
974         GstClockTime base_time, latency;
975
976         /* We are slaved to another clock, take running time of the pipeline clock and
977          * timestamp against it. Somebody else in the pipeline should figure out the
978          * clock drift. We keep the duration we calculated above. */
979         timestamp = gst_clock_get_time (clock);
980         base_time = GST_ELEMENT_CAST (src)->base_time;
981
982         if (GST_CLOCK_DIFF (timestamp, base_time) < 0)
983           timestamp -= base_time;
984         else
985           timestamp = 0;
986
987         /* subtract latency */
988         latency = gst_util_uint64_scale_int (total_samples, GST_SECOND, rate);
989         if (timestamp > latency)
990           timestamp -= latency;
991         else
992           timestamp = 0;
993       }
994       case GST_AUDIO_BASE_SRC_SLAVE_NONE:
995         break;
996     }
997   } else {
998     GstClockTime base_time;
999
1000     if (GST_CLOCK_TIME_IS_VALID (rb_timestamp)) {
1001       /* the read method returned a timestamp so we use this instead */
1002       timestamp = rb_timestamp;
1003     } else {
1004       /* to get the timestamp against the clock we also need to add our offset */
1005       timestamp = gst_audio_clock_adjust (clock, timestamp);
1006     }
1007
1008     /* we are not slaved, subtract base_time */
1009     base_time = GST_ELEMENT_CAST (src)->base_time;
1010
1011     if (GST_CLOCK_DIFF (timestamp, base_time) < 0) {
1012       timestamp -= base_time;
1013       GST_LOG_OBJECT (src,
1014           "buffer timestamp %" GST_TIME_FORMAT " (base_time %" GST_TIME_FORMAT
1015           ")", GST_TIME_ARGS (timestamp), GST_TIME_ARGS (base_time));
1016     } else {
1017       GST_LOG_OBJECT (src,
1018           "buffer timestamp 0, ts %" GST_TIME_FORMAT " <= base_time %"
1019           GST_TIME_FORMAT, GST_TIME_ARGS (timestamp),
1020           GST_TIME_ARGS (base_time));
1021       timestamp = 0;
1022     }
1023   }
1024
1025 no_sync:
1026   GST_OBJECT_UNLOCK (src);
1027
1028   GST_BUFFER_TIMESTAMP (buf) = timestamp;
1029   GST_BUFFER_DURATION (buf) = duration;
1030   GST_BUFFER_OFFSET (buf) = sample;
1031   GST_BUFFER_OFFSET_END (buf) = sample + samples;
1032
1033   *outbuf = buf;
1034
1035   GST_LOG_OBJECT (src, "Pushed buffer timestamp %" GST_TIME_FORMAT,
1036       GST_TIME_ARGS (GST_BUFFER_TIMESTAMP (buf)));
1037
1038   return GST_FLOW_OK;
1039
1040   /* ERRORS */
1041 wrong_state:
1042   {
1043     GST_DEBUG_OBJECT (src, "ringbuffer in wrong state");
1044     return GST_FLOW_FLUSHING;
1045   }
1046 wrong_offset:
1047   {
1048     GST_ELEMENT_ERROR (src, RESOURCE, SEEK,
1049         (NULL), ("resource can only be operated on sequentially but offset %"
1050             G_GUINT64_FORMAT " was given", offset));
1051     return GST_FLOW_ERROR;
1052   }
1053 alloc_failed:
1054   {
1055     GST_DEBUG_OBJECT (src, "alloc failed: %s", gst_flow_get_name (ret));
1056     return ret;
1057   }
1058 stopped:
1059   {
1060     gst_buffer_unref (buf);
1061     GST_DEBUG_OBJECT (src, "ringbuffer stopped");
1062     return GST_FLOW_FLUSHING;
1063   }
1064 }
1065
1066 /**
1067  * gst_audio_base_src_create_ringbuffer:
1068  * @src: a #GstAudioBaseSrc.
1069  *
1070  * Create and return the #GstAudioRingBuffer for @src. This function will call the
1071  * ::create_ringbuffer vmethod and will set @src as the parent of the returned
1072  * buffer (see gst_object_set_parent()).
1073  *
1074  * Returns: (transfer none): The new ringbuffer of @src.
1075  */
1076 GstAudioRingBuffer *
1077 gst_audio_base_src_create_ringbuffer (GstAudioBaseSrc * src)
1078 {
1079   GstAudioBaseSrcClass *bclass;
1080   GstAudioRingBuffer *buffer = NULL;
1081
1082   bclass = GST_AUDIO_BASE_SRC_GET_CLASS (src);
1083   if (bclass->create_ringbuffer)
1084     buffer = bclass->create_ringbuffer (src);
1085
1086   if (G_LIKELY (buffer))
1087     gst_object_set_parent (GST_OBJECT_CAST (buffer), GST_OBJECT_CAST (src));
1088
1089   return buffer;
1090 }
1091
1092 static GstStateChangeReturn
1093 gst_audio_base_src_change_state (GstElement * element,
1094     GstStateChange transition)
1095 {
1096   GstStateChangeReturn ret = GST_STATE_CHANGE_SUCCESS;
1097   GstAudioBaseSrc *src = GST_AUDIO_BASE_SRC (element);
1098
1099   switch (transition) {
1100     case GST_STATE_CHANGE_NULL_TO_READY:
1101       GST_DEBUG_OBJECT (src, "NULL->READY");
1102       GST_OBJECT_LOCK (src);
1103       if (src->ringbuffer == NULL) {
1104         gst_audio_clock_reset (GST_AUDIO_CLOCK (src->clock), 0);
1105         src->ringbuffer = gst_audio_base_src_create_ringbuffer (src);
1106       }
1107       GST_OBJECT_UNLOCK (src);
1108       if (!gst_audio_ring_buffer_open_device (src->ringbuffer))
1109         goto open_failed;
1110       break;
1111     case GST_STATE_CHANGE_READY_TO_PAUSED:
1112       GST_DEBUG_OBJECT (src, "READY->PAUSED");
1113       src->next_sample = -1;
1114       gst_audio_ring_buffer_set_flushing (src->ringbuffer, FALSE);
1115       gst_audio_ring_buffer_may_start (src->ringbuffer, FALSE);
1116       /* Only post clock-provide messages if this is the clock that
1117        * we've created. If the subclass has overriden it the subclass
1118        * should post this messages whenever necessary */
1119       if (src->clock && GST_IS_AUDIO_CLOCK (src->clock) &&
1120           GST_AUDIO_CLOCK_CAST (src->clock)->func ==
1121           (GstAudioClockGetTimeFunc) gst_audio_base_src_get_time)
1122         gst_element_post_message (element,
1123             gst_message_new_clock_provide (GST_OBJECT_CAST (element),
1124                 src->clock, TRUE));
1125       break;
1126     case GST_STATE_CHANGE_PAUSED_TO_PLAYING:
1127       GST_DEBUG_OBJECT (src, "PAUSED->PLAYING");
1128       gst_audio_ring_buffer_may_start (src->ringbuffer, TRUE);
1129       break;
1130     case GST_STATE_CHANGE_PLAYING_TO_PAUSED:
1131       GST_DEBUG_OBJECT (src, "PLAYING->PAUSED");
1132       gst_audio_ring_buffer_may_start (src->ringbuffer, FALSE);
1133       gst_audio_ring_buffer_pause (src->ringbuffer);
1134       break;
1135     case GST_STATE_CHANGE_PAUSED_TO_READY:
1136       GST_DEBUG_OBJECT (src, "PAUSED->READY");
1137       /* Only post clock-lost messages if this is the clock that
1138        * we've created. If the subclass has overriden it the subclass
1139        * should post this messages whenever necessary */
1140       if (src->clock && GST_IS_AUDIO_CLOCK (src->clock) &&
1141           GST_AUDIO_CLOCK_CAST (src->clock)->func ==
1142           (GstAudioClockGetTimeFunc) gst_audio_base_src_get_time)
1143         gst_element_post_message (element,
1144             gst_message_new_clock_lost (GST_OBJECT_CAST (element), src->clock));
1145       gst_audio_ring_buffer_set_flushing (src->ringbuffer, TRUE);
1146       break;
1147     default:
1148       break;
1149   }
1150
1151   ret = GST_ELEMENT_CLASS (parent_class)->change_state (element, transition);
1152
1153   switch (transition) {
1154     case GST_STATE_CHANGE_PAUSED_TO_READY:
1155       GST_DEBUG_OBJECT (src, "PAUSED->READY");
1156       gst_audio_ring_buffer_release (src->ringbuffer);
1157       break;
1158     case GST_STATE_CHANGE_READY_TO_NULL:
1159       GST_DEBUG_OBJECT (src, "READY->NULL");
1160       gst_audio_ring_buffer_close_device (src->ringbuffer);
1161       GST_OBJECT_LOCK (src);
1162       gst_object_unparent (GST_OBJECT_CAST (src->ringbuffer));
1163       src->ringbuffer = NULL;
1164       GST_OBJECT_UNLOCK (src);
1165       break;
1166     default:
1167       break;
1168   }
1169
1170   return ret;
1171
1172   /* ERRORS */
1173 open_failed:
1174   {
1175     /* subclass must post a meaningful error message */
1176     GST_DEBUG_OBJECT (src, "open failed");
1177     return GST_STATE_CHANGE_FAILURE;
1178   }
1179
1180 }