adapter: ensure automagic _unmap in some more cases
[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 #define GST_ADAPTER_GET_PRIVATE(obj)  \
128    (G_TYPE_INSTANCE_GET_PRIVATE ((obj), GST_TYPE_ADAPTER, GstAdapterPrivate))
129
130 struct _GstAdapterPrivate
131 {
132   GstClockTime pts;
133   guint64 pts_distance;
134   GstClockTime dts;
135   guint64 dts_distance;
136
137   gsize scan_offset;
138   GSList *scan_entry;
139
140   gpointer cdata;
141   gsize csize;
142 };
143
144 #define _do_init \
145   GST_DEBUG_CATEGORY_INIT (gst_adapter_debug, "adapter", 0, "object to splice and merge buffers to desired size")
146 #define gst_adapter_parent_class parent_class
147 G_DEFINE_TYPE_WITH_CODE (GstAdapter, gst_adapter, G_TYPE_OBJECT, _do_init);
148
149 static void gst_adapter_dispose (GObject * object);
150 static void gst_adapter_finalize (GObject * object);
151
152 static void
153 gst_adapter_class_init (GstAdapterClass * klass)
154 {
155   GObjectClass *object = G_OBJECT_CLASS (klass);
156
157   g_type_class_add_private (klass, sizeof (GstAdapterPrivate));
158
159   object->dispose = gst_adapter_dispose;
160   object->finalize = gst_adapter_finalize;
161 }
162
163 static void
164 gst_adapter_init (GstAdapter * adapter)
165 {
166   adapter->priv = GST_ADAPTER_GET_PRIVATE (adapter);
167   adapter->assembled_data = g_malloc (DEFAULT_SIZE);
168   adapter->assembled_size = DEFAULT_SIZE;
169   adapter->priv->pts = GST_CLOCK_TIME_NONE;
170   adapter->priv->pts_distance = 0;
171   adapter->priv->dts = GST_CLOCK_TIME_NONE;
172   adapter->priv->dts_distance = 0;
173 }
174
175 static void
176 gst_adapter_dispose (GObject * object)
177 {
178   GstAdapter *adapter = GST_ADAPTER (object);
179
180   gst_adapter_clear (adapter);
181
182   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
183 }
184
185 static void
186 gst_adapter_finalize (GObject * object)
187 {
188   GstAdapter *adapter = GST_ADAPTER (object);
189
190   g_free (adapter->assembled_data);
191
192   GST_CALL_PARENT (G_OBJECT_CLASS, finalize, (object));
193 }
194
195 /**
196  * gst_adapter_new:
197  *
198  * Creates a new #GstAdapter. Free with g_object_unref().
199  *
200  * Returns: (transfer full): a new #GstAdapter
201  */
202 GstAdapter *
203 gst_adapter_new (void)
204 {
205   return g_object_newv (GST_TYPE_ADAPTER, 0, NULL);
206 }
207
208 /**
209  * gst_adapter_clear:
210  * @adapter: a #GstAdapter
211  *
212  * Removes all buffers from @adapter.
213  */
214 void
215 gst_adapter_clear (GstAdapter * adapter)
216 {
217   g_return_if_fail (GST_IS_ADAPTER (adapter));
218
219   if (adapter->priv->cdata) {
220     gst_adapter_unmap (adapter);
221   }
222
223   g_slist_foreach (adapter->buflist, (GFunc) gst_mini_object_unref, NULL);
224   g_slist_free (adapter->buflist);
225   adapter->buflist = NULL;
226   adapter->buflist_end = NULL;
227   adapter->size = 0;
228   adapter->skip = 0;
229   adapter->assembled_len = 0;
230   adapter->priv->pts = GST_CLOCK_TIME_NONE;
231   adapter->priv->pts_distance = 0;
232   adapter->priv->dts = GST_CLOCK_TIME_NONE;
233   adapter->priv->dts_distance = 0;
234   adapter->priv->scan_offset = 0;
235   adapter->priv->scan_entry = NULL;
236 }
237
238 static inline void
239 update_timestamps (GstAdapter * adapter, GstBuffer * buf)
240 {
241   GstClockTime pts, dts;
242
243   pts = GST_BUFFER_PTS (buf);
244   if (GST_CLOCK_TIME_IS_VALID (pts)) {
245     GST_LOG_OBJECT (adapter, "new pts %" GST_TIME_FORMAT, GST_TIME_ARGS (pts));
246     adapter->priv->pts = pts;
247     adapter->priv->pts_distance = 0;
248   }
249   dts = GST_BUFFER_DTS (buf);
250   if (GST_CLOCK_TIME_IS_VALID (dts)) {
251     GST_LOG_OBJECT (adapter, "new dts %" GST_TIME_FORMAT, GST_TIME_ARGS (dts));
252     adapter->priv->dts = dts;
253     adapter->priv->dts_distance = 0;
254   }
255 }
256
257 /* copy data into @dest, skipping @skip bytes from the head buffers */
258 static void
259 copy_into_unchecked (GstAdapter * adapter, guint8 * dest, gsize skip,
260     gsize size)
261 {
262   GSList *g;
263   GstBuffer *buf;
264   gsize bsize, csize;
265
266   /* first step, do skipping */
267   /* we might well be copying where we were scanning */
268   if (adapter->priv->scan_entry && (adapter->priv->scan_offset <= skip)) {
269     g = adapter->priv->scan_entry;
270     skip -= adapter->priv->scan_offset;
271   } else {
272     g = adapter->buflist;
273   }
274   buf = g->data;
275   bsize = gst_buffer_get_size (buf);
276   while (G_UNLIKELY (skip >= bsize)) {
277     skip -= bsize;
278     g = g_slist_next (g);
279     buf = g->data;
280     bsize = gst_buffer_get_size (buf);
281   }
282   /* copy partial buffer */
283   csize = MIN (bsize - skip, size);
284   GST_DEBUG ("bsize %" G_GSIZE_FORMAT ", skip %" G_GSIZE_FORMAT ", csize %"
285       G_GSIZE_FORMAT, bsize, skip, csize);
286   gst_buffer_extract (buf, skip, dest, csize);
287   size -= csize;
288   dest += csize;
289
290   /* second step, copy remainder */
291   while (size > 0) {
292     g = g_slist_next (g);
293     buf = g->data;
294     bsize = gst_buffer_get_size (buf);
295     if (G_LIKELY (bsize > 0)) {
296       csize = MIN (bsize, size);
297       gst_buffer_extract (buf, 0, dest, csize);
298       size -= csize;
299       dest += csize;
300     }
301   }
302 }
303
304 /**
305  * gst_adapter_push:
306  * @adapter: a #GstAdapter
307  * @buf: (transfer full): a #GstBuffer to add to queue in the adapter
308  *
309  * Adds the data from @buf to the data stored inside @adapter and takes
310  * ownership of the buffer.
311  */
312 void
313 gst_adapter_push (GstAdapter * adapter, GstBuffer * buf)
314 {
315   gsize size;
316
317   g_return_if_fail (GST_IS_ADAPTER (adapter));
318   g_return_if_fail (GST_IS_BUFFER (buf));
319
320   size = gst_buffer_get_size (buf);
321   adapter->size += size;
322
323   /* Note: merging buffers at this point is premature. */
324   if (G_UNLIKELY (adapter->buflist == NULL)) {
325     GST_LOG_OBJECT (adapter, "pushing first %" G_GSIZE_FORMAT " bytes", size);
326     adapter->buflist = adapter->buflist_end = g_slist_append (NULL, buf);
327     update_timestamps (adapter, buf);
328   } else {
329     /* Otherwise append to the end, and advance our end pointer */
330     GST_LOG_OBJECT (adapter, "pushing %" G_GSIZE_FORMAT " bytes at end, "
331         "size now %" G_GSIZE_FORMAT, size, adapter->size);
332     adapter->buflist_end = g_slist_append (adapter->buflist_end, buf);
333     adapter->buflist_end = g_slist_next (adapter->buflist_end);
334   }
335 }
336
337 /* Internal method only. Tries to merge buffers at the head of the queue
338  * to form a single larger buffer of size 'size'. Only merges buffers that
339  * where 'gst_buffer_is_span_fast' returns TRUE.
340  *
341  * Returns TRUE if it managed to merge anything.
342  */
343 static gboolean
344 gst_adapter_try_to_merge_up (GstAdapter * adapter, gsize size)
345 {
346   GstBuffer *cur, *head;
347   GSList *g;
348   gboolean ret = FALSE;
349   gsize hsize;
350
351   g = adapter->buflist;
352   if (g == NULL)
353     return FALSE;
354
355   head = g->data;
356   g = g_slist_next (g);
357
358   /* How large do we want our head buffer? The requested size, plus whatever's
359    * been skipped already */
360   size += adapter->skip;
361   hsize = gst_buffer_get_size (head);
362
363   while (g != NULL && hsize < size) {
364     cur = g->data;
365     if (!gst_buffer_is_span_fast (head, cur))
366       return ret;
367
368     /* Merge the head buffer and the next in line */
369     GST_LOG_OBJECT (adapter, "Merging buffers of size %" G_GSIZE_FORMAT " & %"
370         G_GSIZE_FORMAT " in search of target %" G_GSIZE_FORMAT,
371         hsize, gst_buffer_get_size (cur), size);
372
373     head = gst_buffer_join (head, cur);
374     hsize = gst_buffer_get_size (head);
375     ret = TRUE;
376
377     /* Delete the front list item, and store our new buffer in the 2nd list
378      * item */
379     adapter->buflist = g_slist_delete_link (adapter->buflist, adapter->buflist);
380     g->data = head;
381
382     /* invalidate scan position */
383     adapter->priv->scan_offset = 0;
384     adapter->priv->scan_entry = NULL;
385
386     g = g_slist_next (g);
387   }
388
389   return ret;
390 }
391
392 /**
393  * gst_adapter_map:
394  * @adapter: a #GstAdapter
395  * @size: the number of bytes to map/peek
396  *
397  * Gets the first @size bytes stored in the @adapter. The returned pointer is
398  * valid until the next function is called on the adapter.
399  *
400  * Note that setting the returned pointer as the data of a #GstBuffer is
401  * incorrect for general-purpose plugins. The reason is that if a downstream
402  * element stores the buffer so that it has access to it outside of the bounds
403  * of its chain function, the buffer will have an invalid data pointer after
404  * your element flushes the bytes. In that case you should use
405  * gst_adapter_take(), which returns a freshly-allocated buffer that you can set
406  * as #GstBuffer malloc_data or the potentially more performant
407  * gst_adapter_take_buffer().
408  *
409  * Returns #NULL if @size bytes are not available.
410  *
411  * Returns: (transfer none) (array length=size): a pointer to the first
412  *     @size bytes of data, or NULL
413  */
414 gconstpointer
415 gst_adapter_map (GstAdapter * adapter, gsize size)
416 {
417   GstBuffer *cur;
418   gsize skip, csize;
419   gsize toreuse, tocopy;
420   guint8 *data;
421
422   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
423   g_return_val_if_fail (size > 0, NULL);
424
425   if (adapter->priv->cdata) {
426     gst_adapter_unmap (adapter);
427   }
428
429   /* we don't have enough data, return NULL. This is unlikely
430    * as one usually does an _available() first instead of peeking a
431    * random size. */
432   if (G_UNLIKELY (size > adapter->size))
433     return NULL;
434
435   /* we have enough assembled data, return it */
436   if (adapter->assembled_len >= size)
437     return adapter->assembled_data;
438
439   do {
440     cur = adapter->buflist->data;
441     skip = adapter->skip;
442
443     csize = gst_buffer_get_size (cur);
444     if (csize >= size + skip) {
445       data = gst_buffer_map (cur, &csize, NULL, GST_MAP_READ);
446       adapter->priv->cdata = data;
447       adapter->priv->csize = csize;
448       return data + skip;
449     }
450     /* We may be able to efficiently merge buffers in our pool to
451      * gather a big enough chunk to return it from the head buffer directly */
452   } while (gst_adapter_try_to_merge_up (adapter, size));
453
454   /* see how much data we can reuse from the assembled memory and how much
455    * we need to copy */
456   toreuse = adapter->assembled_len;
457   tocopy = size - toreuse;
458
459   /* Gonna need to copy stuff out */
460   if (G_UNLIKELY (adapter->assembled_size < size)) {
461     adapter->assembled_size = (size / DEFAULT_SIZE + 1) * DEFAULT_SIZE;
462     GST_DEBUG_OBJECT (adapter, "resizing internal buffer to %" G_GSIZE_FORMAT,
463         adapter->assembled_size);
464     if (toreuse == 0) {
465       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "alloc new buffer");
466       /* no g_realloc to avoid a memcpy that is not desired here since we are
467        * not going to reuse any data here */
468       g_free (adapter->assembled_data);
469       adapter->assembled_data = g_malloc (adapter->assembled_size);
470     } else {
471       /* we are going to reuse all data, realloc then */
472       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "reusing %" G_GSIZE_FORMAT " bytes",
473           toreuse);
474       adapter->assembled_data =
475           g_realloc (adapter->assembled_data, adapter->assembled_size);
476     }
477   }
478   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy remaining %" G_GSIZE_FORMAT
479       " bytes from adapter", tocopy);
480   data = adapter->assembled_data;
481   copy_into_unchecked (adapter, data + toreuse, skip + toreuse, tocopy);
482   adapter->assembled_len = size;
483
484   return adapter->assembled_data;
485 }
486
487 /**
488  * gst_adapter_unmap:
489  * @adapter: a #GstAdapter
490  *
491  * Releases the memory obtained with the last gst_adapter_map().
492  */
493 void
494 gst_adapter_unmap (GstAdapter * adapter)
495 {
496   g_return_if_fail (GST_IS_ADAPTER (adapter));
497
498   if (adapter->priv->cdata) {
499     GstBuffer *cur = adapter->buflist->data;
500     gst_buffer_unmap (cur, adapter->priv->cdata, adapter->priv->csize);
501     adapter->priv->cdata = NULL;
502   }
503 }
504
505 /**
506  * gst_adapter_copy:
507  * @adapter: a #GstAdapter
508  * @dest: (out caller-allocates) (array length=size): the memory to copy into
509  * @offset: the bytes offset in the adapter to start from
510  * @size: the number of bytes to copy
511  *
512  * Copies @size bytes of data starting at @offset out of the buffers
513  * contained in @GstAdapter into an array @dest provided by the caller.
514  *
515  * The array @dest should be large enough to contain @size bytes.
516  * The user should check that the adapter has (@offset + @size) bytes
517  * available before calling this function.
518  *
519  * Since: 0.10.12
520  */
521 void
522 gst_adapter_copy (GstAdapter * adapter, gpointer dest, gsize offset, gsize size)
523 {
524   g_return_if_fail (GST_IS_ADAPTER (adapter));
525   g_return_if_fail (size > 0);
526   g_return_if_fail (offset + size <= adapter->size);
527
528   copy_into_unchecked (adapter, dest, offset + adapter->skip, size);
529 }
530
531 /**
532  * gst_adapter_flush:
533  * @adapter: a #GstAdapter
534  * @flush: the number of bytes to flush
535  *
536  * Flushes the first @flush bytes in the @adapter. The caller must ensure that
537  * at least this many bytes are available.
538  *
539  * See also: gst_adapter_map(), gst_adapter_unmap()
540  */
541 static void
542 gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush)
543 {
544   GstBuffer *cur;
545   gsize size;
546   GstAdapterPrivate *priv;
547   GSList *g;
548
549   GST_LOG_OBJECT (adapter, "flushing %" G_GSIZE_FORMAT " bytes", flush);
550
551   if (adapter->priv->cdata) {
552     gst_adapter_unmap (adapter);
553   }
554
555   priv = adapter->priv;
556
557   /* clear state */
558   adapter->size -= flush;
559   adapter->assembled_len = 0;
560
561   /* take skip into account */
562   flush += adapter->skip;
563   /* distance is always at least the amount of skipped bytes */
564   priv->pts_distance -= adapter->skip;
565   priv->dts_distance -= adapter->skip;
566
567   g = adapter->buflist;
568   cur = g->data;
569   size = gst_buffer_get_size (cur);
570   while (flush >= size) {
571     /* can skip whole buffer */
572     GST_LOG_OBJECT (adapter, "flushing out head buffer");
573     priv->pts_distance += size;
574     priv->dts_distance += size;
575     flush -= size;
576
577     gst_buffer_unref (cur);
578     g = g_slist_delete_link (g, g);
579
580     if (G_UNLIKELY (g == NULL)) {
581       GST_LOG_OBJECT (adapter, "adapter empty now");
582       adapter->buflist_end = NULL;
583       break;
584     }
585     /* there is a new head buffer, update the timestamps */
586     cur = g->data;
587     update_timestamps (adapter, cur);
588     size = gst_buffer_get_size (cur);
589   }
590   adapter->buflist = g;
591   /* account for the remaining bytes */
592   adapter->skip = flush;
593   adapter->priv->pts_distance += flush;
594   adapter->priv->dts_distance += flush;
595   /* invalidate scan position */
596   priv->scan_offset = 0;
597   priv->scan_entry = NULL;
598 }
599
600 void
601 gst_adapter_flush (GstAdapter * adapter, gsize flush)
602 {
603   g_return_if_fail (GST_IS_ADAPTER (adapter));
604   g_return_if_fail (flush <= adapter->size);
605
606   /* flushing out 0 bytes will do nothing */
607   if (G_UNLIKELY (flush == 0))
608     return;
609
610   gst_adapter_flush_unchecked (adapter, flush);
611 }
612
613 /* internal function, nbytes should be flushed after calling this function */
614 static guint8 *
615 gst_adapter_take_internal (GstAdapter * adapter, gsize nbytes)
616 {
617   guint8 *data;
618   gsize toreuse, tocopy;
619
620   /* see how much data we can reuse from the assembled memory and how much
621    * we need to copy */
622   toreuse = MIN (nbytes, adapter->assembled_len);
623   tocopy = nbytes - toreuse;
624
625   /* find memory to return */
626   if (adapter->assembled_size >= nbytes && toreuse > 0) {
627     /* we reuse already allocated memory but only when we're going to reuse
628      * something from it because else we are worse than the malloc and copy
629      * case below */
630     GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes of assembled"
631         " data", toreuse);
632     /* we have enough free space in the assembled array */
633     data = adapter->assembled_data;
634     /* flush after this function should set the assembled_size to 0 */
635     adapter->assembled_data = g_malloc (adapter->assembled_size);
636   } else {
637     GST_LOG_OBJECT (adapter, "allocating %" G_GSIZE_FORMAT " bytes", nbytes);
638     /* not enough bytes in the assembled array, just allocate new space */
639     data = g_malloc (nbytes);
640     /* reuse what we can from the already assembled data */
641     if (toreuse) {
642       GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes", toreuse);
643       memcpy (data, adapter->assembled_data, toreuse);
644     }
645   }
646   if (tocopy) {
647     /* copy the remaining data */
648     copy_into_unchecked (adapter, toreuse + data, toreuse + adapter->skip,
649         tocopy);
650   }
651   return data;
652 }
653
654 /**
655  * gst_adapter_take:
656  * @adapter: a #GstAdapter
657  * @nbytes: the number of bytes to take
658  *
659  * Returns a freshly allocated buffer containing the first @nbytes bytes of the
660  * @adapter. The returned bytes will be flushed from the adapter.
661  *
662  * Caller owns returned value. g_free after usage.
663  *
664  * Free-function: g_free
665  *
666  * Returns: (transfer full) (array length=nbytes): oven-fresh hot data, or
667  *     #NULL if @nbytes bytes are not available
668  */
669 gpointer
670 gst_adapter_take (GstAdapter * adapter, gsize nbytes)
671 {
672   gpointer data;
673
674   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
675   g_return_val_if_fail (nbytes > 0, NULL);
676
677   /* we don't have enough data, return NULL. This is unlikely
678    * as one usually does an _available() first instead of peeking a
679    * random size. */
680   if (G_UNLIKELY (nbytes > adapter->size))
681     return NULL;
682
683   data = gst_adapter_take_internal (adapter, nbytes);
684
685   gst_adapter_flush_unchecked (adapter, nbytes);
686
687   return data;
688 }
689
690 /**
691  * gst_adapter_take_buffer:
692  * @adapter: a #GstAdapter
693  * @nbytes: the number of bytes to take
694  *
695  * Returns a #GstBuffer containing the first @nbytes bytes of the
696  * @adapter. The returned bytes will be flushed from the adapter.
697  * This function is potentially more performant than gst_adapter_take()
698  * since it can reuse the memory in pushed buffers by subbuffering
699  * or merging.
700  *
701  * Caller owns returned value. gst_buffer_unref() after usage.
702  *
703  * Free-function: gst_buffer_unref
704  *
705  * Returns: (transfer full): a #GstBuffer containing the first @nbytes of
706  *     the adapter, or #NULL if @nbytes bytes are not available
707  *
708  * Since: 0.10.6
709  */
710 GstBuffer *
711 gst_adapter_take_buffer (GstAdapter * adapter, gsize nbytes)
712 {
713   GstBuffer *buffer;
714   GstBuffer *cur;
715   gsize hsize, skip;
716   guint8 *data;
717
718   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
719   g_return_val_if_fail (nbytes > 0, NULL);
720
721   GST_LOG_OBJECT (adapter, "taking buffer of %" G_GSIZE_FORMAT " bytes",
722       nbytes);
723
724   /* we don't have enough data, return NULL. This is unlikely
725    * as one usually does an _available() first instead of grabbing a
726    * random size. */
727   if (G_UNLIKELY (nbytes > adapter->size))
728     return NULL;
729
730   cur = adapter->buflist->data;
731   skip = adapter->skip;
732   hsize = gst_buffer_get_size (cur);
733
734   /* our head buffer has enough data left, return it */
735   if (skip == 0 && hsize == nbytes) {
736     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
737         " as head buffer", nbytes);
738     buffer = gst_buffer_ref (cur);
739     goto done;
740   } else if (hsize >= nbytes + skip) {
741     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
742         " via region copy", nbytes);
743     buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
744     goto done;
745   }
746
747   if (gst_adapter_try_to_merge_up (adapter, nbytes)) {
748     /* Merged something, let's try again for sub-buffering */
749     cur = adapter->buflist->data;
750     if (gst_buffer_get_size (cur) >= nbytes + skip) {
751       GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
752           " via sub-buffer", nbytes);
753       buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
754       goto done;
755     }
756   }
757
758   data = gst_adapter_take_internal (adapter, nbytes);
759
760   buffer = gst_buffer_new ();
761   gst_buffer_take_memory (buffer, -1,
762       gst_memory_new_wrapped (0, data, g_free, nbytes, 0, nbytes));
763
764 done:
765   gst_adapter_flush_unchecked (adapter, nbytes);
766
767   return buffer;
768 }
769
770 /**
771  * gst_adapter_take_list:
772  * @adapter: a #GstAdapter
773  * @nbytes: the number of bytes to take
774  *
775  * Returns a #GList of buffers containing the first @nbytes bytes of the
776  * @adapter. The returned bytes will be flushed from the adapter.
777  * When the caller can deal with individual buffers, this function is more
778  * performant because no memory should be copied.
779  *
780  * Caller owns returned list and contained buffers. gst_buffer_unref() each
781  * buffer in the list before freeing the list after usage.
782  *
783  * Returns: (element-type Gst.Buffer) (transfer full): a #GList of buffers
784  *     containing the first @nbytes of the adapter, or #NULL if @nbytes bytes
785  *     are not available
786  *
787  * Since: 0.10.31
788  */
789 GList *
790 gst_adapter_take_list (GstAdapter * adapter, gsize nbytes)
791 {
792   GQueue queue = G_QUEUE_INIT;
793   GstBuffer *cur;
794   gsize hsize, skip;
795
796   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
797   g_return_val_if_fail (nbytes <= adapter->size, NULL);
798
799   GST_LOG_OBJECT (adapter, "taking %" G_GSIZE_FORMAT " bytes", nbytes);
800
801   while (nbytes > 0) {
802     cur = adapter->buflist->data;
803     skip = adapter->skip;
804     hsize = MIN (nbytes, gst_buffer_get_size (cur) - skip);
805
806     cur = gst_adapter_take_buffer (adapter, hsize);
807
808     g_queue_push_tail (&queue, cur);
809
810     nbytes -= hsize;
811   }
812   return queue.head;
813 }
814
815 /**
816  * gst_adapter_available:
817  * @adapter: a #GstAdapter
818  *
819  * Gets the maximum amount of bytes available, that is it returns the maximum
820  * value that can be supplied to gst_adapter_map() without that function
821  * returning NULL.
822  *
823  * Returns: number of bytes available in @adapter
824  */
825 gsize
826 gst_adapter_available (GstAdapter * adapter)
827 {
828   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
829
830   return adapter->size;
831 }
832
833 /**
834  * gst_adapter_available_fast:
835  * @adapter: a #GstAdapter
836  *
837  * Gets the maximum number of bytes that are immediately available without
838  * requiring any expensive operations (like copying the data into a
839  * temporary buffer).
840  *
841  * Returns: number of bytes that are available in @adapter without expensive
842  * operations
843  */
844 gsize
845 gst_adapter_available_fast (GstAdapter * adapter)
846 {
847   GstBuffer *cur;
848   gsize size;
849   GSList *g;
850
851   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
852
853   /* no data */
854   if (adapter->size == 0)
855     return 0;
856
857   /* some stuff we already assembled */
858   if (adapter->assembled_len)
859     return adapter->assembled_len;
860
861   /* take the first non-zero buffer */
862   g = adapter->buflist;
863   while (TRUE) {
864     cur = g->data;
865     size = gst_buffer_get_size (cur);
866     if (size != 0)
867       break;
868     g = g_slist_next (g);
869   }
870
871   /* we can quickly get the (remaining) data of the first buffer */
872   return size - adapter->skip;
873 }
874
875 /**
876  * gst_adapter_prev_pts:
877  * @adapter: a #GstAdapter
878  * @distance: (out) (allow-none): pointer to location for distance, or NULL
879  *
880  * Get the pts that was before the current byte in the adapter. When
881  * @distance is given, the amount of bytes between the pts and the current
882  * position is returned.
883  *
884  * The pts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
885  * the adapter is first created or when it is cleared. This also means that before
886  * the first byte with a pts is removed from the adapter, the pts
887  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
888  *
889  * Returns: The previously seen pts.
890  */
891 GstClockTime
892 gst_adapter_prev_pts (GstAdapter * adapter, guint64 * distance)
893 {
894   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
895
896   if (distance)
897     *distance = adapter->priv->pts_distance;
898
899   return adapter->priv->pts;
900 }
901
902 /**
903  * gst_adapter_prev_dts:
904  * @adapter: a #GstAdapter
905  * @distance: (out) (allow-none): pointer to location for distance, or NULL
906  *
907  * Get the dts that was before the current byte in the adapter. When
908  * @distance is given, the amount of bytes between the dts and the current
909  * position is returned.
910  *
911  * The dts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
912  * the adapter is first created or when it is cleared. This also means that before
913  * the first byte with a dts is removed from the adapter, the dts
914  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
915  *
916  * Returns: The previously seen dts.
917  */
918 GstClockTime
919 gst_adapter_prev_dts (GstAdapter * adapter, guint64 * distance)
920 {
921   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
922
923   if (distance)
924     *distance = adapter->priv->dts_distance;
925
926   return adapter->priv->dts;
927 }
928
929 /**
930  * gst_adapter_masked_scan_uint32_peek:
931  * @adapter: a #GstAdapter
932  * @mask: mask to apply to data before matching against @pattern
933  * @pattern: pattern to match (after mask is applied)
934  * @offset: offset into the adapter data from which to start scanning, returns
935  *          the last scanned position.
936  * @size: number of bytes to scan from offset
937  * @value: pointer to uint32 to return matching data
938  *
939  * Scan for pattern @pattern with applied mask @mask in the adapter data,
940  * starting from offset @offset.  If a match is found, the value that matched
941  * is returned through @value, otherwise @value is left untouched.
942  *
943  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
944  * of endianness.  All four bytes of the pattern must be present in the
945  * adapter for it to match, even if the first or last bytes are masked out.
946  *
947  * It is an error to call this function without making sure that there is
948  * enough data (offset+size bytes) in the adapter.
949  *
950  * Returns: offset of the first match, or -1 if no match was found.
951  *
952  * Since: 0.10.30
953  */
954 gsize
955 gst_adapter_masked_scan_uint32_peek (GstAdapter * adapter, guint32 mask,
956     guint32 pattern, gsize offset, gsize size, guint32 * value)
957 {
958   GSList *g;
959   gsize skip, bsize, osize, i;
960   guint32 state;
961   guint8 *bdata, *odata;
962   GstBuffer *buf;
963
964   g_return_val_if_fail (size > 0, -1);
965   g_return_val_if_fail (offset + size <= adapter->size, -1);
966   g_return_val_if_fail (((~mask) & pattern) == 0, -1);
967
968   /* we can't find the pattern with less than 4 bytes */
969   if (G_UNLIKELY (size < 4))
970     return -1;
971
972   skip = offset + adapter->skip;
973
974   /* first step, do skipping and position on the first buffer */
975   /* optimistically assume scanning continues sequentially */
976   if (adapter->priv->scan_entry && (adapter->priv->scan_offset <= skip)) {
977     g = adapter->priv->scan_entry;
978     skip -= adapter->priv->scan_offset;
979   } else {
980     g = adapter->buflist;
981     adapter->priv->scan_offset = 0;
982     adapter->priv->scan_entry = NULL;
983   }
984   buf = g->data;
985   bsize = gst_buffer_get_size (buf);
986   while (G_UNLIKELY (skip >= bsize)) {
987     skip -= bsize;
988     g = g_slist_next (g);
989     adapter->priv->scan_offset += bsize;
990     adapter->priv->scan_entry = g;
991     buf = g->data;
992     bsize = gst_buffer_get_size (buf);
993   }
994   /* get the data now */
995   odata = gst_buffer_map (buf, &osize, NULL, GST_MAP_READ);
996
997   bdata = odata + skip;
998   bsize = osize - skip;
999   skip = 0;
1000
1001   /* set the state to something that does not match */
1002   state = ~pattern;
1003
1004   /* now find data */
1005   do {
1006     bsize = MIN (bsize, size);
1007     for (i = 0; i < bsize; i++) {
1008       state = ((state << 8) | bdata[i]);
1009       if (G_UNLIKELY ((state & mask) == pattern)) {
1010         /* we have a match but we need to have skipped at
1011          * least 4 bytes to fill the state. */
1012         if (G_LIKELY (skip + i >= 3)) {
1013           if (G_LIKELY (value))
1014             *value = state;
1015           gst_buffer_unmap (buf, odata, osize);
1016           return offset + skip + i - 3;
1017         }
1018       }
1019     }
1020     size -= bsize;
1021     if (size == 0)
1022       break;
1023
1024     /* nothing found yet, go to next buffer */
1025     skip += bsize;
1026     g = g_slist_next (g);
1027     adapter->priv->scan_offset += osize;
1028     adapter->priv->scan_entry = g;
1029     gst_buffer_unmap (buf, odata, osize);
1030     buf = g->data;
1031
1032     odata = gst_buffer_map (buf, &osize, NULL, GST_MAP_READ);
1033     bsize = osize;
1034     bdata = odata;
1035   } while (TRUE);
1036
1037   gst_buffer_unmap (buf, odata, osize);
1038
1039   /* nothing found */
1040   return -1;
1041 }
1042
1043 /**
1044  * gst_adapter_masked_scan_uint32:
1045  * @adapter: a #GstAdapter
1046  * @mask: mask to apply to data before matching against @pattern
1047  * @pattern: pattern to match (after mask is applied)
1048  * @offset: offset into the adapter data from which to start scanning, returns
1049  *          the last scanned position.
1050  * @size: number of bytes to scan from offset
1051  *
1052  * Scan for pattern @pattern with applied mask @mask in the adapter data,
1053  * starting from offset @offset.
1054  *
1055  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
1056  * of endianness.  All four bytes of the pattern must be present in the
1057  * adapter for it to match, even if the first or last bytes are masked out.
1058  *
1059  * It is an error to call this function without making sure that there is
1060  * enough data (offset+size bytes) in the adapter.
1061  *
1062  * This function calls gst_adapter_masked_scan_uint32_peek() passing NULL
1063  * for value.
1064  *
1065  * Returns: offset of the first match, or -1 if no match was found.
1066  *
1067  * Example:
1068  * <programlisting>
1069  * // Assume the adapter contains 0x00 0x01 0x02 ... 0xfe 0xff
1070  *
1071  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 0, 256);
1072  * // -> returns 0
1073  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 1, 255);
1074  * // -> returns -1
1075  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x01020304, 1, 255);
1076  * // -> returns 1
1077  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0001, 0, 256);
1078  * // -> returns -1
1079  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0203, 0, 256);
1080  * // -> returns 0
1081  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 256);
1082  * // -> returns 2
1083  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 4);
1084  * // -> returns -1
1085  * </programlisting>
1086  *
1087  * Since: 0.10.24
1088  */
1089 gsize
1090 gst_adapter_masked_scan_uint32 (GstAdapter * adapter, guint32 mask,
1091     guint32 pattern, gsize offset, gsize size)
1092 {
1093   return gst_adapter_masked_scan_uint32_peek (adapter, mask, pattern, offset,
1094       size, NULL);
1095 }