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