adapter: make internals private
[platform/upstream/gstreamer.git] / libs / gst / base / gstadapter.c
1 /* GStreamer
2  * Copyright (C) 2004 Benjamin Otte <otte@gnome.org>
3  *               2005 Wim Taymans <wim@fluendo.com>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * SECTION:gstadapter
23  * @short_description: adapts incoming data on a sink pad into chunks of N bytes
24  *
25  * This class is for elements that receive buffers in an undesired size.
26  * While for example raw video contains one image per buffer, the same is not
27  * true for a lot of other formats, especially those that come directly from
28  * a file. So if you have undefined buffer sizes and require a specific size,
29  * this object is for you.
30  *
31  * An adapter is created with gst_adapter_new(). It can be freed again with
32  * g_object_unref().
33  *
34  * The theory of operation is like this: All buffers received are put
35  * into the adapter using gst_adapter_push() and the data is then read back
36  * in chunks of the desired size using gst_adapter_map()/gst_adapter_unmap()
37  * and/or gst_adapter_copy(). After the data has been processed, it is freed
38  * using gst_adapter_unmap().
39  *
40  * Other methods such as gst_adapter_take() and gst_adapter_take_buffer()
41  * combine gst_adapter_map() and gst_adapter_unmap() in one method and are
42  * potentially more convenient for some use cases.
43  *
44  * For example, a sink pad's chain function that needs to pass data to a library
45  * in 512-byte chunks could be implemented like this:
46  * |[
47  * static GstFlowReturn
48  * sink_pad_chain (GstPad *pad, GstBuffer *buffer)
49  * {
50  *   MyElement *this;
51  *   GstAdapter *adapter;
52  *   GstFlowReturn ret = GST_FLOW_OK;
53  *
54  *   // will give the element an extra ref; remember to drop it
55  *   this = MY_ELEMENT (gst_pad_get_parent (pad));
56  *   adapter = this->adapter;
57  *
58  *   // put buffer into adapter
59  *   gst_adapter_push (adapter, buffer);
60  *   // while we can read out 512 bytes, process them
61  *   while (gst_adapter_available (adapter) >= 512 && ret == GST_FLOW_OK) {
62  *     const guint8 *data = gst_adapter_map (adapter, 512);
63  *     // use flowreturn as an error value
64  *     ret = my_library_foo (data);
65  *     gst_adapter_unmap (adapter);
66  *     gst_adapter_flush (adapter, 512);
67  *   }
68  *
69  *   gst_object_unref (this);
70  *   return ret;
71  * }
72  * ]|
73  *
74  * For another example, a simple element inside GStreamer that uses GstAdapter
75  * is the libvisual element.
76  *
77  * An element using GstAdapter in its sink pad chain function should ensure that
78  * when the FLUSH_STOP event is received, that any queued data is cleared using
79  * gst_adapter_clear(). Data should also be cleared or processed on EOS and
80  * when changing state from #GST_STATE_PAUSED to #GST_STATE_READY.
81  *
82  * Also check the GST_BUFFER_FLAG_DISCONT flag on the buffer. Some elements might
83  * need to clear the adapter after a discontinuity.
84  *
85  * Since 0.10.24, the adapter will keep track of the timestamps of the buffers
86  * that were pushed. The last seen timestamp before the current position
87  * can be queried with gst_adapter_prev_timestamp(). This function can
88  * optionally return the amount of bytes between the start of the buffer that
89  * carried the timestamp and the current adapter position. The distance is
90  * useful when dealing with, for example, raw audio samples because it allows
91  * you to calculate the timestamp of the current adapter position by using the
92  * last seen timestamp and the amount of bytes since.
93  *
94  * A last thing to note is that while GstAdapter is pretty optimized,
95  * merging buffers still might be an operation that requires a malloc() and
96  * memcpy() operation, and these operations are not the fastest. Because of
97  * this, some functions like gst_adapter_available_fast() are provided to help
98  * speed up such cases should you want to. To avoid repeated memory allocations,
99  * gst_adapter_copy() can be used to copy data into a (statically allocated)
100  * user provided buffer.
101  *
102  * GstAdapter is not MT safe. All operations on an adapter must be serialized by
103  * the caller. This is not normally a problem, however, as the normal use case
104  * of GstAdapter is inside one pad's chain function, in which case access is
105  * serialized via the pad's STREAM_LOCK.
106  *
107  * Note that gst_adapter_push() takes ownership of the buffer passed. Use
108  * gst_buffer_ref() before pushing it into the adapter if you still want to
109  * access the buffer later. The adapter will never modify the data in the
110  * buffer pushed in it.
111  *
112  * Last reviewed on 2009-05-13 (0.10.24).
113  */
114
115 #include <gst/gst_private.h>
116 #include "gstadapter.h"
117 #include <string.h>
118
119 /* default size for the assembled data buffer */
120 #define DEFAULT_SIZE 4096
121
122 static void gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush);
123
124 GST_DEBUG_CATEGORY_STATIC (gst_adapter_debug);
125 #define GST_CAT_DEFAULT gst_adapter_debug
126
127 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 /* Internal method only. Tries to merge buffers at the head of the queue
353  * to form a single larger buffer of size 'size'.
354  *
355  * Returns TRUE if it managed to merge anything.
356  */
357 static gboolean
358 gst_adapter_try_to_merge_up (GstAdapter * adapter, gsize size)
359 {
360   GstBuffer *cur, *head;
361   GSList *g;
362   gboolean ret = FALSE;
363   gsize hsize;
364
365   g = adapter->buflist;
366   if (g == NULL)
367     return FALSE;
368
369   head = g->data;
370
371   hsize = gst_buffer_get_size (head);
372
373   /* Remove skipped part from the buffer (otherwise the buffer might grow indefinitely) */
374   head = gst_buffer_make_writable (head);
375   gst_buffer_resize (head, adapter->skip, hsize - adapter->skip);
376   hsize -= adapter->skip;
377   adapter->skip = 0;
378   g->data = head;
379
380   g = g_slist_next (g);
381
382   while (g != NULL && hsize < size) {
383     cur = g->data;
384     /* Merge the head buffer and the next in line */
385     GST_LOG_OBJECT (adapter, "Merging buffers of size %" G_GSIZE_FORMAT " & %"
386         G_GSIZE_FORMAT " in search of target %" G_GSIZE_FORMAT,
387         hsize, gst_buffer_get_size (cur), size);
388
389     head = gst_buffer_append (head, cur);
390     hsize = gst_buffer_get_size (head);
391     ret = TRUE;
392
393     /* Delete the front list item, and store our new buffer in the 2nd list
394      * item */
395     adapter->buflist = g_slist_delete_link (adapter->buflist, adapter->buflist);
396     g->data = head;
397
398     /* invalidate scan position */
399     adapter->scan_offset = 0;
400     adapter->scan_entry = NULL;
401
402     g = g_slist_next (g);
403   }
404
405   return ret;
406 }
407
408 /**
409  * gst_adapter_map:
410  * @adapter: a #GstAdapter
411  * @size: the number of bytes to map/peek
412  *
413  * Gets the first @size bytes stored in the @adapter. The returned pointer is
414  * valid until the next function is called on the adapter.
415  *
416  * Note that setting the returned pointer as the data of a #GstBuffer is
417  * incorrect for general-purpose plugins. The reason is that if a downstream
418  * element stores the buffer so that it has access to it outside of the bounds
419  * of its chain function, the buffer will have an invalid data pointer after
420  * your element flushes the bytes. In that case you should use
421  * gst_adapter_take(), which returns a freshly-allocated buffer that you can set
422  * as #GstBuffer malloc_data or the potentially more performant
423  * gst_adapter_take_buffer().
424  *
425  * Returns #NULL if @size bytes are not available.
426  *
427  * Returns: (transfer none) (array length=size): a pointer to the first
428  *     @size bytes of data, or NULL
429  */
430 gconstpointer
431 gst_adapter_map (GstAdapter * adapter, gsize size)
432 {
433   GstBuffer *cur;
434   gsize skip, csize;
435   gsize toreuse, tocopy;
436   guint8 *data;
437
438   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
439   g_return_val_if_fail (size > 0, NULL);
440
441   if (adapter->info.memory)
442     gst_adapter_unmap (adapter);
443
444   /* we don't have enough data, return NULL. This is unlikely
445    * as one usually does an _available() first instead of peeking a
446    * random size. */
447   if (G_UNLIKELY (size > adapter->size))
448     return NULL;
449
450   /* we have enough assembled data, return it */
451   if (adapter->assembled_len >= size)
452     return adapter->assembled_data;
453
454   do {
455     cur = adapter->buflist->data;
456     skip = adapter->skip;
457
458     csize = gst_buffer_get_size (cur);
459     if (csize >= size + skip) {
460       if (!gst_buffer_map (cur, &adapter->info, GST_MAP_READ))
461         return FALSE;
462
463       return (guint8 *) adapter->info.data + skip;
464     }
465     /* We may be able to efficiently merge buffers in our pool to
466      * gather a big enough chunk to return it from the head buffer directly */
467   } while (gst_adapter_try_to_merge_up (adapter, size));
468
469   /* see how much data we can reuse from the assembled memory and how much
470    * we need to copy */
471   toreuse = adapter->assembled_len;
472   tocopy = size - toreuse;
473
474   /* Gonna need to copy stuff out */
475   if (G_UNLIKELY (adapter->assembled_size < size)) {
476     adapter->assembled_size = (size / DEFAULT_SIZE + 1) * DEFAULT_SIZE;
477     GST_DEBUG_OBJECT (adapter, "resizing internal buffer to %" G_GSIZE_FORMAT,
478         adapter->assembled_size);
479     if (toreuse == 0) {
480       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "alloc new buffer");
481       /* no g_realloc to avoid a memcpy that is not desired here since we are
482        * not going to reuse any data here */
483       g_free (adapter->assembled_data);
484       adapter->assembled_data = g_malloc (adapter->assembled_size);
485     } else {
486       /* we are going to reuse all data, realloc then */
487       GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "reusing %" G_GSIZE_FORMAT " bytes",
488           toreuse);
489       adapter->assembled_data =
490           g_realloc (adapter->assembled_data, adapter->assembled_size);
491     }
492   }
493   GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy remaining %" G_GSIZE_FORMAT
494       " bytes from adapter", tocopy);
495   data = adapter->assembled_data;
496   copy_into_unchecked (adapter, data + toreuse, skip + toreuse, tocopy);
497   adapter->assembled_len = size;
498
499   return adapter->assembled_data;
500 }
501
502 /**
503  * gst_adapter_unmap:
504  * @adapter: a #GstAdapter
505  *
506  * Releases the memory obtained with the last gst_adapter_map().
507  */
508 void
509 gst_adapter_unmap (GstAdapter * adapter)
510 {
511   g_return_if_fail (GST_IS_ADAPTER (adapter));
512
513   if (adapter->info.memory) {
514     GstBuffer *cur = adapter->buflist->data;
515     GST_LOG_OBJECT (adapter, "unmap memory buffer %p", cur);
516     gst_buffer_unmap (cur, &adapter->info);
517     adapter->info.memory = NULL;
518   }
519 }
520
521 /**
522  * gst_adapter_copy:
523  * @adapter: a #GstAdapter
524  * @dest: (out caller-allocates) (array length=size): the memory to copy into
525  * @offset: the bytes offset in the adapter to start from
526  * @size: the number of bytes to copy
527  *
528  * Copies @size bytes of data starting at @offset out of the buffers
529  * contained in @GstAdapter into an array @dest provided by the caller.
530  *
531  * The array @dest should be large enough to contain @size bytes.
532  * The user should check that the adapter has (@offset + @size) bytes
533  * available before calling this function.
534  *
535  * Since: 0.10.12
536  */
537 void
538 gst_adapter_copy (GstAdapter * adapter, gpointer dest, gsize offset, gsize size)
539 {
540   g_return_if_fail (GST_IS_ADAPTER (adapter));
541   g_return_if_fail (size > 0);
542   g_return_if_fail (offset + size <= adapter->size);
543
544   copy_into_unchecked (adapter, dest, offset + adapter->skip, size);
545 }
546
547 /**
548  * gst_adapter_flush:
549  * @adapter: a #GstAdapter
550  * @flush: the number of bytes to flush
551  *
552  * Flushes the first @flush bytes in the @adapter. The caller must ensure that
553  * at least this many bytes are available.
554  *
555  * See also: gst_adapter_map(), gst_adapter_unmap()
556  */
557 static void
558 gst_adapter_flush_unchecked (GstAdapter * adapter, gsize flush)
559 {
560   GstBuffer *cur;
561   gsize size;
562   GSList *g;
563
564   GST_LOG_OBJECT (adapter, "flushing %" G_GSIZE_FORMAT " bytes", flush);
565
566   if (adapter->info.memory)
567     gst_adapter_unmap (adapter);
568
569   /* clear state */
570   adapter->size -= flush;
571   adapter->assembled_len = 0;
572
573   /* take skip into account */
574   flush += adapter->skip;
575   /* distance is always at least the amount of skipped bytes */
576   adapter->pts_distance -= adapter->skip;
577   adapter->dts_distance -= adapter->skip;
578
579   g = adapter->buflist;
580   cur = g->data;
581   size = gst_buffer_get_size (cur);
582   while (flush >= size) {
583     /* can skip whole buffer */
584     GST_LOG_OBJECT (adapter, "flushing out head buffer");
585     adapter->pts_distance += size;
586     adapter->dts_distance += size;
587     flush -= size;
588
589     gst_buffer_unref (cur);
590     g = g_slist_delete_link (g, g);
591
592     if (G_UNLIKELY (g == NULL)) {
593       GST_LOG_OBJECT (adapter, "adapter empty now");
594       adapter->buflist_end = NULL;
595       break;
596     }
597     /* there is a new head buffer, update the timestamps */
598     cur = g->data;
599     update_timestamps (adapter, cur);
600     size = gst_buffer_get_size (cur);
601   }
602   adapter->buflist = g;
603   /* account for the remaining bytes */
604   adapter->skip = flush;
605   adapter->pts_distance += flush;
606   adapter->dts_distance += flush;
607   /* invalidate scan position */
608   adapter->scan_offset = 0;
609   adapter->scan_entry = NULL;
610 }
611
612 void
613 gst_adapter_flush (GstAdapter * adapter, gsize flush)
614 {
615   g_return_if_fail (GST_IS_ADAPTER (adapter));
616   g_return_if_fail (flush <= adapter->size);
617
618   /* flushing out 0 bytes will do nothing */
619   if (G_UNLIKELY (flush == 0))
620     return;
621
622   gst_adapter_flush_unchecked (adapter, flush);
623 }
624
625 /* internal function, nbytes should be flushed after calling this function */
626 static guint8 *
627 gst_adapter_take_internal (GstAdapter * adapter, gsize nbytes)
628 {
629   guint8 *data;
630   gsize toreuse, tocopy;
631
632   /* see how much data we can reuse from the assembled memory and how much
633    * we need to copy */
634   toreuse = MIN (nbytes, adapter->assembled_len);
635   tocopy = nbytes - toreuse;
636
637   /* find memory to return */
638   if (adapter->assembled_size >= nbytes && toreuse > 0) {
639     /* we reuse already allocated memory but only when we're going to reuse
640      * something from it because else we are worse than the malloc and copy
641      * case below */
642     GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes of assembled"
643         " data", toreuse);
644     /* we have enough free space in the assembled array */
645     data = adapter->assembled_data;
646     /* flush after this function should set the assembled_size to 0 */
647     adapter->assembled_data = g_malloc (adapter->assembled_size);
648   } else {
649     GST_LOG_OBJECT (adapter, "allocating %" G_GSIZE_FORMAT " bytes", nbytes);
650     /* not enough bytes in the assembled array, just allocate new space */
651     data = g_malloc (nbytes);
652     /* reuse what we can from the already assembled data */
653     if (toreuse) {
654       GST_LOG_OBJECT (adapter, "reusing %" G_GSIZE_FORMAT " bytes", toreuse);
655       GST_CAT_LOG_OBJECT (GST_CAT_PERFORMANCE, adapter,
656           "memcpy %" G_GSIZE_FORMAT " bytes", toreuse);
657       memcpy (data, adapter->assembled_data, toreuse);
658     }
659   }
660   if (tocopy) {
661     /* copy the remaining data */
662     copy_into_unchecked (adapter, toreuse + data, toreuse + adapter->skip,
663         tocopy);
664   }
665   return data;
666 }
667
668 /**
669  * gst_adapter_take:
670  * @adapter: a #GstAdapter
671  * @nbytes: the number of bytes to take
672  *
673  * Returns a freshly allocated buffer containing the first @nbytes bytes of the
674  * @adapter. The returned bytes will be flushed from the adapter.
675  *
676  * Caller owns returned value. g_free after usage.
677  *
678  * Free-function: g_free
679  *
680  * Returns: (transfer full) (array length=nbytes): oven-fresh hot data, or
681  *     #NULL if @nbytes bytes are not available
682  */
683 gpointer
684 gst_adapter_take (GstAdapter * adapter, gsize nbytes)
685 {
686   gpointer data;
687
688   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
689   g_return_val_if_fail (nbytes > 0, NULL);
690
691   /* we don't have enough data, return NULL. This is unlikely
692    * as one usually does an _available() first instead of peeking a
693    * random size. */
694   if (G_UNLIKELY (nbytes > adapter->size))
695     return NULL;
696
697   data = gst_adapter_take_internal (adapter, nbytes);
698
699   gst_adapter_flush_unchecked (adapter, nbytes);
700
701   return data;
702 }
703
704 /**
705  * gst_adapter_take_buffer:
706  * @adapter: a #GstAdapter
707  * @nbytes: the number of bytes to take
708  *
709  * Returns a #GstBuffer containing the first @nbytes bytes of the
710  * @adapter. The returned bytes will be flushed from the adapter.
711  * This function is potentially more performant than gst_adapter_take()
712  * since it can reuse the memory in pushed buffers by subbuffering
713  * or merging.
714  *
715  * Caller owns returned value. gst_buffer_unref() after usage.
716  *
717  * Free-function: gst_buffer_unref
718  *
719  * Returns: (transfer full): a #GstBuffer containing the first @nbytes of
720  *     the adapter, or #NULL if @nbytes bytes are not available
721  *
722  * Since: 0.10.6
723  */
724 GstBuffer *
725 gst_adapter_take_buffer (GstAdapter * adapter, gsize nbytes)
726 {
727   GstBuffer *buffer;
728   GstBuffer *cur;
729   gsize hsize, skip;
730   guint8 *data;
731
732   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
733   g_return_val_if_fail (nbytes > 0, NULL);
734
735   GST_LOG_OBJECT (adapter, "taking buffer of %" G_GSIZE_FORMAT " bytes",
736       nbytes);
737
738   /* we don't have enough data, return NULL. This is unlikely
739    * as one usually does an _available() first instead of grabbing a
740    * random size. */
741   if (G_UNLIKELY (nbytes > adapter->size))
742     return NULL;
743
744   cur = adapter->buflist->data;
745   skip = adapter->skip;
746   hsize = gst_buffer_get_size (cur);
747
748   /* our head buffer has enough data left, return it */
749   if (skip == 0 && hsize == nbytes) {
750     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
751         " as head buffer", nbytes);
752     buffer = gst_buffer_ref (cur);
753     goto done;
754   } else if (hsize >= nbytes + skip) {
755     GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
756         " via region copy", nbytes);
757     buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
758     goto done;
759   }
760
761   if (gst_adapter_try_to_merge_up (adapter, nbytes)) {
762     /* Merged something, let's try again for sub-buffering */
763     cur = adapter->buflist->data;
764     skip = adapter->skip;
765     if (gst_buffer_get_size (cur) >= nbytes + skip) {
766       GST_LOG_OBJECT (adapter, "providing buffer of %" G_GSIZE_FORMAT " bytes"
767           " via sub-buffer", nbytes);
768       buffer = gst_buffer_copy_region (cur, GST_BUFFER_COPY_ALL, skip, nbytes);
769       goto done;
770     }
771   }
772
773   data = gst_adapter_take_internal (adapter, nbytes);
774
775   buffer = gst_buffer_new_wrapped (data, nbytes);
776
777 done:
778   gst_adapter_flush_unchecked (adapter, nbytes);
779
780   return buffer;
781 }
782
783 /**
784  * gst_adapter_take_list:
785  * @adapter: a #GstAdapter
786  * @nbytes: the number of bytes to take
787  *
788  * Returns a #GList of buffers containing the first @nbytes bytes of the
789  * @adapter. The returned bytes will be flushed from the adapter.
790  * When the caller can deal with individual buffers, this function is more
791  * performant because no memory should be copied.
792  *
793  * Caller owns returned list and contained buffers. gst_buffer_unref() each
794  * buffer in the list before freeing the list after usage.
795  *
796  * Returns: (element-type Gst.Buffer) (transfer full): a #GList of buffers
797  *     containing the first @nbytes of the adapter, or #NULL if @nbytes bytes
798  *     are not available
799  *
800  * Since: 0.10.31
801  */
802 GList *
803 gst_adapter_take_list (GstAdapter * adapter, gsize nbytes)
804 {
805   GQueue queue = G_QUEUE_INIT;
806   GstBuffer *cur;
807   gsize hsize, skip;
808
809   g_return_val_if_fail (GST_IS_ADAPTER (adapter), NULL);
810   g_return_val_if_fail (nbytes <= adapter->size, NULL);
811
812   GST_LOG_OBJECT (adapter, "taking %" G_GSIZE_FORMAT " bytes", nbytes);
813
814   while (nbytes > 0) {
815     cur = adapter->buflist->data;
816     skip = adapter->skip;
817     hsize = MIN (nbytes, gst_buffer_get_size (cur) - skip);
818
819     cur = gst_adapter_take_buffer (adapter, hsize);
820
821     g_queue_push_tail (&queue, cur);
822
823     nbytes -= hsize;
824   }
825   return queue.head;
826 }
827
828 /**
829  * gst_adapter_available:
830  * @adapter: a #GstAdapter
831  *
832  * Gets the maximum amount of bytes available, that is it returns the maximum
833  * value that can be supplied to gst_adapter_map() without that function
834  * returning NULL.
835  *
836  * Returns: number of bytes available in @adapter
837  */
838 gsize
839 gst_adapter_available (GstAdapter * adapter)
840 {
841   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
842
843   return adapter->size;
844 }
845
846 /**
847  * gst_adapter_available_fast:
848  * @adapter: a #GstAdapter
849  *
850  * Gets the maximum number of bytes that are immediately available without
851  * requiring any expensive operations (like copying the data into a
852  * temporary buffer).
853  *
854  * Returns: number of bytes that are available in @adapter without expensive
855  * operations
856  */
857 gsize
858 gst_adapter_available_fast (GstAdapter * adapter)
859 {
860   GstBuffer *cur;
861   gsize size;
862   GSList *g;
863
864   g_return_val_if_fail (GST_IS_ADAPTER (adapter), 0);
865
866   /* no data */
867   if (adapter->size == 0)
868     return 0;
869
870   /* some stuff we already assembled */
871   if (adapter->assembled_len)
872     return adapter->assembled_len;
873
874   /* take the first non-zero buffer */
875   g = adapter->buflist;
876   while (TRUE) {
877     cur = g->data;
878     size = gst_buffer_get_size (cur);
879     if (size != 0)
880       break;
881     g = g_slist_next (g);
882   }
883
884   /* we can quickly get the (remaining) data of the first buffer */
885   return size - adapter->skip;
886 }
887
888 /**
889  * gst_adapter_prev_pts:
890  * @adapter: a #GstAdapter
891  * @distance: (out) (allow-none): pointer to location for distance, or NULL
892  *
893  * Get the pts that was before the current byte in the adapter. When
894  * @distance is given, the amount of bytes between the pts and the current
895  * position is returned.
896  *
897  * The pts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
898  * the adapter is first created or when it is cleared. This also means that before
899  * the first byte with a pts is removed from the adapter, the pts
900  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
901  *
902  * Returns: The previously seen pts.
903  */
904 GstClockTime
905 gst_adapter_prev_pts (GstAdapter * adapter, guint64 * distance)
906 {
907   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
908
909   if (distance)
910     *distance = adapter->pts_distance;
911
912   return adapter->pts;
913 }
914
915 /**
916  * gst_adapter_prev_dts:
917  * @adapter: a #GstAdapter
918  * @distance: (out) (allow-none): pointer to location for distance, or NULL
919  *
920  * Get the dts that was before the current byte in the adapter. When
921  * @distance is given, the amount of bytes between the dts and the current
922  * position is returned.
923  *
924  * The dts is reset to GST_CLOCK_TIME_NONE and the distance is set to 0 when
925  * the adapter is first created or when it is cleared. This also means that before
926  * the first byte with a dts is removed from the adapter, the dts
927  * and distance returned are GST_CLOCK_TIME_NONE and 0 respectively.
928  *
929  * Returns: The previously seen dts.
930  */
931 GstClockTime
932 gst_adapter_prev_dts (GstAdapter * adapter, guint64 * distance)
933 {
934   g_return_val_if_fail (GST_IS_ADAPTER (adapter), GST_CLOCK_TIME_NONE);
935
936   if (distance)
937     *distance = adapter->dts_distance;
938
939   return adapter->dts;
940 }
941
942 /**
943  * gst_adapter_masked_scan_uint32_peek:
944  * @adapter: a #GstAdapter
945  * @mask: mask to apply to data before matching against @pattern
946  * @pattern: pattern to match (after mask is applied)
947  * @offset: offset into the adapter data from which to start scanning, returns
948  *          the last scanned position.
949  * @size: number of bytes to scan from offset
950  * @value: pointer to uint32 to return matching data
951  *
952  * Scan for pattern @pattern with applied mask @mask in the adapter data,
953  * starting from offset @offset.  If a match is found, the value that matched
954  * is returned through @value, otherwise @value is left untouched.
955  *
956  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
957  * of endianness.  All four bytes of the pattern must be present in the
958  * adapter for it to match, even if the first or last bytes are masked out.
959  *
960  * It is an error to call this function without making sure that there is
961  * enough data (offset+size bytes) in the adapter.
962  *
963  * Returns: offset of the first match, or -1 if no match was found.
964  *
965  * Since: 0.10.30
966  */
967 gsize
968 gst_adapter_masked_scan_uint32_peek (GstAdapter * adapter, guint32 mask,
969     guint32 pattern, gsize offset, gsize size, guint32 * value)
970 {
971   GSList *g;
972   gsize skip, bsize, i;
973   guint32 state;
974   GstMapInfo info;
975   guint8 *bdata;
976   GstBuffer *buf;
977
978   g_return_val_if_fail (size > 0, -1);
979   g_return_val_if_fail (offset + size <= adapter->size, -1);
980   g_return_val_if_fail (((~mask) & pattern) == 0, -1);
981
982   /* we can't find the pattern with less than 4 bytes */
983   if (G_UNLIKELY (size < 4))
984     return -1;
985
986   skip = offset + adapter->skip;
987
988   /* first step, do skipping and position on the first buffer */
989   /* optimistically assume scanning continues sequentially */
990   if (adapter->scan_entry && (adapter->scan_offset <= skip)) {
991     g = adapter->scan_entry;
992     skip -= adapter->scan_offset;
993   } else {
994     g = adapter->buflist;
995     adapter->scan_offset = 0;
996     adapter->scan_entry = NULL;
997   }
998   buf = g->data;
999   bsize = gst_buffer_get_size (buf);
1000   while (G_UNLIKELY (skip >= bsize)) {
1001     skip -= bsize;
1002     g = g_slist_next (g);
1003     adapter->scan_offset += bsize;
1004     adapter->scan_entry = g;
1005     buf = g->data;
1006     bsize = gst_buffer_get_size (buf);
1007   }
1008   /* get the data now */
1009   if (!gst_buffer_map (buf, &info, GST_MAP_READ))
1010     return -1;
1011
1012   bdata = (guint8 *) info.data + skip;
1013   bsize = info.size - skip;
1014   skip = 0;
1015
1016   /* set the state to something that does not match */
1017   state = ~pattern;
1018
1019   /* now find data */
1020   do {
1021     bsize = MIN (bsize, size);
1022     for (i = 0; i < bsize; i++) {
1023       state = ((state << 8) | bdata[i]);
1024       if (G_UNLIKELY ((state & mask) == pattern)) {
1025         /* we have a match but we need to have skipped at
1026          * least 4 bytes to fill the state. */
1027         if (G_LIKELY (skip + i >= 3)) {
1028           if (G_LIKELY (value))
1029             *value = state;
1030           gst_buffer_unmap (buf, &info);
1031           return offset + skip + i - 3;
1032         }
1033       }
1034     }
1035     size -= bsize;
1036     if (size == 0)
1037       break;
1038
1039     /* nothing found yet, go to next buffer */
1040     skip += bsize;
1041     g = g_slist_next (g);
1042     adapter->scan_offset += info.size;
1043     adapter->scan_entry = g;
1044     gst_buffer_unmap (buf, &info);
1045     buf = g->data;
1046
1047     gst_buffer_map (buf, &info, GST_MAP_READ);
1048     bsize = info.size;
1049     bdata = info.data;
1050   } while (TRUE);
1051
1052   gst_buffer_unmap (buf, &info);
1053
1054   /* nothing found */
1055   return -1;
1056 }
1057
1058 /**
1059  * gst_adapter_masked_scan_uint32:
1060  * @adapter: a #GstAdapter
1061  * @mask: mask to apply to data before matching against @pattern
1062  * @pattern: pattern to match (after mask is applied)
1063  * @offset: offset into the adapter data from which to start scanning, returns
1064  *          the last scanned position.
1065  * @size: number of bytes to scan from offset
1066  *
1067  * Scan for pattern @pattern with applied mask @mask in the adapter data,
1068  * starting from offset @offset.
1069  *
1070  * The bytes in @pattern and @mask are interpreted left-to-right, regardless
1071  * of endianness.  All four bytes of the pattern must be present in the
1072  * adapter for it to match, even if the first or last bytes are masked out.
1073  *
1074  * It is an error to call this function without making sure that there is
1075  * enough data (offset+size bytes) in the adapter.
1076  *
1077  * This function calls gst_adapter_masked_scan_uint32_peek() passing NULL
1078  * for value.
1079  *
1080  * Returns: offset of the first match, or -1 if no match was found.
1081  *
1082  * Example:
1083  * <programlisting>
1084  * // Assume the adapter contains 0x00 0x01 0x02 ... 0xfe 0xff
1085  *
1086  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 0, 256);
1087  * // -> returns 0
1088  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x00010203, 1, 255);
1089  * // -> returns -1
1090  * gst_adapter_masked_scan_uint32 (adapter, 0xffffffff, 0x01020304, 1, 255);
1091  * // -> returns 1
1092  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0001, 0, 256);
1093  * // -> returns -1
1094  * gst_adapter_masked_scan_uint32 (adapter, 0xffff, 0x0203, 0, 256);
1095  * // -> returns 0
1096  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 256);
1097  * // -> returns 2
1098  * gst_adapter_masked_scan_uint32 (adapter, 0xffff0000, 0x02030000, 0, 4);
1099  * // -> returns -1
1100  * </programlisting>
1101  *
1102  * Since: 0.10.24
1103  */
1104 gsize
1105 gst_adapter_masked_scan_uint32 (GstAdapter * adapter, guint32 mask,
1106     guint32 pattern, gsize offset, gsize size)
1107 {
1108   return gst_adapter_masked_scan_uint32_peek (adapter, mask, pattern, offset,
1109       size, NULL);
1110 }