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