gstadapter: Align the comment description with public api instead of internal one.
[platform/upstream/gstreamer.git] / libs / gst / base / gstadapter.c
1 /* GStreamer
2  * Copyright (C) 2004 Benjamin Otte <otte@gnome.org>
3  *               2005 Wim Taymans <wim@fluendo.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:gstadapter
23  * @short_description: adapts incoming data on a sink pad into chunks of N bytes
24  *
25  * This class is for elements that receive buffers in an undesired size.
26  * While for example raw video contains one image per buffer, the same is not
27  * true for a lot of other formats, especially those that come directly from
28  * a file. So if you have undefined buffer sizes and require a specific size,
29  * this object is for you.
30  *
31  * An adapter is created with gst_adapter_new(). It can be freed again with
32  * g_object_unref().
33  *
34  * The theory of operation is like this: All buffers received are put
35  * into the adapter using gst_adapter_push() and the data is then read back
36  * in chunks of the desired size using gst_adapter_map()/gst_adapter_unmap()
37  * and/or gst_adapter_copy(). After the data has been processed, it is freed
38  * using gst_adapter_unmap().
39  *
40  * Other methods such as gst_adapter_take() and gst_adapter_take_buffer()
41  * combine gst_adapter_map() and gst_adapter_unmap() in one method and are
42  * potentially more convenient for some use cases.
43  *
44  * For example, a sink pad's chain function that needs to pass data to a library
45  * in 512-byte chunks could be implemented like this:
46  * |[
47  * static GstFlowReturn
48  * sink_pad_chain (GstPad *pad, GstBuffer *buffer)
49  * {
50  *   MyElement *this;
51  *   GstAdapter *adapter;
52  *   GstFlowReturn ret = GST_FLOW_OK;
53  *
54  *   // will give the element an extra ref; remember to drop it
55  *   this = MY_ELEMENT (gst_pad_get_parent (pad));
56  *   adapter = this->adapter;
57  *
58  *   // put buffer into adapter
59  *   gst_adapter_push (adapter, buffer);
60  *   // while we can read out 512 bytes, process them
61  *   while (gst_adapter_available (adapter) >= 512 && ret == GST_FLOW_OK) {
62  *     const guint8 *data = gst_adapter_map (adapter, 512);
63  *     // use flowreturn as an error value
64  *     ret = my_library_foo (data);
65  *     gst_adapter_unmap (adapter);
66  *     gst_adapter_flush (adapter, 512);
67  *   }
68  *
69  *   gst_object_unref (this);
70  *   return ret;
71  * }
72  * ]|
73  *
74  * For another example, a simple element inside GStreamer that uses GstAdapter
75  * is the libvisual element.
76  *
77  * An element using GstAdapter in its sink pad chain function should ensure that
78  * when the FLUSH_STOP event is received, that any queued data is cleared using
79  * gst_adapter_clear(). Data should also be cleared or processed on EOS and
80  * when changing state from #GST_STATE_PAUSED to #GST_STATE_READY.
81  *
82  * Also check the GST_BUFFER_FLAG_DISCONT flag on the buffer. Some elements might
83  * need to clear the adapter after a discontinuity.
84  *
85  * Since 0.10.24, the adapter will keep track of the timestamps of the buffers
86  * that were pushed. The last seen timestamp before the current position
87  * can be queried with gst_adapter_prev_timestamp(). This function can
88  * optionally return the amount of bytes between the start of the buffer that
89  * carried the timestamp and the current adapter position. The distance is
90  * useful when dealing with, for example, raw audio samples because it allows
91  * you to calculate the timestamp of the current adapter position by using the
92  * last seen timestamp and the amount of bytes since.
93  *
94  * A last thing to note is that while GstAdapter is pretty optimized,
95  * merging buffers still might be an operation that requires a malloc() and
96  * memcpy() operation, and these operations are not the fastest. Because of
97  * this, some functions like gst_adapter_available_fast() are provided to help
98  * speed up such cases should you want to. To avoid repeated memory allocations,
99  * gst_adapter_copy() can be used to copy data into a (statically allocated)
100  * user provided buffer.
101  *
102  * GstAdapter is not MT safe. All operations on an adapter must be serialized by
103  * the caller. This is not normally a problem, however, as the normal use case
104  * of GstAdapter is inside one pad's chain function, in which case access is
105  * serialized via the pad's STREAM_LOCK.
106  *
107  * Note that gst_adapter_push() takes ownership of the buffer passed. Use
108  * gst_buffer_ref() before pushing it into the adapter if you still want to
109  * access the buffer later. The adapter will never modify the data in the
110  * buffer pushed in it.
111  *
112  * Last reviewed on 2009-05-13 (0.10.24).
113  */
114
115 #include <gst/gst_private.h>
116 #include "gstadapter.h"
117 #include <string.h>
118
119 /* default size for the assembled data buffer */
120 #define DEFAULT_SIZE 4096
121
122 static void gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush);
123
124 GST_DEBUG_CATEGORY_STATIC (gst_adapter_debug);
125 #define GST_CAT_DEFAULT gst_adapter_debug
126
127 struct _GstAdapter
128 {
129   GObject object;
130
131   /*< private > */
132   GSList *buflist;
133   GSList *buflist_end;
134   gsize size;
135   gsize skip;
136
137   /* we keep state of assembled pieces */
138   gpointer assembled_data;
139   gsize assembled_size;
140   gsize assembled_len;
141
142   GstClockTime pts;
143   guint64 pts_distance;
144   GstClockTime dts;
145   guint64 dts_distance;
146
147   gsize scan_offset;
148   GSList *scan_entry;
149
150   GstMapInfo info;
151 };
152
153 struct _GstAdapterClass
154 {
155   GObjectClass parent_class;
156 };
157
158 #define _do_init \
159   GST_DEBUG_CATEGORY_INIT (gst_adapter_debug, "adapter", 0, "object to splice and merge buffers to desired size")
160 #define gst_adapter_parent_class parent_class
161 G_DEFINE_TYPE_WITH_CODE (GstAdapter, gst_adapter, G_TYPE_OBJECT, _do_init);
162
163 static void gst_adapter_dispose (GObject * object);
164 static void gst_adapter_finalize (GObject * object);
165
166 static void
167 gst_adapter_class_init (GstAdapterClass * klass)
168 {
169   GObjectClass *object = G_OBJECT_CLASS (klass);
170
171   object->dispose = gst_adapter_dispose;
172   object->finalize = gst_adapter_finalize;
173 }
174
175 static void
176 gst_adapter_init (GstAdapter * adapter)
177 {
178   adapter->assembled_data = g_malloc (DEFAULT_SIZE);
179   adapter->assembled_size = DEFAULT_SIZE;
180   adapter->pts = GST_CLOCK_TIME_NONE;
181   adapter->pts_distance = 0;
182   adapter->dts = GST_CLOCK_TIME_NONE;
183   adapter->dts_distance = 0;
184 }
185
186 static void
187 gst_adapter_dispose (GObject * object)
188 {
189   GstAdapter *adapter = GST_ADAPTER (object);
190
191   gst_adapter_clear (adapter);
192
193   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
194 }
195
196 static void
197 gst_adapter_finalize (GObject * object)
198 {
199   GstAdapter *adapter = GST_ADAPTER (object);
200
201   g_free (adapter->assembled_data);
202
203   GST_CALL_PARENT (G_OBJECT_CLASS, finalize, (object));
204 }
205
206 /**
207  * gst_adapter_new:
208  *
209  * Creates a new #GstAdapter. Free with g_object_unref().
210  *
211  * Returns: (transfer full): a new #GstAdapter
212  */
213 GstAdapter *
214 gst_adapter_new (void)
215 {
216   return g_object_newv (GST_TYPE_ADAPTER, 0, NULL);
217 }
218
219 /**
220  * gst_adapter_clear:
221  * @adapter: a #GstAdapter
222  *
223  * Removes all buffers from @adapter.
224  */
225 void
226 gst_adapter_clear (GstAdapter * adapter)
227 {
228   g_return_if_fail (GST_IS_ADAPTER (adapter));
229
230   if (adapter->info.memory)
231     gst_adapter_unmap (adapter);
232
233   g_slist_foreach (adapter->buflist, (GFunc) gst_mini_object_unref, NULL);
234   g_slist_free (adapter->buflist);
235   adapter->buflist = NULL;
236   adapter->buflist_end = NULL;
237   adapter->size = 0;
238   adapter->skip = 0;
239   adapter->assembled_len = 0;
240   adapter->pts = GST_CLOCK_TIME_NONE;
241   adapter->pts_distance = 0;
242   adapter->dts = GST_CLOCK_TIME_NONE;
243   adapter->dts_distance = 0;
244   adapter->scan_offset = 0;
245   adapter->scan_entry = NULL;
246 }
247
248 static inline void
249 update_timestamps (GstAdapter * adapter, GstBuffer * buf)
250 {
251   GstClockTime pts, dts;
252
253   pts = GST_BUFFER_PTS (buf);
254   if (GST_CLOCK_TIME_IS_VALID (pts)) {
255     GST_LOG_OBJECT (adapter, "new pts %" GST_TIME_FORMAT, GST_TIME_ARGS (pts));
256     adapter->pts = pts;
257     adapter->pts_distance = 0;
258   }
259   dts = GST_BUFFER_DTS (buf);
260   if (GST_CLOCK_TIME_IS_VALID (dts)) {
261     GST_LOG_OBJECT (adapter, "new dts %" GST_TIME_FORMAT, GST_TIME_ARGS (dts));
262     adapter->dts = dts;
263     adapter->dts_distance = 0;
264   }
265 }
266
267 /* copy data into @dest, skipping @skip bytes from the head buffers */
268 static void
269 copy_into_unchecked (GstAdapter * adapter, guint8 * dest, gsize skip,
270     gsize size)
271 {
272   GSList *g;
273   GstBuffer *buf;
274   gsize bsize, csize;
275
276   /* first step, do skipping */
277   /* we might well be copying where we were scanning */
278   if (adapter->scan_entry && (adapter->scan_offset <= skip)) {
279     g = adapter->scan_entry;
280     skip -= adapter->scan_offset;
281   } else {
282     g = adapter->buflist;
283   }
284   buf = g->data;
285   bsize = gst_buffer_get_size (buf);
286   while (G_UNLIKELY (skip >= bsize)) {
287     skip -= bsize;
288     g = g_slist_next (g);
289     buf = g->data;
290     bsize = gst_buffer_get_size (buf);
291   }
292   /* copy partial buffer */
293   csize = MIN (bsize - skip, size);
294   GST_DEBUG ("bsize %" G_GSIZE_FORMAT ", skip %" G_GSIZE_FORMAT ", csize %"
295       G_GSIZE_FORMAT, bsize, skip, csize);
296   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, adapter, "extract %" G_GSIZE_FORMAT
297       " bytes", csize);
298   gst_buffer_extract (buf, skip, dest, csize);
299   size -= csize;
300   dest += csize;
301
302   /* second step, copy remainder */
303   while (size > 0) {
304     g = g_slist_next (g);
305     buf = g->data;
306     bsize = gst_buffer_get_size (buf);
307     if (G_LIKELY (bsize > 0)) {
308       csize = MIN (bsize, size);
309       GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, adapter,
310           "extract %" G_GSIZE_FORMAT " bytes", csize);
311       gst_buffer_extract (buf, 0, dest, csize);
312       size -= csize;
313       dest += csize;
314     }
315   }
316 }
317
318 /**
319  * gst_adapter_push:
320  * @adapter: a #GstAdapter
321  * @buf: (transfer full): a #GstBuffer to add to queue in the adapter
322  *
323  * Adds the data from @buf to the data stored inside @adapter and takes
324  * ownership of the buffer.
325  */
326 void
327 gst_adapter_push (GstAdapter * adapter, GstBuffer * buf)
328 {
329   gsize size;
330
331   g_return_if_fail (GST_IS_ADAPTER (adapter));
332   g_return_if_fail (GST_IS_BUFFER (buf));
333
334   size = gst_buffer_get_size (buf);
335   adapter->size += size;
336
337   /* Note: merging buffers at this point is premature. */
338   if (G_UNLIKELY (adapter->buflist == NULL)) {
339     GST_LOG_OBJECT (adapter, "pushing %p first %" G_GSIZE_FORMAT " bytes",
340         buf, size);
341     adapter->buflist = adapter->buflist_end = g_slist_append (NULL, buf);
342     update_timestamps (adapter, buf);
343   } else {
344     /* Otherwise append to the end, and advance our end pointer */
345     GST_LOG_OBJECT (adapter, "pushing %p %" G_GSIZE_FORMAT " bytes at end, "
346         "size now %" G_GSIZE_FORMAT, buf, size, adapter->size);
347     adapter->buflist_end = g_slist_append (adapter->buflist_end, buf);
348     adapter->buflist_end = g_slist_next (adapter->buflist_end);
349   }
350 }
351
352 #if 0
353 /* Internal method only. Tries to merge buffers at the head of the queue
354  * to form a single larger buffer of size 'size'.
355  *
356  * Returns TRUE if it managed to merge anything.
357  */
358 static gboolean
359 gst_adapter_try_to_merge_up (GstAdapter * adapter, gsize size)
360 {
361   GstBuffer *cur, *head;
362   GSList *g;
363   gboolean ret = FALSE;
364   gsize hsize;
365
366   g = adapter->buflist;
367   if (g == NULL)
368     return FALSE;
369
370   head = g->data;
371
372   hsize = gst_buffer_get_size (head);
373
374   /* Remove skipped part from the buffer (otherwise the buffer might grow indefinitely) */
375   head = gst_buffer_make_writable (head);
376   gst_buffer_resize (head, adapter->skip, hsize - adapter->skip);
377   hsize -= adapter->skip;
378   adapter->skip = 0;
379   g->data = head;
380
381   g = g_slist_next (g);
382
383   while (g != NULL && hsize < size) {
384     cur = g->data;
385     /* Merge the head buffer and the next in line */
386     GST_LOG_OBJECT (adapter, "Merging buffers of size %" G_GSIZE_FORMAT " & %"
387         G_GSIZE_FORMAT " in search of target %" G_GSIZE_FORMAT,
388         hsize, gst_buffer_get_size (cur), size);
389
390     head = gst_buffer_append (head, cur);
391     hsize = gst_buffer_get_size (head);
392     ret = TRUE;
393
394     /* Delete the front list item, and store our new buffer in the 2nd list
395      * item */
396     adapter->buflist = g_slist_delete_link (adapter->buflist, adapter->buflist);
397     g->data = head;
398
399     /* invalidate scan position */
400     adapter->scan_offset = 0;
401     adapter->scan_entry = NULL;
402
403     g = g_slist_next (g);
404   }
405
406   return ret;
407 }
408 #endif
409
410 /**
411  * gst_adapter_map:
412  * @adapter: a #GstAdapter
413  * @size: the number of bytes to map/peek
414  *
415  * Gets the first @size bytes stored in the @adapter. The returned pointer is
416  * valid until the next function is called on the adapter.
417  *
418  * Note that setting the returned pointer as the data of a #GstBuffer is
419  * incorrect for general-purpose plugins. The reason is that if a downstream
420  * element stores the buffer so that it has access to it outside of the bounds
421  * of its chain function, the buffer will have an invalid data pointer after
422  * your element flushes the bytes. In that case you should use
423  * gst_adapter_take(), which returns a freshly-allocated buffer that you can set
424  * as #GstBuffer malloc_data or the potentially more performant
425  * gst_adapter_take_buffer().
426  *
427  * Returns #NULL if @size bytes are not available.
428  *
429  * Returns: (transfer none) (array length=size): a pointer to the first
430  *     @size bytes of data, or NULL
431  */
432 gconstpointer
433 gst_adapter_map (GstAdapter * adapter, gsize size)
434 {
435   GstBuffer *cur;
436   gsize skip, csize;
437   gsize toreuse, tocopy;
438   guint8 *data;
439
440   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
441   g_return_val_if_fail (size > 0, NULL);
442
443   if (adapter->info.memory)
444     gst_adapter_unmap (adapter);
445
446   /* we don't have enough data, return NULL. This is unlikely
447    * as one usually does an _available() first instead of peeking a
448    * random size. */
449   if (G_UNLIKELY (size > adapter->size))
450     return NULL;
451
452   /* we have enough assembled data, return it */
453   if (adapter->assembled_len >= size)
454     return adapter->assembled_data;
455
456 #if 0
457   do {
458 #endif
459     cur = adapter->buflist->data;
460     skip = adapter->skip;
461
462     csize = gst_buffer_get_size (cur);
463     if (csize >= size + skip) {
464       if (!gst_buffer_map (cur, &adapter->info, GST_MAP_READ))
465         return FALSE;
466
467       return (guint8 *) adapter->info.data + skip;
468     }
469     /* We may be able to efficiently merge buffers in our pool to
470      * gather a big enough chunk to return it from the head buffer directly */
471 #if 0
472   } while (gst_adapter_try_to_merge_up (adapter, size));
473 #endif
474
475   /* see how much data we can reuse from the assembled memory and how much
476    * we need to copy */
477   toreuse = adapter->assembled_len;
478   tocopy = size - toreuse;
479
480   /* Gonna need to copy stuff out */
481   if (G_UNLIKELY (adapter->assembled_size < size)) {
482     adapter->assembled_size = (size / DEFAULT_SIZE + 1) * DEFAULT_SIZE;
483     GST_DEBUG_OBJECT (adapter, "resizing internal buffer to %" G_GSIZE_FORMAT,
484         adapter->assembled_size);
485     if (toreuse == 0) {
486       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "alloc new buffer");
487       /* no g_realloc to avoid a memcpy that is not desired here since we are
488        * not going to reuse any data here */
489       g_free (adapter->assembled_data);
490       adapter->assembled_data = g_malloc (adapter->assembled_size);
491     } else {
492       /* we are going to reuse all data, realloc then */
493       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "reusing %" G_GSIZE_FORMAT " bytes",
494           toreuse);
495       adapter->assembled_data =
496           g_realloc (adapter->assembled_data, adapter->assembled_size);
497     }
498   }
499   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy remaining %" G_GSIZE_FORMAT
500       " bytes from adapter", tocopy);
501   data = adapter->assembled_data;
502   copy_into_unchecked (adapter, data + toreuse, skip + toreuse, tocopy);
503   adapter->assembled_len = size;
504
505   return adapter->assembled_data;
506 }
507
508 /**
509  * gst_adapter_unmap:
510  * @adapter: a #GstAdapter
511  *
512  * Releases the memory obtained with the last gst_adapter_map().
513  */
514 void
515 gst_adapter_unmap (GstAdapter * adapter)
516 {
517   g_return_if_fail (GST_IS_ADAPTER (adapter));
518
519   if (adapter->info.memory) {
520     GstBuffer *cur = adapter->buflist->data;
521     GST_LOG_OBJECT (adapter, "unmap memory buffer %p", cur);
522     gst_buffer_unmap (cur, &adapter->info);
523     adapter->info.memory = NULL;
524   }
525 }
526
527 /**
528  * gst_adapter_copy:
529  * @adapter: a #GstAdapter
530  * @dest: (out caller-allocates) (array length=size): the memory to copy into
531  * @offset: the bytes offset in the adapter to start from
532  * @size: the number of bytes to copy
533  *
534  * Copies @size bytes of data starting at @offset out of the buffers
535  * contained in @GstAdapter into an array @dest provided by the caller.
536  *
537  * The array @dest should be large enough to contain @size bytes.
538  * The user should check that the adapter has (@offset + @size) bytes
539  * available before calling this function.
540  *
541  * Since: 0.10.12
542  */
543 void
544 gst_adapter_copy (GstAdapter * adapter, gpointer dest, gsize offset, gsize size)
545 {
546   g_return_if_fail (GST_IS_ADAPTER (adapter));
547   g_return_if_fail (size > 0);
548   g_return_if_fail (offset + size <= adapter->size);
549
550   copy_into_unchecked (adapter, dest, offset + adapter->skip, size);
551 }
552
553 /*Flushes the first @flush bytes in the @adapter*/
554 static void
555 gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush)
556 {
557   GstBuffer *cur;
558   gsize size;
559   GSList *g;
560
561   GST_LOG_OBJECT (adapter, "flushing %" G_GSIZE_FORMAT " bytes", flush);
562
563   if (adapter->info.memory)
564     gst_adapter_unmap (adapter);
565
566   /* clear state */
567   adapter->size -= flush;
568   adapter->assembled_len = 0;
569
570   /* take skip into account */
571   flush += adapter->skip;
572   /* distance is always at least the amount of skipped bytes */
573   adapter->pts_distance -= adapter->skip;
574   adapter->dts_distance -= adapter->skip;
575
576   g = adapter->buflist;
577   cur = g->data;
578   size = gst_buffer_get_size (cur);
579   while (flush >= size) {
580     /* can skip whole buffer */
581     GST_LOG_OBJECT (adapter, "flushing out head buffer");
582     adapter->pts_distance += size;
583     adapter->dts_distance += size;
584     flush -= size;
585
586     gst_buffer_unref (cur);
587     g = g_slist_delete_link (g, g);
588
589     if (G_UNLIKELY (g == NULL)) {
590       GST_LOG_OBJECT (adapter, "adapter empty now");
591       adapter->buflist_end = NULL;
592       break;
593     }
594     /* there is a new head buffer, update the timestamps */
595     cur = g->data;
596     update_timestamps (adapter, cur);
597     size = gst_buffer_get_size (cur);
598   }
599   adapter->buflist = g;
600   /* account for the remaining bytes */
601   adapter->skip = flush;
602   adapter->pts_distance += flush;
603   adapter->dts_distance += flush;
604   /* invalidate scan position */
605   adapter->scan_offset = 0;
606   adapter->scan_entry = NULL;
607 }
608
609 /**
610  * gst_adapter_flush:
611  * @adapter: a #GstAdapter
612  * @flush: the number of bytes to flush
613  *
614  * Flushes the first @flush bytes in the @adapter. The caller must ensure that
615  * at least this many bytes are available.
616  *
617  * See also: gst_adapter_map(), gst_adapter_unmap()
618  */
619 void
620 gst_adapter_flush (GstAdapter * adapter, gsize flush)
621 {
622   g_return_if_fail (GST_IS_ADAPTER (adapter));
623   g_return_if_fail (flush <= adapter->size);
624
625   /* flushing out 0 bytes will do nothing */
626   if (G_UNLIKELY (flush == 0))
627     return;
628
629   gst_adapter_flush_unchecked (adapter, flush);
630 }
631
632 /* internal function, nbytes should be flushed after calling this function */
633 static guint8 *
634 gst_adapter_take_internal (GstAdapter * adapter, gsize nbytes)
635 {
636   guint8 *data;
637   gsize toreuse, tocopy;
638
639   /* see how much data we can reuse from the assembled memory and how much
640    * we need to copy */
641   toreuse = MIN (nbytes, adapter->assembled_len);
642   tocopy = nbytes - toreuse;
643
644   /* find memory to return */
645   if (adapter->assembled_size >= nbytes && toreuse > 0) {
646     /* we reuse already allocated memory but only when we're going to reuse
647      * something from it because else we are worse than the malloc and copy
648      * case below */
649     GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes of assembled"
650         " data", toreuse);
651     /* we have enough free space in the assembled array */
652     data = adapter->assembled_data;
653     /* flush after this function should set the assembled_size to 0 */
654     adapter->assembled_data = g_malloc (adapter->assembled_size);
655   } else {
656     GST_LOG_OBJECT (adapter, "allocating %" G_GSIZE_FORMAT " bytes", nbytes);
657     /* not enough bytes in the assembled array, just allocate new space */
658     data = g_malloc (nbytes);
659     /* reuse what we can from the already assembled data */
660     if (toreuse) {
661       GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes", toreuse);
662       GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, adapter,
663           "memcpy %" G_GSIZE_FORMAT " bytes", toreuse);
664       memcpy (data, adapter->assembled_data, toreuse);
665     }
666   }
667   if (tocopy) {
668     /* copy the remaining data */
669     copy_into_unchecked (adapter, toreuse + data, toreuse + adapter->skip,
670         tocopy);
671   }
672   return data;
673 }
674
675 /**
676  * gst_adapter_take:
677  * @adapter: a #GstAdapter
678  * @nbytes: the number of bytes to take
679  *
680  * Returns a freshly allocated buffer containing the first @nbytes bytes of the
681  * @adapter. The returned bytes will be flushed from the adapter.
682  *
683  * Caller owns returned value. g_free after usage.
684  *
685  * Free-function: g_free
686  *
687  * Returns: (transfer full) (array length=nbytes): oven-fresh hot data, or
688  *     #NULL if @nbytes bytes are not available
689  */
690 gpointer
691 gst_adapter_take (GstAdapter * adapter, gsize nbytes)
692 {
693   gpointer data;
694
695   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
696   g_return_val_if_fail (nbytes > 0, NULL);
697
698   /* we don't have enough data, return NULL. This is unlikely
699    * as one usually does an _available() first instead of peeking a
700    * random size. */
701   if (G_UNLIKELY (nbytes > adapter->size))
702     return NULL;
703
704   data = gst_adapter_take_internal (adapter, nbytes);
705
706   gst_adapter_flush_unchecked (adapter, nbytes);
707
708   return data;
709 }
710
711 /**
712  * gst_adapter_take_buffer:
713  * @adapter: a #GstAdapter
714  * @nbytes: the number of bytes to take
715  *
716  * Returns a #GstBuffer containing the first @nbytes bytes of the
717  * @adapter. The returned bytes will be flushed from the adapter.
718  * This function is potentially more performant than gst_adapter_take()
719  * since it can reuse the memory in pushed buffers by subbuffering
720  * or merging.
721  *
722  * Caller owns returned value. gst_buffer_unref() after usage.
723  *
724  * Free-function: gst_buffer_unref
725  *
726  * Returns: (transfer full): a #GstBuffer containing the first @nbytes of
727  *     the adapter, or #NULL if @nbytes bytes are not available
728  *
729  * Since: 0.10.6
730  */
731 GstBuffer *
732 gst_adapter_take_buffer (GstAdapter * adapter, gsize nbytes)
733 {
734   GstBuffer *buffer;
735   GstBuffer *cur;
736   gsize hsize, skip;
737   guint8 *data;
738
739   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
740   g_return_val_if_fail (nbytes > 0, NULL);
741
742   GST_LOG_OBJECT (adapter, "taking buffer of %" G_GSIZE_FORMAT " bytes",
743       nbytes);
744
745   /* we don't have enough data, return NULL. This is unlikely
746    * as one usually does an _available() first instead of grabbing a
747    * random size. */
748   if (G_UNLIKELY (nbytes > adapter->size))
749     return NULL;
750
751   cur = adapter->buflist->data;
752   skip = adapter->skip;
753   hsize = gst_buffer_get_size (cur);
754
755   /* our head buffer has enough data left, return it */
756   if (skip == 0 && hsize == nbytes) {
757     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
758         " as head buffer", nbytes);
759     buffer = gst_buffer_ref (cur);
760     goto done;
761   } else if (hsize >= nbytes + skip) {
762     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
763         " via region copy", nbytes);
764     buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
765     goto done;
766   }
767 #if 0
768   if (gst_adapter_try_to_merge_up (adapter, nbytes)) {
769     /* Merged something, let's try again for sub-buffering */
770     cur = adapter->buflist->data;
771     skip = adapter->skip;
772     if (gst_buffer_get_size (cur) >= nbytes + skip) {
773       GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
774           " via sub-buffer", nbytes);
775       buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
776       goto done;
777     }
778   }
779 #endif
780
781   data = gst_adapter_take_internal (adapter, nbytes);
782
783   buffer = gst_buffer_new_wrapped (data, nbytes);
784
785 done:
786   gst_adapter_flush_unchecked (adapter, nbytes);
787
788   return buffer;
789 }
790
791 /**
792  * gst_adapter_take_list:
793  * @adapter: a #GstAdapter
794  * @nbytes: the number of bytes to take
795  *
796  * Returns a #GList of buffers containing the first @nbytes bytes of the
797  * @adapter. The returned bytes will be flushed from the adapter.
798  * When the caller can deal with individual buffers, this function is more
799  * performant because no memory should be copied.
800  *
801  * Caller owns returned list and contained buffers. gst_buffer_unref() each
802  * buffer in the list before freeing the list after usage.
803  *
804  * Returns: (element-type Gst.Buffer) (transfer full): a #GList of buffers
805  *     containing the first @nbytes of the adapter, or #NULL if @nbytes bytes
806  *     are not available
807  *
808  * Since: 0.10.31
809  */
810 GList *
811 gst_adapter_take_list (GstAdapter * adapter, gsize nbytes)
812 {
813   GQueue queue = G_QUEUE_INIT;
814   GstBuffer *cur;
815   gsize hsize, skip;
816
817   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
818   g_return_val_if_fail (nbytes <= adapter->size, NULL);
819
820   GST_LOG_OBJECT (adapter, "taking %" G_GSIZE_FORMAT " bytes", nbytes);
821
822   while (nbytes > 0) {
823     cur = adapter->buflist->data;
824     skip = adapter->skip;
825     hsize = MIN (nbytes, gst_buffer_get_size (cur) - skip);
826
827     cur = gst_adapter_take_buffer (adapter, hsize);
828
829     g_queue_push_tail (&queue, cur);
830
831     nbytes -= hsize;
832   }
833   return queue.head;
834 }
835
836 /**
837  * gst_adapter_available:
838  * @adapter: a #GstAdapter
839  *
840  * Gets the maximum amount of bytes available, that is it returns the maximum
841  * value that can be supplied to gst_adapter_map() without that function
842  * returning NULL.
843  *
844  * Returns: number of bytes available in @adapter
845  */
846 gsize
847 gst_adapter_available (GstAdapter * adapter)
848 {
849   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
850
851   return adapter->size;
852 }
853
854 /**
855  * gst_adapter_available_fast:
856  * @adapter: a #GstAdapter
857  *
858  * Gets the maximum number of bytes that are immediately available without
859  * requiring any expensive operations (like copying the data into a
860  * temporary buffer).
861  *
862  * Returns: number of bytes that are available in @adapter without expensive
863  * operations
864  */
865 gsize
866 gst_adapter_available_fast (GstAdapter * adapter)
867 {
868   GstBuffer *cur;
869   gsize size;
870   GSList *g;
871
872   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
873
874   /* no data */
875   if (adapter->size == 0)
876     return 0;
877
878   /* some stuff we already assembled */
879   if (adapter->assembled_len)
880     return adapter->assembled_len;
881
882   /* take the first non-zero buffer */
883   g = adapter->buflist;
884   while (TRUE) {
885     cur = g->data;
886     size = gst_buffer_get_size (cur);
887     if (size != 0)
888       break;
889     g = g_slist_next (g);
890   }
891
892   /* we can quickly get the (remaining) data of the first buffer */
893   return size - adapter->skip;
894 }
895
896 /**
897  * gst_adapter_prev_pts:
898  * @adapter: a #GstAdapter
899  * @distance: (out) (allow-none): pointer to location for distance, or NULL
900  *
901  * Get the pts that was before the current byte in the adapter. When
902  * @distance is given, the amount of bytes between the pts and the current
903  * position is returned.
904  *
905  * The pts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
906  * the adapter is first created or when it is cleared. This also means that before
907  * the first byte with a pts is removed from the adapter, the pts
908  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
909  *
910  * Returns: The previously seen pts.
911  */
912 GstClockTime
913 gst_adapter_prev_pts (GstAdapter * adapter, guint64 * distance)
914 {
915   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
916
917   if (distance)
918     *distance = adapter->pts_distance;
919
920   return adapter->pts;
921 }
922
923 /**
924  * gst_adapter_prev_dts:
925  * @adapter: a #GstAdapter
926  * @distance: (out) (allow-none): pointer to location for distance, or NULL
927  *
928  * Get the dts that was before the current byte in the adapter. When
929  * @distance is given, the amount of bytes between the dts and the current
930  * position is returned.
931  *
932  * The dts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
933  * the adapter is first created or when it is cleared. This also means that before
934  * the first byte with a dts is removed from the adapter, the dts
935  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
936  *
937  * Returns: The previously seen dts.
938  */
939 GstClockTime
940 gst_adapter_prev_dts (GstAdapter * adapter, guint64 * distance)
941 {
942   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
943
944   if (distance)
945     *distance = adapter->dts_distance;
946
947   return adapter->dts;
948 }
949
950 /**
951  * gst_adapter_masked_scan_uint32_peek:
952  * @adapter: a #GstAdapter
953  * @mask: mask to apply to data before matching against @pattern
954  * @pattern: pattern to match (after mask is applied)
955  * @offset: offset into the adapter data from which to start scanning, returns
956  *          the last scanned position.
957  * @size: number of bytes to scan from offset
958  * @value: pointer to uint32 to return matching data
959  *
960  * Scan for pattern @pattern with applied mask @mask in the adapter data,
961  * starting from offset @offset.  If a match is found, the value that matched
962  * is returned through @value, otherwise @value is left untouched.
963  *
964  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
965  * of endianness.  All four bytes of the pattern must be present in the
966  * adapter for it to match, even if the first or last bytes are masked out.
967  *
968  * It is an error to call this function without making sure that there is
969  * enough data (offset+size bytes) in the adapter.
970  *
971  * Returns: offset of the first match, or -1 if no match was found.
972  *
973  * Since: 0.10.30
974  */
975 gsize
976 gst_adapter_masked_scan_uint32_peek (GstAdapter * adapter, guint32 mask,
977     guint32 pattern, gsize offset, gsize size, guint32 * value)
978 {
979   GSList *g;
980   gsize skip, bsize, i;
981   guint32 state;
982   GstMapInfo info;
983   guint8 *bdata;
984   GstBuffer *buf;
985
986   g_return_val_if_fail (size > 0, -1);
987   g_return_val_if_fail (offset + size <= adapter->size, -1);
988   g_return_val_if_fail (((~mask) & pattern) == 0, -1);
989
990   /* we can't find the pattern with less than 4 bytes */
991   if (G_UNLIKELY (size < 4))
992     return -1;
993
994   skip = offset + adapter->skip;
995
996   /* first step, do skipping and position on the first buffer */
997   /* optimistically assume scanning continues sequentially */
998   if (adapter->scan_entry && (adapter->scan_offset <= skip)) {
999     g = adapter->scan_entry;
1000     skip -= adapter->scan_offset;
1001   } else {
1002     g = adapter->buflist;
1003     adapter->scan_offset = 0;
1004     adapter->scan_entry = NULL;
1005   }
1006   buf = g->data;
1007   bsize = gst_buffer_get_size (buf);
1008   while (G_UNLIKELY (skip >= bsize)) {
1009     skip -= bsize;
1010     g = g_slist_next (g);
1011     adapter->scan_offset += bsize;
1012     adapter->scan_entry = g;
1013     buf = g->data;
1014     bsize = gst_buffer_get_size (buf);
1015   }
1016   /* get the data now */
1017   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
1018     return -1;
1019
1020   bdata = (guint8 *) info.data + skip;
1021   bsize = info.size - skip;
1022   skip = 0;
1023
1024   /* set the state to something that does not match */
1025   state = ~pattern;
1026
1027   /* now find data */
1028   do {
1029     bsize = MIN (bsize, size);
1030     for (i = 0; i < bsize; i++) {
1031       state = ((state << 8) | bdata[i]);
1032       if (G_UNLIKELY ((state & mask) == pattern)) {
1033         /* we have a match but we need to have skipped at
1034          * least 4 bytes to fill the state. */
1035         if (G_LIKELY (skip + i >= 3)) {
1036           if (G_LIKELY (value))
1037             *value = state;
1038           gst_buffer_unmap (buf, &info);
1039           return offset + skip + i - 3;
1040         }
1041       }
1042     }
1043     size -= bsize;
1044     if (size == 0)
1045       break;
1046
1047     /* nothing found yet, go to next buffer */
1048     skip += bsize;
1049     g = g_slist_next (g);
1050     adapter->scan_offset += info.size;
1051     adapter->scan_entry = g;
1052     gst_buffer_unmap (buf, &info);
1053     buf = g->data;
1054
1055     gst_buffer_map (buf, &info, GST_MAP_READ);
1056     bsize = info.size;
1057     bdata = info.data;
1058   } while (TRUE);
1059
1060   gst_buffer_unmap (buf, &info);
1061
1062   /* nothing found */
1063   return -1;
1064 }
1065
1066 /**
1067  * gst_adapter_masked_scan_uint32:
1068  * @adapter: a #GstAdapter
1069  * @mask: mask to apply to data before matching against @pattern
1070  * @pattern: pattern to match (after mask is applied)
1071  * @offset: offset into the adapter data from which to start scanning, returns
1072  *          the last scanned position.
1073  * @size: number of bytes to scan from offset
1074  *
1075  * Scan for pattern @pattern with applied mask @mask in the adapter data,
1076  * starting from offset @offset.
1077  *
1078  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
1079  * of endianness.  All four bytes of the pattern must be present in the
1080  * adapter for it to match, even if the first or last bytes are masked out.
1081  *
1082  * It is an error to call this function without making sure that there is
1083  * enough data (offset+size bytes) in the adapter.
1084  *
1085  * This function calls gst_adapter_masked_scan_uint32_peek() passing NULL
1086  * for value.
1087  *
1088  * Returns: offset of the first match, or -1 if no match was found.
1089  *
1090  * Example:
1091  * <programlisting>
1092  * // Assume the adapter contains 0x00 0x01 0x02 ... 0xfe 0xff
1093  *
1094  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 0, 256);
1095  * // -> returns 0
1096  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 1, 255);
1097  * // -> returns -1
1098  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x01020304, 1, 255);
1099  * // -> returns 1
1100  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0001, 0, 256);
1101  * // -> returns -1
1102  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0203, 0, 256);
1103  * // -> returns 0
1104  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 256);
1105  * // -> returns 2
1106  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 4);
1107  * // -> returns -1
1108  * </programlisting>
1109  *
1110  * Since: 0.10.24
1111  */
1112 gsize
1113 gst_adapter_masked_scan_uint32 (GstAdapter * adapter, guint32 mask,
1114     guint32 pattern, gsize offset, gsize size)
1115 {
1116   return gst_adapter_masked_scan_uint32_peek (adapter, mask, pattern, offset,
1117       size, NULL);
1118 }