adapter: Add get variants of the buffer based take functions
[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
114 #include <gst/gst_private.h>
115 #include "gstadapter.h"
116 #include <string.h>
117
118 /* default size for the assembled data buffer */
119 #define DEFAULT_SIZE 4096
120
121 static void gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush);
122
123 GST_DEBUG_CATEGORY_STATIC (gst_adapter_debug);
124 #define GST_CAT_DEFAULT gst_adapter_debug
125
126 struct _GstAdapter
127 {
128   GObject object;
129
130   /*< private > */
131   GSList *buflist;
132   GSList *buflist_end;
133   gsize size;
134   gsize skip;
135   guint count;
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->count = 0;
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   ++adapter->count;
352 }
353
354 #if 0
355 /* Internal method only. Tries to merge buffers at the head of the queue
356  * to form a single larger buffer of size 'size'.
357  *
358  * Returns %TRUE if it managed to merge anything.
359  */
360 static gboolean
361 gst_adapter_try_to_merge_up (GstAdapter * adapter, gsize size)
362 {
363   GstBuffer *cur, *head;
364   GSList *g;
365   gboolean ret = FALSE;
366   gsize hsize;
367
368   g = adapter->buflist;
369   if (g == NULL)
370     return FALSE;
371
372   head = g->data;
373
374   hsize = gst_buffer_get_size (head);
375
376   /* Remove skipped part from the buffer (otherwise the buffer might grow indefinitely) */
377   head = gst_buffer_make_writable (head);
378   gst_buffer_resize (head, adapter->skip, hsize - adapter->skip);
379   hsize -= adapter->skip;
380   adapter->skip = 0;
381   g->data = head;
382
383   g = g_slist_next (g);
384
385   while (g != NULL && hsize < size) {
386     cur = g->data;
387     /* Merge the head buffer and the next in line */
388     GST_LOG_OBJECT (adapter, "Merging buffers of size %" G_GSIZE_FORMAT " & %"
389         G_GSIZE_FORMAT " in search of target %" G_GSIZE_FORMAT,
390         hsize, gst_buffer_get_size (cur), size);
391
392     head = gst_buffer_append (head, cur);
393     hsize = gst_buffer_get_size (head);
394     ret = TRUE;
395
396     /* Delete the front list item, and store our new buffer in the 2nd list
397      * item */
398     adapter->buflist = g_slist_delete_link (adapter->buflist, adapter->buflist);
399     g->data = head;
400
401     /* invalidate scan position */
402     adapter->scan_offset = 0;
403     adapter->scan_entry = NULL;
404
405     g = g_slist_next (g);
406   }
407
408   return ret;
409 }
410 #endif
411
412 /**
413  * gst_adapter_map:
414  * @adapter: a #GstAdapter
415  * @size: the number of bytes to map/peek
416  *
417  * Gets the first @size bytes stored in the @adapter. The returned pointer is
418  * valid until the next function is called on the adapter.
419  *
420  * Note that setting the returned pointer as the data of a #GstBuffer is
421  * incorrect for general-purpose plugins. The reason is that if a downstream
422  * element stores the buffer so that it has access to it outside of the bounds
423  * of its chain function, the buffer will have an invalid data pointer after
424  * your element flushes the bytes. In that case you should use
425  * gst_adapter_take(), which returns a freshly-allocated buffer that you can set
426  * as #GstBuffer memory or the potentially more performant
427  * gst_adapter_take_buffer().
428  *
429  * Returns %NULL if @size bytes are not available.
430  *
431  * Returns: (transfer none) (array length=size) (element-type guint8) (nullable):
432  *     a pointer to the first @size bytes of data, or %NULL
433  */
434 gconstpointer
435 gst_adapter_map (GstAdapter * adapter, gsize size)
436 {
437   GstBuffer *cur;
438   gsize skip, csize;
439   gsize toreuse, tocopy;
440   guint8 *data;
441
442   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
443   g_return_val_if_fail (size > 0, NULL);
444
445   if (adapter->info.memory)
446     gst_adapter_unmap (adapter);
447
448   /* we don't have enough data, return NULL. This is unlikely
449    * as one usually does an _available() first instead of peeking a
450    * random size. */
451   if (G_UNLIKELY (size > adapter->size))
452     return NULL;
453
454   /* we have enough assembled data, return it */
455   if (adapter->assembled_len >= size)
456     return adapter->assembled_data;
457
458 #if 0
459   do {
460 #endif
461     cur = adapter->buflist->data;
462     skip = adapter->skip;
463
464     csize = gst_buffer_get_size (cur);
465     if (csize >= size + skip) {
466       if (!gst_buffer_map (cur, &adapter->info, GST_MAP_READ))
467         return FALSE;
468
469       return (guint8 *) adapter->info.data + skip;
470     }
471     /* We may be able to efficiently merge buffers in our pool to
472      * gather a big enough chunk to return it from the head buffer directly */
473 #if 0
474   } while (gst_adapter_try_to_merge_up (adapter, size));
475 #endif
476
477   /* see how much data we can reuse from the assembled memory and how much
478    * we need to copy */
479   toreuse = adapter->assembled_len;
480   tocopy = size - toreuse;
481
482   /* Gonna need to copy stuff out */
483   if (G_UNLIKELY (adapter->assembled_size < size)) {
484     adapter->assembled_size = (size / DEFAULT_SIZE + 1) * DEFAULT_SIZE;
485     GST_DEBUG_OBJECT (adapter, "resizing internal buffer to %" G_GSIZE_FORMAT,
486         adapter->assembled_size);
487     if (toreuse == 0) {
488       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "alloc new buffer");
489       /* no g_realloc to avoid a memcpy that is not desired here since we are
490        * not going to reuse any data here */
491       g_free (adapter->assembled_data);
492       adapter->assembled_data = g_malloc (adapter->assembled_size);
493     } else {
494       /* we are going to reuse all data, realloc then */
495       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "reusing %" G_GSIZE_FORMAT " bytes",
496           toreuse);
497       adapter->assembled_data =
498           g_realloc (adapter->assembled_data, adapter->assembled_size);
499     }
500   }
501   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy remaining %" G_GSIZE_FORMAT
502       " bytes from adapter", tocopy);
503   data = adapter->assembled_data;
504   copy_into_unchecked (adapter, data + toreuse, skip + toreuse, tocopy);
505   adapter->assembled_len = size;
506
507   return adapter->assembled_data;
508 }
509
510 /**
511  * gst_adapter_unmap:
512  * @adapter: a #GstAdapter
513  *
514  * Releases the memory obtained with the last gst_adapter_map().
515  */
516 void
517 gst_adapter_unmap (GstAdapter * adapter)
518 {
519   g_return_if_fail (GST_IS_ADAPTER (adapter));
520
521   if (adapter->info.memory) {
522     GstBuffer *cur = adapter->buflist->data;
523     GST_LOG_OBJECT (adapter, "unmap memory buffer %p", cur);
524     gst_buffer_unmap (cur, &adapter->info);
525     adapter->info.memory = NULL;
526   }
527 }
528
529 /**
530  * gst_adapter_copy: (skip)
531  * @adapter: a #GstAdapter
532  * @dest: (out caller-allocates) (array length=size) (element-type guint8):
533  *     the memory to copy into
534  * @offset: the bytes offset in the adapter to start from
535  * @size: the number of bytes to copy
536  *
537  * Copies @size bytes of data starting at @offset out of the buffers
538  * contained in #GstAdapter into an array @dest provided by the caller.
539  *
540  * The array @dest should be large enough to contain @size bytes.
541  * The user should check that the adapter has (@offset + @size) bytes
542  * available before calling this function.
543  */
544 void
545 gst_adapter_copy (GstAdapter * adapter, gpointer dest, gsize offset, gsize size)
546 {
547   g_return_if_fail (GST_IS_ADAPTER (adapter));
548   g_return_if_fail (size > 0);
549   g_return_if_fail (offset + size <= adapter->size);
550
551   copy_into_unchecked (adapter, dest, offset + adapter->skip, size);
552 }
553
554 /**
555  * gst_adapter_copy_bytes: (rename-to gst_adapter_copy)
556  * @adapter: a #GstAdapter
557  * @offset: the bytes offset in the adapter to start from
558  * @size: the number of bytes to copy
559  *
560  * Similar to gst_adapter_copy, but more suitable for language bindings. @size
561  * bytes of data starting at @offset will be copied out of the buffers contained
562  * in @adapter and into a new #GBytes structure which is returned. Depending on
563  * the value of the @size argument an empty #GBytes structure may be returned.
564  *
565  * Returns: (transfer full): A new #GBytes structure containing the copied data.
566  *
567  * Since: 1.4
568  */
569 GBytes *
570 gst_adapter_copy_bytes (GstAdapter * adapter, gsize offset, gsize size)
571 {
572   gpointer data;
573   data = g_malloc (size);
574   gst_adapter_copy (adapter, data, offset, size);
575   return g_bytes_new_take (data, size);
576 }
577
578 /*Flushes the first @flush bytes in the @adapter*/
579 static void
580 gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush)
581 {
582   GstBuffer *cur;
583   gsize size;
584   GSList *g;
585
586   GST_LOG_OBJECT (adapter, "flushing %" G_GSIZE_FORMAT " bytes", flush);
587
588   if (adapter->info.memory)
589     gst_adapter_unmap (adapter);
590
591   /* clear state */
592   adapter->size -= flush;
593   adapter->assembled_len = 0;
594
595   /* take skip into account */
596   flush += adapter->skip;
597   /* distance is always at least the amount of skipped bytes */
598   adapter->pts_distance -= adapter->skip;
599   adapter->dts_distance -= adapter->skip;
600
601   g = adapter->buflist;
602   cur = g->data;
603   size = gst_buffer_get_size (cur);
604   while (flush >= size) {
605     /* can skip whole buffer */
606     GST_LOG_OBJECT (adapter, "flushing out head buffer");
607     adapter->pts_distance += size;
608     adapter->dts_distance += size;
609     flush -= size;
610
611     gst_buffer_unref (cur);
612     g = g_slist_delete_link (g, g);
613     --adapter->count;
614
615     if (G_UNLIKELY (g == NULL)) {
616       GST_LOG_OBJECT (adapter, "adapter empty now");
617       adapter->buflist_end = NULL;
618       break;
619     }
620     /* there is a new head buffer, update the timestamps */
621     cur = g->data;
622     update_timestamps (adapter, cur);
623     size = gst_buffer_get_size (cur);
624   }
625   adapter->buflist = g;
626   /* account for the remaining bytes */
627   adapter->skip = flush;
628   adapter->pts_distance += flush;
629   adapter->dts_distance += flush;
630   /* invalidate scan position */
631   adapter->scan_offset = 0;
632   adapter->scan_entry = NULL;
633 }
634
635 /**
636  * gst_adapter_flush:
637  * @adapter: a #GstAdapter
638  * @flush: the number of bytes to flush
639  *
640  * Flushes the first @flush bytes in the @adapter. The caller must ensure that
641  * at least this many bytes are available.
642  *
643  * See also: gst_adapter_map(), gst_adapter_unmap()
644  */
645 void
646 gst_adapter_flush (GstAdapter * adapter, gsize flush)
647 {
648   g_return_if_fail (GST_IS_ADAPTER (adapter));
649   g_return_if_fail (flush <= adapter->size);
650
651   /* flushing out 0 bytes will do nothing */
652   if (G_UNLIKELY (flush == 0))
653     return;
654
655   gst_adapter_flush_unchecked (adapter, flush);
656 }
657
658 /* internal function, nbytes should be flushed if needed after calling this function */
659 static guint8 *
660 gst_adapter_get_internal (GstAdapter * adapter, gsize nbytes)
661 {
662   guint8 *data;
663   gsize toreuse, tocopy;
664
665   /* see how much data we can reuse from the assembled memory and how much
666    * we need to copy */
667   toreuse = MIN (nbytes, adapter->assembled_len);
668   tocopy = nbytes - toreuse;
669
670   /* find memory to return */
671   if (adapter->assembled_size >= nbytes && toreuse > 0) {
672     /* we reuse already allocated memory but only when we're going to reuse
673      * something from it because else we are worse than the malloc and copy
674      * case below */
675     GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes of assembled"
676         " data", toreuse);
677     /* we have enough free space in the assembled array */
678     data = adapter->assembled_data;
679     /* flush after this function should set the assembled_size to 0 */
680     adapter->assembled_data = g_malloc (adapter->assembled_size);
681   } else {
682     GST_LOG_OBJECT (adapter, "allocating %" G_GSIZE_FORMAT " bytes", nbytes);
683     /* not enough bytes in the assembled array, just allocate new space */
684     data = g_malloc (nbytes);
685     /* reuse what we can from the already assembled data */
686     if (toreuse) {
687       GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes", toreuse);
688       GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, adapter,
689           "memcpy %" G_GSIZE_FORMAT " bytes", toreuse);
690       memcpy (data, adapter->assembled_data, toreuse);
691     }
692   }
693   if (tocopy) {
694     /* copy the remaining data */
695     copy_into_unchecked (adapter, toreuse + data, toreuse + adapter->skip,
696         tocopy);
697   }
698   return data;
699 }
700
701 /**
702  * gst_adapter_take:
703  * @adapter: a #GstAdapter
704  * @nbytes: the number of bytes to take
705  *
706  * Returns a freshly allocated buffer containing the first @nbytes bytes of the
707  * @adapter. The returned bytes will be flushed from the adapter.
708  *
709  * Caller owns returned value. g_free after usage.
710  *
711  * Free-function: g_free
712  *
713  * Returns: (transfer full) (array length=nbytes) (element-type guint8) (nullable):
714  *     oven-fresh hot data, or %NULL if @nbytes bytes are not available
715  */
716 gpointer
717 gst_adapter_take (GstAdapter * adapter, gsize nbytes)
718 {
719   gpointer data;
720
721   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
722   g_return_val_if_fail (nbytes > 0, NULL);
723
724   /* we don't have enough data, return NULL. This is unlikely
725    * as one usually does an _available() first instead of peeking a
726    * random size. */
727   if (G_UNLIKELY (nbytes > adapter->size))
728     return NULL;
729
730   data = gst_adapter_get_internal (adapter, nbytes);
731
732   gst_adapter_flush_unchecked (adapter, nbytes);
733
734   return data;
735 }
736
737 /**
738  * gst_adapter_get_buffer_fast:
739  * @adapter:  a #GstAdapter
740  * @nbytes: the number of bytes to get
741  *
742  * Returns a #GstBuffer containing the first @nbytes of the @adapter, but
743  * does not flush them from the adapter. See gst_adapter_take_buffer_fast()
744  * for details.
745  *
746  * Caller owns a reference to the returned buffer. gst_buffer_unref() after
747  * usage.
748  *
749  * Free-function: gst_buffer_unref
750  *
751  * Returns: (transfer full) (nullable): a #GstBuffer containing the first
752  *     @nbytes of the adapter, or %NULL if @nbytes bytes are not available.
753  *     gst_buffer_unref() when no longer needed.
754  *
755  * Since: 1.6
756  */
757 GstBuffer *
758 gst_adapter_get_buffer_fast (GstAdapter * adapter, gsize nbytes)
759 {
760   GstBuffer *buffer = NULL;
761   GstBuffer *cur;
762   GSList *item;
763   gsize skip;
764   gsize left = nbytes;
765
766   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
767   g_return_val_if_fail (nbytes > 0, NULL);
768
769   GST_LOG_OBJECT (adapter, "getting buffer of %" G_GSIZE_FORMAT " bytes",
770       nbytes);
771
772   /* we don't have enough data, return NULL. This is unlikely
773    * as one usually does an _available() first instead of grabbing a
774    * random size. */
775   if (G_UNLIKELY (nbytes > adapter->size))
776     return NULL;
777
778   skip = adapter->skip;
779   cur = adapter->buflist->data;
780
781   if (skip == 0 && gst_buffer_get_size (cur) == nbytes) {
782     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
783         " as head buffer", nbytes);
784     buffer = gst_buffer_ref (cur);
785     goto done;
786   }
787
788   for (item = adapter->buflist; item && left > 0; item = item->next) {
789     gsize size, cur_size;
790
791     cur = item->data;
792     cur_size = gst_buffer_get_size (cur);
793     size = MIN (cur_size - skip, left);
794
795     GST_LOG_OBJECT (adapter, "appending %" G_GSIZE_FORMAT " bytes"
796         " via region copy", size);
797     if (buffer)
798       gst_buffer_copy_into (buffer, cur, GST_BUFFER_COPY_MEMORY, skip, size);
799     else
800       buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, size);
801     skip = 0;
802     left -= size;
803   }
804
805 done:
806
807   return buffer;
808 }
809
810 /**
811  * gst_adapter_take_buffer_fast:
812  * @adapter:  a #GstAdapter
813  * @nbytes: the number of bytes to take
814  *
815  * Returns a #GstBuffer containing the first @nbytes of the @adapter.
816  * The returned bytes will be flushed from the adapter.  This function
817  * is potentially more performant than gst_adapter_take_buffer() since
818  * it can reuse the memory in pushed buffers by subbuffering or
819  * merging. Unlike gst_adapter_take_buffer(), the returned buffer may
820  * be composed of multiple non-contiguous #GstMemory objects, no
821  * copies are made.
822  *
823  * Note that no assumptions should be made as to whether certain buffer
824  * flags such as the DISCONT flag are set on the returned buffer, or not.
825  * The caller needs to explicitly set or unset flags that should be set or
826  * unset.
827  *
828  * This will also copy over all GstMeta of the input buffers except
829  * for meta with the %GST_META_FLAG_POOLED flag or with the "memory" tag.
830  *
831  * This function can return buffer up to the return value of
832  * gst_adapter_available() without making copies if possible.
833  *
834  * Caller owns a reference to the returned buffer. gst_buffer_unref() after
835  * usage.
836  *
837  * Free-function: gst_buffer_unref
838  *
839  * Returns: (transfer full) (nullable): a #GstBuffer containing the first
840  *     @nbytes of the adapter, or %NULL if @nbytes bytes are not available.
841  *     gst_buffer_unref() when no longer needed.
842  *
843  * Since: 1.2
844  */
845 GstBuffer *
846 gst_adapter_take_buffer_fast (GstAdapter * adapter, gsize nbytes)
847 {
848   GstBuffer *buffer;
849
850   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
851   g_return_val_if_fail (nbytes > 0, NULL);
852
853   buffer = gst_adapter_get_buffer_fast (adapter, nbytes);
854   if (buffer)
855     gst_adapter_flush_unchecked (adapter, nbytes);
856
857   return buffer;
858 }
859
860 static gboolean
861 foreach_metadata (GstBuffer * inbuf, GstMeta ** meta, gpointer user_data)
862 {
863   GstBuffer *outbuf = user_data;
864   const GstMetaInfo *info = (*meta)->info;
865   gboolean do_copy = FALSE;
866
867   if (GST_META_FLAG_IS_SET (*meta, GST_META_FLAG_POOLED)) {
868     /* never call the transform_meta with pool private metadata */
869     GST_DEBUG ("not copying pooled metadata %s", g_type_name (info->api));
870     do_copy = FALSE;
871   } else if (gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)) {
872     /* never call the transform_meta with memory specific metadata */
873     GST_DEBUG ("not copying memory specific metadata %s",
874         g_type_name (info->api));
875     do_copy = FALSE;
876   } else {
877     do_copy = TRUE;
878     GST_DEBUG ("copying metadata %s", g_type_name (info->api));
879   }
880
881   if (do_copy) {
882     GstMetaTransformCopy copy_data = { FALSE, 0, -1 };
883     GST_DEBUG ("copy metadata %s", g_type_name (info->api));
884     /* simply copy then */
885     info->transform_func (outbuf, *meta, inbuf,
886         _gst_meta_transform_copy, &copy_data);
887   }
888   return TRUE;
889 }
890
891 /**
892  * gst_adapter_get_buffer:
893  * @adapter: a #GstAdapter
894  * @nbytes: the number of bytes to get
895  *
896  * Returns a #GstBuffer containing the first @nbytes of the @adapter, but
897  * does not flush them from the adapter. See gst_adapter_take_buffer()
898  * for details.
899  *
900  * Caller owns a reference to the returned buffer. gst_buffer_unref() after
901  * usage.
902  *
903  * Free-function: gst_buffer_unref
904  *
905  * Returns: (transfer full) (nullable): a #GstBuffer containing the first
906  *     @nbytes of the adapter, or %NULL if @nbytes bytes are not available.
907  *     gst_buffer_unref() when no longer needed.
908  *
909  * Since: 1.6
910  */
911 GstBuffer *
912 gst_adapter_get_buffer (GstAdapter * adapter, gsize nbytes)
913 {
914   GstBuffer *buffer;
915   GstBuffer *cur;
916   gsize hsize, skip;
917   guint8 *data;
918
919   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
920   g_return_val_if_fail (nbytes > 0, NULL);
921
922   GST_LOG_OBJECT (adapter, "getting buffer of %" G_GSIZE_FORMAT " bytes",
923       nbytes);
924
925   /* we don't have enough data, return NULL. This is unlikely
926    * as one usually does an _available() first instead of grabbing a
927    * random size. */
928   if (G_UNLIKELY (nbytes > adapter->size))
929     return NULL;
930
931   cur = adapter->buflist->data;
932   skip = adapter->skip;
933   hsize = gst_buffer_get_size (cur);
934
935   /* our head buffer has enough data left, return it */
936   if (skip == 0 && hsize == nbytes) {
937     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
938         " as head buffer", nbytes);
939     buffer = gst_buffer_ref (cur);
940     goto done;
941   } else if (hsize >= nbytes + skip) {
942     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
943         " via region copy", nbytes);
944     buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
945     goto done;
946   }
947 #if 0
948   if (gst_adapter_try_to_merge_up (adapter, nbytes)) {
949     /* Merged something, let's try again for sub-buffering */
950     cur = adapter->buflist->data;
951     skip = adapter->skip;
952     if (gst_buffer_get_size (cur) >= nbytes + skip) {
953       GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
954           " via sub-buffer", nbytes);
955       buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
956       goto done;
957     }
958   }
959 #endif
960
961   data = gst_adapter_get_internal (adapter, nbytes);
962
963   buffer = gst_buffer_new_wrapped (data, nbytes);
964
965   {
966     GSList *g;
967     GstBuffer *cur;
968     gsize read_offset = 0;
969
970     g = adapter->buflist;
971     while (g && read_offset < nbytes + adapter->skip) {
972       cur = g->data;
973
974       gst_buffer_foreach_meta (cur, foreach_metadata, buffer);
975       read_offset += gst_buffer_get_size (cur);
976
977       g = g_slist_next (g);
978     }
979   }
980
981 done:
982
983   return buffer;
984 }
985
986 /**
987  * gst_adapter_take_buffer:
988  * @adapter: a #GstAdapter
989  * @nbytes: the number of bytes to take
990  *
991  * Returns a #GstBuffer containing the first @nbytes bytes of the
992  * @adapter. The returned bytes will be flushed from the adapter.
993  * This function is potentially more performant than
994  * gst_adapter_take() since it can reuse the memory in pushed buffers
995  * by subbuffering or merging. This function will always return a
996  * buffer with a single memory region.
997  *
998  * Note that no assumptions should be made as to whether certain buffer
999  * flags such as the DISCONT flag are set on the returned buffer, or not.
1000  * The caller needs to explicitly set or unset flags that should be set or
1001  * unset.
1002  *
1003  * Since 1.6 this will also copy over all GstMeta of the input buffers except
1004  * for meta with the %GST_META_FLAG_POOLED flag or with the "memory" tag.
1005  *
1006  * Caller owns a reference to the returned buffer. gst_buffer_unref() after
1007  * usage.
1008  *
1009  * Free-function: gst_buffer_unref
1010  *
1011  * Returns: (transfer full) (nullable): a #GstBuffer containing the first
1012  *     @nbytes of the adapter, or %NULL if @nbytes bytes are not available.
1013  *     gst_buffer_unref() when no longer needed.
1014  */
1015 GstBuffer *
1016 gst_adapter_take_buffer (GstAdapter * adapter, gsize nbytes)
1017 {
1018   GstBuffer *buffer;
1019
1020   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
1021   g_return_val_if_fail (nbytes > 0, NULL);
1022
1023   buffer = gst_adapter_get_buffer (adapter, nbytes);
1024   if (buffer)
1025     gst_adapter_flush_unchecked (adapter, nbytes);
1026
1027   return buffer;
1028 }
1029
1030 /**
1031  * gst_adapter_take_list:
1032  * @adapter: a #GstAdapter
1033  * @nbytes: the number of bytes to take
1034  *
1035  * Returns a #GList of buffers containing the first @nbytes bytes of the
1036  * @adapter. The returned bytes will be flushed from the adapter.
1037  * When the caller can deal with individual buffers, this function is more
1038  * performant because no memory should be copied.
1039  *
1040  * Caller owns returned list and contained buffers. gst_buffer_unref() each
1041  * buffer in the list before freeing the list after usage.
1042  *
1043  * Returns: (element-type Gst.Buffer) (transfer full) (nullable): a #GList of
1044  *     buffers containing the first @nbytes of the adapter, or %NULL if @nbytes
1045  *     bytes are not available
1046  */
1047 GList *
1048 gst_adapter_take_list (GstAdapter * adapter, gsize nbytes)
1049 {
1050   GQueue queue = G_QUEUE_INIT;
1051   GstBuffer *cur;
1052   gsize hsize, skip, cur_size;
1053
1054   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
1055   g_return_val_if_fail (nbytes <= adapter->size, NULL);
1056
1057   GST_LOG_OBJECT (adapter, "taking %" G_GSIZE_FORMAT " bytes", nbytes);
1058
1059   while (nbytes > 0) {
1060     cur = adapter->buflist->data;
1061     skip = adapter->skip;
1062     cur_size = gst_buffer_get_size (cur);
1063     hsize = MIN (nbytes, cur_size - skip);
1064
1065     cur = gst_adapter_take_buffer (adapter, hsize);
1066
1067     g_queue_push_tail (&queue, cur);
1068
1069     nbytes -= hsize;
1070   }
1071   return queue.head;
1072 }
1073
1074 /**
1075  * gst_adapter_get_list:
1076  * @adapter: a #GstAdapter
1077  * @nbytes: the number of bytes to get
1078  *
1079  * Returns a #GList of buffers containing the first @nbytes bytes of the
1080  * @adapter, but does not flush them from the adapter. See
1081  * gst_adapter_take_list() for details.
1082  *
1083  * Caller owns returned list and contained buffers. gst_buffer_unref() each
1084  * buffer in the list before freeing the list after usage.
1085  *
1086  * Returns: (element-type Gst.Buffer) (transfer full) (nullable): a #GList of
1087  *     buffers containing the first @nbytes of the adapter, or %NULL if @nbytes
1088  *     bytes are not available
1089  *
1090  * Since: 1.6
1091  */
1092 GList *
1093 gst_adapter_get_list (GstAdapter * adapter, gsize nbytes)
1094 {
1095   GQueue queue = G_QUEUE_INIT;
1096   GstBuffer *cur;
1097   gsize hsize, skip, cur_size;
1098
1099   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
1100   g_return_val_if_fail (nbytes <= adapter->size, NULL);
1101
1102   GST_LOG_OBJECT (adapter, "getting %" G_GSIZE_FORMAT " bytes", nbytes);
1103
1104   while (nbytes > 0) {
1105     cur = adapter->buflist->data;
1106     skip = adapter->skip;
1107     cur_size = gst_buffer_get_size (cur);
1108     hsize = MIN (nbytes, cur_size - skip);
1109
1110     cur = gst_adapter_get_buffer (adapter, hsize);
1111
1112     g_queue_push_tail (&queue, cur);
1113
1114     nbytes -= hsize;
1115   }
1116   return queue.head;
1117 }
1118
1119 /**
1120  * gst_adapter_take_buffer_list:
1121  * @adapter: a #GstAdapter
1122  * @nbytes: the number of bytes to take
1123  *
1124  * Returns a #GstBufferList of buffers containing the first @nbytes bytes of
1125  * the @adapter. The returned bytes will be flushed from the adapter.
1126  * When the caller can deal with individual buffers, this function is more
1127  * performant because no memory should be copied.
1128  *
1129  * Caller owns the returned list. Call gst_buffer_list_unref() to free
1130  * the list after usage.
1131  *
1132  * Returns: (transfer full) (nullable): a #GstBufferList of buffers containing
1133  *     the first @nbytes of the adapter, or %NULL if @nbytes bytes are not
1134  *     available
1135  *
1136  * Since: 1.6
1137  */
1138 GstBufferList *
1139 gst_adapter_take_buffer_list (GstAdapter * adapter, gsize nbytes)
1140 {
1141   GstBufferList *buffer_list;
1142   GstBuffer *cur;
1143   gsize hsize, skip, cur_size;
1144   guint n_bufs;
1145
1146   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
1147
1148   if (nbytes > adapter->size)
1149     return NULL;
1150
1151   GST_LOG_OBJECT (adapter, "taking %" G_GSIZE_FORMAT " bytes", nbytes);
1152
1153   /* try to create buffer list with sufficient size, so no resize is done later */
1154   if (adapter->count < 64)
1155     n_bufs = adapter->count;
1156   else
1157     n_bufs = (adapter->count * nbytes * 1.2 / adapter->size) + 1;
1158
1159   buffer_list = gst_buffer_list_new_sized (n_bufs);
1160
1161   while (nbytes > 0) {
1162     cur = adapter->buflist->data;
1163     skip = adapter->skip;
1164     cur_size = gst_buffer_get_size (cur);
1165     hsize = MIN (nbytes, cur_size - skip);
1166
1167     gst_buffer_list_add (buffer_list, gst_adapter_take_buffer (adapter, hsize));
1168     nbytes -= hsize;
1169   }
1170   return buffer_list;
1171 }
1172
1173 /**
1174  * gst_adapter_get_buffer_list:
1175  * @adapter: a #GstAdapter
1176  * @nbytes: the number of bytes to get
1177  *
1178  * Returns a #GstBufferList of buffers containing the first @nbytes bytes of
1179  * the @adapter but does not flush them from the adapter. See
1180  * gst_adapter_take_buffer_list() for details.
1181  *
1182  * Caller owns the returned list. Call gst_buffer_list_unref() to free
1183  * the list after usage.
1184  *
1185  * Returns: (transfer full) (nullable): a #GstBufferList of buffers containing
1186  *     the first @nbytes of the adapter, or %NULL if @nbytes bytes are not
1187  *     available
1188  *
1189  * Since: 1.6
1190  */
1191 GstBufferList *
1192 gst_adapter_get_buffer_list (GstAdapter * adapter, gsize nbytes)
1193 {
1194   GstBufferList *buffer_list;
1195   GstBuffer *cur;
1196   gsize hsize, skip, cur_size;
1197   guint n_bufs;
1198
1199   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
1200
1201   if (nbytes > adapter->size)
1202     return NULL;
1203
1204   GST_LOG_OBJECT (adapter, "getting %" G_GSIZE_FORMAT " bytes", nbytes);
1205
1206   /* try to create buffer list with sufficient size, so no resize is done later */
1207   if (adapter->count < 64)
1208     n_bufs = adapter->count;
1209   else
1210     n_bufs = (adapter->count * nbytes * 1.2 / adapter->size) + 1;
1211
1212   buffer_list = gst_buffer_list_new_sized (n_bufs);
1213
1214   while (nbytes > 0) {
1215     cur = adapter->buflist->data;
1216     skip = adapter->skip;
1217     cur_size = gst_buffer_get_size (cur);
1218     hsize = MIN (nbytes, cur_size - skip);
1219
1220     gst_buffer_list_add (buffer_list, gst_adapter_get_buffer (adapter, hsize));
1221     nbytes -= hsize;
1222   }
1223   return buffer_list;
1224 }
1225
1226 /**
1227  * gst_adapter_available:
1228  * @adapter: a #GstAdapter
1229  *
1230  * Gets the maximum amount of bytes available, that is it returns the maximum
1231  * value that can be supplied to gst_adapter_map() without that function
1232  * returning %NULL.
1233  *
1234  * Returns: number of bytes available in @adapter
1235  */
1236 gsize
1237 gst_adapter_available (GstAdapter * adapter)
1238 {
1239   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
1240
1241   return adapter->size;
1242 }
1243
1244 /**
1245  * gst_adapter_available_fast:
1246  * @adapter: a #GstAdapter
1247  *
1248  * Gets the maximum number of bytes that are immediately available without
1249  * requiring any expensive operations (like copying the data into a
1250  * temporary buffer).
1251  *
1252  * Returns: number of bytes that are available in @adapter without expensive
1253  * operations
1254  */
1255 gsize
1256 gst_adapter_available_fast (GstAdapter * adapter)
1257 {
1258   GstBuffer *cur;
1259   gsize size;
1260   GSList *g;
1261
1262   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
1263
1264   /* no data */
1265   if (adapter->size == 0)
1266     return 0;
1267
1268   /* some stuff we already assembled */
1269   if (adapter->assembled_len)
1270     return adapter->assembled_len;
1271
1272   /* take the first non-zero buffer */
1273   g = adapter->buflist;
1274   while (TRUE) {
1275     cur = g->data;
1276     size = gst_buffer_get_size (cur);
1277     if (size != 0)
1278       break;
1279     g = g_slist_next (g);
1280   }
1281
1282   /* we can quickly get the (remaining) data of the first buffer */
1283   return size - adapter->skip;
1284 }
1285
1286 /**
1287  * gst_adapter_prev_pts:
1288  * @adapter: a #GstAdapter
1289  * @distance: (out) (allow-none): pointer to location for distance, or %NULL
1290  *
1291  * Get the pts that was before the current byte in the adapter. When
1292  * @distance is given, the amount of bytes between the pts and the current
1293  * position is returned.
1294  *
1295  * The pts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
1296  * the adapter is first created or when it is cleared. This also means that before
1297  * the first byte with a pts is removed from the adapter, the pts
1298  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
1299  *
1300  * Returns: The previously seen pts.
1301  */
1302 GstClockTime
1303 gst_adapter_prev_pts (GstAdapter * adapter, guint64 * distance)
1304 {
1305   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1306
1307   if (distance)
1308     *distance = adapter->pts_distance;
1309
1310   return adapter->pts;
1311 }
1312
1313 /**
1314  * gst_adapter_prev_dts:
1315  * @adapter: a #GstAdapter
1316  * @distance: (out) (allow-none): pointer to location for distance, or %NULL
1317  *
1318  * Get the dts that was before the current byte in the adapter. When
1319  * @distance is given, the amount of bytes between the dts and the current
1320  * position is returned.
1321  *
1322  * The dts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
1323  * the adapter is first created or when it is cleared. This also means that before
1324  * the first byte with a dts is removed from the adapter, the dts
1325  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
1326  *
1327  * Returns: The previously seen dts.
1328  */
1329 GstClockTime
1330 gst_adapter_prev_dts (GstAdapter * adapter, guint64 * distance)
1331 {
1332   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1333
1334   if (distance)
1335     *distance = adapter->dts_distance;
1336
1337   return adapter->dts;
1338 }
1339
1340 /**
1341  * gst_adapter_prev_pts_at_offset:
1342  * @adapter: a #GstAdapter
1343  * @offset: the offset in the adapter at which to get timestamp
1344  * @distance: (out) (allow-none): pointer to location for distance, or %NULL
1345  *
1346  * Get the pts that was before the byte at offset @offset in the adapter. When
1347  * @distance is given, the amount of bytes between the pts and the current
1348  * position is returned.
1349  *
1350  * The pts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
1351  * the adapter is first created or when it is cleared. This also means that before
1352  * the first byte with a pts is removed from the adapter, the pts
1353  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
1354  *
1355  * Since: 1.2
1356  * Returns: The previously seen pts at given offset.
1357  */
1358 GstClockTime
1359 gst_adapter_prev_pts_at_offset (GstAdapter * adapter, gsize offset,
1360     guint64 * distance)
1361 {
1362   GstBuffer *cur;
1363   GSList *g;
1364   gsize read_offset = 0;
1365   GstClockTime pts = adapter->pts;
1366
1367   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1368
1369   g = adapter->buflist;
1370
1371   while (g && read_offset < offset + adapter->skip) {
1372     cur = g->data;
1373
1374     read_offset += gst_buffer_get_size (cur);
1375     if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_PTS (cur))) {
1376       pts = GST_BUFFER_PTS (cur);
1377     }
1378
1379     g = g_slist_next (g);
1380   }
1381
1382   if (distance)
1383     *distance = adapter->dts_distance + offset;
1384
1385   return pts;
1386 }
1387
1388 /**
1389  * gst_adapter_prev_dts_at_offset:
1390  * @adapter: a #GstAdapter
1391  * @offset: the offset in the adapter at which to get timestamp
1392  * @distance: (out) (allow-none): pointer to location for distance, or %NULL
1393  *
1394  * Get the dts that was before the byte at offset @offset in the adapter. When
1395  * @distance is given, the amount of bytes between the dts and the current
1396  * position is returned.
1397  *
1398  * The dts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
1399  * the adapter is first created or when it is cleared. This also means that before
1400  * the first byte with a dts is removed from the adapter, the dts
1401  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
1402  *
1403  * Since: 1.2
1404  * Returns: The previously seen dts at given offset.
1405  */
1406 GstClockTime
1407 gst_adapter_prev_dts_at_offset (GstAdapter * adapter, gsize offset,
1408     guint64 * distance)
1409 {
1410   GstBuffer *cur;
1411   GSList *g;
1412   gsize read_offset = 0;
1413   GstClockTime dts = adapter->dts;
1414
1415   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
1416
1417   g = adapter->buflist;
1418
1419   while (g && read_offset < offset + adapter->skip) {
1420     cur = g->data;
1421
1422     read_offset += gst_buffer_get_size (cur);
1423     if (GST_CLOCK_TIME_IS_VALID (GST_BUFFER_DTS (cur))) {
1424       dts = GST_BUFFER_DTS (cur);
1425     }
1426
1427     g = g_slist_next (g);
1428   }
1429
1430   if (distance)
1431     *distance = adapter->dts_distance + offset;
1432
1433   return dts;
1434 }
1435
1436 /**
1437  * gst_adapter_masked_scan_uint32_peek:
1438  * @adapter: a #GstAdapter
1439  * @mask: mask to apply to data before matching against @pattern
1440  * @pattern: pattern to match (after mask is applied)
1441  * @offset: offset into the adapter data from which to start scanning, returns
1442  *          the last scanned position.
1443  * @size: number of bytes to scan from offset
1444  * @value: (out) (allow-none): pointer to uint32 to return matching data
1445  *
1446  * Scan for pattern @pattern with applied mask @mask in the adapter data,
1447  * starting from offset @offset.  If a match is found, the value that matched
1448  * is returned through @value, otherwise @value is left untouched.
1449  *
1450  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
1451  * of endianness.  All four bytes of the pattern must be present in the
1452  * adapter for it to match, even if the first or last bytes are masked out.
1453  *
1454  * It is an error to call this function without making sure that there is
1455  * enough data (offset+size bytes) in the adapter.
1456  *
1457  * Returns: offset of the first match, or -1 if no match was found.
1458  */
1459 gssize
1460 gst_adapter_masked_scan_uint32_peek (GstAdapter * adapter, guint32 mask,
1461     guint32 pattern, gsize offset, gsize size, guint32 * value)
1462 {
1463   GSList *g;
1464   gsize skip, bsize, i;
1465   guint32 state;
1466   GstMapInfo info;
1467   guint8 *bdata;
1468   GstBuffer *buf;
1469
1470   g_return_val_if_fail (size > 0, -1);
1471   g_return_val_if_fail (offset + size <= adapter->size, -1);
1472   g_return_val_if_fail (((~mask) & pattern) == 0, -1);
1473
1474   /* we can't find the pattern with less than 4 bytes */
1475   if (G_UNLIKELY (size < 4))
1476     return -1;
1477
1478   skip = offset + adapter->skip;
1479
1480   /* first step, do skipping and position on the first buffer */
1481   /* optimistically assume scanning continues sequentially */
1482   if (adapter->scan_entry && (adapter->scan_offset <= skip)) {
1483     g = adapter->scan_entry;
1484     skip -= adapter->scan_offset;
1485   } else {
1486     g = adapter->buflist;
1487     adapter->scan_offset = 0;
1488     adapter->scan_entry = NULL;
1489   }
1490   buf = g->data;
1491   bsize = gst_buffer_get_size (buf);
1492   while (G_UNLIKELY (skip >= bsize)) {
1493     skip -= bsize;
1494     g = g_slist_next (g);
1495     adapter->scan_offset += bsize;
1496     adapter->scan_entry = g;
1497     buf = g->data;
1498     bsize = gst_buffer_get_size (buf);
1499   }
1500   /* get the data now */
1501   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
1502     return -1;
1503
1504   bdata = (guint8 *) info.data + skip;
1505   bsize = info.size - skip;
1506   skip = 0;
1507
1508   /* set the state to something that does not match */
1509   state = ~pattern;
1510
1511   /* now find data */
1512   do {
1513     bsize = MIN (bsize, size);
1514     for (i = 0; i < bsize; i++) {
1515       state = ((state << 8) | bdata[i]);
1516       if (G_UNLIKELY ((state & mask) == pattern)) {
1517         /* we have a match but we need to have skipped at
1518          * least 4 bytes to fill the state. */
1519         if (G_LIKELY (skip + i >= 3)) {
1520           if (G_LIKELY (value))
1521             *value = state;
1522           gst_buffer_unmap (buf, &info);
1523           return offset + skip + i - 3;
1524         }
1525       }
1526     }
1527     size -= bsize;
1528     if (size == 0)
1529       break;
1530
1531     /* nothing found yet, go to next buffer */
1532     skip += bsize;
1533     g = g_slist_next (g);
1534     adapter->scan_offset += info.size;
1535     adapter->scan_entry = g;
1536     gst_buffer_unmap (buf, &info);
1537     buf = g->data;
1538
1539     if (!gst_buffer_map (buf, &info, GST_MAP_READ))
1540       return -1;
1541
1542     bsize = info.size;
1543     bdata = info.data;
1544   } while (TRUE);
1545
1546   gst_buffer_unmap (buf, &info);
1547
1548   /* nothing found */
1549   return -1;
1550 }
1551
1552 /**
1553  * gst_adapter_masked_scan_uint32:
1554  * @adapter: a #GstAdapter
1555  * @mask: mask to apply to data before matching against @pattern
1556  * @pattern: pattern to match (after mask is applied)
1557  * @offset: offset into the adapter data from which to start scanning, returns
1558  *          the last scanned position.
1559  * @size: number of bytes to scan from offset
1560  *
1561  * Scan for pattern @pattern with applied mask @mask in the adapter data,
1562  * starting from offset @offset.
1563  *
1564  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
1565  * of endianness.  All four bytes of the pattern must be present in the
1566  * adapter for it to match, even if the first or last bytes are masked out.
1567  *
1568  * It is an error to call this function without making sure that there is
1569  * enough data (offset+size bytes) in the adapter.
1570  *
1571  * This function calls gst_adapter_masked_scan_uint32_peek() passing %NULL
1572  * for value.
1573  *
1574  * Returns: offset of the first match, or -1 if no match was found.
1575  *
1576  * Example:
1577  * <programlisting>
1578  * // Assume the adapter contains 0x00 0x01 0x02 ... 0xfe 0xff
1579  *
1580  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 0, 256);
1581  * // -> returns 0
1582  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 1, 255);
1583  * // -> returns -1
1584  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x01020304, 1, 255);
1585  * // -> returns 1
1586  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0001, 0, 256);
1587  * // -> returns -1
1588  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0203, 0, 256);
1589  * // -> returns 0
1590  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 256);
1591  * // -> returns 2
1592  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 4);
1593  * // -> returns -1
1594  * </programlisting>
1595  */
1596 gssize
1597 gst_adapter_masked_scan_uint32 (GstAdapter * adapter, guint32 mask,
1598     guint32 pattern, gsize offset, gsize size)
1599 {
1600   return gst_adapter_masked_scan_uint32_peek (adapter, mask, pattern, offset,
1601       size, NULL);
1602 }