adapter: Take account of the skip in gst_adapter_take_buffer_fast()
[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., 51 Franklin St, Fifth Floor,
18  * Boston, MA 02110-1301, 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, GstObject *parent, GstBuffer *buffer)
49  * {
50  *   MyElement *this;
51  *   GstAdapter *adapter;
52  *   GstFlowReturn ret = GST_FLOW_OK;
53  *
54  *   this = MY_ELEMENT (parent);
55  *
56  *   adapter = this->adapter;
57  *
58  *   // put buffer into adapter
59  *   gst_adapter_push (adapter, buffer);
60  *
61  *   // while we can read out 512 bytes, process them
62  *   while (gst_adapter_available (adapter) >= 512 && ret == GST_FLOW_OK) {
63  *     const guint8 *data = gst_adapter_map (adapter, 512);
64  *     // use flowreturn as an error value
65  *     ret = my_library_foo (data);
66  *     gst_adapter_unmap (adapter);
67  *     gst_adapter_flush (adapter, 512);
68  *   }
69  *   return ret;
70  * }
71  * ]|
72  *
73  * For another example, a simple element inside GStreamer that uses GstAdapter
74  * is the libvisual element.
75  *
76  * An element using GstAdapter in its sink pad chain function should ensure that
77  * when the FLUSH_STOP event is received, that any queued data is cleared using
78  * gst_adapter_clear(). Data should also be cleared or processed on EOS and
79  * when changing state from #GST_STATE_PAUSED to #GST_STATE_READY.
80  *
81  * Also check the GST_BUFFER_FLAG_DISCONT flag on the buffer. Some elements might
82  * need to clear the adapter after a discontinuity.
83  *
84  * The adapter will keep track of the timestamps of the buffers
85  * that were pushed. The last seen timestamp before the current position
86  * can be queried with gst_adapter_prev_pts(). This function can
87  * optionally return the number of bytes between the start of the buffer that
88  * carried the timestamp and the current adapter position. The distance is
89  * useful when dealing with, for example, raw audio samples because it allows
90  * you to calculate the timestamp of the current adapter position by using the
91  * last seen timestamp and the amount of bytes since.  Additionally, the
92  * gst_adapter_prev_pts_at_offset() can be used to determine the last
93  * seen timestamp at a particular offset in the adapter.
94  *
95  * A last thing to note is that while GstAdapter is pretty optimized,
96  * merging buffers still might be an operation that requires a malloc() and
97  * memcpy() operation, and these operations are not the fastest. Because of
98  * this, some functions like gst_adapter_available_fast() are provided to help
99  * speed up such cases should you want to. To avoid repeated memory allocations,
100  * gst_adapter_copy() can be used to copy data into a (statically allocated)
101  * user provided buffer.
102  *
103  * GstAdapter is not MT safe. All operations on an adapter must be serialized by
104  * the caller. This is not normally a problem, however, as the normal use case
105  * of GstAdapter is inside one pad's chain function, in which case access is
106  * serialized via the pad's STREAM_LOCK.
107  *
108  * Note that gst_adapter_push() takes ownership of the buffer passed. Use
109  * gst_buffer_ref() before pushing it into the adapter if you still want to
110  * access the buffer later. The adapter will never modify the data in the
111  * buffer pushed in it.
112  *
113  * Last reviewed on 2009-05-13 (0.10.24).
114  */
115
116 #include <gst/gst_private.h>
117 #include "gstadapter.h"
118 #include <string.h>
119
120 /* default size for the assembled data buffer */
121 #define DEFAULT_SIZE 4096
122
123 static void gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush);
124
125 GST_DEBUG_CATEGORY_STATIC (gst_adapter_debug);
126 #define GST_CAT_DEFAULT gst_adapter_debug
127
128 struct _GstAdapter
129 {
130   GObject object;
131
132   /*< private > */
133   GSList *buflist;
134   GSList *buflist_end;
135   gsize size;
136   gsize skip;
137
138   /* we keep state of assembled pieces */
139   gpointer assembled_data;
140   gsize assembled_size;
141   gsize assembled_len;
142
143   GstClockTime pts;
144   guint64 pts_distance;
145   GstClockTime dts;
146   guint64 dts_distance;
147
148   gsize scan_offset;
149   GSList *scan_entry;
150
151   GstMapInfo info;
152 };
153
154 struct _GstAdapterClass
155 {
156   GObjectClass parent_class;
157 };
158
159 #define _do_init \
160   GST_DEBUG_CATEGORY_INIT (gst_adapter_debug, "adapter", 0, "object to splice and merge buffers to desired size")
161 #define gst_adapter_parent_class parent_class
162 G_DEFINE_TYPE_WITH_CODE (GstAdapter, gst_adapter, G_TYPE_OBJECT, _do_init);
163
164 static void gst_adapter_dispose (GObject * object);
165 static void gst_adapter_finalize (GObject * object);
166
167 static void
168 gst_adapter_class_init (GstAdapterClass * klass)
169 {
170   GObjectClass *object = G_OBJECT_CLASS (klass);
171
172   object->dispose = gst_adapter_dispose;
173   object->finalize = gst_adapter_finalize;
174 }
175
176 static void
177 gst_adapter_init (GstAdapter * adapter)
178 {
179   adapter->assembled_data = g_malloc (DEFAULT_SIZE);
180   adapter->assembled_size = DEFAULT_SIZE;
181   adapter->pts = GST_CLOCK_TIME_NONE;
182   adapter->pts_distance = 0;
183   adapter->dts = GST_CLOCK_TIME_NONE;
184   adapter->dts_distance = 0;
185 }
186
187 static void
188 gst_adapter_dispose (GObject * object)
189 {
190   GstAdapter *adapter = GST_ADAPTER (object);
191
192   gst_adapter_clear (adapter);
193
194   GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object));
195 }
196
197 static void
198 gst_adapter_finalize (GObject * object)
199 {
200   GstAdapter *adapter = GST_ADAPTER (object);
201
202   g_free (adapter->assembled_data);
203
204   GST_CALL_PARENT (G_OBJECT_CLASS, finalize, (object));
205 }
206
207 /**
208  * gst_adapter_new:
209  *
210  * Creates a new #GstAdapter. Free with g_object_unref().
211  *
212  * Returns: (transfer full): a new #GstAdapter
213  */
214 GstAdapter *
215 gst_adapter_new (void)
216 {
217   return g_object_newv (GST_TYPE_ADAPTER, 0, NULL);
218 }
219
220 /**
221  * gst_adapter_clear:
222  * @adapter: a #GstAdapter
223  *
224  * Removes all buffers from @adapter.
225  */
226 void
227 gst_adapter_clear (GstAdapter * adapter)
228 {
229   g_return_if_fail (GST_IS_ADAPTER (adapter));
230
231   if (adapter->info.memory)
232     gst_adapter_unmap (adapter);
233
234   g_slist_foreach (adapter->buflist, (GFunc) gst_mini_object_unref, NULL);
235   g_slist_free (adapter->buflist);
236   adapter->buflist = NULL;
237   adapter->buflist_end = NULL;
238   adapter->size = 0;
239   adapter->skip = 0;
240   adapter->assembled_len = 0;
241   adapter->pts = GST_CLOCK_TIME_NONE;
242   adapter->pts_distance = 0;
243   adapter->dts = GST_CLOCK_TIME_NONE;
244   adapter->dts_distance = 0;
245   adapter->scan_offset = 0;
246   adapter->scan_entry = NULL;
247 }
248
249 static inline void
250 update_timestamps (GstAdapter * adapter, GstBuffer * buf)
251 {
252   GstClockTime pts, dts;
253
254   pts = GST_BUFFER_PTS (buf);
255   if (GST_CLOCK_TIME_IS_VALID (pts)) {
256     GST_LOG_OBJECT (adapter, "new pts %" GST_TIME_FORMAT, GST_TIME_ARGS (pts));
257     adapter->pts = pts;
258     adapter->pts_distance = 0;
259   }
260   dts = GST_BUFFER_DTS (buf);
261   if (GST_CLOCK_TIME_IS_VALID (dts)) {
262     GST_LOG_OBJECT (adapter, "new dts %" GST_TIME_FORMAT, GST_TIME_ARGS (dts));
263     adapter->dts = dts;
264     adapter->dts_distance = 0;
265   }
266 }
267
268 /* copy data into @dest, skipping @skip bytes from the head buffers */
269 static void
270 copy_into_unchecked (GstAdapter * adapter, guint8 * dest, gsize skip,
271     gsize size)
272 {
273   GSList *g;
274   GstBuffer *buf;
275   gsize bsize, csize;
276
277   /* first step, do skipping */
278   /* we might well be copying where we were scanning */
279   if (adapter->scan_entry && (adapter->scan_offset <= skip)) {
280     g = adapter->scan_entry;
281     skip -= adapter->scan_offset;
282   } else {
283     g = adapter->buflist;
284   }
285   buf = g->data;
286   bsize = gst_buffer_get_size (buf);
287   while (G_UNLIKELY (skip >= bsize)) {
288     skip -= bsize;
289     g = g_slist_next (g);
290     buf = g->data;
291     bsize = gst_buffer_get_size (buf);
292   }
293   /* copy partial buffer */
294   csize = MIN (bsize - skip, size);
295   GST_DEBUG ("bsize %" G_GSIZE_FORMAT ", skip %" G_GSIZE_FORMAT ", csize %"
296       G_GSIZE_FORMAT, bsize, skip, csize);
297   GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, adapter, "extract %" G_GSIZE_FORMAT
298       " bytes", csize);
299   gst_buffer_extract (buf, skip, dest, csize);
300   size -= csize;
301   dest += csize;
302
303   /* second step, copy remainder */
304   while (size > 0) {
305     g = g_slist_next (g);
306     buf = g->data;
307     bsize = gst_buffer_get_size (buf);
308     if (G_LIKELY (bsize > 0)) {
309       csize = MIN (bsize, size);
310       GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, adapter,
311           "extract %" G_GSIZE_FORMAT " bytes", csize);
312       gst_buffer_extract (buf, 0, dest, csize);
313       size -= csize;
314       dest += csize;
315     }
316   }
317 }
318
319 /**
320  * gst_adapter_push:
321  * @adapter: a #GstAdapter
322  * @buf: (transfer full): a #GstBuffer to add to queue in the adapter
323  *
324  * Adds the data from @buf to the data stored inside @adapter and takes
325  * ownership of the buffer.
326  */
327 void
328 gst_adapter_push (GstAdapter * adapter, GstBuffer * buf)
329 {
330   gsize size;
331
332   g_return_if_fail (GST_IS_ADAPTER (adapter));
333   g_return_if_fail (GST_IS_BUFFER (buf));
334
335   size = gst_buffer_get_size (buf);
336   adapter->size += size;
337
338   /* Note: merging buffers at this point is premature. */
339   if (G_UNLIKELY (adapter->buflist == NULL)) {
340     GST_LOG_OBJECT (adapter, "pushing %p first %" G_GSIZE_FORMAT " bytes",
341         buf, size);
342     adapter->buflist = adapter->buflist_end = g_slist_append (NULL, buf);
343     update_timestamps (adapter, buf);
344   } else {
345     /* Otherwise append to the end, and advance our end pointer */
346     GST_LOG_OBJECT (adapter, "pushing %p %" G_GSIZE_FORMAT " bytes at end, "
347         "size now %" G_GSIZE_FORMAT, buf, size, adapter->size);
348     adapter->buflist_end = g_slist_append (adapter->buflist_end, buf);
349     adapter->buflist_end = g_slist_next (adapter->buflist_end);
350   }
351 }
352
353 #if 0
354 /* Internal method only. Tries to merge buffers at the head of the queue
355  * to form a single larger buffer of size 'size'.
356  *
357  * Returns TRUE if it managed to merge anything.
358  */
359 static gboolean
360 gst_adapter_try_to_merge_up (GstAdapter * adapter, gsize size)
361 {
362   GstBuffer *cur, *head;
363   GSList *g;
364   gboolean ret = FALSE;
365   gsize hsize;
366
367   g = adapter->buflist;
368   if (g == NULL)
369     return FALSE;
370
371   head = g->data;
372
373   hsize = gst_buffer_get_size (head);
374
375   /* Remove skipped part from the buffer (otherwise the buffer might grow indefinitely) */
376   head = gst_buffer_make_writable (head);
377   gst_buffer_resize (head, adapter->skip, hsize - adapter->skip);
378   hsize -= adapter->skip;
379   adapter->skip = 0;
380   g->data = head;
381
382   g = g_slist_next (g);
383
384   while (g != NULL && hsize < size) {
385     cur = g->data;
386     /* Merge the head buffer and the next in line */
387     GST_LOG_OBJECT (adapter, "Merging buffers of size %" G_GSIZE_FORMAT " & %"
388         G_GSIZE_FORMAT " in search of target %" G_GSIZE_FORMAT,
389         hsize, gst_buffer_get_size (cur), size);
390
391     head = gst_buffer_append (head, cur);
392     hsize = gst_buffer_get_size (head);
393     ret = TRUE;
394
395     /* Delete the front list item, and store our new buffer in the 2nd list
396      * item */
397     adapter->buflist = g_slist_delete_link (adapter->buflist, adapter->buflist);
398     g->data = head;
399
400     /* invalidate scan position */
401     adapter->scan_offset = 0;
402     adapter->scan_entry = NULL;
403
404     g = g_slist_next (g);
405   }
406
407   return ret;
408 }
409 #endif
410
411 /**
412  * gst_adapter_map:
413  * @adapter: a #GstAdapter
414  * @size: the number of bytes to map/peek
415  *
416  * Gets the first @size bytes stored in the @adapter. The returned pointer is
417  * valid until the next function is called on the adapter.
418  *
419  * Note that setting the returned pointer as the data of a #GstBuffer is
420  * incorrect for general-purpose plugins. The reason is that if a downstream
421  * element stores the buffer so that it has access to it outside of the bounds
422  * of its chain function, the buffer will have an invalid data pointer after
423  * your element flushes the bytes. In that case you should use
424  * gst_adapter_take(), which returns a freshly-allocated buffer that you can set
425  * as #GstBuffer memory or the potentially more performant
426  * gst_adapter_take_buffer().
427  *
428  * Returns #NULL if @size bytes are not available.
429  *
430  * Returns: (transfer none) (array length=size) (element-type guint8):
431  *     a pointer to the first @size bytes of data, or NULL
432  */
433 gconstpointer
434 gst_adapter_map (GstAdapter * adapter, gsize size)
435 {
436   GstBuffer *cur;
437   gsize skip, csize;
438   gsize toreuse, tocopy;
439   guint8 *data;
440
441   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
442   g_return_val_if_fail (size > 0, NULL);
443
444   if (adapter->info.memory)
445     gst_adapter_unmap (adapter);
446
447   /* we don't have enough data, return NULL. This is unlikely
448    * as one usually does an _available() first instead of peeking a
449    * random size. */
450   if (G_UNLIKELY (size > adapter->size))
451     return NULL;
452
453   /* we have enough assembled data, return it */
454   if (adapter->assembled_len >= size)
455     return adapter->assembled_data;
456
457 #if 0
458   do {
459 #endif
460     cur = adapter->buflist->data;
461     skip = adapter->skip;
462
463     csize = gst_buffer_get_size (cur);
464     if (csize >= size + skip) {
465       if (!gst_buffer_map (cur, &adapter->info, GST_MAP_READ))
466         return FALSE;
467
468       return (guint8 *) adapter->info.data + skip;
469     }
470     /* We may be able to efficiently merge buffers in our pool to
471      * gather a big enough chunk to return it from the head buffer directly */
472 #if 0
473   } while (gst_adapter_try_to_merge_up (adapter, size));
474 #endif
475
476   /* see how much data we can reuse from the assembled memory and how much
477    * we need to copy */
478   toreuse = adapter->assembled_len;
479   tocopy = size - toreuse;
480
481   /* Gonna need to copy stuff out */
482   if (G_UNLIKELY (adapter->assembled_size < size)) {
483     adapter->assembled_size = (size / DEFAULT_SIZE + 1) * DEFAULT_SIZE;
484     GST_DEBUG_OBJECT (adapter, "resizing internal buffer to %" G_GSIZE_FORMAT,
485         adapter->assembled_size);
486     if (toreuse == 0) {
487       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "alloc new buffer");
488       /* no g_realloc to avoid a memcpy that is not desired here since we are
489        * not going to reuse any data here */
490       g_free (adapter->assembled_data);
491       adapter->assembled_data = g_malloc (adapter->assembled_size);
492     } else {
493       /* we are going to reuse all data, realloc then */
494       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "reusing %" G_GSIZE_FORMAT " bytes",
495           toreuse);
496       adapter->assembled_data =
497           g_realloc (adapter->assembled_data, adapter->assembled_size);
498     }
499   }
500   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy remaining %" G_GSIZE_FORMAT
501       " bytes from adapter", tocopy);
502   data = adapter->assembled_data;
503   copy_into_unchecked (adapter, data + toreuse, skip + toreuse, tocopy);
504   adapter->assembled_len = size;
505
506   return adapter->assembled_data;
507 }
508
509 /**
510  * gst_adapter_unmap:
511  * @adapter: a #GstAdapter
512  *
513  * Releases the memory obtained with the last gst_adapter_map().
514  */
515 void
516 gst_adapter_unmap (GstAdapter * adapter)
517 {
518   g_return_if_fail (GST_IS_ADAPTER (adapter));
519
520   if (adapter->info.memory) {
521     GstBuffer *cur = adapter->buflist->data;
522     GST_LOG_OBJECT (adapter, "unmap memory buffer %p", cur);
523     gst_buffer_unmap (cur, &adapter->info);
524     adapter->info.memory = NULL;
525   }
526 }
527
528 /**
529  * gst_adapter_copy:
530  * @adapter: a #GstAdapter
531  * @dest: (out caller-allocates) (array length=size) (element-type guint8):
532  *     the memory to copy into
533  * @offset: the bytes offset in the adapter to start from
534  * @size: the number of bytes to copy
535  *
536  * Copies @size bytes of data starting at @offset out of the buffers
537  * contained in @GstAdapter into an array @dest provided by the caller.
538  *
539  * The array @dest should be large enough to contain @size bytes.
540  * The user should check that the adapter has (@offset + @size) bytes
541  * available before calling this function.
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) (element-type guint8):
688  *     oven-fresh hot data, or #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_fast:
713  * @adapter:  a #GstAdapter
714  * @nbytes: the number of bytes to take
715  *
716  * Returns a #GstBuffer containing the first @nbytes of the @adapter.
717  * The returned bytes will be flushed from the adapter.  This function
718  * is potentially more performant than gst_adapter_take_buffer() since
719  * it can reuse the memory in pushed buffers by subbuffering or
720  * merging. Unlike gst_adapter_take_buffer(), the returned buffer may
721  * be composed of multiple non-contiguous #GstMemory objects, no
722  * copies are made.
723  *
724  * Note that no assumptions should be made as to whether certain buffer
725  * flags such as the DISCONT flag are set on the returned buffer, or not.
726  * The caller needs to explicitly set or unset flags that should be set or
727  * unset.
728  *
729  * This function can return buffer up to the return value of
730  * gst_adapter_available() without making copies if possible.
731  *
732  * Caller owns a reference to the returned buffer. gst_buffer_unref() after
733  * usage.
734  *
735  * Free-function: gst_buffer_unref
736  *
737  * Returns: (transfer full): a #GstBuffer containing the first @nbytes of
738  *     the adapter, or #NULL if @nbytes bytes are not available.
739  *     gst_buffer_unref() when no longer needed.
740  *
741  * Since: 1.2
742  */
743
744 GstBuffer *
745 gst_adapter_take_buffer_fast (GstAdapter * adapter, gsize nbytes)
746 {
747   GstBuffer *buffer = NULL;
748   GstBuffer *cur;
749   GSList *item;
750   gsize skip;
751   gsize left = nbytes;
752
753   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
754   g_return_val_if_fail (nbytes > 0, NULL);
755
756   GST_LOG_OBJECT (adapter, "taking buffer of %" G_GSIZE_FORMAT " bytes",
757       nbytes);
758
759   /* we don't have enough data, return NULL. This is unlikely
760    * as one usually does an _available() first instead of grabbing a
761    * random size. */
762   if (G_UNLIKELY (nbytes > adapter->size))
763     return NULL;
764
765   skip = adapter->skip;
766   cur = adapter->buflist->data;
767
768   if (skip == 0 && gst_buffer_get_size (cur) == nbytes) {
769     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
770         " as head buffer", nbytes);
771     buffer = gst_buffer_ref (cur);
772     goto done;
773   }
774
775   for (item = adapter->buflist; item && left > 0; item = item->next) {
776     gsize size;
777
778     cur = item->data;
779     size = MIN (gst_buffer_get_size (cur) - skip, left);
780
781     GST_LOG_OBJECT (adapter, "appending %" G_GSIZE_FORMAT " bytes"
782         " via region copy", size);
783     if (buffer)
784       gst_buffer_copy_into (buffer, cur, GST_BUFFER_COPY_MEMORY, skip, size);
785     else
786       buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, size);
787     skip = 0;
788     left -= size;
789   }
790
791 done:
792   gst_adapter_flush_unchecked (adapter, nbytes);
793
794   return buffer;
795 }
796
797 /**
798  * gst_adapter_take_buffer:
799  * @adapter: a #GstAdapter
800  * @nbytes: the number of bytes to take
801  *
802  * Returns a #GstBuffer containing the first @nbytes bytes of the
803  * @adapter. The returned bytes will be flushed from the adapter.
804  * This function is potentially more performant than
805  * gst_adapter_take() since it can reuse the memory in pushed buffers
806  * by subbuffering or merging. This function will always return a
807  * buffer with a single memory region.
808  *
809  * Note that no assumptions should be made as to whether certain buffer
810  * flags such as the DISCONT flag are set on the returned buffer, or not.
811  * The caller needs to explicitly set or unset flags that should be set or
812  * unset.
813  *
814  * Caller owns a reference to the returned buffer. gst_buffer_unref() after
815  * usage.
816  *
817  * Free-function: gst_buffer_unref
818  *
819  * Returns: (transfer full): a #GstBuffer containing the first @nbytes of
820  *     the adapter, or #NULL if @nbytes bytes are not available.
821  *     gst_buffer_unref() when no longer needed.
822  */
823 GstBuffer *
824 gst_adapter_take_buffer (GstAdapter * adapter, gsize nbytes)
825 {
826   GstBuffer *buffer;
827   GstBuffer *cur;
828   gsize hsize, skip;
829   guint8 *data;
830
831   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
832   g_return_val_if_fail (nbytes > 0, NULL);
833
834   GST_LOG_OBJECT (adapter, "taking buffer of %" G_GSIZE_FORMAT " bytes",
835       nbytes);
836
837   /* we don't have enough data, return NULL. This is unlikely
838    * as one usually does an _available() first instead of grabbing a
839    * random size. */
840   if (G_UNLIKELY (nbytes > adapter->size))
841     return NULL;
842
843   cur = adapter->buflist->data;
844   skip = adapter->skip;
845   hsize = gst_buffer_get_size (cur);
846
847   /* our head buffer has enough data left, return it */
848   if (skip == 0 && hsize == nbytes) {
849     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
850         " as head buffer", nbytes);
851     buffer = gst_buffer_ref (cur);
852     goto done;
853   } else if (hsize >= nbytes + skip) {
854     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
855         " via region copy", nbytes);
856     buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
857     goto done;
858   }
859 #if 0
860   if (gst_adapter_try_to_merge_up (adapter, nbytes)) {
861     /* Merged something, let's try again for sub-buffering */
862     cur = adapter->buflist->data;
863     skip = adapter->skip;
864     if (gst_buffer_get_size (cur) >= nbytes + skip) {
865       GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
866           " via sub-buffer", nbytes);
867       buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
868       goto done;
869     }
870   }
871 #endif
872
873   data = gst_adapter_take_internal (adapter, nbytes);
874
875   buffer = gst_buffer_new_wrapped (data, nbytes);
876
877 done:
878   gst_adapter_flush_unchecked (adapter, nbytes);
879
880   return buffer;
881 }
882
883 /**
884  * gst_adapter_take_list:
885  * @adapter: a #GstAdapter
886  * @nbytes: the number of bytes to take
887  *
888  * Returns a #GList of buffers containing the first @nbytes bytes of the
889  * @adapter. The returned bytes will be flushed from the adapter.
890  * When the caller can deal with individual buffers, this function is more
891  * performant because no memory should be copied.
892  *
893  * Caller owns returned list and contained buffers. gst_buffer_unref() each
894  * buffer in the list before freeing the list after usage.
895  *
896  * Returns: (element-type Gst.Buffer) (transfer full): a #GList of buffers
897  *     containing the first @nbytes of the adapter, or #NULL if @nbytes bytes
898  *     are not available
899  */
900 GList *
901 gst_adapter_take_list (GstAdapter * adapter, gsize nbytes)
902 {
903   GQueue queue = G_QUEUE_INIT;
904   GstBuffer *cur;
905   gsize hsize, skip;
906
907   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
908   g_return_val_if_fail (nbytes <= adapter->size, NULL);
909
910   GST_LOG_OBJECT (adapter, "taking %" G_GSIZE_FORMAT " bytes", nbytes);
911
912   while (nbytes > 0) {
913     cur = adapter->buflist->data;
914     skip = adapter->skip;
915     hsize = MIN (nbytes, gst_buffer_get_size (cur) - skip);
916
917     cur = gst_adapter_take_buffer (adapter, hsize);
918
919     g_queue_push_tail (&queue, cur);
920
921     nbytes -= hsize;
922   }
923   return queue.head;
924 }
925
926 /**
927  * gst_adapter_available:
928  * @adapter: a #GstAdapter
929  *
930  * Gets the maximum amount of bytes available, that is it returns the maximum
931  * value that can be supplied to gst_adapter_map() without that function
932  * returning NULL.
933  *
934  * Returns: number of bytes available in @adapter
935  */
936 gsize
937 gst_adapter_available (GstAdapter * adapter)
938 {
939   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
940
941   return adapter->size;
942 }
943
944 /**
945  * gst_adapter_available_fast:
946  * @adapter: a #GstAdapter
947  *
948  * Gets the maximum number of bytes that are immediately available without
949  * requiring any expensive operations (like copying the data into a
950  * temporary buffer).
951  *
952  * Returns: number of bytes that are available in @adapter without expensive
953  * operations
954  */
955 gsize
956 gst_adapter_available_fast (GstAdapter * adapter)
957 {
958   GstBuffer *cur;
959   gsize size;
960   GSList *g;
961
962   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
963
964   /* no data */
965   if (adapter->size == 0)
966     return 0;
967
968   /* some stuff we already assembled */
969   if (adapter->assembled_len)
970     return adapter->assembled_len;
971
972   /* take the first non-zero buffer */
973   g = adapter->buflist;
974   while (TRUE) {
975     cur = g->data;
976     size = gst_buffer_get_size (cur);
977     if (size != 0)
978       break;
979     g = g_slist_next (g);
980   }
981
982   /* we can quickly get the (remaining) data of the first buffer */
983   return size - adapter->skip;
984 }
985
986 /**
987  * gst_adapter_prev_pts:
988  * @adapter: a #GstAdapter
989  * @distance: (out) (allow-none): pointer to location for distance, or NULL
990  *
991  * Get the pts that was before the current byte in the adapter. When
992  * @distance is given, the amount of bytes between the pts and the current
993  * position is returned.
994  *
995  * The pts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
996  * the adapter is first created or when it is cleared. This also means that before
997  * the first byte with a pts is removed from the adapter, the pts
998  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
999  *
1000  * Returns: The previously seen pts.
1001  */
1002 GstClockTime
1003 gst_adapter_prev_pts (GstAdapter * adapter, guint64 * distance)
1004 {
1005   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1006
1007   if (distance)
1008     *distance = adapter->pts_distance;
1009
1010   return adapter->pts;
1011 }
1012
1013 /**
1014  * gst_adapter_prev_dts:
1015  * @adapter: a #GstAdapter
1016  * @distance: (out) (allow-none): pointer to location for distance, or NULL
1017  *
1018  * Get the dts that was before the current byte in the adapter. When
1019  * @distance is given, the amount of bytes between the dts and the current
1020  * position is returned.
1021  *
1022  * The dts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
1023  * the adapter is first created or when it is cleared. This also means that before
1024  * the first byte with a dts is removed from the adapter, the dts
1025  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
1026  *
1027  * Returns: The previously seen dts.
1028  */
1029 GstClockTime
1030 gst_adapter_prev_dts (GstAdapter * adapter, guint64 * distance)
1031 {
1032   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1033
1034   if (distance)
1035     *distance = adapter->dts_distance;
1036
1037   return adapter->dts;
1038 }
1039
1040 /**
1041  * gst_adapter_prev_pts_at_offset:
1042  * @adapter: a #GstAdapter
1043  * @offset: the offset in the adapter at which to get timestamp
1044  * @distance: (out) (allow-none): pointer to location for distance, or NULL
1045  *
1046  * Get the pts that was before the byte at offset @offset in the adapter. When
1047  * @distance is given, the amount of bytes between the pts and the current
1048  * position is returned.
1049  *
1050  * The pts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
1051  * the adapter is first created or when it is cleared. This also means that before
1052  * the first byte with a pts is removed from the adapter, the pts
1053  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
1054  *
1055  * Since: 1.2
1056  * Returns: The previously seen pts at given offset.
1057  */
1058 GstClockTime
1059 gst_adapter_prev_pts_at_offset (GstAdapter * adapter, gsize offset,
1060     guint64 * distance)
1061 {
1062   GstBuffer *cur;
1063   GSList *g;
1064   gsize read_offset = 0;
1065   GstClockTime pts = adapter->pts;
1066
1067   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1068   g_return_val_if_fail (offset >= 0, GST_CLOCK_TIME_NONE);
1069
1070   g = adapter->buflist;
1071
1072   while (g && read_offset < offset + adapter->skip) {
1073     cur = g->data;
1074
1075     read_offset += gst_buffer_get_size (cur);
1076     if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_PTS (cur))) {
1077       pts = GST_BUFFER_PTS (cur);
1078     }
1079
1080     g = g_slist_next (g);
1081   }
1082
1083   if (distance)
1084     *distance = adapter->dts_distance + offset;
1085
1086   return pts;
1087 }
1088
1089 /**
1090  * gst_adapter_prev_dts_at_offset:
1091  * @adapter: a #GstAdapter
1092  * @offset: the offset in the adapter at which to get timestamp
1093  * @distance: (out) (allow-none): pointer to location for distance, or NULL
1094  *
1095  * Get the dts that was before the byte at offset @offset in the adapter. When
1096  * @distance is given, the amount of bytes between the dts and the current
1097  * position is returned.
1098  *
1099  * The dts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
1100  * the adapter is first created or when it is cleared. This also means that before
1101  * the first byte with a dts is removed from the adapter, the dts
1102  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
1103  *
1104  * Since: 1.2
1105  * Returns: The previously seen dts at given offset.
1106  */
1107 GstClockTime
1108 gst_adapter_prev_dts_at_offset (GstAdapter * adapter, gsize offset,
1109     guint64 * distance)
1110 {
1111   GstBuffer *cur;
1112   GSList *g;
1113   gsize read_offset = 0;
1114   GstClockTime dts = adapter->dts;
1115
1116   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1117   g_return_val_if_fail (offset >= 0, GST_CLOCK_TIME_NONE);
1118
1119   g = adapter->buflist;
1120
1121   while (g && read_offset < offset + adapter->skip) {
1122     cur = g->data;
1123
1124     read_offset += gst_buffer_get_size (cur);
1125     if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (cur))) {
1126       dts = GST_BUFFER_DTS (cur);
1127     }
1128
1129     g = g_slist_next (g);
1130   }
1131
1132   if (distance)
1133     *distance = adapter->dts_distance + offset;
1134
1135   return dts;
1136 }
1137
1138 /**
1139  * gst_adapter_masked_scan_uint32_peek:
1140  * @adapter: a #GstAdapter
1141  * @mask: mask to apply to data before matching against @pattern
1142  * @pattern: pattern to match (after mask is applied)
1143  * @offset: offset into the adapter data from which to start scanning, returns
1144  *          the last scanned position.
1145  * @size: number of bytes to scan from offset
1146  * @value: pointer to uint32 to return matching data
1147  *
1148  * Scan for pattern @pattern with applied mask @mask in the adapter data,
1149  * starting from offset @offset.  If a match is found, the value that matched
1150  * is returned through @value, otherwise @value is left untouched.
1151  *
1152  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
1153  * of endianness.  All four bytes of the pattern must be present in the
1154  * adapter for it to match, even if the first or last bytes are masked out.
1155  *
1156  * It is an error to call this function without making sure that there is
1157  * enough data (offset+size bytes) in the adapter.
1158  *
1159  * Returns: offset of the first match, or -1 if no match was found.
1160  */
1161 gssize
1162 gst_adapter_masked_scan_uint32_peek (GstAdapter * adapter, guint32 mask,
1163     guint32 pattern, gsize offset, gsize size, guint32 * value)
1164 {
1165   GSList *g;
1166   gsize skip, bsize, i;
1167   guint32 state;
1168   GstMapInfo info;
1169   guint8 *bdata;
1170   GstBuffer *buf;
1171
1172   g_return_val_if_fail (size > 0, -1);
1173   g_return_val_if_fail (offset + size <= adapter->size, -1);
1174   g_return_val_if_fail (((~mask) & pattern) == 0, -1);
1175
1176   /* we can't find the pattern with less than 4 bytes */
1177   if (G_UNLIKELY (size < 4))
1178     return -1;
1179
1180   skip = offset + adapter->skip;
1181
1182   /* first step, do skipping and position on the first buffer */
1183   /* optimistically assume scanning continues sequentially */
1184   if (adapter->scan_entry && (adapter->scan_offset <= skip)) {
1185     g = adapter->scan_entry;
1186     skip -= adapter->scan_offset;
1187   } else {
1188     g = adapter->buflist;
1189     adapter->scan_offset = 0;
1190     adapter->scan_entry = NULL;
1191   }
1192   buf = g->data;
1193   bsize = gst_buffer_get_size (buf);
1194   while (G_UNLIKELY (skip >= bsize)) {
1195     skip -= bsize;
1196     g = g_slist_next (g);
1197     adapter->scan_offset += bsize;
1198     adapter->scan_entry = g;
1199     buf = g->data;
1200     bsize = gst_buffer_get_size (buf);
1201   }
1202   /* get the data now */
1203   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
1204     return -1;
1205
1206   bdata = (guint8 *) info.data + skip;
1207   bsize = info.size - skip;
1208   skip = 0;
1209
1210   /* set the state to something that does not match */
1211   state = ~pattern;
1212
1213   /* now find data */
1214   do {
1215     bsize = MIN (bsize, size);
1216     for (i = 0; i < bsize; i++) {
1217       state = ((state << 8) | bdata[i]);
1218       if (G_UNLIKELY ((state & mask) == pattern)) {
1219         /* we have a match but we need to have skipped at
1220          * least 4 bytes to fill the state. */
1221         if (G_LIKELY (skip + i >= 3)) {
1222           if (G_LIKELY (value))
1223             *value = state;
1224           gst_buffer_unmap (buf, &info);
1225           return offset + skip + i - 3;
1226         }
1227       }
1228     }
1229     size -= bsize;
1230     if (size == 0)
1231       break;
1232
1233     /* nothing found yet, go to next buffer */
1234     skip += bsize;
1235     g = g_slist_next (g);
1236     adapter->scan_offset += info.size;
1237     adapter->scan_entry = g;
1238     gst_buffer_unmap (buf, &info);
1239     buf = g->data;
1240
1241     if (!gst_buffer_map (buf, &info, GST_MAP_READ))
1242       return -1;
1243
1244     bsize = info.size;
1245     bdata = info.data;
1246   } while (TRUE);
1247
1248   gst_buffer_unmap (buf, &info);
1249
1250   /* nothing found */
1251   return -1;
1252 }
1253
1254 /**
1255  * gst_adapter_masked_scan_uint32:
1256  * @adapter: a #GstAdapter
1257  * @mask: mask to apply to data before matching against @pattern
1258  * @pattern: pattern to match (after mask is applied)
1259  * @offset: offset into the adapter data from which to start scanning, returns
1260  *          the last scanned position.
1261  * @size: number of bytes to scan from offset
1262  *
1263  * Scan for pattern @pattern with applied mask @mask in the adapter data,
1264  * starting from offset @offset.
1265  *
1266  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
1267  * of endianness.  All four bytes of the pattern must be present in the
1268  * adapter for it to match, even if the first or last bytes are masked out.
1269  *
1270  * It is an error to call this function without making sure that there is
1271  * enough data (offset+size bytes) in the adapter.
1272  *
1273  * This function calls gst_adapter_masked_scan_uint32_peek() passing NULL
1274  * for value.
1275  *
1276  * Returns: offset of the first match, or -1 if no match was found.
1277  *
1278  * Example:
1279  * <programlisting>
1280  * // Assume the adapter contains 0x00 0x01 0x02 ... 0xfe 0xff
1281  *
1282  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 0, 256);
1283  * // -> returns 0
1284  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 1, 255);
1285  * // -> returns -1
1286  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x01020304, 1, 255);
1287  * // -> returns 1
1288  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0001, 0, 256);
1289  * // -> returns -1
1290  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0203, 0, 256);
1291  * // -> returns 0
1292  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 256);
1293  * // -> returns 2
1294  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 4);
1295  * // -> returns -1
1296  * </programlisting>
1297  */
1298 gssize
1299 gst_adapter_masked_scan_uint32 (GstAdapter * adapter, guint32 mask,
1300     guint32 pattern, gsize offset, gsize size)
1301 {
1302   return gst_adapter_masked_scan_uint32_peek (adapter, mask, pattern, offset,
1303       size, NULL);
1304 }