ab1880c687ae9a6874d0561af1ac2fc3e54b7efe
[platform/upstream/gstreamer.git] / gst-libs / gst / audio / gstringbuffer.c
1 /* GStreamer
2  * Copyright (C) 2005 Wim Taymans <wim@fluendo.com>
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /**
21  * SECTION:gstringbuffer
22  * @short_description: Base class for audio ringbuffer implementations
23  * @see_also: #GstBaseAudioSink, #GstAudioSink
24  *
25  * <refsect2>
26  * <para>
27  * This object is the base class for audio ringbuffers used by the base
28  * audio source and sink classes.
29  * </para>
30  * <para>
31  * The ringbuffer abstracts a circular buffer of data. One reader and
32  * one writer can operate on the data from different threads in a lockfree
33  * manner. The base class is sufficiently flexible to be used as an
34  * abstraction for DMA based ringbuffers as well as a pure software
35  * implementations.
36  * </para>
37  * </refsect2>
38  *
39  * Last reviewed on 2006-02-02 (0.10.4)
40  */
41
42 #include <string.h>
43
44 #include "gstringbuffer.h"
45
46 GST_DEBUG_CATEGORY_STATIC (gst_ring_buffer_debug);
47 #define GST_CAT_DEFAULT gst_ring_buffer_debug
48
49 static void gst_ring_buffer_dispose (GObject * object);
50 static void gst_ring_buffer_finalize (GObject * object);
51
52 static gboolean gst_ring_buffer_pause_unlocked (GstRingBuffer * buf);
53 static void default_clear_all (GstRingBuffer * buf);
54 static guint default_commit (GstRingBuffer * buf, guint64 * sample,
55     guchar * data, gint in_samples, gint out_samples, gint * accum);
56
57 /* ringbuffer abstract base class */
58 G_DEFINE_ABSTRACT_TYPE (GstRingBuffer, gst_ring_buffer, GST_TYPE_OBJECT);
59
60 static void
61 gst_ring_buffer_class_init (GstRingBufferClass * klass)
62 {
63   GObjectClass *gobject_class;
64   GstRingBufferClass *gstringbuffer_class;
65
66   gobject_class = (GObjectClass *) klass;
67   gstringbuffer_class = (GstRingBufferClass *) klass;
68
69   GST_DEBUG_CATEGORY_INIT (gst_ring_buffer_debug, "ringbuffer", 0,
70       "ringbuffer class");
71
72   gobject_class->dispose = gst_ring_buffer_dispose;
73   gobject_class->finalize = gst_ring_buffer_finalize;
74
75   gstringbuffer_class->clear_all = GST_DEBUG_FUNCPTR (default_clear_all);
76   gstringbuffer_class->commit = GST_DEBUG_FUNCPTR (default_commit);
77 }
78
79 static void
80 gst_ring_buffer_init (GstRingBuffer * ringbuffer)
81 {
82   ringbuffer->open = FALSE;
83   ringbuffer->acquired = FALSE;
84   ringbuffer->state = GST_RING_BUFFER_STATE_STOPPED;
85   ringbuffer->cond = g_cond_new ();
86   ringbuffer->waiting = 0;
87   ringbuffer->empty_seg = NULL;
88   ringbuffer->abidata.ABI.flushing = TRUE;
89 }
90
91 static void
92 gst_ring_buffer_dispose (GObject * object)
93 {
94   GstRingBuffer *ringbuffer = GST_RING_BUFFER (object);
95
96   gst_caps_replace (&ringbuffer->spec.caps, NULL);
97
98   G_OBJECT_CLASS (gst_ring_buffer_parent_class)->dispose (G_OBJECT
99       (ringbuffer));
100 }
101
102 static void
103 gst_ring_buffer_finalize (GObject * object)
104 {
105   GstRingBuffer *ringbuffer = GST_RING_BUFFER (object);
106
107   g_cond_free (ringbuffer->cond);
108   g_free (ringbuffer->empty_seg);
109
110   G_OBJECT_CLASS (gst_ring_buffer_parent_class)->finalize (G_OBJECT
111       (ringbuffer));
112 }
113
114 typedef struct
115 {
116   const GstBufferFormat format;
117   const guint8 silence[4];
118 } FormatDef;
119
120 static const FormatDef linear_defs[4 * 2 * 2] = {
121   {GST_S8, {0x00, 0x00, 0x00, 0x00}},
122   {GST_S8, {0x00, 0x00, 0x00, 0x00}},
123   {GST_U8, {0x80, 0x80, 0x80, 0x80}},
124   {GST_U8, {0x80, 0x80, 0x80, 0x80}},
125   {GST_S16_LE, {0x00, 0x00, 0x00, 0x00}},
126   {GST_S16_BE, {0x00, 0x00, 0x00, 0x00}},
127   {GST_U16_LE, {0x00, 0x80, 0x00, 0x80}},
128   {GST_U16_BE, {0x80, 0x00, 0x80, 0x00}},
129   {GST_S24_LE, {0x00, 0x00, 0x00, 0x00}},
130   {GST_S24_BE, {0x00, 0x00, 0x00, 0x00}},
131   {GST_U24_LE, {0x00, 0x00, 0x80, 0x00}},
132   {GST_U24_BE, {0x80, 0x00, 0x00, 0x00}},
133   {GST_S32_LE, {0x00, 0x00, 0x00, 0x00}},
134   {GST_S32_BE, {0x00, 0x00, 0x00, 0x00}},
135   {GST_U32_LE, {0x00, 0x00, 0x00, 0x80}},
136   {GST_U32_BE, {0x80, 0x00, 0x00, 0x00}}
137 };
138
139 static const FormatDef linear24_defs[3 * 2 * 2] = {
140   {GST_S24_3LE, {0x00, 0x00, 0x00, 0x00}},
141   {GST_S24_3BE, {0x00, 0x00, 0x00, 0x00}},
142   {GST_U24_3LE, {0x00, 0x00, 0x80, 0x00}},
143   {GST_U24_3BE, {0x80, 0x00, 0x00, 0x00}},
144   {GST_S20_3LE, {0x00, 0x00, 0x00, 0x00}},
145   {GST_S20_3BE, {0x00, 0x00, 0x00, 0x00}},
146   {GST_U20_3LE, {0x00, 0x00, 0x08, 0x00}},
147   {GST_U20_3BE, {0x08, 0x00, 0x00, 0x00}},
148   {GST_S18_3LE, {0x00, 0x00, 0x00, 0x00}},
149   {GST_S18_3BE, {0x00, 0x00, 0x00, 0x00}},
150   {GST_U18_3LE, {0x00, 0x00, 0x02, 0x00}},
151   {GST_U18_3BE, {0x02, 0x00, 0x00, 0x00}}
152 };
153
154 static const FormatDef *
155 build_linear_format (int depth, int width, int unsignd, int big_endian)
156 {
157   const FormatDef *formats;
158
159   if (width == 24) {
160     switch (depth) {
161       case 24:
162         formats = &linear24_defs[0];
163         break;
164       case 20:
165         formats = &linear24_defs[4];
166         break;
167       case 18:
168         formats = &linear24_defs[8];
169         break;
170       default:
171         return NULL;
172     }
173   } else {
174     switch (depth) {
175       case 8:
176         formats = &linear_defs[0];
177         break;
178       case 16:
179         formats = &linear_defs[4];
180         break;
181       case 24:
182         formats = &linear_defs[8];
183         break;
184       case 32:
185         formats = &linear_defs[12];
186         break;
187       default:
188         return NULL;
189     }
190   }
191   if (unsignd)
192     formats += 2;
193   if (big_endian)
194     formats += 1;
195
196   return formats;
197 }
198
199 #ifndef GST_DISABLE_GST_DEBUG
200 static const gchar *format_type_names[] = {
201   "linear",
202   "float",
203   "mu law",
204   "a law",
205   "ima adpcm",
206   "mpeg",
207   "gsm",
208   "iec958",
209   "ac3",
210   "eac3",
211   "dts"
212 };
213
214 static const gchar *format_names[] = {
215   "unknown",
216   "s8",
217   "u8",
218   "s16_le",
219   "s16_be",
220   "u16_le",
221   "u16_be",
222   "s24_le",
223   "s24_be",
224   "u24_le",
225   "u24_be",
226   "s32_le",
227   "s32_be",
228   "u32_le",
229   "u32_be",
230   "s24_3le",
231   "s24_3be",
232   "u24_3le",
233   "u24_3be",
234   "s20_3le",
235   "s20_3be",
236   "u20_3le",
237   "u20_3be",
238   "s18_3le",
239   "s18_3be",
240   "u18_3le",
241   "u18_3be",
242   "float32_le",
243   "float32_be",
244   "float64_le",
245   "float64_be",
246   "mu_law",
247   "a_law",
248   "ima_adpcm",
249   "mpeg",
250   "gsm",
251   "iec958",
252   "ac3",
253   "eac3",
254   "dts"
255 };
256 #endif
257
258 /**
259  * gst_ring_buffer_debug_spec_caps:
260  * @spec: the spec to debug
261  *
262  * Print debug info about the parsed caps in @spec to the debug log.
263  */
264 void
265 gst_ring_buffer_debug_spec_caps (GstRingBufferSpec * spec)
266 {
267   gint i, bytes;
268
269   GST_DEBUG ("spec caps: %p %" GST_PTR_FORMAT, spec->caps, spec->caps);
270   GST_DEBUG ("parsed caps: type:         %d, '%s'", spec->type,
271       format_type_names[spec->type]);
272   GST_DEBUG ("parsed caps: format:       %d, '%s'", spec->format,
273       format_names[spec->format]);
274   GST_DEBUG ("parsed caps: width:        %d", spec->width);
275   GST_DEBUG ("parsed caps: depth:        %d", spec->depth);
276   GST_DEBUG ("parsed caps: sign:         %d", spec->sign);
277   GST_DEBUG ("parsed caps: bigend:       %d", spec->bigend);
278   GST_DEBUG ("parsed caps: rate:         %d", spec->rate);
279   GST_DEBUG ("parsed caps: channels:     %d", spec->channels);
280   GST_DEBUG ("parsed caps: sample bytes: %d", spec->bytes_per_sample);
281   bytes = (spec->width >> 3) * spec->channels;
282   for (i = 0; i < bytes; i++) {
283     GST_DEBUG ("silence byte %d: %02x", i, spec->silence_sample[i]);
284   }
285 }
286
287 /**
288  * gst_ring_buffer_debug_spec_buff:
289  * @spec: the spec to debug
290  *
291  * Print debug info about the buffer sized in @spec to the debug log.
292  */
293 void
294 gst_ring_buffer_debug_spec_buff (GstRingBufferSpec * spec)
295 {
296   GST_DEBUG ("acquire ringbuffer: buffer time: %" G_GINT64_FORMAT " usec",
297       spec->buffer_time);
298   GST_DEBUG ("acquire ringbuffer: latency time: %" G_GINT64_FORMAT " usec",
299       spec->latency_time);
300   GST_DEBUG ("acquire ringbuffer: total segments: %d", spec->segtotal);
301   GST_DEBUG ("acquire ringbuffer: latency segments: %d", spec->seglatency);
302   GST_DEBUG ("acquire ringbuffer: segment size: %d bytes = %d samples",
303       spec->segsize, spec->segsize / spec->bytes_per_sample);
304   GST_DEBUG ("acquire ringbuffer: buffer size: %d bytes = %d samples",
305       spec->segsize * spec->segtotal,
306       spec->segsize * spec->segtotal / spec->bytes_per_sample);
307 }
308
309 /**
310  * gst_ring_buffer_parse_caps:
311  * @spec: a spec
312  * @caps: a #GstCaps
313  *
314  * Parse @caps into @spec.
315  *
316  * Returns: TRUE if the caps could be parsed.
317  */
318 gboolean
319 gst_ring_buffer_parse_caps (GstRingBufferSpec * spec, GstCaps * caps)
320 {
321   const gchar *mimetype;
322   GstStructure *structure;
323   gint i;
324
325   structure = gst_caps_get_structure (caps, 0);
326
327   /* we have to differentiate between int and float formats */
328   mimetype = gst_structure_get_name (structure);
329
330   if (g_str_equal (mimetype, "audio/x-raw-int")) {
331     gint endianness;
332     const FormatDef *def;
333     gint j, bytes;
334
335     spec->type = GST_BUFTYPE_LINEAR;
336
337     /* extract the needed information from the cap */
338     if (!(gst_structure_get_int (structure, "rate", &spec->rate) &&
339             gst_structure_get_int (structure, "channels", &spec->channels) &&
340             gst_structure_get_int (structure, "width", &spec->width) &&
341             gst_structure_get_int (structure, "depth", &spec->depth) &&
342             gst_structure_get_boolean (structure, "signed", &spec->sign)))
343       goto parse_error;
344
345     /* extract endianness if needed */
346     if (spec->width > 8) {
347       if (!gst_structure_get_int (structure, "endianness", &endianness))
348         goto parse_error;
349     } else {
350       endianness = G_BYTE_ORDER;
351     }
352
353     spec->bigend = endianness == G_LITTLE_ENDIAN ? FALSE : TRUE;
354
355     def = build_linear_format (spec->depth, spec->width, spec->sign ? 0 : 1,
356         spec->bigend ? 1 : 0);
357
358     if (def == NULL)
359       goto parse_error;
360
361     spec->format = def->format;
362
363     bytes = spec->width >> 3;
364
365     for (i = 0; i < spec->channels; i++) {
366       for (j = 0; j < bytes; j++) {
367         spec->silence_sample[i * bytes + j] = def->silence[j];
368       }
369     }
370   } else if (g_str_equal (mimetype, "audio/x-raw-float")) {
371
372     spec->type = GST_BUFTYPE_FLOAT;
373
374     /* extract the needed information from the cap */
375     if (!(gst_structure_get_int (structure, "rate", &spec->rate) &&
376             gst_structure_get_int (structure, "channels", &spec->channels) &&
377             gst_structure_get_int (structure, "width", &spec->width)))
378       goto parse_error;
379
380     /* match layout to format wrt to endianness */
381     switch (spec->width) {
382       case 32:
383         spec->format =
384             G_BYTE_ORDER == G_LITTLE_ENDIAN ? GST_FLOAT32_LE : GST_FLOAT32_BE;
385         break;
386       case 64:
387         spec->format =
388             G_BYTE_ORDER == G_LITTLE_ENDIAN ? GST_FLOAT64_LE : GST_FLOAT64_BE;
389         break;
390       default:
391         goto parse_error;
392     }
393     /* float silence is all zeros.. */
394     memset (spec->silence_sample, 0, 32);
395   } else if (g_str_equal (mimetype, "audio/x-alaw")) {
396     /* extract the needed information from the cap */
397     if (!(gst_structure_get_int (structure, "rate", &spec->rate) &&
398             gst_structure_get_int (structure, "channels", &spec->channels)))
399       goto parse_error;
400
401     spec->type = GST_BUFTYPE_A_LAW;
402     spec->format = GST_A_LAW;
403     spec->width = 8;
404     spec->depth = 8;
405     for (i = 0; i < spec->channels; i++)
406       spec->silence_sample[i] = 0xd5;
407   } else if (g_str_equal (mimetype, "audio/x-mulaw")) {
408     /* extract the needed information from the cap */
409     if (!(gst_structure_get_int (structure, "rate", &spec->rate) &&
410             gst_structure_get_int (structure, "channels", &spec->channels)))
411       goto parse_error;
412
413     spec->type = GST_BUFTYPE_MU_LAW;
414     spec->format = GST_MU_LAW;
415     spec->width = 8;
416     spec->depth = 8;
417     for (i = 0; i < spec->channels; i++)
418       spec->silence_sample[i] = 0xff;
419   } else if (g_str_equal (mimetype, "audio/x-iec958")) {
420     /* extract the needed information from the cap */
421     if (!(gst_structure_get_int (structure, "rate", &spec->rate)))
422       goto parse_error;
423
424     spec->type = GST_BUFTYPE_IEC958;
425     spec->format = GST_IEC958;
426     spec->width = 16;
427     spec->depth = 16;
428     spec->channels = 2;
429   } else if (g_str_equal (mimetype, "audio/x-ac3")) {
430     /* extract the needed information from the cap */
431     if (!(gst_structure_get_int (structure, "rate", &spec->rate)))
432       goto parse_error;
433
434     spec->type = GST_BUFTYPE_AC3;
435     spec->format = GST_AC3;
436     spec->width = 16;
437     spec->depth = 16;
438     spec->channels = 2;
439   } else if (g_str_equal (mimetype, "audio/x-eac3")) {
440     /* extract the needed information from the cap */
441     if (!(gst_structure_get_int (structure, "rate", &spec->rate)))
442       goto parse_error;
443
444     spec->type = GST_BUFTYPE_EAC3;
445     spec->format = GST_EAC3;
446     spec->width = 64;
447     spec->depth = 64;
448     spec->channels = 2;
449   } else if (g_str_equal (mimetype, "audio/x-dts")) {
450     /* extract the needed information from the cap */
451     if (!(gst_structure_get_int (structure, "rate", &spec->rate)))
452       goto parse_error;
453
454     spec->type = GST_BUFTYPE_DTS;
455     spec->format = GST_DTS;
456     spec->width = 16;
457     spec->depth = 16;
458     spec->channels = 2;
459   } else if (g_str_equal (mimetype, "audio/mpeg") &&
460       gst_structure_get_int (structure, "mpegaudioversion", &i) &&
461       (i == 1 || i == 2)) {
462     /* Now we know this is MPEG-1 or MPEG-2 (non AAC) */
463     /* extract the needed information from the cap */
464     if (!(gst_structure_get_int (structure, "rate", &spec->rate)))
465       goto parse_error;
466
467     spec->type = GST_BUFTYPE_MPEG;
468     spec->format = GST_MPEG;
469     spec->width = 16;
470     spec->depth = 16;
471     spec->channels = 2;
472   } else {
473     goto parse_error;
474   }
475
476   spec->bytes_per_sample = (spec->width >> 3) * spec->channels;
477
478   gst_caps_replace (&spec->caps, caps);
479
480   g_return_val_if_fail (spec->latency_time != 0, FALSE);
481
482   /* calculate suggested segsize and segtotal. segsize should be one unit
483    * of 'latency_time' samples, scaling for the fact that latency_time is
484    * currently stored in microseconds (FIXME: in 0.11) */
485   spec->segsize = gst_util_uint64_scale (spec->rate * spec->bytes_per_sample,
486       spec->latency_time, GST_SECOND / GST_USECOND);
487   /* Round to an integer number of samples */
488   spec->segsize -= spec->segsize % spec->bytes_per_sample;
489
490   spec->segtotal = spec->buffer_time / spec->latency_time;
491   /* leave the latency undefined now, implementations can change it but if it's
492    * not changed, we assume the same value as segtotal */
493   spec->seglatency = -1;
494
495   gst_ring_buffer_debug_spec_caps (spec);
496   gst_ring_buffer_debug_spec_buff (spec);
497
498   return TRUE;
499
500   /* ERRORS */
501 parse_error:
502   {
503     GST_DEBUG ("could not parse caps");
504     return FALSE;
505   }
506 }
507
508 /**
509  * gst_ring_buffer_convert:
510  * @buf: the #GstRingBuffer
511  * @src_fmt: the source format
512  * @src_val: the source value
513  * @dest_fmt: the destination format
514  * @dest_val: a location to store the converted value
515  *
516  * Convert @src_val in @src_fmt to the equivalent value in @dest_fmt. The result
517  * will be put in @dest_val.
518  *
519  * Returns: TRUE if the conversion succeeded.
520  *
521  * Since: 0.10.22.
522  */
523 gboolean
524 gst_ring_buffer_convert (GstRingBuffer * buf,
525     GstFormat src_fmt, gint64 src_val, GstFormat dest_fmt, gint64 * dest_val)
526 {
527   gboolean res = TRUE;
528   gint bps, rate;
529
530   GST_DEBUG ("converting value %" G_GINT64_FORMAT " from %s (%d) to %s (%d)",
531       src_val, gst_format_get_name (src_fmt), src_fmt,
532       gst_format_get_name (dest_fmt), dest_fmt);
533
534   if (src_fmt == dest_fmt || src_val == -1) {
535     *dest_val = src_val;
536     goto done;
537   }
538
539   /* get important info */
540   GST_OBJECT_LOCK (buf);
541   bps = buf->spec.bytes_per_sample;
542   rate = buf->spec.rate;
543   GST_OBJECT_UNLOCK (buf);
544
545   if (bps == 0 || rate == 0) {
546     GST_DEBUG ("no rate or bps configured");
547     res = FALSE;
548     goto done;
549   }
550
551   switch (src_fmt) {
552     case GST_FORMAT_BYTES:
553       switch (dest_fmt) {
554         case GST_FORMAT_TIME:
555           *dest_val = gst_util_uint64_scale_int (src_val / bps, GST_SECOND,
556               rate);
557           break;
558         case GST_FORMAT_DEFAULT:
559           *dest_val = src_val / bps;
560           break;
561         default:
562           res = FALSE;
563           break;
564       }
565       break;
566     case GST_FORMAT_DEFAULT:
567       switch (dest_fmt) {
568         case GST_FORMAT_TIME:
569           *dest_val = gst_util_uint64_scale_int (src_val, GST_SECOND, rate);
570           break;
571         case GST_FORMAT_BYTES:
572           *dest_val = src_val * bps;
573           break;
574         default:
575           res = FALSE;
576           break;
577       }
578       break;
579     case GST_FORMAT_TIME:
580       switch (dest_fmt) {
581         case GST_FORMAT_DEFAULT:
582           *dest_val = gst_util_uint64_scale_int (src_val, rate, GST_SECOND);
583           break;
584         case GST_FORMAT_BYTES:
585           *dest_val = gst_util_uint64_scale_int (src_val, rate, GST_SECOND);
586           *dest_val *= bps;
587           break;
588         default:
589           res = FALSE;
590           break;
591       }
592       break;
593     default:
594       res = FALSE;
595       break;
596   }
597 done:
598   GST_DEBUG ("ret=%d result %" G_GINT64_FORMAT, res, *dest_val);
599
600   return res;
601 }
602
603 /**
604  * gst_ring_buffer_set_callback:
605  * @buf: the #GstRingBuffer to set the callback on
606  * @cb: the callback to set
607  * @user_data: user data passed to the callback
608  *
609  * Sets the given callback function on the buffer. This function
610  * will be called every time a segment has been written to a device.
611  *
612  * MT safe.
613  */
614 void
615 gst_ring_buffer_set_callback (GstRingBuffer * buf, GstRingBufferCallback cb,
616     gpointer user_data)
617 {
618   g_return_if_fail (GST_IS_RING_BUFFER (buf));
619
620   GST_OBJECT_LOCK (buf);
621   buf->callback = cb;
622   buf->cb_data = user_data;
623   GST_OBJECT_UNLOCK (buf);
624 }
625
626
627 /**
628  * gst_ring_buffer_open_device:
629  * @buf: the #GstRingBuffer
630  *
631  * Open the audio device associated with the ring buffer. Does not perform any
632  * setup on the device. You must open the device before acquiring the ring
633  * buffer.
634  *
635  * Returns: TRUE if the device could be opened, FALSE on error.
636  *
637  * MT safe.
638  */
639 gboolean
640 gst_ring_buffer_open_device (GstRingBuffer * buf)
641 {
642   gboolean res = TRUE;
643   GstRingBufferClass *rclass;
644
645   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
646
647   GST_DEBUG_OBJECT (buf, "opening device");
648
649   GST_OBJECT_LOCK (buf);
650   if (G_UNLIKELY (buf->open))
651     goto was_opened;
652
653   buf->open = TRUE;
654
655   /* if this fails, something is wrong in this file */
656   g_assert (!buf->acquired);
657
658   rclass = GST_RING_BUFFER_GET_CLASS (buf);
659   if (G_LIKELY (rclass->open_device))
660     res = rclass->open_device (buf);
661
662   if (G_UNLIKELY (!res))
663     goto open_failed;
664
665   GST_DEBUG_OBJECT (buf, "opened device");
666
667 done:
668   GST_OBJECT_UNLOCK (buf);
669
670   return res;
671
672   /* ERRORS */
673 was_opened:
674   {
675     GST_DEBUG_OBJECT (buf, "Device for ring buffer already open");
676     g_warning ("Device for ring buffer %p already open, fix your code", buf);
677     res = TRUE;
678     goto done;
679   }
680 open_failed:
681   {
682     buf->open = FALSE;
683     GST_DEBUG_OBJECT (buf, "failed opening device");
684     goto done;
685   }
686 }
687
688 /**
689  * gst_ring_buffer_close_device:
690  * @buf: the #GstRingBuffer
691  *
692  * Close the audio device associated with the ring buffer. The ring buffer
693  * should already have been released via gst_ring_buffer_release().
694  *
695  * Returns: TRUE if the device could be closed, FALSE on error.
696  *
697  * MT safe.
698  */
699 gboolean
700 gst_ring_buffer_close_device (GstRingBuffer * buf)
701 {
702   gboolean res = TRUE;
703   GstRingBufferClass *rclass;
704
705   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
706
707   GST_DEBUG_OBJECT (buf, "closing device");
708
709   GST_OBJECT_LOCK (buf);
710   if (G_UNLIKELY (!buf->open))
711     goto was_closed;
712
713   if (G_UNLIKELY (buf->acquired))
714     goto was_acquired;
715
716   buf->open = FALSE;
717
718   rclass = GST_RING_BUFFER_GET_CLASS (buf);
719   if (G_LIKELY (rclass->close_device))
720     res = rclass->close_device (buf);
721
722   if (G_UNLIKELY (!res))
723     goto close_error;
724
725   GST_DEBUG_OBJECT (buf, "closed device");
726
727 done:
728   GST_OBJECT_UNLOCK (buf);
729
730   return res;
731
732   /* ERRORS */
733 was_closed:
734   {
735     GST_DEBUG_OBJECT (buf, "Device for ring buffer already closed");
736     g_warning ("Device for ring buffer %p already closed, fix your code", buf);
737     res = TRUE;
738     goto done;
739   }
740 was_acquired:
741   {
742     GST_DEBUG_OBJECT (buf, "Resources for ring buffer still acquired");
743     g_critical ("Resources for ring buffer %p still acquired", buf);
744     res = FALSE;
745     goto done;
746   }
747 close_error:
748   {
749     buf->open = TRUE;
750     GST_DEBUG_OBJECT (buf, "error closing device");
751     goto done;
752   }
753 }
754
755 /**
756  * gst_ring_buffer_device_is_open:
757  * @buf: the #GstRingBuffer
758  *
759  * Checks the status of the device associated with the ring buffer.
760  *
761  * Returns: TRUE if the device was open, FALSE if it was closed.
762  *
763  * MT safe.
764  */
765 gboolean
766 gst_ring_buffer_device_is_open (GstRingBuffer * buf)
767 {
768   gboolean res = TRUE;
769
770   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
771
772   GST_OBJECT_LOCK (buf);
773   res = buf->open;
774   GST_OBJECT_UNLOCK (buf);
775
776   return res;
777 }
778
779 /**
780  * gst_ring_buffer_acquire:
781  * @buf: the #GstRingBuffer to acquire
782  * @spec: the specs of the buffer
783  *
784  * Allocate the resources for the ringbuffer. This function fills
785  * in the data pointer of the ring buffer with a valid #GstBuffer
786  * to which samples can be written.
787  *
788  * Returns: TRUE if the device could be acquired, FALSE on error.
789  *
790  * MT safe.
791  */
792 gboolean
793 gst_ring_buffer_acquire (GstRingBuffer * buf, GstRingBufferSpec * spec)
794 {
795   gboolean res = FALSE;
796   GstRingBufferClass *rclass;
797   gint i, j;
798   gint segsize, bps;
799
800   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
801
802   GST_DEBUG_OBJECT (buf, "acquiring device %p", buf);
803
804   GST_OBJECT_LOCK (buf);
805   if (G_UNLIKELY (!buf->open))
806     goto not_opened;
807
808   if (G_UNLIKELY (buf->acquired))
809     goto was_acquired;
810
811   buf->acquired = TRUE;
812
813   rclass = GST_RING_BUFFER_GET_CLASS (buf);
814   if (G_LIKELY (rclass->acquire))
815     res = rclass->acquire (buf, spec);
816
817   if (G_UNLIKELY (!res))
818     goto acquire_failed;
819
820   if (G_UNLIKELY ((bps = buf->spec.bytes_per_sample) == 0))
821     goto invalid_bps;
822
823   /* if the seglatency was overwritten with something else than -1, use it, else
824    * assume segtotal as the latency */
825   if (buf->spec.seglatency == -1)
826     buf->spec.seglatency = buf->spec.segtotal;
827
828   segsize = buf->spec.segsize;
829
830   buf->samples_per_seg = segsize / bps;
831
832   /* create an empty segment */
833   g_free (buf->empty_seg);
834   buf->empty_seg = g_malloc (segsize);
835
836   /* FIXME, we only have 32 silence samples, which might not be enough to
837    * represent silence in all channels */
838   bps = MIN (bps, 32);
839   for (i = 0, j = 0; i < segsize; i++) {
840     buf->empty_seg[i] = buf->spec.silence_sample[j];
841     j = (j + 1) % bps;
842   }
843   GST_DEBUG_OBJECT (buf, "acquired device");
844
845 done:
846   GST_OBJECT_UNLOCK (buf);
847
848   return res;
849
850   /* ERRORS */
851 not_opened:
852   {
853     GST_DEBUG_OBJECT (buf, "device not opened");
854     g_critical ("Device for %p not opened", buf);
855     res = FALSE;
856     goto done;
857   }
858 was_acquired:
859   {
860     res = TRUE;
861     GST_DEBUG_OBJECT (buf, "device was acquired");
862     goto done;
863   }
864 acquire_failed:
865   {
866     buf->acquired = FALSE;
867     GST_DEBUG_OBJECT (buf, "failed to acquire device");
868     goto done;
869   }
870 invalid_bps:
871   {
872     g_warning
873         ("invalid bytes_per_sample from acquire ringbuffer %p, fix the element",
874         buf);
875     buf->acquired = FALSE;
876     res = FALSE;
877     goto done;
878   }
879 }
880
881 /**
882  * gst_ring_buffer_release:
883  * @buf: the #GstRingBuffer to release
884  *
885  * Free the resources of the ringbuffer.
886  *
887  * Returns: TRUE if the device could be released, FALSE on error.
888  *
889  * MT safe.
890  */
891 gboolean
892 gst_ring_buffer_release (GstRingBuffer * buf)
893 {
894   gboolean res = FALSE;
895   GstRingBufferClass *rclass;
896
897   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
898
899   GST_DEBUG_OBJECT (buf, "releasing device");
900
901   gst_ring_buffer_stop (buf);
902
903   GST_OBJECT_LOCK (buf);
904   if (G_UNLIKELY (!buf->acquired))
905     goto was_released;
906
907   buf->acquired = FALSE;
908
909   /* if this fails, something is wrong in this file */
910   g_assert (buf->open == TRUE);
911
912   rclass = GST_RING_BUFFER_GET_CLASS (buf);
913   if (G_LIKELY (rclass->release))
914     res = rclass->release (buf);
915
916   /* signal any waiters */
917   GST_DEBUG_OBJECT (buf, "signal waiter");
918   GST_RING_BUFFER_SIGNAL (buf);
919
920   if (G_UNLIKELY (!res))
921     goto release_failed;
922
923   g_free (buf->empty_seg);
924   buf->empty_seg = NULL;
925   GST_DEBUG_OBJECT (buf, "released device");
926
927 done:
928   GST_OBJECT_UNLOCK (buf);
929
930   return res;
931
932   /* ERRORS */
933 was_released:
934   {
935     res = TRUE;
936     GST_DEBUG_OBJECT (buf, "device was released");
937     goto done;
938   }
939 release_failed:
940   {
941     buf->acquired = TRUE;
942     GST_DEBUG_OBJECT (buf, "failed to release device");
943     goto done;
944   }
945 }
946
947 /**
948  * gst_ring_buffer_is_acquired:
949  * @buf: the #GstRingBuffer to check
950  *
951  * Check if the ringbuffer is acquired and ready to use.
952  *
953  * Returns: TRUE if the ringbuffer is acquired, FALSE on error.
954  *
955  * MT safe.
956  */
957 gboolean
958 gst_ring_buffer_is_acquired (GstRingBuffer * buf)
959 {
960   gboolean res;
961
962   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
963
964   GST_OBJECT_LOCK (buf);
965   res = buf->acquired;
966   GST_OBJECT_UNLOCK (buf);
967
968   return res;
969 }
970
971 /**
972  * gst_ring_buffer_activate:
973  * @buf: the #GstRingBuffer to activate
974  * @active: the new mode
975  *
976  * Activate @buf to start or stop pulling data.
977  *
978  * MT safe.
979  *
980  * Returns: TRUE if the device could be activated in the requested mode,
981  * FALSE on error.
982  *
983  * Since: 0.10.22.
984  */
985 gboolean
986 gst_ring_buffer_activate (GstRingBuffer * buf, gboolean active)
987 {
988   gboolean res = FALSE;
989   GstRingBufferClass *rclass;
990
991   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
992
993   GST_DEBUG_OBJECT (buf, "activate device");
994
995   GST_OBJECT_LOCK (buf);
996   if (G_UNLIKELY (active && !buf->acquired))
997     goto not_acquired;
998
999   if (G_UNLIKELY (buf->abidata.ABI.active == active))
1000     goto was_active;
1001
1002   rclass = GST_RING_BUFFER_GET_CLASS (buf);
1003   /* if there is no activate function we assume it was started/released
1004    * in the acquire method */
1005   if (G_LIKELY (rclass->activate))
1006     res = rclass->activate (buf, active);
1007   else
1008     res = TRUE;
1009
1010   if (G_UNLIKELY (!res))
1011     goto activate_failed;
1012
1013   buf->abidata.ABI.active = active;
1014
1015 done:
1016   GST_OBJECT_UNLOCK (buf);
1017
1018   return res;
1019
1020   /* ERRORS */
1021 not_acquired:
1022   {
1023     GST_DEBUG_OBJECT (buf, "device not acquired");
1024     g_critical ("Device for %p not acquired", buf);
1025     res = FALSE;
1026     goto done;
1027   }
1028 was_active:
1029   {
1030     res = TRUE;
1031     GST_DEBUG_OBJECT (buf, "device was active in mode %d", active);
1032     goto done;
1033   }
1034 activate_failed:
1035   {
1036     GST_DEBUG_OBJECT (buf, "failed to activate device");
1037     goto done;
1038   }
1039 }
1040
1041 /**
1042  * gst_ring_buffer_is_active:
1043  * @buf: the #GstRingBuffer
1044  *
1045  * Check if @buf is activated.
1046  *
1047  * MT safe.
1048  *
1049  * Returns: TRUE if the device is active.
1050  *
1051  * Since: 0.10.22.
1052  */
1053 gboolean
1054 gst_ring_buffer_is_active (GstRingBuffer * buf)
1055 {
1056   gboolean res;
1057
1058   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
1059
1060   GST_OBJECT_LOCK (buf);
1061   res = buf->abidata.ABI.active;
1062   GST_OBJECT_UNLOCK (buf);
1063
1064   return res;
1065 }
1066
1067
1068 /**
1069  * gst_ring_buffer_set_flushing:
1070  * @buf: the #GstRingBuffer to flush
1071  * @flushing: the new mode
1072  *
1073  * Set the ringbuffer to flushing mode or normal mode.
1074  *
1075  * MT safe.
1076  */
1077 void
1078 gst_ring_buffer_set_flushing (GstRingBuffer * buf, gboolean flushing)
1079 {
1080   g_return_if_fail (GST_IS_RING_BUFFER (buf));
1081
1082   GST_OBJECT_LOCK (buf);
1083   buf->abidata.ABI.flushing = flushing;
1084
1085   if (flushing) {
1086     gst_ring_buffer_pause_unlocked (buf);
1087   } else {
1088     gst_ring_buffer_clear_all (buf);
1089   }
1090   GST_OBJECT_UNLOCK (buf);
1091 }
1092
1093 /**
1094  * gst_ring_buffer_start:
1095  * @buf: the #GstRingBuffer to start
1096  *
1097  * Start processing samples from the ringbuffer.
1098  *
1099  * Returns: TRUE if the device could be started, FALSE on error.
1100  *
1101  * MT safe.
1102  */
1103 gboolean
1104 gst_ring_buffer_start (GstRingBuffer * buf)
1105 {
1106   gboolean res = FALSE;
1107   GstRingBufferClass *rclass;
1108   gboolean resume = FALSE;
1109
1110   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
1111
1112   GST_DEBUG_OBJECT (buf, "starting ringbuffer");
1113
1114   GST_OBJECT_LOCK (buf);
1115   if (G_UNLIKELY (buf->abidata.ABI.flushing))
1116     goto flushing;
1117
1118   if (G_UNLIKELY (!buf->acquired))
1119     goto not_acquired;
1120
1121   if (G_UNLIKELY (g_atomic_int_get (&buf->abidata.ABI.may_start) == FALSE))
1122     goto may_not_start;
1123
1124   /* if stopped, set to started */
1125   res = g_atomic_int_compare_and_exchange (&buf->state,
1126       GST_RING_BUFFER_STATE_STOPPED, GST_RING_BUFFER_STATE_STARTED);
1127
1128   if (!res) {
1129     GST_DEBUG_OBJECT (buf, "was not stopped, try paused");
1130     /* was not stopped, try from paused */
1131     res = g_atomic_int_compare_and_exchange (&buf->state,
1132         GST_RING_BUFFER_STATE_PAUSED, GST_RING_BUFFER_STATE_STARTED);
1133     if (!res) {
1134       /* was not paused either, must be started then */
1135       res = TRUE;
1136       GST_DEBUG_OBJECT (buf, "was not paused, must have been started");
1137       goto done;
1138     }
1139     resume = TRUE;
1140     GST_DEBUG_OBJECT (buf, "resuming");
1141   }
1142
1143   rclass = GST_RING_BUFFER_GET_CLASS (buf);
1144   if (resume) {
1145     if (G_LIKELY (rclass->resume))
1146       res = rclass->resume (buf);
1147   } else {
1148     if (G_LIKELY (rclass->start))
1149       res = rclass->start (buf);
1150   }
1151
1152   if (G_UNLIKELY (!res)) {
1153     buf->state = GST_RING_BUFFER_STATE_PAUSED;
1154     GST_DEBUG_OBJECT (buf, "failed to start");
1155   } else {
1156     GST_DEBUG_OBJECT (buf, "started");
1157   }
1158
1159 done:
1160   GST_OBJECT_UNLOCK (buf);
1161
1162   return res;
1163
1164 flushing:
1165   {
1166     GST_DEBUG_OBJECT (buf, "we are flushing");
1167     GST_OBJECT_UNLOCK (buf);
1168     return FALSE;
1169   }
1170 not_acquired:
1171   {
1172     GST_DEBUG_OBJECT (buf, "we are not acquired");
1173     GST_OBJECT_UNLOCK (buf);
1174     return FALSE;
1175   }
1176 may_not_start:
1177   {
1178     GST_DEBUG_OBJECT (buf, "we may not start");
1179     GST_OBJECT_UNLOCK (buf);
1180     return FALSE;
1181   }
1182 }
1183
1184 static gboolean
1185 gst_ring_buffer_pause_unlocked (GstRingBuffer * buf)
1186 {
1187   gboolean res = FALSE;
1188   GstRingBufferClass *rclass;
1189
1190   GST_DEBUG_OBJECT (buf, "pausing ringbuffer");
1191
1192   /* if started, set to paused */
1193   res = g_atomic_int_compare_and_exchange (&buf->state,
1194       GST_RING_BUFFER_STATE_STARTED, GST_RING_BUFFER_STATE_PAUSED);
1195
1196   if (!res)
1197     goto not_started;
1198
1199   /* signal any waiters */
1200   GST_DEBUG_OBJECT (buf, "signal waiter");
1201   GST_RING_BUFFER_SIGNAL (buf);
1202
1203   rclass = GST_RING_BUFFER_GET_CLASS (buf);
1204   if (G_LIKELY (rclass->pause))
1205     res = rclass->pause (buf);
1206
1207   if (G_UNLIKELY (!res)) {
1208     buf->state = GST_RING_BUFFER_STATE_STARTED;
1209     GST_DEBUG_OBJECT (buf, "failed to pause");
1210   } else {
1211     GST_DEBUG_OBJECT (buf, "paused");
1212   }
1213
1214   return res;
1215
1216 not_started:
1217   {
1218     /* was not started */
1219     GST_DEBUG_OBJECT (buf, "was not started");
1220     return TRUE;
1221   }
1222 }
1223
1224 /**
1225  * gst_ring_buffer_pause:
1226  * @buf: the #GstRingBuffer to pause
1227  *
1228  * Pause processing samples from the ringbuffer.
1229  *
1230  * Returns: TRUE if the device could be paused, FALSE on error.
1231  *
1232  * MT safe.
1233  */
1234 gboolean
1235 gst_ring_buffer_pause (GstRingBuffer * buf)
1236 {
1237   gboolean res = FALSE;
1238
1239   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
1240
1241   GST_OBJECT_LOCK (buf);
1242   if (G_UNLIKELY (buf->abidata.ABI.flushing))
1243     goto flushing;
1244
1245   if (G_UNLIKELY (!buf->acquired))
1246     goto not_acquired;
1247
1248   res = gst_ring_buffer_pause_unlocked (buf);
1249   GST_OBJECT_UNLOCK (buf);
1250
1251   return res;
1252
1253   /* ERRORS */
1254 flushing:
1255   {
1256     GST_DEBUG_OBJECT (buf, "we are flushing");
1257     GST_OBJECT_UNLOCK (buf);
1258     return FALSE;
1259   }
1260 not_acquired:
1261   {
1262     GST_DEBUG_OBJECT (buf, "not acquired");
1263     GST_OBJECT_UNLOCK (buf);
1264     return FALSE;
1265   }
1266 }
1267
1268 /**
1269  * gst_ring_buffer_stop:
1270  * @buf: the #GstRingBuffer to stop
1271  *
1272  * Stop processing samples from the ringbuffer.
1273  *
1274  * Returns: TRUE if the device could be stopped, FALSE on error.
1275  *
1276  * MT safe.
1277  */
1278 gboolean
1279 gst_ring_buffer_stop (GstRingBuffer * buf)
1280 {
1281   gboolean res = FALSE;
1282   GstRingBufferClass *rclass;
1283
1284   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
1285
1286   GST_DEBUG_OBJECT (buf, "stopping");
1287
1288   GST_OBJECT_LOCK (buf);
1289
1290   /* if started, set to stopped */
1291   res = g_atomic_int_compare_and_exchange (&buf->state,
1292       GST_RING_BUFFER_STATE_STARTED, GST_RING_BUFFER_STATE_STOPPED);
1293
1294   if (!res) {
1295     GST_DEBUG_OBJECT (buf, "was not started, try paused");
1296     /* was not started, try from paused */
1297     res = g_atomic_int_compare_and_exchange (&buf->state,
1298         GST_RING_BUFFER_STATE_PAUSED, GST_RING_BUFFER_STATE_STOPPED);
1299     if (!res) {
1300       /* was not paused either, must have been stopped then */
1301       res = TRUE;
1302       GST_DEBUG_OBJECT (buf, "was not paused, must have been stopped");
1303       goto done;
1304     }
1305   }
1306
1307   /* signal any waiters */
1308   GST_DEBUG_OBJECT (buf, "signal waiter");
1309   GST_RING_BUFFER_SIGNAL (buf);
1310
1311   rclass = GST_RING_BUFFER_GET_CLASS (buf);
1312   if (G_LIKELY (rclass->stop))
1313     res = rclass->stop (buf);
1314
1315   if (G_UNLIKELY (!res)) {
1316     buf->state = GST_RING_BUFFER_STATE_STARTED;
1317     GST_DEBUG_OBJECT (buf, "failed to stop");
1318   } else {
1319     GST_DEBUG_OBJECT (buf, "stopped");
1320   }
1321 done:
1322   GST_OBJECT_UNLOCK (buf);
1323
1324   return res;
1325 }
1326
1327 /**
1328  * gst_ring_buffer_delay:
1329  * @buf: the #GstRingBuffer to query
1330  *
1331  * Get the number of samples queued in the audio device. This is
1332  * usually less than the segment size but can be bigger when the
1333  * implementation uses another internal buffer between the audio
1334  * device.
1335  *
1336  * For playback ringbuffers this is the amount of samples transfered from the
1337  * ringbuffer to the device but still not played.
1338  *
1339  * For capture ringbuffers this is the amount of samples in the device that are
1340  * not yet transfered to the ringbuffer.
1341  *
1342  * Returns: The number of samples queued in the audio device.
1343  *
1344  * MT safe.
1345  */
1346 guint
1347 gst_ring_buffer_delay (GstRingBuffer * buf)
1348 {
1349   GstRingBufferClass *rclass;
1350   guint res;
1351
1352   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), 0);
1353
1354   /* buffer must be acquired */
1355   if (G_UNLIKELY (!gst_ring_buffer_is_acquired (buf)))
1356     goto not_acquired;
1357
1358   rclass = GST_RING_BUFFER_GET_CLASS (buf);
1359   if (G_LIKELY (rclass->delay))
1360     res = rclass->delay (buf);
1361   else
1362     res = 0;
1363
1364   return res;
1365
1366 not_acquired:
1367   {
1368     GST_DEBUG_OBJECT (buf, "not acquired");
1369     return 0;
1370   }
1371 }
1372
1373 /**
1374  * gst_ring_buffer_samples_done:
1375  * @buf: the #GstRingBuffer to query
1376  *
1377  * Get the number of samples that were processed by the ringbuffer
1378  * since it was last started. This does not include the number of samples not
1379  * yet processed (see gst_ring_buffer_delay()).
1380  *
1381  * Returns: The number of samples processed by the ringbuffer.
1382  *
1383  * MT safe.
1384  */
1385 guint64
1386 gst_ring_buffer_samples_done (GstRingBuffer * buf)
1387 {
1388   gint segdone;
1389   guint64 samples;
1390
1391   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), 0);
1392
1393   /* get the amount of segments we processed */
1394   segdone = g_atomic_int_get (&buf->segdone);
1395
1396   /* convert to samples */
1397   samples = ((guint64) segdone) * buf->samples_per_seg;
1398
1399   return samples;
1400 }
1401
1402 /**
1403  * gst_ring_buffer_set_sample:
1404  * @buf: the #GstRingBuffer to use
1405  * @sample: the sample number to set
1406  *
1407  * Make sure that the next sample written to the device is
1408  * accounted for as being the @sample sample written to the
1409  * device. This value will be used in reporting the current
1410  * sample position of the ringbuffer.
1411  *
1412  * This function will also clear the buffer with silence.
1413  *
1414  * MT safe.
1415  */
1416 void
1417 gst_ring_buffer_set_sample (GstRingBuffer * buf, guint64 sample)
1418 {
1419   g_return_if_fail (GST_IS_RING_BUFFER (buf));
1420
1421   if (sample == -1)
1422     sample = 0;
1423
1424   if (G_UNLIKELY (buf->samples_per_seg == 0))
1425     return;
1426
1427   /* FIXME, we assume the ringbuffer can restart at a random 
1428    * position, round down to the beginning and keep track of
1429    * offset when calculating the processed samples. */
1430   buf->segbase = buf->segdone - sample / buf->samples_per_seg;
1431
1432   gst_ring_buffer_clear_all (buf);
1433
1434   GST_DEBUG_OBJECT (buf, "set sample to %" G_GUINT64_FORMAT ", segbase %d",
1435       sample, buf->segbase);
1436 }
1437
1438 static void
1439 default_clear_all (GstRingBuffer * buf)
1440 {
1441   gint i;
1442
1443   /* not fatal, we just are not negotiated yet */
1444   if (G_UNLIKELY (buf->spec.segtotal <= 0))
1445     return;
1446
1447   GST_DEBUG_OBJECT (buf, "clear all segments");
1448
1449   for (i = 0; i < buf->spec.segtotal; i++) {
1450     gst_ring_buffer_clear (buf, i);
1451   }
1452 }
1453
1454 /**
1455  * gst_ring_buffer_clear_all:
1456  * @buf: the #GstRingBuffer to clear
1457  *
1458  * Fill the ringbuffer with silence.
1459  *
1460  * MT safe.
1461  */
1462 void
1463 gst_ring_buffer_clear_all (GstRingBuffer * buf)
1464 {
1465   GstRingBufferClass *rclass;
1466
1467   g_return_if_fail (GST_IS_RING_BUFFER (buf));
1468
1469   rclass = GST_RING_BUFFER_GET_CLASS (buf);
1470
1471   if (G_LIKELY (rclass->clear_all))
1472     rclass->clear_all (buf);
1473 }
1474
1475
1476 static gboolean
1477 wait_segment (GstRingBuffer * buf)
1478 {
1479   gint segments;
1480   gboolean wait = TRUE;
1481
1482   /* buffer must be started now or we deadlock since nobody is reading */
1483   if (G_UNLIKELY (g_atomic_int_get (&buf->state) !=
1484           GST_RING_BUFFER_STATE_STARTED)) {
1485     /* see if we are allowed to start it */
1486     if (G_UNLIKELY (g_atomic_int_get (&buf->abidata.ABI.may_start) == FALSE))
1487       goto no_start;
1488
1489     GST_DEBUG_OBJECT (buf, "start!");
1490     segments = g_atomic_int_get (&buf->segdone);
1491     gst_ring_buffer_start (buf);
1492
1493     /* After starting, the writer may have wrote segments already and then we
1494      * don't need to wait anymore */
1495     if (G_LIKELY (g_atomic_int_get (&buf->segdone) != segments))
1496       wait = FALSE;
1497   }
1498
1499   /* take lock first, then update our waiting flag */
1500   GST_OBJECT_LOCK (buf);
1501   if (G_UNLIKELY (buf->abidata.ABI.flushing))
1502     goto flushing;
1503
1504   if (G_UNLIKELY (g_atomic_int_get (&buf->state) !=
1505           GST_RING_BUFFER_STATE_STARTED))
1506     goto not_started;
1507
1508   if (G_LIKELY (wait)) {
1509     if (g_atomic_int_compare_and_exchange (&buf->waiting, 0, 1)) {
1510       GST_DEBUG_OBJECT (buf, "waiting..");
1511       GST_RING_BUFFER_WAIT (buf);
1512
1513       if (G_UNLIKELY (buf->abidata.ABI.flushing))
1514         goto flushing;
1515
1516       if (G_UNLIKELY (g_atomic_int_get (&buf->state) !=
1517               GST_RING_BUFFER_STATE_STARTED))
1518         goto not_started;
1519     }
1520   }
1521   GST_OBJECT_UNLOCK (buf);
1522
1523   return TRUE;
1524
1525   /* ERROR */
1526 not_started:
1527   {
1528     g_atomic_int_compare_and_exchange (&buf->waiting, 1, 0);
1529     GST_DEBUG_OBJECT (buf, "stopped processing");
1530     GST_OBJECT_UNLOCK (buf);
1531     return FALSE;
1532   }
1533 flushing:
1534   {
1535     g_atomic_int_compare_and_exchange (&buf->waiting, 1, 0);
1536     GST_DEBUG_OBJECT (buf, "flushing");
1537     GST_OBJECT_UNLOCK (buf);
1538     return FALSE;
1539   }
1540 no_start:
1541   {
1542     GST_DEBUG_OBJECT (buf, "not allowed to start");
1543     return FALSE;
1544   }
1545 }
1546
1547 #define FWD_SAMPLES(s,se,d,de)                  \
1548 G_STMT_START {                                  \
1549   /* no rate conversion */                      \
1550   guint towrite = MIN (se + bps - s, de - d);   \
1551   /* simple copy */                             \
1552   if (!skip)                                    \
1553     memcpy (d, s, towrite);                     \
1554   in_samples -= towrite / bps;                  \
1555   out_samples -= towrite / bps;                 \
1556   s += towrite;                                 \
1557   GST_DEBUG ("copy %u bytes", towrite);         \
1558 } G_STMT_END
1559
1560 /* in_samples >= out_samples, rate > 1.0 */
1561 #define FWD_UP_SAMPLES(s,se,d,de)               \
1562 G_STMT_START {                                  \
1563   guint8 *sb = s, *db = d;                      \
1564   while (s <= se && d < de) {                   \
1565     if (!skip)                                  \
1566       memcpy (d, s, bps);                       \
1567     s += bps;                                   \
1568     *accum += outr;                             \
1569     if ((*accum << 1) >= inr) {                 \
1570       *accum -= inr;                            \
1571       d += bps;                                 \
1572     }                                           \
1573   }                                             \
1574   in_samples -= (s - sb)/bps;                   \
1575   out_samples -= (d - db)/bps;                  \
1576   GST_DEBUG ("fwd_up end %d/%d",*accum,*toprocess);     \
1577 } G_STMT_END
1578
1579 /* out_samples > in_samples, for rates smaller than 1.0 */
1580 #define FWD_DOWN_SAMPLES(s,se,d,de)             \
1581 G_STMT_START {                                  \
1582   guint8 *sb = s, *db = d;                      \
1583   while (s <= se && d < de) {                   \
1584     if (!skip)                                  \
1585       memcpy (d, s, bps);                       \
1586     d += bps;                                   \
1587     *accum += inr;                              \
1588     if ((*accum << 1) >= outr) {                \
1589       *accum -= outr;                           \
1590       s += bps;                                 \
1591     }                                           \
1592   }                                             \
1593   in_samples -= (s - sb)/bps;                   \
1594   out_samples -= (d - db)/bps;                  \
1595   GST_DEBUG ("fwd_down end %d/%d",*accum,*toprocess);   \
1596 } G_STMT_END
1597
1598 #define REV_UP_SAMPLES(s,se,d,de)               \
1599 G_STMT_START {                                  \
1600   guint8 *sb = se, *db = d;                     \
1601   while (s <= se && d < de) {                   \
1602     if (!skip)                                  \
1603       memcpy (d, se, bps);                      \
1604     se -= bps;                                  \
1605     *accum += outr;                             \
1606     while (d < de && (*accum << 1) >= inr) {    \
1607       *accum -= inr;                            \
1608       d += bps;                                 \
1609     }                                           \
1610   }                                             \
1611   in_samples -= (sb - se)/bps;                  \
1612   out_samples -= (d - db)/bps;                  \
1613   GST_DEBUG ("rev_up end %d/%d",*accum,*toprocess);     \
1614 } G_STMT_END
1615
1616 #define REV_DOWN_SAMPLES(s,se,d,de)             \
1617 G_STMT_START {                                  \
1618   guint8 *sb = se, *db = d;                     \
1619   while (s <= se && d < de) {                   \
1620     if (!skip)                                  \
1621       memcpy (d, se, bps);                      \
1622     d += bps;                                   \
1623     *accum += inr;                              \
1624     while (s <= se && (*accum << 1) >= outr) {  \
1625       *accum -= outr;                           \
1626       se -= bps;                                \
1627     }                                           \
1628   }                                             \
1629   in_samples -= (sb - se)/bps;                  \
1630   out_samples -= (d - db)/bps;                  \
1631   GST_DEBUG ("rev_down end %d/%d",*accum,*toprocess);   \
1632 } G_STMT_END
1633
1634 static guint
1635 default_commit (GstRingBuffer * buf, guint64 * sample,
1636     guchar * data, gint in_samples, gint out_samples, gint * accum)
1637 {
1638   gint segdone;
1639   gint segsize, segtotal, bps, sps;
1640   guint8 *dest, *data_end;
1641   gint writeseg, sampleoff;
1642   gint *toprocess;
1643   gint inr, outr;
1644   gboolean reverse;
1645
1646   g_return_val_if_fail (buf->data != NULL, -1);
1647   g_return_val_if_fail (data != NULL, -1);
1648
1649   dest = GST_BUFFER_DATA (buf->data);
1650   segsize = buf->spec.segsize;
1651   segtotal = buf->spec.segtotal;
1652   bps = buf->spec.bytes_per_sample;
1653   sps = buf->samples_per_seg;
1654
1655   reverse = out_samples < 0;
1656   out_samples = ABS (out_samples);
1657
1658   if (in_samples >= out_samples)
1659     toprocess = &in_samples;
1660   else
1661     toprocess = &out_samples;
1662
1663   inr = in_samples - 1;
1664   outr = out_samples - 1;
1665
1666   /* data_end points to the last sample we have to write, not past it. This is
1667    * needed to properly handle reverse playback: it points to the last sample. */
1668   data_end = data + (bps * inr);
1669
1670   /* figure out the segment and the offset inside the segment where
1671    * the first sample should be written. */
1672   writeseg = *sample / sps;
1673   sampleoff = (*sample % sps) * bps;
1674
1675   /* write out all samples */
1676   while (*toprocess > 0) {
1677     gint avail;
1678     guint8 *d, *d_end;
1679     gint ws;
1680     gboolean skip;
1681
1682     while (TRUE) {
1683       gint diff;
1684
1685       /* get the currently processed segment */
1686       segdone = g_atomic_int_get (&buf->segdone) - buf->segbase;
1687
1688       /* see how far away it is from the write segment */
1689       diff = writeseg - segdone;
1690
1691       GST_DEBUG
1692           ("pointer at %d, write to %d-%d, diff %d, segtotal %d, segsize %d, base %d",
1693           segdone, writeseg, sampleoff, diff, segtotal, segsize, buf->segbase);
1694
1695       /* segment too far ahead, writer too slow, we need to drop, hopefully UNLIKELY */
1696       if (G_UNLIKELY (diff < 0)) {
1697         /* we need to drop one segment at a time, pretend we wrote a
1698          * segment. */
1699         skip = TRUE;
1700         break;
1701       }
1702
1703       /* write segment is within writable range, we can break the loop and
1704        * start writing the data. */
1705       if (diff < segtotal) {
1706         skip = FALSE;
1707         break;
1708       }
1709
1710       /* else we need to wait for the segment to become writable. */
1711       if (!wait_segment (buf))
1712         goto not_started;
1713     }
1714
1715     /* we can write now */
1716     ws = writeseg % segtotal;
1717     avail = MIN (segsize - sampleoff, bps * out_samples);
1718
1719     d = dest + (ws * segsize) + sampleoff;
1720     d_end = d + avail;
1721     *sample += avail / bps;
1722
1723     GST_DEBUG_OBJECT (buf, "write @%p seg %d, sps %d, off %d, avail %d",
1724         dest + ws * segsize, ws, sps, sampleoff, avail);
1725
1726     if (G_LIKELY (inr == outr && !reverse)) {
1727       /* no rate conversion, simply copy samples */
1728       FWD_SAMPLES (data, data_end, d, d_end);
1729     } else if (!reverse) {
1730       if (inr >= outr)
1731         /* forward speed up */
1732         FWD_UP_SAMPLES (data, data_end, d, d_end);
1733       else
1734         /* forward slow down */
1735         FWD_DOWN_SAMPLES (data, data_end, d, d_end);
1736     } else {
1737       if (inr >= outr)
1738         /* reverse speed up */
1739         REV_UP_SAMPLES (data, data_end, d, d_end);
1740       else
1741         /* reverse slow down */
1742         REV_DOWN_SAMPLES (data, data_end, d, d_end);
1743     }
1744
1745     /* for the next iteration we write to the next segment at the beginning. */
1746     writeseg++;
1747     sampleoff = 0;
1748   }
1749   /* we consumed all samples here */
1750   data = data_end + bps;
1751
1752 done:
1753   return inr - ((data_end - data) / bps);
1754
1755   /* ERRORS */
1756 not_started:
1757   {
1758     GST_DEBUG_OBJECT (buf, "stopped processing");
1759     goto done;
1760   }
1761 }
1762
1763 /**
1764  * gst_ring_buffer_commit_full:
1765  * @buf: the #GstRingBuffer to commit
1766  * @sample: the sample position of the data
1767  * @data: the data to commit
1768  * @in_samples: the number of samples in the data to commit
1769  * @out_samples: the number of samples to write to the ringbuffer
1770  * @accum: accumulator for rate conversion.
1771  *
1772  * Commit @in_samples samples pointed to by @data to the ringbuffer @buf. 
1773  *
1774  * @in_samples and @out_samples define the rate conversion to perform on the
1775  * samples in @data. For negative rates, @out_samples must be negative and
1776  * @in_samples positive.
1777  *
1778  * When @out_samples is positive, the first sample will be written at position @sample
1779  * in the ringbuffer. When @out_samples is negative, the last sample will be written to
1780  * @sample in reverse order.
1781  *
1782  * @out_samples does not need to be a multiple of the segment size of the ringbuffer
1783  * although it is recommended for optimal performance. 
1784  *
1785  * @accum will hold a temporary accumulator used in rate conversion and should be
1786  * set to 0 when this function is first called. In case the commit operation is
1787  * interrupted, one can resume the processing by passing the previously returned
1788  * @accum value back to this function.
1789  *
1790  * MT safe.
1791  *
1792  * Returns: The number of samples written to the ringbuffer or -1 on error. The
1793  * number of samples written can be less than @out_samples when @buf was interrupted
1794  * with a flush or stop.
1795  *
1796  * Since: 0.10.11.
1797  */
1798 guint
1799 gst_ring_buffer_commit_full (GstRingBuffer * buf, guint64 * sample,
1800     guchar * data, gint in_samples, gint out_samples, gint * accum)
1801 {
1802   GstRingBufferClass *rclass;
1803   guint res = -1;
1804
1805   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), -1);
1806
1807   if (G_UNLIKELY (in_samples == 0 || out_samples == 0))
1808     return in_samples;
1809
1810   rclass = GST_RING_BUFFER_GET_CLASS (buf);
1811
1812   if (G_LIKELY (rclass->commit))
1813     res = rclass->commit (buf, sample, data, in_samples, out_samples, accum);
1814
1815   return res;
1816 }
1817
1818 /**
1819  * gst_ring_buffer_commit:
1820  * @buf: the #GstRingBuffer to commit
1821  * @sample: the sample position of the data
1822  * @data: the data to commit
1823  * @len: the number of samples in the data to commit
1824  *
1825  * Same as gst_ring_buffer_commit_full() but with a in_samples and out_samples
1826  * equal to @len, ignoring accum.
1827  *
1828  * Returns: The number of samples written to the ringbuffer or -1 on
1829  * error.
1830  *
1831  * MT safe.
1832  */
1833 guint
1834 gst_ring_buffer_commit (GstRingBuffer * buf, guint64 sample, guchar * data,
1835     guint len)
1836 {
1837   guint res;
1838   guint64 samplep = sample;
1839
1840   res = gst_ring_buffer_commit_full (buf, &samplep, data, len, len, NULL);
1841
1842   return res;
1843 }
1844
1845 /**
1846  * gst_ring_buffer_read:
1847  * @buf: the #GstRingBuffer to read from
1848  * @sample: the sample position of the data
1849  * @data: where the data should be read
1850  * @len: the number of samples in data to read
1851  *
1852  * Read @len samples from the ringbuffer into the memory pointed 
1853  * to by @data.
1854  * The first sample should be read from position @sample in
1855  * the ringbuffer.
1856  *
1857  * @len should not be a multiple of the segment size of the ringbuffer
1858  * although it is recommended.
1859  *
1860  * Returns: The number of samples read from the ringbuffer or -1 on
1861  * error.
1862  *
1863  * MT safe.
1864  */
1865 guint
1866 gst_ring_buffer_read (GstRingBuffer * buf, guint64 sample, guchar * data,
1867     guint len)
1868 {
1869   gint segdone;
1870   gint segsize, segtotal, bps, sps;
1871   guint8 *dest;
1872   guint to_read;
1873
1874   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), -1);
1875   g_return_val_if_fail (buf->data != NULL, -1);
1876   g_return_val_if_fail (data != NULL, -1);
1877
1878   dest = GST_BUFFER_DATA (buf->data);
1879   segsize = buf->spec.segsize;
1880   segtotal = buf->spec.segtotal;
1881   bps = buf->spec.bytes_per_sample;
1882   sps = buf->samples_per_seg;
1883
1884   to_read = len;
1885   /* read enough samples */
1886   while (to_read > 0) {
1887     gint sampleslen;
1888     gint readseg, sampleoff;
1889
1890     /* figure out the segment and the offset inside the segment where
1891      * the sample should be read from. */
1892     readseg = sample / sps;
1893     sampleoff = (sample % sps);
1894
1895     while (TRUE) {
1896       gint diff;
1897
1898       /* get the currently processed segment */
1899       segdone = g_atomic_int_get (&buf->segdone) - buf->segbase;
1900
1901       /* see how far away it is from the read segment, normally segdone (where
1902        * the hardware is writing) is bigger than readseg (where software is
1903        * reading) */
1904       diff = segdone - readseg;
1905
1906       GST_DEBUG
1907           ("pointer at %d, sample %" G_GUINT64_FORMAT
1908           ", read from %d-%d, to_read %d, diff %d, segtotal %d, segsize %d",
1909           segdone, sample, readseg, sampleoff, to_read, diff, segtotal,
1910           segsize);
1911
1912       /* segment too far ahead, reader too slow */
1913       if (G_UNLIKELY (diff >= segtotal)) {
1914         /* pretend we read an empty segment. */
1915         sampleslen = MIN (sps, to_read);
1916         memcpy (data, buf->empty_seg, sampleslen * bps);
1917         goto next;
1918       }
1919
1920       /* read segment is within readable range, we can break the loop and
1921        * start reading the data. */
1922       if (diff > 0)
1923         break;
1924
1925       /* else we need to wait for the segment to become readable. */
1926       if (!wait_segment (buf))
1927         goto not_started;
1928     }
1929
1930     /* we can read now */
1931     readseg = readseg % segtotal;
1932     sampleslen = MIN (sps - sampleoff, to_read);
1933
1934     GST_DEBUG_OBJECT (buf, "read @%p seg %d, off %d, sampleslen %d",
1935         dest + readseg * segsize, readseg, sampleoff, sampleslen);
1936
1937     memcpy (data, dest + (readseg * segsize) + (sampleoff * bps),
1938         (sampleslen * bps));
1939
1940   next:
1941     to_read -= sampleslen;
1942     sample += sampleslen;
1943     data += sampleslen * bps;
1944   }
1945
1946   return len - to_read;
1947
1948   /* ERRORS */
1949 not_started:
1950   {
1951     GST_DEBUG_OBJECT (buf, "stopped processing");
1952     return len - to_read;
1953   }
1954 }
1955
1956 /**
1957  * gst_ring_buffer_prepare_read:
1958  * @buf: the #GstRingBuffer to read from
1959  * @segment: the segment to read
1960  * @readptr: the pointer to the memory where samples can be read
1961  * @len: the number of bytes to read
1962  *
1963  * Returns a pointer to memory where the data from segment @segment
1964  * can be found. This function is mostly used by subclasses.
1965  *
1966  * Returns: FALSE if the buffer is not started.
1967  *
1968  * MT safe.
1969  */
1970 gboolean
1971 gst_ring_buffer_prepare_read (GstRingBuffer * buf, gint * segment,
1972     guint8 ** readptr, gint * len)
1973 {
1974   guint8 *data;
1975   gint segdone;
1976
1977   g_return_val_if_fail (GST_IS_RING_BUFFER (buf), FALSE);
1978
1979   if (buf->callback == NULL) {
1980     /* push mode, fail when nothing is started */
1981     if (g_atomic_int_get (&buf->state) != GST_RING_BUFFER_STATE_STARTED)
1982       return FALSE;
1983   }
1984
1985   g_return_val_if_fail (buf->data != NULL, FALSE);
1986   g_return_val_if_fail (segment != NULL, FALSE);
1987   g_return_val_if_fail (readptr != NULL, FALSE);
1988   g_return_val_if_fail (len != NULL, FALSE);
1989
1990   data = GST_BUFFER_DATA (buf->data);
1991
1992   /* get the position of the pointer */
1993   segdone = g_atomic_int_get (&buf->segdone);
1994
1995   *segment = segdone % buf->spec.segtotal;
1996   *len = buf->spec.segsize;
1997   *readptr = data + *segment * *len;
1998
1999   GST_LOG ("prepare read from segment %d (real %d) @%p",
2000       *segment, segdone, *readptr);
2001
2002   /* callback to fill the memory with data, for pull based
2003    * scheduling. */
2004   if (buf->callback)
2005     buf->callback (buf, *readptr, *len, buf->cb_data);
2006
2007   return TRUE;
2008 }
2009
2010 /**
2011  * gst_ring_buffer_advance:
2012  * @buf: the #GstRingBuffer to advance
2013  * @advance: the number of segments written
2014  *
2015  * Subclasses should call this function to notify the fact that 
2016  * @advance segments are now processed by the device.
2017  *
2018  * MT safe.
2019  */
2020 void
2021 gst_ring_buffer_advance (GstRingBuffer * buf, guint advance)
2022 {
2023   g_return_if_fail (GST_IS_RING_BUFFER (buf));
2024
2025   /* update counter */
2026   g_atomic_int_add (&buf->segdone, advance);
2027
2028   /* the lock is already taken when the waiting flag is set,
2029    * we grab the lock as well to make sure the waiter is actually
2030    * waiting for the signal */
2031   if (g_atomic_int_compare_and_exchange (&buf->waiting, 1, 0)) {
2032     GST_OBJECT_LOCK (buf);
2033     GST_DEBUG_OBJECT (buf, "signal waiter");
2034     GST_RING_BUFFER_SIGNAL (buf);
2035     GST_OBJECT_UNLOCK (buf);
2036   }
2037 }
2038
2039 /**
2040  * gst_ring_buffer_clear:
2041  * @buf: the #GstRingBuffer to clear
2042  * @segment: the segment to clear
2043  *
2044  * Clear the given segment of the buffer with silence samples.
2045  * This function is used by subclasses.
2046  *
2047  * MT safe.
2048  */
2049 void
2050 gst_ring_buffer_clear (GstRingBuffer * buf, gint segment)
2051 {
2052   guint8 *data;
2053
2054   g_return_if_fail (GST_IS_RING_BUFFER (buf));
2055
2056   /* no data means it's already cleared */
2057   if (G_UNLIKELY (buf->data == NULL))
2058     return;
2059
2060   /* no empty_seg means it's not opened */
2061   if (G_UNLIKELY (buf->empty_seg == NULL))
2062     return;
2063
2064   segment %= buf->spec.segtotal;
2065
2066   data = GST_BUFFER_DATA (buf->data);
2067   data += segment * buf->spec.segsize;
2068
2069   GST_LOG ("clear segment %d @%p", segment, data);
2070
2071   memcpy (data, buf->empty_seg, buf->spec.segsize);
2072 }
2073
2074 /**
2075  * gst_ring_buffer_may_start:
2076  * @buf: the #GstRingBuffer
2077  * @allowed: the new value
2078  *
2079  * Tell the ringbuffer that it is allowed to start playback when
2080  * the ringbuffer is filled with samples. 
2081  *
2082  * MT safe.
2083  *
2084  * Since: 0.10.6
2085  */
2086 void
2087 gst_ring_buffer_may_start (GstRingBuffer * buf, gboolean allowed)
2088 {
2089   g_return_if_fail (GST_IS_RING_BUFFER (buf));
2090
2091   GST_LOG_OBJECT (buf, "may start: %d", allowed);
2092   g_atomic_int_set (&buf->abidata.ABI.may_start, allowed);
2093 }