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