buffer: store sequence number for metas
[platform/upstream/gstreamer.git] / gst / gstbuffer.c
1 /* GStreamer
2  * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
3  *                    2000 Wim Taymans <wtay@chello.be>
4  *
5  * gstbuffer.c: Buffer operations
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /**
24  * SECTION:gstbuffer
25  * @title: GstBuffer
26  * @short_description: Data-passing buffer type
27  * @see_also: #GstPad, #GstMiniObject, #GstMemory, #GstMeta, #GstBufferPool
28  *
29  * Buffers are the basic unit of data transfer in GStreamer. They contain the
30  * timing and offset along with other arbitrary metadata that is associated
31  * with the #GstMemory blocks that the buffer contains.
32  *
33  * Buffers are usually created with gst_buffer_new(). After a buffer has been
34  * created one will typically allocate memory for it and add it to the buffer.
35  * The following example creates a buffer that can hold a given video frame
36  * with a given width, height and bits per plane.
37  * |[<!-- language="C" -->
38  *   GstBuffer *buffer;
39  *   GstMemory *memory;
40  *   gint size, width, height, bpp;
41  *   ...
42  *   size = width * height * bpp;
43  *   buffer = gst_buffer_new ();
44  *   memory = gst_allocator_alloc (NULL, size, NULL);
45  *   gst_buffer_insert_memory (buffer, -1, memory);
46  *   ...
47  * ]|
48  *
49  * Alternatively, use gst_buffer_new_allocate() to create a buffer with
50  * preallocated data of a given size.
51  *
52  * Buffers can contain a list of #GstMemory objects. You can retrieve how many
53  * memory objects with gst_buffer_n_memory() and you can get a pointer
54  * to memory with gst_buffer_peek_memory()
55  *
56  * A buffer will usually have timestamps, and a duration, but neither of these
57  * are guaranteed (they may be set to #GST_CLOCK_TIME_NONE). Whenever a
58  * meaningful value can be given for these, they should be set. The timestamps
59  * and duration are measured in nanoseconds (they are #GstClockTime values).
60  *
61  * The buffer DTS refers to the timestamp when the buffer should be decoded and
62  * is usually monotonically increasing. The buffer PTS refers to the timestamp when
63  * the buffer content should be presented to the user and is not always
64  * monotonically increasing.
65  *
66  * A buffer can also have one or both of a start and an end offset. These are
67  * media-type specific. For video buffers, the start offset will generally be
68  * the frame number. For audio buffers, it will be the number of samples
69  * produced so far. For compressed data, it could be the byte offset in a
70  * source or destination file. Likewise, the end offset will be the offset of
71  * the end of the buffer. These can only be meaningfully interpreted if you
72  * know the media type of the buffer (the preceding CAPS event). Either or both
73  * can be set to #GST_BUFFER_OFFSET_NONE.
74  *
75  * gst_buffer_ref() is used to increase the refcount of a buffer. This must be
76  * done when you want to keep a handle to the buffer after pushing it to the
77  * next element. The buffer refcount determines the writability of the buffer, a
78  * buffer is only writable when the refcount is exactly 1, i.e. when the caller
79  * has the only reference to the buffer.
80  *
81  * To efficiently create a smaller buffer out of an existing one, you can
82  * use gst_buffer_copy_region(). This method tries to share the memory objects
83  * between the two buffers.
84  *
85  * If a plug-in wants to modify the buffer data or metadata in-place, it should
86  * first obtain a buffer that is safe to modify by using
87  * gst_buffer_make_writable().  This function is optimized so that a copy will
88  * only be made when it is necessary.
89  *
90  * Several flags of the buffer can be set and unset with the
91  * GST_BUFFER_FLAG_SET() and GST_BUFFER_FLAG_UNSET() macros. Use
92  * GST_BUFFER_FLAG_IS_SET() to test if a certain #GstBufferFlags flag is set.
93  *
94  * Buffers can be efficiently merged into a larger buffer with
95  * gst_buffer_append(). Copying of memory will only be done when absolutely
96  * needed.
97  *
98  * Arbitrary extra metadata can be set on a buffer with gst_buffer_add_meta().
99  * Metadata can be retrieved with gst_buffer_get_meta(). See also #GstMeta
100  *
101  * An element should either unref the buffer or push it out on a src pad
102  * using gst_pad_push() (see #GstPad).
103  *
104  * Buffers are usually freed by unreffing them with gst_buffer_unref(). When
105  * the refcount drops to 0, any memory and metadata pointed to by the buffer is
106  * unreffed as well. Buffers allocated from a #GstBufferPool will be returned to
107  * the pool when the refcount drops to 0.
108  *
109  * The #GstParentBufferMeta is a meta which can be attached to a #GstBuffer
110  * to hold a reference to another buffer that is only released when the child
111  * #GstBuffer is released.
112  *
113  * Typically, #GstParentBufferMeta is used when the child buffer is directly
114  * using the #GstMemory of the parent buffer, and wants to prevent the parent
115  * buffer from being returned to a buffer pool until the #GstMemory is available
116  * for re-use. (Since 1.6)
117  *
118  */
119 #include "gst_private.h"
120
121 #ifdef HAVE_UNISTD_H
122 #include <unistd.h>
123 #endif
124 #ifdef HAVE_STDLIB_H
125 #include <stdlib.h>
126 #endif
127
128 #include "gstbuffer.h"
129 #include "gstbufferpool.h"
130 #include "gstinfo.h"
131 #include "gstutils.h"
132 #include "gstversion.h"
133
134 GType _gst_buffer_type = 0;
135
136 /* info->size will be sizeof(FooMeta) which contains a GstMeta at the beginning
137  * too, and then there is again a GstMeta in GstMetaItem, so subtract one. */
138 #define ITEM_SIZE(info) ((info)->size + sizeof (GstMetaItem) - sizeof (GstMeta))
139
140 #define GST_BUFFER_MEM_MAX         16
141
142 #define GST_BUFFER_SLICE_SIZE(b)   (((GstBufferImpl *)(b))->slice_size)
143 #define GST_BUFFER_MEM_LEN(b)      (((GstBufferImpl *)(b))->len)
144 #define GST_BUFFER_MEM_ARRAY(b)    (((GstBufferImpl *)(b))->mem)
145 #define GST_BUFFER_MEM_PTR(b,i)    (((GstBufferImpl *)(b))->mem[i])
146 #define GST_BUFFER_BUFMEM(b)       (((GstBufferImpl *)(b))->bufmem)
147 #define GST_BUFFER_META(b)         (((GstBufferImpl *)(b))->item)
148
149 typedef struct
150 {
151   GstBuffer buffer;
152
153   gsize slice_size;
154
155   /* the memory blocks */
156   guint len;
157   GstMemory *mem[GST_BUFFER_MEM_MAX];
158
159   /* memory of the buffer when allocated from 1 chunk */
160   GstMemory *bufmem;
161
162   /* FIXME, make metadata allocation more efficient by using part of the
163    * GstBufferImpl */
164   GstMetaItem *item;
165 } GstBufferImpl;
166
167 static gint64 meta_seq;         /* 0 *//* ATOMIC */
168
169 /* TODO: use GLib's once https://gitlab.gnome.org/GNOME/glib/issues/1076 lands */
170 #if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)
171 static inline gint64
172 gst_atomic_int64_inc (volatile gint64 * atomic)
173 {
174   return __sync_fetch_and_add (atomic, 1);
175 }
176 #elif defined (G_PLATFORM_WIN32)
177 #include <windows.h>
178 static inline gint64
179 gst_atomic_int64_inc (volatile gint64 * atomic)
180 {
181   InterlockedExchangeAdd (atomic, 1);
182 }
183 #else
184 #warning No 64-bit atomic int defined for this platform/toolchain!
185 #define NO_64BIT_ATOMIC_INT_FOR_PLATFORM
186 G_LOCK_DEFINE_STATIC (meta_seq);
187 static inline gint64
188 gst_atomic_int64_inc (volatile gint64 * atomic)
189 {
190   gint64 ret;
191
192   G_LOCK (meta_seq);
193   ret = *atomic++;
194   G_UNLOCK (meta_seq);
195
196   return ret;
197 }
198 #endif
199
200 static gboolean
201 _is_span (GstMemory ** mem, gsize len, gsize * poffset, GstMemory ** parent)
202 {
203   GstMemory *mcur, *mprv;
204   gboolean have_offset = FALSE;
205   gsize i;
206
207   mcur = mprv = NULL;
208
209   for (i = 0; i < len; i++) {
210     if (mcur)
211       mprv = mcur;
212     mcur = mem[i];
213
214     if (mprv && mcur) {
215       gsize poffs;
216
217       /* check if memory is contiguous */
218       if (!gst_memory_is_span (mprv, mcur, &poffs))
219         return FALSE;
220
221       if (!have_offset) {
222         if (poffset)
223           *poffset = poffs;
224         if (parent)
225           *parent = mprv->parent;
226
227         have_offset = TRUE;
228       }
229     }
230   }
231   return have_offset;
232 }
233
234 static GstMemory *
235 _get_merged_memory (GstBuffer * buffer, guint idx, guint length)
236 {
237   GstMemory **mem, *result = NULL;
238
239   GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %u, length %u", buffer, idx,
240       length);
241
242   mem = GST_BUFFER_MEM_ARRAY (buffer);
243
244   if (G_UNLIKELY (length == 0)) {
245     result = NULL;
246   } else if (G_LIKELY (length == 1)) {
247     result = gst_memory_ref (mem[idx]);
248   } else {
249     GstMemory *parent = NULL;
250     gsize size, poffset = 0;
251
252     size = gst_buffer_get_sizes_range (buffer, idx, length, NULL, NULL);
253
254     if (G_UNLIKELY (_is_span (mem + idx, length, &poffset, &parent))) {
255       if (!GST_MEMORY_IS_NO_SHARE (parent))
256         result = gst_memory_share (parent, poffset, size);
257       if (!result) {
258         GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy for merge %p", parent);
259         result = gst_memory_copy (parent, poffset, size);
260       }
261     } else {
262       gsize i, tocopy, left;
263       GstMapInfo sinfo, dinfo;
264       guint8 *ptr;
265
266       result = gst_allocator_alloc (NULL, size, NULL);
267       if (result == NULL || !gst_memory_map (result, &dinfo, GST_MAP_WRITE)) {
268         GST_CAT_ERROR (GST_CAT_BUFFER, "Failed to map memory writable");
269         if (result)
270           gst_memory_unref (result);
271         return NULL;
272       }
273
274       ptr = dinfo.data;
275       left = size;
276
277       for (i = idx; i < (idx + length) && left > 0; i++) {
278         if (!gst_memory_map (mem[i], &sinfo, GST_MAP_READ)) {
279           GST_CAT_ERROR (GST_CAT_BUFFER,
280               "buffer %p, idx %u, length %u failed to map readable", buffer,
281               idx, length);
282           gst_memory_unmap (result, &dinfo);
283           gst_memory_unref (result);
284           return NULL;
285         }
286         tocopy = MIN (sinfo.size, left);
287         GST_CAT_DEBUG (GST_CAT_PERFORMANCE,
288             "memcpy %" G_GSIZE_FORMAT " bytes for merge %p from memory %p",
289             tocopy, result, mem[i]);
290         memcpy (ptr, (guint8 *) sinfo.data, tocopy);
291         left -= tocopy;
292         ptr += tocopy;
293         gst_memory_unmap (mem[i], &sinfo);
294       }
295       gst_memory_unmap (result, &dinfo);
296     }
297   }
298   return result;
299 }
300
301 static void
302 _replace_memory (GstBuffer * buffer, guint len, guint idx, guint length,
303     GstMemory * mem)
304 {
305   gsize end, i;
306
307   end = idx + length;
308
309   GST_CAT_LOG (GST_CAT_BUFFER,
310       "buffer %p replace %u-%" G_GSIZE_FORMAT " with memory %p", buffer, idx,
311       end, mem);
312
313   /* unref old memory */
314   for (i = idx; i < end; i++) {
315     GstMemory *old = GST_BUFFER_MEM_PTR (buffer, i);
316
317     gst_memory_unlock (old, GST_LOCK_FLAG_EXCLUSIVE);
318     gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (old),
319         GST_MINI_OBJECT_CAST (buffer));
320     gst_memory_unref (old);
321   }
322
323   if (mem != NULL) {
324     /* replace with single memory */
325     gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (mem),
326         GST_MINI_OBJECT_CAST (buffer));
327     gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
328     GST_BUFFER_MEM_PTR (buffer, idx) = mem;
329     idx++;
330     length--;
331   }
332
333   if (end < len) {
334     memmove (&GST_BUFFER_MEM_PTR (buffer, idx),
335         &GST_BUFFER_MEM_PTR (buffer, end), (len - end) * sizeof (gpointer));
336   }
337   GST_BUFFER_MEM_LEN (buffer) = len - length;
338   GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
339 }
340
341 /**
342  * gst_buffer_get_flags:
343  * @buffer: a #GstBuffer
344  *
345  * Get the #GstBufferFlags flags set on this buffer.
346  *
347  * Returns: the flags set on this buffer.
348  *
349  * Since: 1.10
350  */
351 GstBufferFlags
352 gst_buffer_get_flags (GstBuffer * buffer)
353 {
354   return (GstBufferFlags) GST_BUFFER_FLAGS (buffer);
355 }
356
357 /**
358  * gst_buffer_flag_is_set:
359  * @buffer: a #GstBuffer
360  * @flags: the #GstBufferFlags flag to check.
361  *
362  * Gives the status of a specific flag on a buffer.
363  *
364  * Returns: %TRUE if all flags in @flags are found on @buffer.
365  *
366  * Since: 1.10
367  */
368 gboolean
369 gst_buffer_has_flags (GstBuffer * buffer, GstBufferFlags flags)
370 {
371   return GST_BUFFER_FLAG_IS_SET (buffer, flags);
372 }
373
374 /**
375  * gst_buffer_set_flags:
376  * @buffer: a #GstBuffer
377  * @flags: the #GstBufferFlags to set.
378  *
379  * Sets one or more buffer flags on a buffer.
380  *
381  * Returns: %TRUE if @flags were successfully set on buffer.
382  *
383  * Since: 1.10
384  */
385 gboolean
386 gst_buffer_set_flags (GstBuffer * buffer, GstBufferFlags flags)
387 {
388   GST_BUFFER_FLAG_SET (buffer, flags);
389   return TRUE;
390 }
391
392 /**
393  * gst_buffer_unset_flags:
394  * @buffer: a #GstBuffer
395  * @flags: the #GstBufferFlags to clear
396  *
397  * Clears one or more buffer flags.
398  *
399  * Returns: true if @flags is successfully cleared from buffer.
400  *
401  * Since: 1.10
402  */
403 gboolean
404 gst_buffer_unset_flags (GstBuffer * buffer, GstBufferFlags flags)
405 {
406   GST_BUFFER_FLAG_UNSET (buffer, flags);
407   return TRUE;
408 }
409
410
411
412 /* transfer full for return and transfer none for @mem */
413 static inline GstMemory *
414 _memory_get_exclusive_reference (GstMemory * mem)
415 {
416   GstMemory *ret = NULL;
417
418   if (gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE)) {
419     ret = gst_memory_ref (mem);
420   } else {
421     /* we cannot take another exclusive lock as the memory is already
422      * locked WRITE + EXCLUSIVE according to part-miniobject.txt */
423     ret = gst_memory_copy (mem, 0, -1);
424
425     if (ret) {
426       if (!gst_memory_lock (ret, GST_LOCK_FLAG_EXCLUSIVE)) {
427         gst_memory_unref (ret);
428         ret = NULL;
429       }
430     }
431   }
432
433   if (!ret)
434     GST_CAT_WARNING (GST_CAT_BUFFER, "Failed to acquire an exclusive lock for "
435         "memory %p", mem);
436
437   return ret;
438 }
439
440 static inline void
441 _memory_add (GstBuffer * buffer, gint idx, GstMemory * mem)
442 {
443   guint i, len = GST_BUFFER_MEM_LEN (buffer);
444
445   GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %d, mem %p", buffer, idx, mem);
446
447   if (G_UNLIKELY (len >= GST_BUFFER_MEM_MAX)) {
448     /* too many buffer, span them. */
449     /* FIXME, there is room for improvement here: We could only try to merge
450      * 2 buffers to make some room. If we can't efficiently merge 2 buffers we
451      * could try to only merge the two smallest buffers to avoid memcpy, etc. */
452     GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "memory array overflow in buffer %p",
453         buffer);
454     _replace_memory (buffer, len, 0, len, _get_merged_memory (buffer, 0, len));
455     /* we now have 1 single spanned buffer */
456     len = 1;
457   }
458
459   if (idx == -1)
460     idx = len;
461
462   for (i = len; i > idx; i--) {
463     /* move buffers to insert, FIXME, we need to insert first and then merge */
464     GST_BUFFER_MEM_PTR (buffer, i) = GST_BUFFER_MEM_PTR (buffer, i - 1);
465   }
466   /* and insert the new buffer */
467   GST_BUFFER_MEM_PTR (buffer, idx) = mem;
468   GST_BUFFER_MEM_LEN (buffer) = len + 1;
469   gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (mem),
470       GST_MINI_OBJECT_CAST (buffer));
471
472   GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
473 }
474
475 GST_DEFINE_MINI_OBJECT_TYPE (GstBuffer, gst_buffer);
476
477 void
478 _priv_gst_buffer_initialize (void)
479 {
480   _gst_buffer_type = gst_buffer_get_type ();
481
482 #ifdef NO_64BIT_ATOMIC_INT_FOR_PLATFORM
483   GST_CAT_WARNING (GST_CAT_PERFORMANCE,
484       "No 64-bit atomic int defined for this platform/toolchain!");
485 #endif
486 }
487
488 /**
489  * gst_buffer_get_max_memory:
490  *
491  * Get the maximum amount of memory blocks that a buffer can hold. This is a
492  * compile time constant that can be queried with the function.
493  *
494  * When more memory blocks are added, existing memory blocks will be merged
495  * together to make room for the new block.
496  *
497  * Returns: the maximum amount of memory blocks that a buffer can hold.
498  *
499  * Since: 1.2
500  */
501 guint
502 gst_buffer_get_max_memory (void)
503 {
504   return GST_BUFFER_MEM_MAX;
505 }
506
507 /**
508  * gst_buffer_copy_into:
509  * @dest: a destination #GstBuffer
510  * @src: a source #GstBuffer
511  * @flags: flags indicating what metadata fields should be copied.
512  * @offset: offset to copy from
513  * @size: total size to copy. If -1, all data is copied.
514  *
515  * Copies the information from @src into @dest.
516  *
517  * If @dest already contains memory and @flags contains GST_BUFFER_COPY_MEMORY,
518  * the memory from @src will be appended to @dest.
519  *
520  * @flags indicate which fields will be copied.
521  *
522  * Returns: %TRUE if the copying succeeded, %FALSE otherwise.
523  */
524 gboolean
525 gst_buffer_copy_into (GstBuffer * dest, GstBuffer * src,
526     GstBufferCopyFlags flags, gsize offset, gsize size)
527 {
528   GstMetaItem *walk;
529   gsize bufsize;
530   gboolean region = FALSE;
531
532   g_return_val_if_fail (dest != NULL, FALSE);
533   g_return_val_if_fail (src != NULL, FALSE);
534
535   /* nothing to copy if the buffers are the same */
536   if (G_UNLIKELY (dest == src))
537     return TRUE;
538
539   g_return_val_if_fail (gst_buffer_is_writable (dest), FALSE);
540
541   bufsize = gst_buffer_get_size (src);
542   g_return_val_if_fail (bufsize >= offset, FALSE);
543   if (offset > 0)
544     region = TRUE;
545   if (size == -1)
546     size = bufsize - offset;
547   if (size < bufsize)
548     region = TRUE;
549   g_return_val_if_fail (bufsize >= offset + size, FALSE);
550
551   GST_CAT_LOG (GST_CAT_BUFFER, "copy %p to %p, offset %" G_GSIZE_FORMAT
552       "-%" G_GSIZE_FORMAT "/%" G_GSIZE_FORMAT, src, dest, offset, size,
553       bufsize);
554
555   if (flags & GST_BUFFER_COPY_FLAGS) {
556     /* copy flags */
557     guint flags_mask = ~GST_BUFFER_FLAG_TAG_MEMORY;
558
559     GST_MINI_OBJECT_FLAGS (dest) =
560         (GST_MINI_OBJECT_FLAGS (src) & flags_mask) |
561         (GST_MINI_OBJECT_FLAGS (dest) & ~flags_mask);
562   }
563
564   if (flags & GST_BUFFER_COPY_TIMESTAMPS) {
565     if (offset == 0) {
566       GST_BUFFER_PTS (dest) = GST_BUFFER_PTS (src);
567       GST_BUFFER_DTS (dest) = GST_BUFFER_DTS (src);
568       GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
569       if (size == bufsize) {
570         GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
571         GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
572       }
573     } else {
574       GST_BUFFER_PTS (dest) = GST_CLOCK_TIME_NONE;
575       GST_BUFFER_DTS (dest) = GST_CLOCK_TIME_NONE;
576       GST_BUFFER_DURATION (dest) = GST_CLOCK_TIME_NONE;
577       GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET_NONE;
578       GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_NONE;
579     }
580   }
581
582   if (flags & GST_BUFFER_COPY_MEMORY) {
583     gsize skip, left, len, dest_len, i, bsize;
584     gboolean deep;
585
586     deep = flags & GST_BUFFER_COPY_DEEP;
587
588     len = GST_BUFFER_MEM_LEN (src);
589     dest_len = GST_BUFFER_MEM_LEN (dest);
590     left = size;
591     skip = offset;
592
593     /* copy and make regions of the memory */
594     for (i = 0; i < len && left > 0; i++) {
595       GstMemory *mem = GST_BUFFER_MEM_PTR (src, i);
596
597       bsize = gst_memory_get_sizes (mem, NULL, NULL);
598
599       if (bsize <= skip) {
600         /* don't copy buffer */
601         skip -= bsize;
602       } else {
603         GstMemory *newmem = NULL;
604         gsize tocopy;
605
606         tocopy = MIN (bsize - skip, left);
607
608         if (tocopy < bsize && !deep && !GST_MEMORY_IS_NO_SHARE (mem)) {
609           /* we need to clip something */
610           newmem = gst_memory_share (mem, skip, tocopy);
611           if (newmem) {
612             gst_memory_lock (newmem, GST_LOCK_FLAG_EXCLUSIVE);
613             skip = 0;
614           }
615         }
616
617         if (deep || GST_MEMORY_IS_NO_SHARE (mem) || (!newmem && tocopy < bsize)) {
618           /* deep copy or we're not allowed to share this memory
619            * between buffers, always copy then */
620           newmem = gst_memory_copy (mem, skip, tocopy);
621           if (newmem) {
622             gst_memory_lock (newmem, GST_LOCK_FLAG_EXCLUSIVE);
623             skip = 0;
624           }
625         } else if (!newmem) {
626           newmem = _memory_get_exclusive_reference (mem);
627         }
628
629         if (!newmem) {
630           gst_buffer_remove_memory_range (dest, dest_len, -1);
631           return FALSE;
632         }
633
634         _memory_add (dest, -1, newmem);
635         left -= tocopy;
636       }
637     }
638     if (flags & GST_BUFFER_COPY_MERGE) {
639       GstMemory *mem;
640
641       len = GST_BUFFER_MEM_LEN (dest);
642       mem = _get_merged_memory (dest, 0, len);
643       if (!mem) {
644         gst_buffer_remove_memory_range (dest, dest_len, -1);
645         return FALSE;
646       }
647       _replace_memory (dest, len, 0, len, mem);
648     }
649   }
650
651   if (flags & GST_BUFFER_COPY_META) {
652     /* NOTE: GstGLSyncMeta copying relies on the meta
653      *       being copied now, after the buffer data,
654      *       so this has to happen last */
655     for (walk = GST_BUFFER_META (src); walk; walk = walk->next) {
656       GstMeta *meta = &walk->meta;
657       const GstMetaInfo *info = meta->info;
658
659       /* Don't copy memory metas if we only copied part of the buffer, didn't
660        * copy memories or merged memories. In all these cases the memory
661        * structure has changed and the memory meta becomes meaningless.
662        */
663       if ((region || !(flags & GST_BUFFER_COPY_MEMORY)
664               || (flags & GST_BUFFER_COPY_MERGE))
665           && gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)) {
666         GST_CAT_DEBUG (GST_CAT_BUFFER,
667             "don't copy memory meta %p of API type %s", meta,
668             g_type_name (info->api));
669       } else if (info->transform_func) {
670         GstMetaTransformCopy copy_data;
671
672         copy_data.region = region;
673         copy_data.offset = offset;
674         copy_data.size = size;
675
676         if (!info->transform_func (dest, meta, src,
677                 _gst_meta_transform_copy, &copy_data)) {
678           GST_CAT_ERROR (GST_CAT_BUFFER,
679               "failed to copy meta %p of API type %s", meta,
680               g_type_name (info->api));
681         }
682       }
683     }
684   }
685
686   return TRUE;
687 }
688
689 static GstBuffer *
690 gst_buffer_copy_with_flags (const GstBuffer * buffer, GstBufferCopyFlags flags)
691 {
692   GstBuffer *copy;
693
694   g_return_val_if_fail (buffer != NULL, NULL);
695
696   /* create a fresh new buffer */
697   copy = gst_buffer_new ();
698
699   /* copy what the 'flags' want from our parent */
700   /* FIXME why we can't pass const to gst_buffer_copy_into() ? */
701   if (!gst_buffer_copy_into (copy, (GstBuffer *) buffer, flags, 0, -1))
702     gst_buffer_replace (&copy, NULL);
703
704   if (copy)
705     GST_BUFFER_FLAG_UNSET (copy, GST_BUFFER_FLAG_TAG_MEMORY);
706
707   return copy;
708 }
709
710 static GstBuffer *
711 _gst_buffer_copy (const GstBuffer * buffer)
712 {
713   return gst_buffer_copy_with_flags (buffer, GST_BUFFER_COPY_ALL);
714 }
715
716 /**
717  * gst_buffer_copy_deep:
718  * @buf: a #GstBuffer.
719  *
720  * Create a copy of the given buffer. This will make a newly allocated
721  * copy of the data the source buffer contains.
722  *
723  * Returns: (transfer full): a new copy of @buf.
724  *
725  * Since: 1.6
726  */
727 GstBuffer *
728 gst_buffer_copy_deep (const GstBuffer * buffer)
729 {
730   return gst_buffer_copy_with_flags (buffer,
731       GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP);
732 }
733
734 /* the default dispose function revives the buffer and returns it to the
735  * pool when there is a pool */
736 static gboolean
737 _gst_buffer_dispose (GstBuffer * buffer)
738 {
739   GstBufferPool *pool;
740
741   /* no pool, do free */
742   if ((pool = buffer->pool) == NULL)
743     return TRUE;
744
745   /* keep the buffer alive */
746   gst_buffer_ref (buffer);
747   /* return the buffer to the pool */
748   GST_CAT_LOG (GST_CAT_BUFFER, "release %p to pool %p", buffer, pool);
749   gst_buffer_pool_release_buffer (pool, buffer);
750
751   return FALSE;
752 }
753
754 static void
755 _gst_buffer_free (GstBuffer * buffer)
756 {
757   GstMetaItem *walk, *next;
758   guint i, len;
759   gsize msize;
760
761   g_return_if_fail (buffer != NULL);
762
763   GST_CAT_LOG (GST_CAT_BUFFER, "finalize %p", buffer);
764
765   /* free metadata */
766   for (walk = GST_BUFFER_META (buffer); walk; walk = next) {
767     GstMeta *meta = &walk->meta;
768     const GstMetaInfo *info = meta->info;
769
770     /* call free_func if any */
771     if (info->free_func)
772       info->free_func (meta, buffer);
773
774     next = walk->next;
775     /* and free the slice */
776     g_slice_free1 (ITEM_SIZE (info), walk);
777   }
778
779   /* get the size, when unreffing the memory, we could also unref the buffer
780    * itself */
781   msize = GST_BUFFER_SLICE_SIZE (buffer);
782
783   /* free our memory */
784   len = GST_BUFFER_MEM_LEN (buffer);
785   for (i = 0; i < len; i++) {
786     gst_memory_unlock (GST_BUFFER_MEM_PTR (buffer, i), GST_LOCK_FLAG_EXCLUSIVE);
787     gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (GST_BUFFER_MEM_PTR
788             (buffer, i)), GST_MINI_OBJECT_CAST (buffer));
789     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
790   }
791
792   /* we set msize to 0 when the buffer is part of the memory block */
793   if (msize) {
794 #ifdef USE_POISONING
795     memset (buffer, 0xff, msize);
796 #endif
797     g_slice_free1 (msize, buffer);
798   } else {
799     gst_memory_unref (GST_BUFFER_BUFMEM (buffer));
800   }
801 }
802
803 static void
804 gst_buffer_init (GstBufferImpl * buffer, gsize size)
805 {
806   gst_mini_object_init (GST_MINI_OBJECT_CAST (buffer), 0, _gst_buffer_type,
807       (GstMiniObjectCopyFunction) _gst_buffer_copy,
808       (GstMiniObjectDisposeFunction) _gst_buffer_dispose,
809       (GstMiniObjectFreeFunction) _gst_buffer_free);
810
811   GST_BUFFER_SLICE_SIZE (buffer) = size;
812
813   GST_BUFFER (buffer)->pool = NULL;
814   GST_BUFFER_PTS (buffer) = GST_CLOCK_TIME_NONE;
815   GST_BUFFER_DTS (buffer) = GST_CLOCK_TIME_NONE;
816   GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
817   GST_BUFFER_OFFSET (buffer) = GST_BUFFER_OFFSET_NONE;
818   GST_BUFFER_OFFSET_END (buffer) = GST_BUFFER_OFFSET_NONE;
819
820   GST_BUFFER_MEM_LEN (buffer) = 0;
821   GST_BUFFER_META (buffer) = NULL;
822 }
823
824 /**
825  * gst_buffer_new:
826  *
827  * Creates a newly allocated buffer without any data.
828  *
829  * MT safe.
830  *
831  * Returns: (transfer full): the new #GstBuffer.
832  */
833 GstBuffer *
834 gst_buffer_new (void)
835 {
836   GstBufferImpl *newbuf;
837
838   newbuf = g_slice_new (GstBufferImpl);
839   GST_CAT_LOG (GST_CAT_BUFFER, "new %p", newbuf);
840
841   gst_buffer_init (newbuf, sizeof (GstBufferImpl));
842
843   return GST_BUFFER_CAST (newbuf);
844 }
845
846 /**
847  * gst_buffer_new_allocate:
848  * @allocator: (transfer none) (allow-none): the #GstAllocator to use, or %NULL to use the
849  *     default allocator
850  * @size: the size in bytes of the new buffer's data.
851  * @params: (transfer none) (allow-none): optional parameters
852  *
853  * Tries to create a newly allocated buffer with data of the given size and
854  * extra parameters from @allocator. If the requested amount of memory can't be
855  * allocated, %NULL will be returned. The allocated buffer memory is not cleared.
856  *
857  * When @allocator is %NULL, the default memory allocator will be used.
858  *
859  * Note that when @size == 0, the buffer will not have memory associated with it.
860  *
861  * MT safe.
862  *
863  * Returns: (transfer full) (nullable): a new #GstBuffer, or %NULL if
864  *     the memory couldn't be allocated.
865  */
866 GstBuffer *
867 gst_buffer_new_allocate (GstAllocator * allocator, gsize size,
868     GstAllocationParams * params)
869 {
870   GstBuffer *newbuf;
871   GstMemory *mem;
872 #if 0
873   guint8 *data;
874   gsize asize;
875 #endif
876
877 #if 1
878   if (size > 0) {
879     mem = gst_allocator_alloc (allocator, size, params);
880     if (G_UNLIKELY (mem == NULL))
881       goto no_memory;
882   } else {
883     mem = NULL;
884   }
885
886   newbuf = gst_buffer_new ();
887
888   if (mem != NULL) {
889     gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
890     _memory_add (newbuf, -1, mem);
891   }
892
893   GST_CAT_LOG (GST_CAT_BUFFER,
894       "new buffer %p of size %" G_GSIZE_FORMAT " from allocator %p", newbuf,
895       size, allocator);
896 #endif
897
898 #if 0
899   asize = sizeof (GstBufferImpl) + size;
900   data = g_slice_alloc (asize);
901   if (G_UNLIKELY (data == NULL))
902     goto no_memory;
903
904   newbuf = GST_BUFFER_CAST (data);
905
906   gst_buffer_init ((GstBufferImpl *) data, asize);
907   if (size > 0) {
908     mem = gst_memory_new_wrapped (0, data + sizeof (GstBufferImpl), NULL,
909         size, 0, size);
910     _memory_add (newbuf, -1, mem, TRUE);
911   }
912 #endif
913
914 #if 0
915   /* allocate memory and buffer, it might be interesting to do this but there
916    * are many complications. We need to keep the memory mapped to access the
917    * buffer fields and the memory for the buffer might be just very slow. We
918    * also need to do some more magic to get the alignment right. */
919   asize = sizeof (GstBufferImpl) + size;
920   mem = gst_allocator_alloc (allocator, asize, align);
921   if (G_UNLIKELY (mem == NULL))
922     goto no_memory;
923
924   /* map the data part and init the buffer in it, set the buffer size to 0 so
925    * that a finalize won't free the buffer */
926   data = gst_memory_map (mem, &asize, NULL, GST_MAP_WRITE);
927   gst_buffer_init ((GstBufferImpl *) data, 0);
928   gst_memory_unmap (mem);
929
930   /* strip off the buffer */
931   gst_memory_resize (mem, sizeof (GstBufferImpl), size);
932
933   newbuf = GST_BUFFER_CAST (data);
934   GST_BUFFER_BUFMEM (newbuf) = mem;
935
936   if (size > 0)
937     _memory_add (newbuf, -1, gst_memory_ref (mem), TRUE);
938 #endif
939   GST_BUFFER_FLAG_UNSET (newbuf, GST_BUFFER_FLAG_TAG_MEMORY);
940
941   return newbuf;
942
943   /* ERRORS */
944 no_memory:
945   {
946     GST_CAT_WARNING (GST_CAT_BUFFER,
947         "failed to allocate %" G_GSIZE_FORMAT " bytes", size);
948     return NULL;
949   }
950 }
951
952 /**
953  * gst_buffer_new_wrapped_full:
954  * @flags: #GstMemoryFlags
955  * @data: (array length=size) (element-type guint8) (transfer none): data to wrap
956  * @maxsize: allocated size of @data
957  * @offset: offset in @data
958  * @size: size of valid data
959  * @user_data: (allow-none): user_data
960  * @notify: (allow-none) (scope async) (closure user_data): called with @user_data when the memory is freed
961  *
962  * Allocate a new buffer that wraps the given memory. @data must point to
963  * @maxsize of memory, the wrapped buffer will have the region from @offset and
964  * @size visible.
965  *
966  * When the buffer is destroyed, @notify will be called with @user_data.
967  *
968  * The prefix/padding must be filled with 0 if @flags contains
969  * #GST_MEMORY_FLAG_ZERO_PREFIXED and #GST_MEMORY_FLAG_ZERO_PADDED respectively.
970  *
971  * Returns: (transfer full): a new #GstBuffer
972  */
973 GstBuffer *
974 gst_buffer_new_wrapped_full (GstMemoryFlags flags, gpointer data,
975     gsize maxsize, gsize offset, gsize size, gpointer user_data,
976     GDestroyNotify notify)
977 {
978   GstMemory *mem;
979   GstBuffer *newbuf;
980
981   newbuf = gst_buffer_new ();
982   mem =
983       gst_memory_new_wrapped (flags, data, maxsize, offset, size, user_data,
984       notify);
985   gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
986   _memory_add (newbuf, -1, mem);
987   GST_BUFFER_FLAG_UNSET (newbuf, GST_BUFFER_FLAG_TAG_MEMORY);
988
989   return newbuf;
990 }
991
992 /**
993  * gst_buffer_new_wrapped:
994  * @data: (array length=size) (element-type guint8) (transfer full): data to wrap
995  * @size: allocated size of @data
996  *
997  * Creates a new buffer that wraps the given @data. The memory will be freed
998  * with g_free and will be marked writable.
999  *
1000  * MT safe.
1001  *
1002  * Returns: (transfer full): a new #GstBuffer
1003  */
1004 GstBuffer *
1005 gst_buffer_new_wrapped (gpointer data, gsize size)
1006 {
1007   return gst_buffer_new_wrapped_full (0, data, size, 0, size, data, g_free);
1008 }
1009
1010 /**
1011  * gst_buffer_new_wrapped_bytes:
1012  * @bytes: (transfer none): a #GBytes to wrap
1013  *
1014  * Creates a new #GstBuffer that wraps the given @bytes. The data inside
1015  * @bytes cannot be %NULL and the resulting buffer will be marked as read only.
1016  *
1017  * MT safe.
1018  *
1019  * Returns: (transfer full): a new #GstBuffer wrapping @bytes
1020  *
1021  * Since: 1.16
1022  */
1023 GstBuffer *
1024 gst_buffer_new_wrapped_bytes (GBytes * bytes)
1025 {
1026   guint8 *bytes_data;
1027   gsize size;
1028
1029   g_return_val_if_fail (bytes != NULL, NULL);
1030   bytes_data = (guint8 *) g_bytes_get_data (bytes, &size);
1031   g_return_val_if_fail (bytes_data != NULL, NULL);
1032
1033   return gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, bytes_data,
1034       size, 0, size, g_bytes_ref (bytes), (GDestroyNotify) g_bytes_unref);
1035 }
1036
1037 /**
1038  * gst_buffer_n_memory:
1039  * @buffer: a #GstBuffer.
1040  *
1041  * Get the amount of memory blocks that this buffer has. This amount is never
1042  * larger than what gst_buffer_get_max_memory() returns.
1043  *
1044  * Returns: the number of memory blocks this buffer is made of.
1045  */
1046 guint
1047 gst_buffer_n_memory (GstBuffer * buffer)
1048 {
1049   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1050
1051   return GST_BUFFER_MEM_LEN (buffer);
1052 }
1053
1054 /**
1055  * gst_buffer_prepend_memory:
1056  * @buffer: a #GstBuffer.
1057  * @mem: (transfer full): a #GstMemory.
1058  *
1059  * Prepend the memory block @mem to @buffer. This function takes
1060  * ownership of @mem and thus doesn't increase its refcount.
1061  *
1062  * This function is identical to gst_buffer_insert_memory() with an index of 0.
1063  * See gst_buffer_insert_memory() for more details.
1064  */
1065 void
1066 gst_buffer_prepend_memory (GstBuffer * buffer, GstMemory * mem)
1067 {
1068   gst_buffer_insert_memory (buffer, 0, mem);
1069 }
1070
1071 /**
1072  * gst_buffer_append_memory:
1073  * @buffer: a #GstBuffer.
1074  * @mem: (transfer full): a #GstMemory.
1075  *
1076  * Append the memory block @mem to @buffer. This function takes
1077  * ownership of @mem and thus doesn't increase its refcount.
1078  *
1079  * This function is identical to gst_buffer_insert_memory() with an index of -1.
1080  * See gst_buffer_insert_memory() for more details.
1081  */
1082 void
1083 gst_buffer_append_memory (GstBuffer * buffer, GstMemory * mem)
1084 {
1085   gst_buffer_insert_memory (buffer, -1, mem);
1086 }
1087
1088 /**
1089  * gst_buffer_insert_memory:
1090  * @buffer: a #GstBuffer.
1091  * @idx: the index to add the memory at, or -1 to append it to the end
1092  * @mem: (transfer full): a #GstMemory.
1093  *
1094  * Insert the memory block @mem to @buffer at @idx. This function takes ownership
1095  * of @mem and thus doesn't increase its refcount.
1096  *
1097  * Only gst_buffer_get_max_memory() can be added to a buffer. If more memory is
1098  * added, existing memory blocks will automatically be merged to make room for
1099  * the new memory.
1100  */
1101 void
1102 gst_buffer_insert_memory (GstBuffer * buffer, gint idx, GstMemory * mem)
1103 {
1104   GstMemory *tmp;
1105
1106   g_return_if_fail (GST_IS_BUFFER (buffer));
1107   g_return_if_fail (gst_buffer_is_writable (buffer));
1108   g_return_if_fail (mem != NULL);
1109   g_return_if_fail (idx == -1 ||
1110       (idx >= 0 && idx <= GST_BUFFER_MEM_LEN (buffer)));
1111
1112   tmp = _memory_get_exclusive_reference (mem);
1113   g_return_if_fail (tmp != NULL);
1114   gst_memory_unref (mem);
1115   _memory_add (buffer, idx, tmp);
1116 }
1117
1118 static GstMemory *
1119 _get_mapped (GstBuffer * buffer, guint idx, GstMapInfo * info,
1120     GstMapFlags flags)
1121 {
1122   GstMemory *mem, *mapped;
1123
1124   mem = gst_memory_ref (GST_BUFFER_MEM_PTR (buffer, idx));
1125
1126   mapped = gst_memory_make_mapped (mem, info, flags);
1127
1128   if (mapped != mem) {
1129     /* memory changed, lock new memory */
1130     gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (mapped),
1131         GST_MINI_OBJECT_CAST (buffer));
1132     gst_memory_lock (mapped, GST_LOCK_FLAG_EXCLUSIVE);
1133     GST_BUFFER_MEM_PTR (buffer, idx) = mapped;
1134     /* unlock old memory */
1135     gst_memory_unlock (mem, GST_LOCK_FLAG_EXCLUSIVE);
1136     gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
1137         GST_MINI_OBJECT_CAST (buffer));
1138     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1139   }
1140   gst_memory_unref (mem);
1141
1142   return mapped;
1143 }
1144
1145 /**
1146  * gst_buffer_peek_memory:
1147  * @buffer: a #GstBuffer.
1148  * @idx: an index
1149  *
1150  * Get the memory block at @idx in @buffer. The memory block stays valid until
1151  * the memory block in @buffer is removed, replaced or merged, typically with
1152  * any call that modifies the memory in @buffer.
1153  *
1154  * Returns: (transfer none) (nullable): the #GstMemory at @idx.
1155  */
1156 GstMemory *
1157 gst_buffer_peek_memory (GstBuffer * buffer, guint idx)
1158 {
1159   guint len;
1160
1161   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
1162   len = GST_BUFFER_MEM_LEN (buffer);
1163   g_return_val_if_fail (idx < len, NULL);
1164
1165   return GST_BUFFER_MEM_PTR (buffer, idx);
1166 }
1167
1168 /**
1169  * gst_buffer_get_memory:
1170  * @buffer: a #GstBuffer.
1171  * @idx: an index
1172  *
1173  * Get the memory block at index @idx in @buffer.
1174  *
1175  * Returns: (transfer full) (nullable): a #GstMemory that contains the data of the
1176  * memory block at @idx. Use gst_memory_unref () after usage.
1177  */
1178 GstMemory *
1179 gst_buffer_get_memory (GstBuffer * buffer, guint idx)
1180 {
1181   return gst_buffer_get_memory_range (buffer, idx, 1);
1182 }
1183
1184 /**
1185  * gst_buffer_get_all_memory:
1186  * @buffer: a #GstBuffer.
1187  *
1188  * Get all the memory block in @buffer. The memory blocks will be merged
1189  * into one large #GstMemory.
1190  *
1191  * Returns: (transfer full) (nullable): a #GstMemory that contains the merged memory.
1192  * Use gst_memory_unref () after usage.
1193  */
1194 GstMemory *
1195 gst_buffer_get_all_memory (GstBuffer * buffer)
1196 {
1197   return gst_buffer_get_memory_range (buffer, 0, -1);
1198 }
1199
1200 /**
1201  * gst_buffer_get_memory_range:
1202  * @buffer: a #GstBuffer.
1203  * @idx: an index
1204  * @length: a length
1205  *
1206  * Get @length memory blocks in @buffer starting at @idx. The memory blocks will
1207  * be merged into one large #GstMemory.
1208  *
1209  * If @length is -1, all memory starting from @idx is merged.
1210  *
1211  * Returns: (transfer full) (nullable): a #GstMemory that contains the merged data of @length
1212  *    blocks starting at @idx. Use gst_memory_unref () after usage.
1213  */
1214 GstMemory *
1215 gst_buffer_get_memory_range (GstBuffer * buffer, guint idx, gint length)
1216 {
1217   guint len;
1218
1219   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d", idx, length);
1220
1221   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
1222   len = GST_BUFFER_MEM_LEN (buffer);
1223   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1224       (length == -1 && idx < len) || (length > 0 && length + idx <= len), NULL);
1225
1226   if (length == -1)
1227     length = len - idx;
1228
1229   return _get_merged_memory (buffer, idx, length);
1230 }
1231
1232 /**
1233  * gst_buffer_replace_memory:
1234  * @buffer: a #GstBuffer.
1235  * @idx: an index
1236  * @mem: (transfer full): a #GstMemory
1237  *
1238  * Replaces the memory block at index @idx in @buffer with @mem.
1239  */
1240 void
1241 gst_buffer_replace_memory (GstBuffer * buffer, guint idx, GstMemory * mem)
1242 {
1243   gst_buffer_replace_memory_range (buffer, idx, 1, mem);
1244 }
1245
1246 /**
1247  * gst_buffer_replace_all_memory:
1248  * @buffer: a #GstBuffer.
1249  * @mem: (transfer full): a #GstMemory
1250  *
1251  * Replaces all memory in @buffer with @mem.
1252  */
1253 void
1254 gst_buffer_replace_all_memory (GstBuffer * buffer, GstMemory * mem)
1255 {
1256   gst_buffer_replace_memory_range (buffer, 0, -1, mem);
1257 }
1258
1259 /**
1260  * gst_buffer_replace_memory_range:
1261  * @buffer: a #GstBuffer.
1262  * @idx: an index
1263  * @length: a length should not be 0
1264  * @mem: (transfer full): a #GstMemory
1265  *
1266  * Replaces @length memory blocks in @buffer starting at @idx with @mem.
1267  *
1268  * If @length is -1, all memory starting from @idx will be removed and
1269  * replaced with @mem.
1270  *
1271  * @buffer should be writable.
1272  */
1273 void
1274 gst_buffer_replace_memory_range (GstBuffer * buffer, guint idx, gint length,
1275     GstMemory * mem)
1276 {
1277   guint len;
1278
1279   g_return_if_fail (GST_IS_BUFFER (buffer));
1280   g_return_if_fail (gst_buffer_is_writable (buffer));
1281
1282   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d, %p", idx, length, mem);
1283
1284   len = GST_BUFFER_MEM_LEN (buffer);
1285   g_return_if_fail ((len == 0 && idx == 0 && length == -1) ||
1286       (length == -1 && idx < len) || (length > 0 && length + idx <= len));
1287
1288   if (length == -1)
1289     length = len - idx;
1290
1291   _replace_memory (buffer, len, idx, length, mem);
1292 }
1293
1294 /**
1295  * gst_buffer_remove_memory:
1296  * @buffer: a #GstBuffer.
1297  * @idx: an index
1298  *
1299  * Remove the memory block in @b at index @i.
1300  */
1301 void
1302 gst_buffer_remove_memory (GstBuffer * buffer, guint idx)
1303 {
1304   gst_buffer_remove_memory_range (buffer, idx, 1);
1305 }
1306
1307 /**
1308  * gst_buffer_remove_all_memory:
1309  * @buffer: a #GstBuffer.
1310  *
1311  * Remove all the memory blocks in @buffer.
1312  */
1313 void
1314 gst_buffer_remove_all_memory (GstBuffer * buffer)
1315 {
1316   gst_buffer_remove_memory_range (buffer, 0, -1);
1317 }
1318
1319 /**
1320  * gst_buffer_remove_memory_range:
1321  * @buffer: a #GstBuffer.
1322  * @idx: an index
1323  * @length: a length
1324  *
1325  * Remove @length memory blocks in @buffer starting from @idx.
1326  *
1327  * @length can be -1, in which case all memory starting from @idx is removed.
1328  */
1329 void
1330 gst_buffer_remove_memory_range (GstBuffer * buffer, guint idx, gint length)
1331 {
1332   guint len;
1333
1334   g_return_if_fail (GST_IS_BUFFER (buffer));
1335   g_return_if_fail (gst_buffer_is_writable (buffer));
1336
1337   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d", idx, length);
1338
1339   len = GST_BUFFER_MEM_LEN (buffer);
1340   g_return_if_fail ((len == 0 && idx == 0 && length == -1) ||
1341       (length == -1 && idx < len) || length + idx <= len);
1342
1343   if (length == -1)
1344     length = len - idx;
1345
1346   _replace_memory (buffer, len, idx, length, NULL);
1347 }
1348
1349 /**
1350  * gst_buffer_find_memory:
1351  * @buffer: a #GstBuffer.
1352  * @offset: an offset
1353  * @size: a size
1354  * @idx: (out): pointer to index
1355  * @length: (out): pointer to length
1356  * @skip: (out): pointer to skip
1357  *
1358  * Find the memory blocks that span @size bytes starting from @offset
1359  * in @buffer.
1360  *
1361  * When this function returns %TRUE, @idx will contain the index of the first
1362  * memory block where the byte for @offset can be found and @length contains the
1363  * number of memory blocks containing the @size remaining bytes. @skip contains
1364  * the number of bytes to skip in the memory block at @idx to get to the byte
1365  * for @offset.
1366  *
1367  * @size can be -1 to get all the memory blocks after @idx.
1368  *
1369  * Returns: %TRUE when @size bytes starting from @offset could be found in
1370  * @buffer and @idx, @length and @skip will be filled.
1371  */
1372 gboolean
1373 gst_buffer_find_memory (GstBuffer * buffer, gsize offset, gsize size,
1374     guint * idx, guint * length, gsize * skip)
1375 {
1376   guint i, len, found;
1377
1378   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1379   g_return_val_if_fail (idx != NULL, FALSE);
1380   g_return_val_if_fail (length != NULL, FALSE);
1381   g_return_val_if_fail (skip != NULL, FALSE);
1382
1383   len = GST_BUFFER_MEM_LEN (buffer);
1384
1385   found = 0;
1386   for (i = 0; i < len; i++) {
1387     GstMemory *mem;
1388     gsize s;
1389
1390     mem = GST_BUFFER_MEM_PTR (buffer, i);
1391     s = gst_memory_get_sizes (mem, NULL, NULL);
1392
1393     if (s <= offset) {
1394       /* block before offset, or empty block, skip */
1395       offset -= s;
1396     } else {
1397       /* block after offset */
1398       if (found == 0) {
1399         /* first block, remember index and offset */
1400         *idx = i;
1401         *skip = offset;
1402         if (size == -1) {
1403           /* return remaining blocks */
1404           *length = len - i;
1405           return TRUE;
1406         }
1407         s -= offset;
1408         offset = 0;
1409       }
1410       /* count the amount of found bytes */
1411       found += s;
1412       if (found >= size) {
1413         /* we have enough bytes */
1414         *length = i - *idx + 1;
1415         return TRUE;
1416       }
1417     }
1418   }
1419   return FALSE;
1420 }
1421
1422 /**
1423  * gst_buffer_is_memory_range_writable:
1424  * @buffer: a #GstBuffer.
1425  * @idx: an index
1426  * @length: a length should not be 0
1427  *
1428  * Check if @length memory blocks in @buffer starting from @idx are writable.
1429  *
1430  * @length can be -1 to check all the memory blocks after @idx.
1431  *
1432  * Note that this function does not check if @buffer is writable, use
1433  * gst_buffer_is_writable() to check that if needed.
1434  *
1435  * Returns: %TRUE if the memory range is writable
1436  *
1437  * Since: 1.4
1438  */
1439 gboolean
1440 gst_buffer_is_memory_range_writable (GstBuffer * buffer, guint idx, gint length)
1441 {
1442   guint i, len;
1443
1444   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1445
1446   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d", idx, length);
1447
1448   len = GST_BUFFER_MEM_LEN (buffer);
1449   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1450       (length == -1 && idx < len) || (length > 0 && length + idx <= len),
1451       FALSE);
1452
1453   if (length == -1)
1454     len -= idx;
1455   else
1456     len = length;
1457
1458   for (i = 0; i < len; i++) {
1459     if (!gst_memory_is_writable (GST_BUFFER_MEM_PTR (buffer, i + idx)))
1460       return FALSE;
1461   }
1462   return TRUE;
1463 }
1464
1465 /**
1466  * gst_buffer_is_all_memory_writable:
1467  * @buffer: a #GstBuffer.
1468  *
1469  * Check if all memory blocks in @buffer are writable.
1470  *
1471  * Note that this function does not check if @buffer is writable, use
1472  * gst_buffer_is_writable() to check that if needed.
1473  *
1474  * Returns: %TRUE if all memory blocks in @buffer are writable
1475  *
1476  * Since: 1.4
1477  */
1478 gboolean
1479 gst_buffer_is_all_memory_writable (GstBuffer * buffer)
1480 {
1481   return gst_buffer_is_memory_range_writable (buffer, 0, -1);
1482 }
1483
1484 /**
1485  * gst_buffer_get_sizes:
1486  * @buffer: a #GstBuffer.
1487  * @offset: (out) (allow-none): a pointer to the offset
1488  * @maxsize: (out) (allow-none): a pointer to the maxsize
1489  *
1490  * Get the total size of the memory blocks in @b.
1491  *
1492  * When not %NULL, @offset will contain the offset of the data in the
1493  * first memory block in @buffer and @maxsize will contain the sum of
1494  * the size and @offset and the amount of extra padding on the last
1495  * memory block.  @offset and @maxsize can be used to resize the
1496  * buffer memory blocks with gst_buffer_resize().
1497  *
1498  * Returns: total size of the memory blocks in @buffer.
1499  */
1500 gsize
1501 gst_buffer_get_sizes (GstBuffer * buffer, gsize * offset, gsize * maxsize)
1502 {
1503   return gst_buffer_get_sizes_range (buffer, 0, -1, offset, maxsize);
1504 }
1505
1506 /**
1507  * gst_buffer_get_size:
1508  * @buffer: a #GstBuffer.
1509  *
1510  * Get the total size of the memory blocks in @buffer.
1511  *
1512  * Returns: total size of the memory blocks in @buffer.
1513  */
1514 gsize
1515 gst_buffer_get_size (GstBuffer * buffer)
1516 {
1517   return gst_buffer_get_sizes_range (buffer, 0, -1, NULL, NULL);
1518 }
1519
1520 /**
1521  * gst_buffer_get_sizes_range:
1522  * @buffer: a #GstBuffer.
1523  * @idx: an index
1524  * @length: a length
1525  * @offset: (out) (allow-none): a pointer to the offset
1526  * @maxsize: (out) (allow-none): a pointer to the maxsize
1527  *
1528  * Get the total size of @length memory blocks stating from @idx in @buffer.
1529  *
1530  * When not %NULL, @offset will contain the offset of the data in the
1531  * memory block in @buffer at @idx and @maxsize will contain the sum of the size
1532  * and @offset and the amount of extra padding on the memory block at @idx +
1533  * @length -1.
1534  * @offset and @maxsize can be used to resize the buffer memory blocks with
1535  * gst_buffer_resize_range().
1536  *
1537  * Returns: total size of @length memory blocks starting at @idx in @buffer.
1538  */
1539 gsize
1540 gst_buffer_get_sizes_range (GstBuffer * buffer, guint idx, gint length,
1541     gsize * offset, gsize * maxsize)
1542 {
1543   guint len;
1544   gsize size;
1545   GstMemory *mem;
1546
1547   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1548   len = GST_BUFFER_MEM_LEN (buffer);
1549   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1550       (length == -1 && idx < len) || (length + idx <= len), 0);
1551
1552   if (length == -1)
1553     length = len - idx;
1554
1555   if (G_LIKELY (length == 1)) {
1556     /* common case */
1557     mem = GST_BUFFER_MEM_PTR (buffer, idx);
1558     size = gst_memory_get_sizes (mem, offset, maxsize);
1559   } else {
1560     guint i, end;
1561     gsize extra, offs;
1562
1563     end = idx + length;
1564     size = offs = extra = 0;
1565     for (i = idx; i < end; i++) {
1566       gsize s, o, ms;
1567
1568       mem = GST_BUFFER_MEM_PTR (buffer, i);
1569       s = gst_memory_get_sizes (mem, &o, &ms);
1570
1571       if (s) {
1572         if (size == 0)
1573           /* first size, take accumulated data before as the offset */
1574           offs = extra + o;
1575         /* add sizes */
1576         size += s;
1577         /* save the amount of data after this block */
1578         extra = ms - (o + s);
1579       } else {
1580         /* empty block, add as extra */
1581         extra += ms;
1582       }
1583     }
1584     if (offset)
1585       *offset = offs;
1586     if (maxsize)
1587       *maxsize = offs + size + extra;
1588   }
1589   return size;
1590 }
1591
1592 /**
1593  * gst_buffer_resize:
1594  * @buffer: a #GstBuffer.
1595  * @offset: the offset adjustment
1596  * @size: the new size or -1 to just adjust the offset
1597  *
1598  * Set the offset and total size of the memory blocks in @buffer.
1599  */
1600 void
1601 gst_buffer_resize (GstBuffer * buffer, gssize offset, gssize size)
1602 {
1603   gst_buffer_resize_range (buffer, 0, -1, offset, size);
1604 }
1605
1606 /**
1607  * gst_buffer_set_size:
1608  * @buffer: a #GstBuffer.
1609  * @size: the new size
1610  *
1611  * Set the total size of the memory blocks in @buffer.
1612  */
1613 void
1614 gst_buffer_set_size (GstBuffer * buffer, gssize size)
1615 {
1616   gst_buffer_resize_range (buffer, 0, -1, 0, size);
1617 }
1618
1619 /**
1620  * gst_buffer_resize_range:
1621  * @buffer: a #GstBuffer.
1622  * @idx: an index
1623  * @length: a length
1624  * @offset: the offset adjustment
1625  * @size: the new size or -1 to just adjust the offset
1626  *
1627  * Set the total size of the @length memory blocks starting at @idx in
1628  * @buffer
1629  *
1630  * Returns: %TRUE if resizing succeeded, %FALSE otherwise.
1631  */
1632 gboolean
1633 gst_buffer_resize_range (GstBuffer * buffer, guint idx, gint length,
1634     gssize offset, gssize size)
1635 {
1636   guint i, len, end;
1637   gsize bsize, bufsize, bufoffs, bufmax;
1638
1639   g_return_val_if_fail (gst_buffer_is_writable (buffer), FALSE);
1640   g_return_val_if_fail (size >= -1, FALSE);
1641
1642   len = GST_BUFFER_MEM_LEN (buffer);
1643   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1644       (length == -1 && idx < len) || (length + idx <= len), FALSE);
1645
1646   if (length == -1)
1647     length = len - idx;
1648
1649   bufsize = gst_buffer_get_sizes_range (buffer, idx, length, &bufoffs, &bufmax);
1650
1651   GST_CAT_LOG (GST_CAT_BUFFER, "trim %p %" G_GSSIZE_FORMAT "-%" G_GSSIZE_FORMAT
1652       " size:%" G_GSIZE_FORMAT " offs:%" G_GSIZE_FORMAT " max:%"
1653       G_GSIZE_FORMAT, buffer, offset, size, bufsize, bufoffs, bufmax);
1654
1655   /* we can't go back further than the current offset or past the end of the
1656    * buffer */
1657   g_return_val_if_fail ((offset < 0 && bufoffs >= -offset) || (offset >= 0
1658           && bufoffs + offset <= bufmax), FALSE);
1659   if (size == -1) {
1660     g_return_val_if_fail (bufsize >= offset, FALSE);
1661     size = bufsize - offset;
1662   }
1663   g_return_val_if_fail (bufmax >= bufoffs + offset + size, FALSE);
1664
1665   /* no change */
1666   if (offset == 0 && size == bufsize)
1667     return TRUE;
1668
1669   end = idx + length;
1670   /* copy and trim */
1671   for (i = idx; i < end; i++) {
1672     GstMemory *mem;
1673     gsize left, noffs;
1674
1675     mem = GST_BUFFER_MEM_PTR (buffer, i);
1676     bsize = gst_memory_get_sizes (mem, NULL, NULL);
1677
1678     noffs = 0;
1679     /* last buffer always gets resized to the remaining size */
1680     if (i + 1 == end)
1681       left = size;
1682     /* shrink buffers before the offset */
1683     else if ((gssize) bsize <= offset) {
1684       left = 0;
1685       noffs = offset - bsize;
1686       offset = 0;
1687     }
1688     /* clip other buffers */
1689     else
1690       left = MIN (bsize - offset, size);
1691
1692     if (offset != 0 || left != bsize) {
1693       if (gst_memory_is_writable (mem)) {
1694         gst_memory_resize (mem, offset, left);
1695       } else {
1696         GstMemory *newmem = NULL;
1697
1698         if (!GST_MEMORY_IS_NO_SHARE (mem))
1699           newmem = gst_memory_share (mem, offset, left);
1700
1701         if (!newmem)
1702           newmem = gst_memory_copy (mem, offset, left);
1703
1704         if (newmem == NULL)
1705           return FALSE;
1706
1707         gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (newmem),
1708             GST_MINI_OBJECT_CAST (buffer));
1709         gst_memory_lock (newmem, GST_LOCK_FLAG_EXCLUSIVE);
1710         GST_BUFFER_MEM_PTR (buffer, i) = newmem;
1711         gst_memory_unlock (mem, GST_LOCK_FLAG_EXCLUSIVE);
1712         gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
1713             GST_MINI_OBJECT_CAST (buffer));
1714         gst_memory_unref (mem);
1715
1716         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1717       }
1718     }
1719
1720     offset = noffs;
1721     size -= left;
1722   }
1723
1724   return TRUE;
1725 }
1726
1727 /**
1728  * gst_buffer_map:
1729  * @buffer: a #GstBuffer.
1730  * @info: (out): info about the mapping
1731  * @flags: flags for the mapping
1732  *
1733  * This function fills @info with the #GstMapInfo of all merged memory
1734  * blocks in @buffer.
1735  *
1736  * @flags describe the desired access of the memory. When @flags is
1737  * #GST_MAP_WRITE, @buffer should be writable (as returned from
1738  * gst_buffer_is_writable()).
1739  *
1740  * When @buffer is writable but the memory isn't, a writable copy will
1741  * automatically be created and returned. The readonly copy of the
1742  * buffer memory will then also be replaced with this writable copy.
1743  *
1744  * The memory in @info should be unmapped with gst_buffer_unmap() after
1745  * usage.
1746  *
1747  * Returns: %TRUE if the map succeeded and @info contains valid data.
1748  */
1749 gboolean
1750 gst_buffer_map (GstBuffer * buffer, GstMapInfo * info, GstMapFlags flags)
1751 {
1752   return gst_buffer_map_range (buffer, 0, -1, info, flags);
1753 }
1754
1755 /**
1756  * gst_buffer_map_range:
1757  * @buffer: a #GstBuffer.
1758  * @idx: an index
1759  * @length: a length
1760  * @info: (out): info about the mapping
1761  * @flags: flags for the mapping
1762  *
1763  * This function fills @info with the #GstMapInfo of @length merged memory blocks
1764  * starting at @idx in @buffer. When @length is -1, all memory blocks starting
1765  * from @idx are merged and mapped.
1766  *
1767  * @flags describe the desired access of the memory. When @flags is
1768  * #GST_MAP_WRITE, @buffer should be writable (as returned from
1769  * gst_buffer_is_writable()).
1770  *
1771  * When @buffer is writable but the memory isn't, a writable copy will
1772  * automatically be created and returned. The readonly copy of the buffer memory
1773  * will then also be replaced with this writable copy.
1774  *
1775  * The memory in @info should be unmapped with gst_buffer_unmap() after usage.
1776  *
1777  * Returns: %TRUE if the map succeeded and @info contains valid
1778  * data.
1779  */
1780 gboolean
1781 gst_buffer_map_range (GstBuffer * buffer, guint idx, gint length,
1782     GstMapInfo * info, GstMapFlags flags)
1783 {
1784   GstMemory *mem, *nmem;
1785   gboolean write, writable;
1786   gsize len;
1787
1788   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1789   g_return_val_if_fail (info != NULL, FALSE);
1790   len = GST_BUFFER_MEM_LEN (buffer);
1791   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1792       (length == -1 && idx < len) || (length > 0
1793           && length + idx <= len), FALSE);
1794
1795   GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %u, length %d, flags %04x",
1796       buffer, idx, length, flags);
1797
1798   write = (flags & GST_MAP_WRITE) != 0;
1799   writable = gst_buffer_is_writable (buffer);
1800
1801   /* check if we can write when asked for write access */
1802   if (G_UNLIKELY (write && !writable))
1803     goto not_writable;
1804
1805   if (length == -1)
1806     length = len - idx;
1807
1808   mem = _get_merged_memory (buffer, idx, length);
1809   if (G_UNLIKELY (mem == NULL))
1810     goto no_memory;
1811
1812   /* now try to map */
1813   nmem = gst_memory_make_mapped (mem, info, flags);
1814   if (G_UNLIKELY (nmem == NULL))
1815     goto cannot_map;
1816
1817   /* if we merged or when the map returned a different memory, we try to replace
1818    * the memory in the buffer */
1819   if (G_UNLIKELY (length > 1 || nmem != mem)) {
1820     /* if the buffer is writable, replace the memory */
1821     if (writable) {
1822       _replace_memory (buffer, len, idx, length, gst_memory_ref (nmem));
1823     } else {
1824       if (len > 1) {
1825         GST_CAT_DEBUG (GST_CAT_PERFORMANCE,
1826             "temporary mapping for memory %p in buffer %p", nmem, buffer);
1827       }
1828     }
1829   }
1830   return TRUE;
1831
1832   /* ERROR */
1833 not_writable:
1834   {
1835     GST_WARNING_OBJECT (buffer, "write map requested on non-writable buffer");
1836     g_critical ("write map requested on non-writable buffer");
1837     memset (info, 0, sizeof (GstMapInfo));
1838     return FALSE;
1839   }
1840 no_memory:
1841   {
1842     /* empty buffer, we need to return NULL */
1843     GST_DEBUG_OBJECT (buffer, "can't get buffer memory");
1844     memset (info, 0, sizeof (GstMapInfo));
1845     return TRUE;
1846   }
1847 cannot_map:
1848   {
1849     GST_DEBUG_OBJECT (buffer, "cannot map memory");
1850     memset (info, 0, sizeof (GstMapInfo));
1851     return FALSE;
1852   }
1853 }
1854
1855 /**
1856  * gst_buffer_unmap:
1857  * @buffer: a #GstBuffer.
1858  * @info: a #GstMapInfo
1859  *
1860  * Release the memory previously mapped with gst_buffer_map().
1861  */
1862 void
1863 gst_buffer_unmap (GstBuffer * buffer, GstMapInfo * info)
1864 {
1865   g_return_if_fail (GST_IS_BUFFER (buffer));
1866   g_return_if_fail (info != NULL);
1867
1868   /* we need to check for NULL, it is possible that we tried to map a buffer
1869    * without memory and we should be able to unmap that fine */
1870   if (G_LIKELY (info->memory)) {
1871     gst_memory_unmap (info->memory, info);
1872     gst_memory_unref (info->memory);
1873   }
1874 }
1875
1876 /**
1877  * gst_buffer_fill:
1878  * @buffer: a #GstBuffer.
1879  * @offset: the offset to fill
1880  * @src: (array length=size) (element-type guint8): the source address
1881  * @size: the size to fill
1882  *
1883  * Copy @size bytes from @src to @buffer at @offset.
1884  *
1885  * Returns: The amount of bytes copied. This value can be lower than @size
1886  *    when @buffer did not contain enough data.
1887  */
1888 gsize
1889 gst_buffer_fill (GstBuffer * buffer, gsize offset, gconstpointer src,
1890     gsize size)
1891 {
1892   gsize i, len, left;
1893   const guint8 *ptr = src;
1894
1895   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1896   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1897   g_return_val_if_fail (src != NULL || size == 0, 0);
1898
1899   GST_CAT_LOG (GST_CAT_BUFFER,
1900       "buffer %p, offset %" G_GSIZE_FORMAT ", size %" G_GSIZE_FORMAT, buffer,
1901       offset, size);
1902
1903   len = GST_BUFFER_MEM_LEN (buffer);
1904   left = size;
1905
1906   for (i = 0; i < len && left > 0; i++) {
1907     GstMapInfo info;
1908     gsize tocopy;
1909     GstMemory *mem;
1910
1911     mem = _get_mapped (buffer, i, &info, GST_MAP_WRITE);
1912     if (info.size > offset) {
1913       /* we have enough */
1914       tocopy = MIN (info.size - offset, left);
1915       memcpy ((guint8 *) info.data + offset, ptr, tocopy);
1916       left -= tocopy;
1917       ptr += tocopy;
1918       offset = 0;
1919     } else {
1920       /* offset past buffer, skip */
1921       offset -= info.size;
1922     }
1923     gst_memory_unmap (mem, &info);
1924   }
1925   return size - left;
1926 }
1927
1928 /**
1929  * gst_buffer_extract:
1930  * @buffer: a #GstBuffer.
1931  * @offset: the offset to extract
1932  * @dest: (out caller-allocates) (array length=size) (element-type guint8):
1933  *     the destination address
1934  * @size: the size to extract
1935  *
1936  * Copy @size bytes starting from @offset in @buffer to @dest.
1937  *
1938  * Returns: The amount of bytes extracted. This value can be lower than @size
1939  *    when @buffer did not contain enough data.
1940  */
1941 gsize
1942 gst_buffer_extract (GstBuffer * buffer, gsize offset, gpointer dest, gsize size)
1943 {
1944   gsize i, len, left;
1945   guint8 *ptr = dest;
1946
1947   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1948   g_return_val_if_fail (dest != NULL, 0);
1949
1950   GST_CAT_LOG (GST_CAT_BUFFER,
1951       "buffer %p, offset %" G_GSIZE_FORMAT ", size %" G_GSIZE_FORMAT, buffer,
1952       offset, size);
1953
1954   len = GST_BUFFER_MEM_LEN (buffer);
1955   left = size;
1956
1957   for (i = 0; i < len && left > 0; i++) {
1958     GstMapInfo info;
1959     gsize tocopy;
1960     GstMemory *mem;
1961
1962     mem = _get_mapped (buffer, i, &info, GST_MAP_READ);
1963     if (info.size > offset) {
1964       /* we have enough */
1965       tocopy = MIN (info.size - offset, left);
1966       memcpy (ptr, (guint8 *) info.data + offset, tocopy);
1967       left -= tocopy;
1968       ptr += tocopy;
1969       offset = 0;
1970     } else {
1971       /* offset past buffer, skip */
1972       offset -= info.size;
1973     }
1974     gst_memory_unmap (mem, &info);
1975   }
1976   return size - left;
1977 }
1978
1979 /**
1980  * gst_buffer_memcmp:
1981  * @buffer: a #GstBuffer.
1982  * @offset: the offset in @buffer
1983  * @mem: (array length=size) (element-type guint8): the memory to compare
1984  * @size: the size to compare
1985  *
1986  * Compare @size bytes starting from @offset in @buffer with the memory in @mem.
1987  *
1988  * Returns: 0 if the memory is equal.
1989  */
1990 gint
1991 gst_buffer_memcmp (GstBuffer * buffer, gsize offset, gconstpointer mem,
1992     gsize size)
1993 {
1994   gsize i, len;
1995   const guint8 *ptr = mem;
1996   gint res = 0;
1997
1998   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1999   g_return_val_if_fail (mem != NULL, 0);
2000
2001   GST_CAT_LOG (GST_CAT_BUFFER,
2002       "buffer %p, offset %" G_GSIZE_FORMAT ", size %" G_GSIZE_FORMAT, buffer,
2003       offset, size);
2004
2005   if (G_UNLIKELY (gst_buffer_get_size (buffer) < offset + size))
2006     return -1;
2007
2008   len = GST_BUFFER_MEM_LEN (buffer);
2009
2010   for (i = 0; i < len && size > 0 && res == 0; i++) {
2011     GstMapInfo info;
2012     gsize tocmp;
2013     GstMemory *mem;
2014
2015     mem = _get_mapped (buffer, i, &info, GST_MAP_READ);
2016     if (info.size > offset) {
2017       /* we have enough */
2018       tocmp = MIN (info.size - offset, size);
2019       res = memcmp (ptr, (guint8 *) info.data + offset, tocmp);
2020       size -= tocmp;
2021       ptr += tocmp;
2022       offset = 0;
2023     } else {
2024       /* offset past buffer, skip */
2025       offset -= info.size;
2026     }
2027     gst_memory_unmap (mem, &info);
2028   }
2029   return res;
2030 }
2031
2032 /**
2033  * gst_buffer_memset:
2034  * @buffer: a #GstBuffer.
2035  * @offset: the offset in @buffer
2036  * @val: the value to set
2037  * @size: the size to set
2038  *
2039  * Fill @buf with @size bytes with @val starting from @offset.
2040  *
2041  * Returns: The amount of bytes filled. This value can be lower than @size
2042  *    when @buffer did not contain enough data.
2043  */
2044 gsize
2045 gst_buffer_memset (GstBuffer * buffer, gsize offset, guint8 val, gsize size)
2046 {
2047   gsize i, len, left;
2048
2049   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
2050   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
2051
2052   GST_CAT_LOG (GST_CAT_BUFFER,
2053       "buffer %p, offset %" G_GSIZE_FORMAT ", val %02x, size %" G_GSIZE_FORMAT,
2054       buffer, offset, val, size);
2055
2056   len = GST_BUFFER_MEM_LEN (buffer);
2057   left = size;
2058
2059   for (i = 0; i < len && left > 0; i++) {
2060     GstMapInfo info;
2061     gsize toset;
2062     GstMemory *mem;
2063
2064     mem = _get_mapped (buffer, i, &info, GST_MAP_WRITE);
2065     if (info.size > offset) {
2066       /* we have enough */
2067       toset = MIN (info.size - offset, left);
2068       memset ((guint8 *) info.data + offset, val, toset);
2069       left -= toset;
2070       offset = 0;
2071     } else {
2072       /* offset past buffer, skip */
2073       offset -= info.size;
2074     }
2075     gst_memory_unmap (mem, &info);
2076   }
2077   return size - left;
2078 }
2079
2080 /**
2081  * gst_buffer_copy_region:
2082  * @parent: a #GstBuffer.
2083  * @flags: the #GstBufferCopyFlags
2084  * @offset: the offset into parent #GstBuffer at which the new sub-buffer
2085  *          begins.
2086  * @size: the size of the new #GstBuffer sub-buffer, in bytes. If -1, all
2087  *        data is copied.
2088  *
2089  * Creates a sub-buffer from @parent at @offset and @size.
2090  * This sub-buffer uses the actual memory space of the parent buffer.
2091  * This function will copy the offset and timestamp fields when the
2092  * offset is 0. If not, they will be set to #GST_CLOCK_TIME_NONE and
2093  * #GST_BUFFER_OFFSET_NONE.
2094  * If @offset equals 0 and @size equals the total size of @buffer, the
2095  * duration and offset end fields are also copied. If not they will be set
2096  * to #GST_CLOCK_TIME_NONE and #GST_BUFFER_OFFSET_NONE.
2097  *
2098  * MT safe.
2099  *
2100  * Returns: (transfer full): the new #GstBuffer or %NULL if the arguments were
2101  *     invalid.
2102  */
2103 GstBuffer *
2104 gst_buffer_copy_region (GstBuffer * buffer, GstBufferCopyFlags flags,
2105     gsize offset, gsize size)
2106 {
2107   GstBuffer *copy;
2108
2109   g_return_val_if_fail (buffer != NULL, NULL);
2110
2111   /* create the new buffer */
2112   copy = gst_buffer_new ();
2113
2114   GST_CAT_LOG (GST_CAT_BUFFER, "new region copy %p of %p %" G_GSIZE_FORMAT
2115       "-%" G_GSIZE_FORMAT, copy, buffer, offset, size);
2116
2117   if (!gst_buffer_copy_into (copy, buffer, flags, offset, size))
2118     gst_buffer_replace (&copy, NULL);
2119
2120   return copy;
2121 }
2122
2123 /**
2124  * gst_buffer_append:
2125  * @buf1: (transfer full): the first source #GstBuffer to append.
2126  * @buf2: (transfer full): the second source #GstBuffer to append.
2127  *
2128  * Append all the memory from @buf2 to @buf1. The result buffer will contain a
2129  * concatenation of the memory of @buf1 and @buf2.
2130  *
2131  * Returns: (transfer full): the new #GstBuffer that contains the memory
2132  *     of the two source buffers.
2133  */
2134 GstBuffer *
2135 gst_buffer_append (GstBuffer * buf1, GstBuffer * buf2)
2136 {
2137   return gst_buffer_append_region (buf1, buf2, 0, -1);
2138 }
2139
2140 /**
2141  * gst_buffer_append_region:
2142  * @buf1: (transfer full): the first source #GstBuffer to append.
2143  * @buf2: (transfer full): the second source #GstBuffer to append.
2144  * @offset: the offset in @buf2
2145  * @size: the size or -1 of @buf2
2146  *
2147  * Append @size bytes at @offset from @buf2 to @buf1. The result buffer will
2148  * contain a concatenation of the memory of @buf1 and the requested region of
2149  * @buf2.
2150  *
2151  * Returns: (transfer full): the new #GstBuffer that contains the memory
2152  *     of the two source buffers.
2153  */
2154 GstBuffer *
2155 gst_buffer_append_region (GstBuffer * buf1, GstBuffer * buf2, gssize offset,
2156     gssize size)
2157 {
2158   gsize i, len;
2159
2160   g_return_val_if_fail (GST_IS_BUFFER (buf1), NULL);
2161   g_return_val_if_fail (GST_IS_BUFFER (buf2), NULL);
2162
2163   buf1 = gst_buffer_make_writable (buf1);
2164   buf2 = gst_buffer_make_writable (buf2);
2165
2166   gst_buffer_resize (buf2, offset, size);
2167
2168   len = GST_BUFFER_MEM_LEN (buf2);
2169   for (i = 0; i < len; i++) {
2170     GstMemory *mem;
2171
2172     mem = GST_BUFFER_MEM_PTR (buf2, i);
2173     gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
2174         GST_MINI_OBJECT_CAST (buf2));
2175     GST_BUFFER_MEM_PTR (buf2, i) = NULL;
2176     _memory_add (buf1, -1, mem);
2177   }
2178
2179   GST_BUFFER_MEM_LEN (buf2) = 0;
2180   GST_BUFFER_FLAG_SET (buf2, GST_BUFFER_FLAG_TAG_MEMORY);
2181   gst_buffer_unref (buf2);
2182
2183   return buf1;
2184 }
2185
2186 /**
2187  * gst_buffer_get_meta:
2188  * @buffer: a #GstBuffer
2189  * @api: the #GType of an API
2190  *
2191  * Get the metadata for @api on buffer. When there is no such metadata, %NULL is
2192  * returned. If multiple metadata with the given @api are attached to this
2193  * buffer only the first one is returned.  To handle multiple metadata with a
2194  * given API use gst_buffer_iterate_meta() or gst_buffer_foreach_meta() instead
2195  * and check the meta->info.api member for the API type.
2196  *
2197  * Returns: (transfer none) (nullable): the metadata for @api on
2198  * @buffer.
2199  */
2200 GstMeta *
2201 gst_buffer_get_meta (GstBuffer * buffer, GType api)
2202 {
2203   GstMetaItem *item;
2204   GstMeta *result = NULL;
2205
2206   g_return_val_if_fail (buffer != NULL, NULL);
2207   g_return_val_if_fail (api != 0, NULL);
2208
2209   /* find GstMeta of the requested API */
2210   for (item = GST_BUFFER_META (buffer); item; item = item->next) {
2211     GstMeta *meta = &item->meta;
2212     if (meta->info->api == api) {
2213       result = meta;
2214       break;
2215     }
2216   }
2217   return result;
2218 }
2219
2220 /**
2221  * gst_buffer_get_n_meta:
2222  * @buffer: a #GstBuffer
2223  * @api_type: the #GType of an API
2224  *
2225  * Returns: number of metas of type @api_type on @buffer.
2226  *
2227  * Since: 1.14
2228  */
2229 guint
2230 gst_buffer_get_n_meta (GstBuffer * buffer, GType api_type)
2231 {
2232   gpointer state = NULL;
2233   GstMeta *meta;
2234   guint n = 0;
2235
2236   while ((meta = gst_buffer_iterate_meta_filtered (buffer, &state, api_type)))
2237     ++n;
2238
2239   return n;
2240 }
2241
2242 /**
2243  * gst_buffer_add_meta:
2244  * @buffer: a #GstBuffer
2245  * @info: a #GstMetaInfo
2246  * @params: params for @info
2247  *
2248  * Add metadata for @info to @buffer using the parameters in @params.
2249  *
2250  * Returns: (transfer none) (nullable): the metadata for the api in @info on @buffer.
2251  */
2252 GstMeta *
2253 gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
2254     gpointer params)
2255 {
2256   GstMetaItem *item;
2257   GstMeta *result = NULL;
2258   gsize size;
2259
2260   g_return_val_if_fail (buffer != NULL, NULL);
2261   g_return_val_if_fail (info != NULL, NULL);
2262   g_return_val_if_fail (gst_buffer_is_writable (buffer), NULL);
2263
2264   /* create a new slice */
2265   size = ITEM_SIZE (info);
2266   /* We warn in gst_meta_register() about metas without
2267    * init function but let's play safe here and prevent
2268    * uninitialized memory
2269    */
2270   if (!info->init_func)
2271     item = g_slice_alloc0 (size);
2272   else
2273     item = g_slice_alloc (size);
2274   result = &item->meta;
2275   result->info = info;
2276   result->flags = GST_META_FLAG_NONE;
2277   GST_CAT_DEBUG (GST_CAT_BUFFER,
2278       "alloc metadata %p (%s) of size %" G_GSIZE_FORMAT, result,
2279       g_type_name (info->type), info->size);
2280
2281   /* call the init_func when needed */
2282   if (info->init_func)
2283     if (!info->init_func (result, params, buffer))
2284       goto init_failed;
2285
2286   item->seq_num = gst_atomic_int64_inc (&meta_seq);
2287
2288   /* and add to the list of metadata */
2289   item->next = GST_BUFFER_META (buffer);
2290   GST_BUFFER_META (buffer) = item;
2291
2292   return result;
2293
2294 init_failed:
2295   {
2296     g_slice_free1 (size, item);
2297     return NULL;
2298   }
2299 }
2300
2301 /**
2302  * gst_buffer_remove_meta:
2303  * @buffer: a #GstBuffer
2304  * @meta: a #GstMeta
2305  *
2306  * Remove the metadata for @meta on @buffer.
2307  *
2308  * Returns: %TRUE if the metadata existed and was removed, %FALSE if no such
2309  * metadata was on @buffer.
2310  */
2311 gboolean
2312 gst_buffer_remove_meta (GstBuffer * buffer, GstMeta * meta)
2313 {
2314   GstMetaItem *walk, *prev;
2315
2316   g_return_val_if_fail (buffer != NULL, FALSE);
2317   g_return_val_if_fail (meta != NULL, FALSE);
2318   g_return_val_if_fail (gst_buffer_is_writable (buffer), FALSE);
2319   g_return_val_if_fail (!GST_META_FLAG_IS_SET (meta, GST_META_FLAG_LOCKED),
2320       FALSE);
2321
2322   /* find the metadata and delete */
2323   prev = GST_BUFFER_META (buffer);
2324   for (walk = prev; walk; walk = walk->next) {
2325     GstMeta *m = &walk->meta;
2326     if (m == meta) {
2327       const GstMetaInfo *info = meta->info;
2328
2329       /* remove from list */
2330       if (GST_BUFFER_META (buffer) == walk)
2331         GST_BUFFER_META (buffer) = walk->next;
2332       else
2333         prev->next = walk->next;
2334       /* call free_func if any */
2335       if (info->free_func)
2336         info->free_func (m, buffer);
2337
2338       /* and free the slice */
2339       g_slice_free1 (ITEM_SIZE (info), walk);
2340       break;
2341     }
2342     prev = walk;
2343   }
2344   return walk != NULL;
2345 }
2346
2347 /**
2348  * gst_buffer_iterate_meta: (skip)
2349  * @buffer: a #GstBuffer
2350  * @state: (out caller-allocates): an opaque state pointer
2351  *
2352  * Retrieve the next #GstMeta after @current. If @state points
2353  * to %NULL, the first metadata is returned.
2354  *
2355  * @state will be updated with an opaque state pointer
2356  *
2357  * Returns: (transfer none) (nullable): The next #GstMeta or %NULL
2358  * when there are no more items.
2359  */
2360 GstMeta *
2361 gst_buffer_iterate_meta (GstBuffer * buffer, gpointer * state)
2362 {
2363   GstMetaItem **meta;
2364
2365   g_return_val_if_fail (buffer != NULL, NULL);
2366   g_return_val_if_fail (state != NULL, NULL);
2367
2368   meta = (GstMetaItem **) state;
2369   if (*meta == NULL)
2370     /* state NULL, move to first item */
2371     *meta = GST_BUFFER_META (buffer);
2372   else
2373     /* state !NULL, move to next item in list */
2374     *meta = (*meta)->next;
2375
2376   if (*meta)
2377     return &(*meta)->meta;
2378   else
2379     return NULL;
2380 }
2381
2382 /**
2383  * gst_buffer_iterate_meta_filtered: (skip)
2384  * @buffer: a #GstBuffer
2385  * @state: (out caller-allocates): an opaque state pointer
2386  * @meta_api_type: only return #GstMeta of this type
2387  *
2388  * Retrieve the next #GstMeta of type @meta_api_type after the current one
2389  * according to @state. If @state points to %NULL, the first metadata of
2390  * type @meta_api_type is returned.
2391  *
2392  * @state will be updated with an opaque state pointer
2393  *
2394  * Returns: (transfer none) (nullable): The next #GstMeta of type
2395  * @meta_api_type or %NULL when there are no more items.
2396  *
2397  * Since: 1.12
2398  */
2399 GstMeta *
2400 gst_buffer_iterate_meta_filtered (GstBuffer * buffer, gpointer * state,
2401     GType meta_api_type)
2402 {
2403   GstMetaItem **meta;
2404
2405   g_return_val_if_fail (buffer != NULL, NULL);
2406   g_return_val_if_fail (state != NULL, NULL);
2407
2408   meta = (GstMetaItem **) state;
2409   if (*meta == NULL)
2410     /* state NULL, move to first item */
2411     *meta = GST_BUFFER_META (buffer);
2412   else
2413     /* state !NULL, move to next item in list */
2414     *meta = (*meta)->next;
2415
2416   while (*meta != NULL && (*meta)->meta.info->api != meta_api_type)
2417     *meta = (*meta)->next;
2418
2419   if (*meta)
2420     return &(*meta)->meta;
2421   else
2422     return NULL;
2423 }
2424
2425 /**
2426  * gst_buffer_foreach_meta:
2427  * @buffer: a #GstBuffer
2428  * @func: (scope call): a #GstBufferForeachMetaFunc to call
2429  * @user_data: (closure): user data passed to @func
2430  *
2431  * Call @func with @user_data for each meta in @buffer.
2432  *
2433  * @func can modify the passed meta pointer or its contents. The return value
2434  * of @func define if this function returns or if the remaining metadata items
2435  * in the buffer should be skipped.
2436  *
2437  * Returns: %FALSE when @func returned %FALSE for one of the metadata.
2438  */
2439 gboolean
2440 gst_buffer_foreach_meta (GstBuffer * buffer, GstBufferForeachMetaFunc func,
2441     gpointer user_data)
2442 {
2443   GstMetaItem *walk, *prev, *next;
2444   gboolean res = TRUE;
2445
2446   g_return_val_if_fail (buffer != NULL, FALSE);
2447   g_return_val_if_fail (func != NULL, FALSE);
2448
2449   /* find the metadata and delete */
2450   prev = GST_BUFFER_META (buffer);
2451   for (walk = prev; walk; walk = next) {
2452     GstMeta *m, *new;
2453
2454     m = new = &walk->meta;
2455     next = walk->next;
2456
2457     res = func (buffer, &new, user_data);
2458
2459     if (new == NULL) {
2460       const GstMetaInfo *info = m->info;
2461
2462       GST_CAT_DEBUG (GST_CAT_BUFFER, "remove metadata %p (%s)", m,
2463           g_type_name (info->type));
2464
2465       g_return_val_if_fail (gst_buffer_is_writable (buffer), FALSE);
2466       g_return_val_if_fail (!GST_META_FLAG_IS_SET (m, GST_META_FLAG_LOCKED),
2467           FALSE);
2468
2469       /* remove from list */
2470       if (GST_BUFFER_META (buffer) == walk)
2471         prev = GST_BUFFER_META (buffer) = next;
2472       else
2473         prev->next = next;
2474
2475       /* call free_func if any */
2476       if (info->free_func)
2477         info->free_func (m, buffer);
2478
2479       /* and free the slice */
2480       g_slice_free1 (ITEM_SIZE (info), walk);
2481     } else {
2482       prev = walk;
2483     }
2484     if (!res)
2485       break;
2486   }
2487   return res;
2488 }
2489
2490 /**
2491  * gst_buffer_extract_dup:
2492  * @buffer: a #GstBuffer
2493  * @offset: the offset to extract
2494  * @size: the size to extract
2495  * @dest: (array length=dest_size) (element-type guint8) (out): A pointer where
2496  *  the destination array will be written. Might be %NULL if the size is 0.
2497  * @dest_size: (out): A location where the size of @dest can be written
2498  *
2499  * Extracts a copy of at most @size bytes the data at @offset into
2500  * newly-allocated memory. @dest must be freed using g_free() when done.
2501  *
2502  * Since: 1.0.10
2503  */
2504
2505 void
2506 gst_buffer_extract_dup (GstBuffer * buffer, gsize offset, gsize size,
2507     gpointer * dest, gsize * dest_size)
2508 {
2509   gsize real_size, alloc_size;
2510
2511   real_size = gst_buffer_get_size (buffer);
2512
2513   alloc_size = MIN (real_size - offset, size);
2514   if (alloc_size == 0) {
2515     *dest = NULL;
2516     *dest_size = 0;
2517   } else {
2518     *dest = g_malloc (alloc_size);
2519     *dest_size = gst_buffer_extract (buffer, offset, *dest, size);
2520   }
2521 }
2522
2523 GST_DEBUG_CATEGORY_STATIC (gst_parent_buffer_meta_debug);
2524
2525 /**
2526  * gst_buffer_add_parent_buffer_meta:
2527  * @buffer: (transfer none): a #GstBuffer
2528  * @ref: (transfer none): a #GstBuffer to ref
2529  *
2530  * Add a #GstParentBufferMeta to @buffer that holds a reference on
2531  * @ref until the buffer is freed.
2532  *
2533  * Returns: (transfer none) (nullable): The #GstParentBufferMeta that was added to the buffer
2534  *
2535  * Since: 1.6
2536  */
2537 GstParentBufferMeta *
2538 gst_buffer_add_parent_buffer_meta (GstBuffer * buffer, GstBuffer * ref)
2539 {
2540   GstParentBufferMeta *meta;
2541
2542   g_return_val_if_fail (GST_IS_BUFFER (ref), NULL);
2543
2544   meta =
2545       (GstParentBufferMeta *) gst_buffer_add_meta (buffer,
2546       GST_PARENT_BUFFER_META_INFO, NULL);
2547
2548   if (!meta)
2549     return NULL;
2550
2551   meta->buffer = gst_buffer_ref (ref);
2552
2553   return meta;
2554 }
2555
2556 static gboolean
2557 _gst_parent_buffer_meta_transform (GstBuffer * dest, GstMeta * meta,
2558     GstBuffer * buffer, GQuark type, gpointer data)
2559 {
2560   GstParentBufferMeta *dmeta, *smeta;
2561
2562   smeta = (GstParentBufferMeta *) meta;
2563
2564   if (GST_META_TRANSFORM_IS_COPY (type)) {
2565     /* copy over the reference to the parent buffer.
2566      * Usually, this meta means we need to keep the parent buffer
2567      * alive because one of the child memories is in use, which
2568      * might not be the case if memory is deep copied or sub-regioned,
2569      * but we can't tell, so keep the meta */
2570     dmeta = gst_buffer_add_parent_buffer_meta (dest, smeta->buffer);
2571     if (!dmeta)
2572       return FALSE;
2573
2574     GST_CAT_DEBUG (gst_parent_buffer_meta_debug,
2575         "copy buffer reference metadata");
2576   } else {
2577     /* return FALSE, if transform type is not supported */
2578     return FALSE;
2579   }
2580   return TRUE;
2581 }
2582
2583 static void
2584 _gst_parent_buffer_meta_free (GstParentBufferMeta * parent_meta,
2585     GstBuffer * buffer)
2586 {
2587   GST_CAT_DEBUG (gst_parent_buffer_meta_debug,
2588       "Dropping reference on buffer %p", parent_meta->buffer);
2589   gst_buffer_unref (parent_meta->buffer);
2590 }
2591
2592 static gboolean
2593 _gst_parent_buffer_meta_init (GstParentBufferMeta * parent_meta,
2594     gpointer params, GstBuffer * buffer)
2595 {
2596   static volatile gsize _init;
2597
2598   if (g_once_init_enter (&_init)) {
2599     GST_DEBUG_CATEGORY_INIT (gst_parent_buffer_meta_debug, "parentbuffermeta",
2600         0, "parentbuffermeta");
2601     g_once_init_leave (&_init, 1);
2602   }
2603
2604   parent_meta->buffer = NULL;
2605
2606   return TRUE;
2607 }
2608
2609 GType
2610 gst_parent_buffer_meta_api_get_type (void)
2611 {
2612   static volatile GType type = 0;
2613   static const gchar *tags[] = { NULL };
2614
2615   if (g_once_init_enter (&type)) {
2616     GType _type = gst_meta_api_type_register ("GstParentBufferMetaAPI", tags);
2617     g_once_init_leave (&type, _type);
2618   }
2619
2620   return type;
2621 }
2622
2623 /**
2624  * gst_parent_buffer_meta_get_info:
2625  *
2626  * Get the global #GstMetaInfo describing  the #GstParentBufferMeta meta.
2627  *
2628  * Returns: (transfer none): The #GstMetaInfo
2629  *
2630  * Since: 1.6
2631  */
2632 const GstMetaInfo *
2633 gst_parent_buffer_meta_get_info (void)
2634 {
2635   static const GstMetaInfo *meta_info = NULL;
2636
2637   if (g_once_init_enter ((GstMetaInfo **) & meta_info)) {
2638     const GstMetaInfo *meta =
2639         gst_meta_register (gst_parent_buffer_meta_api_get_type (),
2640         "GstParentBufferMeta",
2641         sizeof (GstParentBufferMeta),
2642         (GstMetaInitFunction) _gst_parent_buffer_meta_init,
2643         (GstMetaFreeFunction) _gst_parent_buffer_meta_free,
2644         _gst_parent_buffer_meta_transform);
2645     g_once_init_leave ((GstMetaInfo **) & meta_info, (GstMetaInfo *) meta);
2646   }
2647
2648   return meta_info;
2649 }
2650
2651 GST_DEBUG_CATEGORY_STATIC (gst_reference_timestamp_meta_debug);
2652
2653 /**
2654  * gst_buffer_add_reference_timestamp_meta:
2655  * @buffer: (transfer none): a #GstBuffer
2656  * @reference: (transfer none): identifier for the timestamp reference.
2657  * @timestamp: timestamp
2658  * @duration: duration, or %GST_CLOCK_TIME_NONE
2659  *
2660  * Add a #GstReferenceTimestampMeta to @buffer that holds a @timestamp and
2661  * optionally @duration based on a specific timestamp @reference. See the
2662  * documentation of #GstReferenceTimestampMeta for details.
2663  *
2664  * Returns: (transfer none) (nullable): The #GstReferenceTimestampMeta that was added to the buffer
2665  *
2666  * Since: 1.14
2667  */
2668 GstReferenceTimestampMeta *
2669 gst_buffer_add_reference_timestamp_meta (GstBuffer * buffer,
2670     GstCaps * reference, GstClockTime timestamp, GstClockTime duration)
2671 {
2672   GstReferenceTimestampMeta *meta;
2673
2674   g_return_val_if_fail (GST_IS_CAPS (reference), NULL);
2675   g_return_val_if_fail (timestamp != GST_CLOCK_TIME_NONE, NULL);
2676
2677   meta =
2678       (GstReferenceTimestampMeta *) gst_buffer_add_meta (buffer,
2679       GST_REFERENCE_TIMESTAMP_META_INFO, NULL);
2680
2681   if (!meta)
2682     return NULL;
2683
2684   meta->reference = gst_caps_ref (reference);
2685   meta->timestamp = timestamp;
2686   meta->duration = duration;
2687
2688   return meta;
2689 }
2690
2691 /**
2692  * gst_buffer_get_reference_timestamp_meta:
2693  * @buffer: a #GstBuffer
2694  * @reference: (allow-none): a reference #GstCaps
2695  *
2696  * Find the first #GstReferenceTimestampMeta on @buffer that conforms to
2697  * @reference. Conformance is tested by checking if the meta's reference is a
2698  * subset of @reference.
2699  *
2700  * Buffers can contain multiple #GstReferenceTimestampMeta metadata items.
2701  *
2702  * Returns: (transfer none) (nullable): the #GstReferenceTimestampMeta or %NULL when there
2703  * is no such metadata on @buffer.
2704  *
2705  * Since: 1.14
2706  */
2707 GstReferenceTimestampMeta *
2708 gst_buffer_get_reference_timestamp_meta (GstBuffer * buffer,
2709     GstCaps * reference)
2710 {
2711   gpointer state = NULL;
2712   GstMeta *meta;
2713   const GstMetaInfo *info = GST_REFERENCE_TIMESTAMP_META_INFO;
2714
2715   while ((meta = gst_buffer_iterate_meta (buffer, &state))) {
2716     if (meta->info->api == info->api) {
2717       GstReferenceTimestampMeta *rmeta = (GstReferenceTimestampMeta *) meta;
2718
2719       if (!reference)
2720         return rmeta;
2721       if (gst_caps_is_subset (rmeta->reference, reference))
2722         return rmeta;
2723     }
2724   }
2725   return NULL;
2726 }
2727
2728 static gboolean
2729 _gst_reference_timestamp_meta_transform (GstBuffer * dest, GstMeta * meta,
2730     GstBuffer * buffer, GQuark type, gpointer data)
2731 {
2732   GstReferenceTimestampMeta *dmeta, *smeta;
2733
2734   /* we copy over the reference timestamp meta, independent of transformation
2735    * that happens. If it applied to the original buffer, it still applies to
2736    * the new buffer as it refers to the time when the media was captured */
2737   smeta = (GstReferenceTimestampMeta *) meta;
2738   dmeta =
2739       gst_buffer_add_reference_timestamp_meta (dest, smeta->reference,
2740       smeta->timestamp, smeta->duration);
2741   if (!dmeta)
2742     return FALSE;
2743
2744   GST_CAT_DEBUG (gst_reference_timestamp_meta_debug,
2745       "copy reference timestamp metadata from buffer %p to %p", buffer, dest);
2746
2747   return TRUE;
2748 }
2749
2750 static void
2751 _gst_reference_timestamp_meta_free (GstReferenceTimestampMeta * meta,
2752     GstBuffer * buffer)
2753 {
2754   if (meta->reference)
2755     gst_caps_unref (meta->reference);
2756 }
2757
2758 static gboolean
2759 _gst_reference_timestamp_meta_init (GstReferenceTimestampMeta * meta,
2760     gpointer params, GstBuffer * buffer)
2761 {
2762   static volatile gsize _init;
2763
2764   if (g_once_init_enter (&_init)) {
2765     GST_DEBUG_CATEGORY_INIT (gst_reference_timestamp_meta_debug,
2766         "referencetimestampmeta", 0, "referencetimestampmeta");
2767     g_once_init_leave (&_init, 1);
2768   }
2769
2770   meta->reference = NULL;
2771   meta->timestamp = GST_CLOCK_TIME_NONE;
2772   meta->duration = GST_CLOCK_TIME_NONE;
2773
2774   return TRUE;
2775 }
2776
2777 GType
2778 gst_reference_timestamp_meta_api_get_type (void)
2779 {
2780   static volatile GType type = 0;
2781   static const gchar *tags[] = { NULL };
2782
2783   if (g_once_init_enter (&type)) {
2784     GType _type =
2785         gst_meta_api_type_register ("GstReferenceTimestampMetaAPI", tags);
2786     g_once_init_leave (&type, _type);
2787   }
2788
2789   return type;
2790 }
2791
2792 /**
2793  * gst_reference_timestamp_meta_get_info:
2794  *
2795  * Get the global #GstMetaInfo describing  the #GstReferenceTimestampMeta meta.
2796  *
2797  * Returns: (transfer none): The #GstMetaInfo
2798  *
2799  * Since: 1.14
2800  */
2801 const GstMetaInfo *
2802 gst_reference_timestamp_meta_get_info (void)
2803 {
2804   static const GstMetaInfo *meta_info = NULL;
2805
2806   if (g_once_init_enter ((GstMetaInfo **) & meta_info)) {
2807     const GstMetaInfo *meta =
2808         gst_meta_register (gst_reference_timestamp_meta_api_get_type (),
2809         "GstReferenceTimestampMeta",
2810         sizeof (GstReferenceTimestampMeta),
2811         (GstMetaInitFunction) _gst_reference_timestamp_meta_init,
2812         (GstMetaFreeFunction) _gst_reference_timestamp_meta_free,
2813         _gst_reference_timestamp_meta_transform);
2814     g_once_init_leave ((GstMetaInfo **) & meta_info, (GstMetaInfo *) meta);
2815   }
2816
2817   return meta_info;
2818 }