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