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