cb84f4762c9265203251d18627b12a7bdf0a89d1
[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 meta with memory references %" GST_PTR_FORMAT, meta);
695       } else if (info->transform_func) {
696         GstMetaTransformCopy copy_data;
697
698         copy_data.region = region;
699         copy_data.offset = offset;
700         copy_data.size = size;
701
702         if (!info->transform_func (dest, meta, src,
703                 _gst_meta_transform_copy, &copy_data)) {
704           GST_CAT_ERROR (GST_CAT_BUFFER,
705               "failed to copy meta %p of API type %s", meta,
706               g_type_name (info->api));
707         }
708       }
709     }
710   }
711
712   return TRUE;
713 }
714
715 static GstBuffer *
716 gst_buffer_copy_with_flags (const GstBuffer * buffer, GstBufferCopyFlags flags)
717 {
718   GstBuffer *copy;
719
720   g_return_val_if_fail (buffer != NULL, NULL);
721
722   /* create a fresh new buffer */
723   copy = gst_buffer_new ();
724
725   /* copy what the 'flags' want from our parent */
726   /* FIXME why we can't pass const to gst_buffer_copy_into() ? */
727   if (!gst_buffer_copy_into (copy, (GstBuffer *) buffer, flags, 0, -1))
728     gst_buffer_replace (&copy, NULL);
729
730   if (copy)
731     GST_BUFFER_FLAG_UNSET (copy, GST_BUFFER_FLAG_TAG_MEMORY);
732
733   return copy;
734 }
735
736 static GstBuffer *
737 _gst_buffer_copy (const GstBuffer * buffer)
738 {
739   return gst_buffer_copy_with_flags (buffer, GST_BUFFER_COPY_ALL);
740 }
741
742 /**
743  * gst_buffer_copy_deep:
744  * @buf: a #GstBuffer.
745  *
746  * Creates a copy of the given buffer. This will make a newly allocated
747  * copy of the data the source buffer contains.
748  *
749  * Returns: (transfer full): a new copy of @buf.
750  *
751  * Since: 1.6
752  */
753 GstBuffer *
754 gst_buffer_copy_deep (const GstBuffer * buffer)
755 {
756   return gst_buffer_copy_with_flags (buffer,
757       GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP);
758 }
759
760 /* the default dispose function revives the buffer and returns it to the
761  * pool when there is a pool */
762 static gboolean
763 _gst_buffer_dispose (GstBuffer * buffer)
764 {
765   GstBufferPool *pool;
766
767   /* no pool, do free */
768   if ((pool = buffer->pool) == NULL)
769     return TRUE;
770
771   /* keep the buffer alive */
772   gst_buffer_ref (buffer);
773   /* return the buffer to the pool */
774   GST_CAT_LOG (GST_CAT_BUFFER, "release %p to pool %p", buffer, pool);
775   gst_buffer_pool_release_buffer (pool, buffer);
776
777   return FALSE;
778 }
779
780 static void
781 _gst_buffer_free (GstBuffer * buffer)
782 {
783   GstMetaItem *walk, *next;
784   guint i, len;
785   gsize msize;
786
787   g_return_if_fail (buffer != NULL);
788
789   GST_CAT_LOG (GST_CAT_BUFFER, "finalize %p", buffer);
790
791   /* free metadata */
792   for (walk = GST_BUFFER_META (buffer); walk; walk = next) {
793     GstMeta *meta = &walk->meta;
794     const GstMetaInfo *info = meta->info;
795
796     /* call free_func if any */
797     if (info->free_func)
798       info->free_func (meta, buffer);
799
800     next = walk->next;
801     /* and free the slice */
802     g_slice_free1 (ITEM_SIZE (info), walk);
803   }
804
805   /* get the size, when unreffing the memory, we could also unref the buffer
806    * itself */
807   msize = GST_BUFFER_SLICE_SIZE (buffer);
808
809   /* free our memory */
810   len = GST_BUFFER_MEM_LEN (buffer);
811   for (i = 0; i < len; i++) {
812     gst_memory_unlock (GST_BUFFER_MEM_PTR (buffer, i), GST_LOCK_FLAG_EXCLUSIVE);
813     gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (GST_BUFFER_MEM_PTR
814             (buffer, i)), GST_MINI_OBJECT_CAST (buffer));
815     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
816   }
817
818   /* we set msize to 0 when the buffer is part of the memory block */
819   if (msize) {
820 #ifdef USE_POISONING
821     memset (buffer, 0xff, msize);
822 #endif
823     g_slice_free1 (msize, buffer);
824   } else {
825     gst_memory_unref (GST_BUFFER_BUFMEM (buffer));
826   }
827 }
828
829 static void
830 gst_buffer_init (GstBufferImpl * buffer, gsize size)
831 {
832   gst_mini_object_init (GST_MINI_OBJECT_CAST (buffer), 0, _gst_buffer_type,
833       (GstMiniObjectCopyFunction) _gst_buffer_copy,
834       (GstMiniObjectDisposeFunction) _gst_buffer_dispose,
835       (GstMiniObjectFreeFunction) _gst_buffer_free);
836
837   GST_BUFFER_SLICE_SIZE (buffer) = size;
838
839   GST_BUFFER (buffer)->pool = NULL;
840   GST_BUFFER_PTS (buffer) = GST_CLOCK_TIME_NONE;
841   GST_BUFFER_DTS (buffer) = GST_CLOCK_TIME_NONE;
842   GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
843   GST_BUFFER_OFFSET (buffer) = GST_BUFFER_OFFSET_NONE;
844   GST_BUFFER_OFFSET_END (buffer) = GST_BUFFER_OFFSET_NONE;
845
846   GST_BUFFER_MEM_LEN (buffer) = 0;
847   GST_BUFFER_META (buffer) = NULL;
848 }
849
850 /**
851  * gst_buffer_new:
852  *
853  * Creates a newly allocated buffer without any data.
854  *
855  * Returns: (transfer full): the new #GstBuffer.
856  */
857 GstBuffer *
858 gst_buffer_new (void)
859 {
860   GstBufferImpl *newbuf;
861
862   newbuf = g_slice_new (GstBufferImpl);
863   GST_CAT_LOG (GST_CAT_BUFFER, "new %p", newbuf);
864
865   gst_buffer_init (newbuf, sizeof (GstBufferImpl));
866
867   return GST_BUFFER_CAST (newbuf);
868 }
869
870 /**
871  * gst_buffer_new_allocate:
872  * @allocator: (transfer none) (allow-none): the #GstAllocator to use, or %NULL to use the
873  *     default allocator
874  * @size: the size in bytes of the new buffer's data.
875  * @params: (transfer none) (allow-none): optional parameters
876  *
877  * Tries to create a newly allocated buffer with data of the given size and
878  * extra parameters from @allocator. If the requested amount of memory can't be
879  * allocated, %NULL will be returned. The allocated buffer memory is not cleared.
880  *
881  * When @allocator is %NULL, the default memory allocator will be used.
882  *
883  * Note that when @size == 0, the buffer will not have memory associated with it.
884  *
885  * Returns: (transfer full) (nullable): a new #GstBuffer
886  */
887 GstBuffer *
888 gst_buffer_new_allocate (GstAllocator * allocator, gsize size,
889     GstAllocationParams * params)
890 {
891   GstBuffer *newbuf;
892   GstMemory *mem;
893 #if 0
894   guint8 *data;
895   gsize asize;
896 #endif
897
898 #if 1
899   if (size > 0) {
900     mem = gst_allocator_alloc (allocator, size, params);
901     if (G_UNLIKELY (mem == NULL))
902       goto no_memory;
903   } else {
904     mem = NULL;
905   }
906
907   newbuf = gst_buffer_new ();
908
909   if (mem != NULL) {
910     gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
911     _memory_add (newbuf, -1, mem);
912   }
913
914   GST_CAT_LOG (GST_CAT_BUFFER,
915       "new buffer %p of size %" G_GSIZE_FORMAT " from allocator %p", newbuf,
916       size, allocator);
917 #endif
918
919 #if 0
920   asize = sizeof (GstBufferImpl) + size;
921   data = g_slice_alloc (asize);
922   if (G_UNLIKELY (data == NULL))
923     goto no_memory;
924
925   newbuf = GST_BUFFER_CAST (data);
926
927   gst_buffer_init ((GstBufferImpl *) data, asize);
928   if (size > 0) {
929     mem = gst_memory_new_wrapped (0, data + sizeof (GstBufferImpl), NULL,
930         size, 0, size);
931     _memory_add (newbuf, -1, mem, TRUE);
932   }
933 #endif
934
935 #if 0
936   /* allocate memory and buffer, it might be interesting to do this but there
937    * are many complications. We need to keep the memory mapped to access the
938    * buffer fields and the memory for the buffer might be just very slow. We
939    * also need to do some more magic to get the alignment right. */
940   asize = sizeof (GstBufferImpl) + size;
941   mem = gst_allocator_alloc (allocator, asize, align);
942   if (G_UNLIKELY (mem == NULL))
943     goto no_memory;
944
945   /* map the data part and init the buffer in it, set the buffer size to 0 so
946    * that a finalize won't free the buffer */
947   data = gst_memory_map (mem, &asize, NULL, GST_MAP_WRITE);
948   gst_buffer_init ((GstBufferImpl *) data, 0);
949   gst_memory_unmap (mem);
950
951   /* strip off the buffer */
952   gst_memory_resize (mem, sizeof (GstBufferImpl), size);
953
954   newbuf = GST_BUFFER_CAST (data);
955   GST_BUFFER_BUFMEM (newbuf) = mem;
956
957   if (size > 0)
958     _memory_add (newbuf, -1, gst_memory_ref (mem), TRUE);
959 #endif
960   GST_BUFFER_FLAG_UNSET (newbuf, GST_BUFFER_FLAG_TAG_MEMORY);
961
962   return newbuf;
963
964   /* ERRORS */
965 no_memory:
966   {
967     GST_CAT_WARNING (GST_CAT_BUFFER,
968         "failed to allocate %" G_GSIZE_FORMAT " bytes", size);
969     return NULL;
970   }
971 }
972
973 /**
974  * gst_buffer_new_wrapped_full:
975  * @flags: #GstMemoryFlags
976  * @data: (array length=size) (element-type guint8) (transfer none): data to wrap
977  * @maxsize: allocated size of @data
978  * @offset: offset in @data
979  * @size: size of valid data
980  * @user_data: (allow-none): user_data
981  * @notify: (allow-none) (scope async) (closure user_data): called with @user_data when the memory is freed
982  *
983  * Allocates a new buffer that wraps the given memory. @data must point to
984  * @maxsize of memory, the wrapped buffer will have the region from @offset and
985  * @size visible.
986  *
987  * When the buffer is destroyed, @notify will be called with @user_data.
988  *
989  * The prefix/padding must be filled with 0 if @flags contains
990  * #GST_MEMORY_FLAG_ZERO_PREFIXED and #GST_MEMORY_FLAG_ZERO_PADDED respectively.
991  *
992  * Returns: (transfer full): a new #GstBuffer
993  */
994 GstBuffer *
995 gst_buffer_new_wrapped_full (GstMemoryFlags flags, gpointer data,
996     gsize maxsize, gsize offset, gsize size, gpointer user_data,
997     GDestroyNotify notify)
998 {
999   GstMemory *mem;
1000   GstBuffer *newbuf;
1001
1002   newbuf = gst_buffer_new ();
1003   mem =
1004       gst_memory_new_wrapped (flags, data, maxsize, offset, size, user_data,
1005       notify);
1006   gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
1007   _memory_add (newbuf, -1, mem);
1008   GST_BUFFER_FLAG_UNSET (newbuf, GST_BUFFER_FLAG_TAG_MEMORY);
1009
1010   return newbuf;
1011 }
1012
1013 /**
1014  * gst_buffer_new_wrapped:
1015  * @data: (array length=size) (element-type guint8) (transfer full): data to wrap
1016  * @size: allocated size of @data
1017  *
1018  * Creates a new buffer that wraps the given @data. The memory will be freed
1019  * with g_free() and will be marked writable.
1020  *
1021  * Returns: (transfer full): a new #GstBuffer
1022  */
1023 GstBuffer *
1024 gst_buffer_new_wrapped (gpointer data, gsize size)
1025 {
1026   return gst_buffer_new_wrapped_full (0, data, size, 0, size, data, g_free);
1027 }
1028
1029 /**
1030  * gst_buffer_new_wrapped_bytes:
1031  * @bytes: (transfer none): a #GBytes to wrap
1032  *
1033  * Creates a new #GstBuffer that wraps the given @bytes. The data inside
1034  * @bytes cannot be %NULL and the resulting buffer will be marked as read only.
1035  *
1036  * Returns: (transfer full): a new #GstBuffer wrapping @bytes
1037  *
1038  * Since: 1.16
1039  */
1040 GstBuffer *
1041 gst_buffer_new_wrapped_bytes (GBytes * bytes)
1042 {
1043   guint8 *bytes_data;
1044   gsize size;
1045
1046   g_return_val_if_fail (bytes != NULL, NULL);
1047   bytes_data = (guint8 *) g_bytes_get_data (bytes, &size);
1048   g_return_val_if_fail (bytes_data != NULL, NULL);
1049
1050   return gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, bytes_data,
1051       size, 0, size, g_bytes_ref (bytes), (GDestroyNotify) g_bytes_unref);
1052 }
1053
1054 /**
1055  * gst_buffer_new_memdup:
1056  * @data: (array length=size) (element-type guint8) (transfer none): data to copy into new buffer
1057  * @size: size of @data in bytes
1058  *
1059  * Creates a new buffer of size @size and fills it with a copy of @data.
1060  *
1061  * Returns: (transfer full): a new #GstBuffer
1062  *
1063  * Since: 1.20
1064  */
1065 GstBuffer *
1066 gst_buffer_new_memdup (gconstpointer data, gsize size)
1067 {
1068   gpointer data2 = g_memdup2 (data, size);
1069
1070   return gst_buffer_new_wrapped_full (0, data2, size, 0, size, data2, g_free);
1071 }
1072
1073 /**
1074  * gst_buffer_n_memory:
1075  * @buffer: a #GstBuffer.
1076  *
1077  * Gets the amount of memory blocks that this buffer has. This amount is never
1078  * larger than what gst_buffer_get_max_memory() returns.
1079  *
1080  * Returns: the number of memory blocks this buffer is made of.
1081  */
1082 guint
1083 gst_buffer_n_memory (GstBuffer * buffer)
1084 {
1085   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1086
1087   return GST_BUFFER_MEM_LEN (buffer);
1088 }
1089
1090 /**
1091  * gst_buffer_prepend_memory:
1092  * @buffer: a #GstBuffer.
1093  * @mem: (transfer full): a #GstMemory.
1094  *
1095  * Prepends the memory block @mem to @buffer. This function takes
1096  * ownership of @mem and thus doesn't increase its refcount.
1097  *
1098  * This function is identical to gst_buffer_insert_memory() with an index of 0.
1099  * See gst_buffer_insert_memory() for more details.
1100  */
1101 void
1102 gst_buffer_prepend_memory (GstBuffer * buffer, GstMemory * mem)
1103 {
1104   gst_buffer_insert_memory (buffer, 0, mem);
1105 }
1106
1107 /**
1108  * gst_buffer_append_memory:
1109  * @buffer: a #GstBuffer.
1110  * @mem: (transfer full): a #GstMemory.
1111  *
1112  * Appends the memory block @mem to @buffer. This function takes
1113  * ownership of @mem and thus doesn't increase its refcount.
1114  *
1115  * This function is identical to gst_buffer_insert_memory() with an index of -1.
1116  * See gst_buffer_insert_memory() for more details.
1117  */
1118 void
1119 gst_buffer_append_memory (GstBuffer * buffer, GstMemory * mem)
1120 {
1121   gst_buffer_insert_memory (buffer, -1, mem);
1122 }
1123
1124 /**
1125  * gst_buffer_insert_memory:
1126  * @buffer: a #GstBuffer.
1127  * @idx: the index to add the memory at, or -1 to append it to the end
1128  * @mem: (transfer full): a #GstMemory.
1129  *
1130  * Inserts the memory block @mem into @buffer at @idx. This function takes ownership
1131  * of @mem and thus doesn't increase its refcount.
1132  *
1133  * Only gst_buffer_get_max_memory() can be added to a buffer. If more memory is
1134  * added, existing memory blocks will automatically be merged to make room for
1135  * the new memory.
1136  */
1137 void
1138 gst_buffer_insert_memory (GstBuffer * buffer, gint idx, GstMemory * mem)
1139 {
1140   GstMemory *tmp;
1141
1142   g_return_if_fail (GST_IS_BUFFER (buffer));
1143   g_return_if_fail (gst_buffer_is_writable (buffer));
1144   g_return_if_fail (mem != NULL);
1145   g_return_if_fail (idx == -1 ||
1146       (idx >= 0 && idx <= GST_BUFFER_MEM_LEN (buffer)));
1147
1148   tmp = _memory_get_exclusive_reference (mem);
1149   g_return_if_fail (tmp != NULL);
1150   gst_memory_unref (mem);
1151   _memory_add (buffer, idx, tmp);
1152 }
1153
1154 static GstMemory *
1155 _get_mapped (GstBuffer * buffer, guint idx, GstMapInfo * info,
1156     GstMapFlags flags)
1157 {
1158   GstMemory *mem, *mapped;
1159
1160   mem = gst_memory_ref (GST_BUFFER_MEM_PTR (buffer, idx));
1161
1162   mapped = gst_memory_make_mapped (mem, info, flags);
1163
1164   if (mapped != mem) {
1165     /* memory changed, lock new memory */
1166     gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (mapped),
1167         GST_MINI_OBJECT_CAST (buffer));
1168     gst_memory_lock (mapped, GST_LOCK_FLAG_EXCLUSIVE);
1169     GST_BUFFER_MEM_PTR (buffer, idx) = mapped;
1170     /* unlock old memory */
1171     gst_memory_unlock (mem, GST_LOCK_FLAG_EXCLUSIVE);
1172     gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
1173         GST_MINI_OBJECT_CAST (buffer));
1174     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1175   }
1176   gst_memory_unref (mem);
1177
1178   return mapped;
1179 }
1180
1181 /**
1182  * gst_buffer_peek_memory:
1183  * @buffer: a #GstBuffer.
1184  * @idx: an index
1185  *
1186  * Gets the memory block at @idx in @buffer. The memory block stays valid until
1187  * the memory block in @buffer is removed, replaced or merged, typically with
1188  * any call that modifies the memory in @buffer.
1189  *
1190  * Returns: (transfer none) (nullable): the #GstMemory at @idx.
1191  */
1192 GstMemory *
1193 gst_buffer_peek_memory (GstBuffer * buffer, guint idx)
1194 {
1195   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
1196   g_return_val_if_fail (idx < GST_BUFFER_MEM_LEN (buffer), NULL);
1197
1198   return GST_BUFFER_MEM_PTR (buffer, idx);
1199 }
1200
1201 /**
1202  * gst_buffer_get_memory:
1203  * @buffer: a #GstBuffer.
1204  * @idx: an index
1205  *
1206  * Gets the memory block at index @idx in @buffer.
1207  *
1208  * Returns: (transfer full) (nullable): a #GstMemory that contains the data of the
1209  * memory block at @idx.
1210  */
1211 GstMemory *
1212 gst_buffer_get_memory (GstBuffer * buffer, guint idx)
1213 {
1214   return gst_buffer_get_memory_range (buffer, idx, 1);
1215 }
1216
1217 /**
1218  * gst_buffer_get_all_memory:
1219  * @buffer: a #GstBuffer.
1220  *
1221  * Gets all the memory blocks in @buffer. The memory blocks will be merged
1222  * into one large #GstMemory.
1223  *
1224  * Returns: (transfer full) (nullable): a #GstMemory that contains the merged memory.
1225  */
1226 GstMemory *
1227 gst_buffer_get_all_memory (GstBuffer * buffer)
1228 {
1229   return gst_buffer_get_memory_range (buffer, 0, -1);
1230 }
1231
1232 /**
1233  * gst_buffer_get_memory_range:
1234  * @buffer: a #GstBuffer.
1235  * @idx: an index
1236  * @length: a length
1237  *
1238  * Gets @length memory blocks in @buffer starting at @idx. The memory blocks will
1239  * be merged into one large #GstMemory.
1240  *
1241  * If @length is -1, all memory starting from @idx is merged.
1242  *
1243  * Returns: (transfer full) (nullable): a #GstMemory that contains the merged data of @length
1244  *    blocks starting at @idx.
1245  */
1246 GstMemory *
1247 gst_buffer_get_memory_range (GstBuffer * buffer, guint idx, gint length)
1248 {
1249   guint len;
1250
1251   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d", idx, length);
1252
1253   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
1254   len = GST_BUFFER_MEM_LEN (buffer);
1255   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1256       (length == -1 && idx < len) || (length > 0 && length + idx <= len), NULL);
1257
1258   if (length == -1)
1259     length = len - idx;
1260
1261   return _get_merged_memory (buffer, idx, length);
1262 }
1263
1264 /**
1265  * gst_buffer_replace_memory:
1266  * @buffer: a #GstBuffer.
1267  * @idx: an index
1268  * @mem: (transfer full): a #GstMemory
1269  *
1270  * Replaces the memory block at index @idx in @buffer with @mem.
1271  */
1272 void
1273 gst_buffer_replace_memory (GstBuffer * buffer, guint idx, GstMemory * mem)
1274 {
1275   gst_buffer_replace_memory_range (buffer, idx, 1, mem);
1276 }
1277
1278 /**
1279  * gst_buffer_replace_all_memory:
1280  * @buffer: a #GstBuffer.
1281  * @mem: (transfer full): a #GstMemory
1282  *
1283  * Replaces all memory in @buffer with @mem.
1284  */
1285 void
1286 gst_buffer_replace_all_memory (GstBuffer * buffer, GstMemory * mem)
1287 {
1288   gst_buffer_replace_memory_range (buffer, 0, -1, mem);
1289 }
1290
1291 /**
1292  * gst_buffer_replace_memory_range:
1293  * @buffer: a #GstBuffer.
1294  * @idx: an index
1295  * @length: a length, should not be 0
1296  * @mem: (transfer full): a #GstMemory
1297  *
1298  * Replaces @length memory blocks in @buffer starting at @idx with @mem.
1299  *
1300  * If @length is -1, all memory starting from @idx will be removed and
1301  * replaced with @mem.
1302  *
1303  * @buffer should be writable.
1304  */
1305 void
1306 gst_buffer_replace_memory_range (GstBuffer * buffer, guint idx, gint length,
1307     GstMemory * mem)
1308 {
1309   guint len;
1310
1311   g_return_if_fail (GST_IS_BUFFER (buffer));
1312   g_return_if_fail (gst_buffer_is_writable (buffer));
1313
1314   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d, %p", idx, length, mem);
1315
1316   len = GST_BUFFER_MEM_LEN (buffer);
1317   g_return_if_fail ((len == 0 && idx == 0 && length == -1) ||
1318       (length == -1 && idx < len) || (length > 0 && length + idx <= len));
1319
1320   if (length == -1)
1321     length = len - idx;
1322
1323   _replace_memory (buffer, len, idx, length, mem);
1324 }
1325
1326 /**
1327  * gst_buffer_remove_memory:
1328  * @buffer: a #GstBuffer.
1329  * @idx: an index
1330  *
1331  * Removes the memory block in @b at index @i.
1332  */
1333 void
1334 gst_buffer_remove_memory (GstBuffer * buffer, guint idx)
1335 {
1336   gst_buffer_remove_memory_range (buffer, idx, 1);
1337 }
1338
1339 /**
1340  * gst_buffer_remove_all_memory:
1341  * @buffer: a #GstBuffer.
1342  *
1343  * Removes all the memory blocks in @buffer.
1344  */
1345 void
1346 gst_buffer_remove_all_memory (GstBuffer * buffer)
1347 {
1348   if (GST_BUFFER_MEM_LEN (buffer))
1349     gst_buffer_remove_memory_range (buffer, 0, -1);
1350 }
1351
1352 /**
1353  * gst_buffer_remove_memory_range:
1354  * @buffer: a #GstBuffer.
1355  * @idx: an index
1356  * @length: a length
1357  *
1358  * Removes @length memory blocks in @buffer starting from @idx.
1359  *
1360  * @length can be -1, in which case all memory starting from @idx is removed.
1361  */
1362 void
1363 gst_buffer_remove_memory_range (GstBuffer * buffer, guint idx, gint length)
1364 {
1365   guint len;
1366
1367   g_return_if_fail (GST_IS_BUFFER (buffer));
1368   g_return_if_fail (gst_buffer_is_writable (buffer));
1369
1370   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d", idx, length);
1371
1372   len = GST_BUFFER_MEM_LEN (buffer);
1373   g_return_if_fail ((len == 0 && idx == 0 && length == -1) ||
1374       (length == -1 && idx < len) || length + idx <= len);
1375
1376   if (length == -1)
1377     length = len - idx;
1378
1379   _replace_memory (buffer, len, idx, length, NULL);
1380 }
1381
1382 /**
1383  * gst_buffer_find_memory:
1384  * @buffer: a #GstBuffer.
1385  * @offset: an offset
1386  * @size: a size
1387  * @idx: (out): pointer to index
1388  * @length: (out): pointer to length
1389  * @skip: (out): pointer to skip
1390  *
1391  * Finds the memory blocks that span @size bytes starting from @offset
1392  * in @buffer.
1393  *
1394  * When this function returns %TRUE, @idx will contain the index of the first
1395  * memory block where the byte for @offset can be found and @length contains the
1396  * number of memory blocks containing the @size remaining bytes. @skip contains
1397  * the number of bytes to skip in the memory block at @idx to get to the byte
1398  * for @offset.
1399  *
1400  * @size can be -1 to get all the memory blocks after @idx.
1401  *
1402  * Returns: %TRUE when @size bytes starting from @offset could be found in
1403  * @buffer and @idx, @length and @skip will be filled.
1404  */
1405 gboolean
1406 gst_buffer_find_memory (GstBuffer * buffer, gsize offset, gsize size,
1407     guint * idx, guint * length, gsize * skip)
1408 {
1409   guint i, len, found;
1410
1411   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1412   g_return_val_if_fail (idx != NULL, FALSE);
1413   g_return_val_if_fail (length != NULL, FALSE);
1414   g_return_val_if_fail (skip != NULL, FALSE);
1415
1416   len = GST_BUFFER_MEM_LEN (buffer);
1417
1418   found = 0;
1419   for (i = 0; i < len; i++) {
1420     GstMemory *mem;
1421     gsize s;
1422
1423     mem = GST_BUFFER_MEM_PTR (buffer, i);
1424     s = mem->size;
1425
1426     if (s <= offset) {
1427       /* block before offset, or empty block, skip */
1428       offset -= s;
1429     } else {
1430       /* block after offset */
1431       if (found == 0) {
1432         /* first block, remember index and offset */
1433         *idx = i;
1434         *skip = offset;
1435         if (size == -1) {
1436           /* return remaining blocks */
1437           *length = len - i;
1438           return TRUE;
1439         }
1440         s -= offset;
1441         offset = 0;
1442       }
1443       /* count the amount of found bytes */
1444       found += s;
1445       if (found >= size) {
1446         /* we have enough bytes */
1447         *length = i - *idx + 1;
1448         return TRUE;
1449       }
1450     }
1451   }
1452   return FALSE;
1453 }
1454
1455 /**
1456  * gst_buffer_is_memory_range_writable:
1457  * @buffer: a #GstBuffer.
1458  * @idx: an index
1459  * @length: a length, should not be 0
1460  *
1461  * Checks if @length memory blocks in @buffer starting from @idx are writable.
1462  *
1463  * @length can be -1 to check all the memory blocks after @idx.
1464  *
1465  * Note that this function does not check if @buffer is writable, use
1466  * gst_buffer_is_writable() to check that if needed.
1467  *
1468  * Returns: %TRUE if the memory range is writable
1469  *
1470  * Since: 1.4
1471  */
1472 gboolean
1473 gst_buffer_is_memory_range_writable (GstBuffer * buffer, guint idx, gint length)
1474 {
1475   guint i, len;
1476
1477   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1478
1479   GST_CAT_DEBUG (GST_CAT_BUFFER, "idx %u, length %d", idx, length);
1480
1481   len = GST_BUFFER_MEM_LEN (buffer);
1482   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1483       (length == -1 && idx < len) || (length > 0 && length + idx <= len),
1484       FALSE);
1485
1486   if (length == -1)
1487     len -= idx;
1488   else
1489     len = length;
1490
1491   for (i = 0; i < len; i++) {
1492     if (!gst_memory_is_writable (GST_BUFFER_MEM_PTR (buffer, i + idx)))
1493       return FALSE;
1494   }
1495   return TRUE;
1496 }
1497
1498 /**
1499  * gst_buffer_is_all_memory_writable:
1500  * @buffer: a #GstBuffer.
1501  *
1502  * Checks if all memory blocks in @buffer are writable.
1503  *
1504  * Note that this function does not check if @buffer is writable, use
1505  * gst_buffer_is_writable() to check that if needed.
1506  *
1507  * Returns: %TRUE if all memory blocks in @buffer are writable
1508  *
1509  * Since: 1.4
1510  */
1511 gboolean
1512 gst_buffer_is_all_memory_writable (GstBuffer * buffer)
1513 {
1514   return gst_buffer_is_memory_range_writable (buffer, 0, -1);
1515 }
1516
1517 /**
1518  * gst_buffer_get_sizes:
1519  * @buffer: a #GstBuffer.
1520  * @offset: (out) (allow-none): a pointer to the offset
1521  * @maxsize: (out) (allow-none): a pointer to the maxsize
1522  *
1523  * Gets the total size of the memory blocks in @buffer.
1524  *
1525  * When not %NULL, @offset will contain the offset of the data in the
1526  * first memory block in @buffer and @maxsize will contain the sum of
1527  * the size and @offset and the amount of extra padding on the last
1528  * memory block.  @offset and @maxsize can be used to resize the
1529  * buffer memory blocks with gst_buffer_resize().
1530  *
1531  * Returns: total size of the memory blocks in @buffer.
1532  */
1533 gsize
1534 gst_buffer_get_sizes (GstBuffer * buffer, gsize * offset, gsize * maxsize)
1535 {
1536   return gst_buffer_get_sizes_range (buffer, 0, -1, offset, maxsize);
1537 }
1538
1539 /**
1540  * gst_buffer_get_size:
1541  * @buffer: a #GstBuffer.
1542  *
1543  * Gets the total size of the memory blocks in @buffer.
1544  *
1545  * Returns: total size of the memory blocks in @buffer.
1546  */
1547 gsize
1548 gst_buffer_get_size (GstBuffer * buffer)
1549 {
1550   guint i;
1551   gsize size, len;
1552
1553   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1554
1555   /* FAST PATH */
1556   len = GST_BUFFER_MEM_LEN (buffer);
1557   for (i = 0, size = 0; i < len; i++)
1558     size += GST_BUFFER_MEM_PTR (buffer, i)->size;
1559   return size;
1560 }
1561
1562 /**
1563  * gst_buffer_get_sizes_range:
1564  * @buffer: a #GstBuffer.
1565  * @idx: an index
1566  * @length: a length
1567  * @offset: (out) (allow-none): a pointer to the offset
1568  * @maxsize: (out) (allow-none): a pointer to the maxsize
1569  *
1570  * Gets the total size of @length memory blocks stating from @idx in @buffer.
1571  *
1572  * When not %NULL, @offset will contain the offset of the data in the
1573  * memory block in @buffer at @idx and @maxsize will contain the sum of the size
1574  * and @offset and the amount of extra padding on the memory block at @idx +
1575  * @length -1.
1576  * @offset and @maxsize can be used to resize the buffer memory blocks with
1577  * gst_buffer_resize_range().
1578  *
1579  * Returns: total size of @length memory blocks starting at @idx in @buffer.
1580  */
1581 gsize
1582 gst_buffer_get_sizes_range (GstBuffer * buffer, guint idx, gint length,
1583     gsize * offset, gsize * maxsize)
1584 {
1585   guint len;
1586   gsize size;
1587   GstMemory *mem;
1588
1589   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1590   len = GST_BUFFER_MEM_LEN (buffer);
1591   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1592       (length == -1 && idx < len) || (length + idx <= len), 0);
1593
1594   if (length == -1)
1595     length = len - idx;
1596
1597   if (G_LIKELY (length == 1)) {
1598     /* common case */
1599     mem = GST_BUFFER_MEM_PTR (buffer, idx);
1600     size = gst_memory_get_sizes (mem, offset, maxsize);
1601   } else if (offset == NULL && maxsize == NULL) {
1602     /* FAST PATH ! */
1603     guint i, end;
1604
1605     size = 0;
1606     end = idx + length;
1607     for (i = idx; i < end; i++) {
1608       mem = GST_BUFFER_MEM_PTR (buffer, i);
1609       size += mem->size;
1610     }
1611   } else {
1612     guint i, end;
1613     gsize extra, offs;
1614
1615     end = idx + length;
1616     size = offs = extra = 0;
1617     for (i = idx; i < end; i++) {
1618       gsize s, o, ms;
1619
1620       mem = GST_BUFFER_MEM_PTR (buffer, i);
1621       s = gst_memory_get_sizes (mem, &o, &ms);
1622
1623       if (s) {
1624         if (size == 0)
1625           /* first size, take accumulated data before as the offset */
1626           offs = extra + o;
1627         /* add sizes */
1628         size += s;
1629         /* save the amount of data after this block */
1630         extra = ms - (o + s);
1631       } else {
1632         /* empty block, add as extra */
1633         extra += ms;
1634       }
1635     }
1636     if (offset)
1637       *offset = offs;
1638     if (maxsize)
1639       *maxsize = offs + size + extra;
1640   }
1641   return size;
1642 }
1643
1644 /**
1645  * gst_buffer_resize:
1646  * @buffer: a #GstBuffer.
1647  * @offset: the offset adjustment
1648  * @size: the new size or -1 to just adjust the offset
1649  *
1650  * Sets the offset and total size of the memory blocks in @buffer.
1651  */
1652 void
1653 gst_buffer_resize (GstBuffer * buffer, gssize offset, gssize size)
1654 {
1655   gst_buffer_resize_range (buffer, 0, -1, offset, size);
1656 }
1657
1658 /**
1659  * gst_buffer_set_size:
1660  * @buffer: a #GstBuffer.
1661  * @size: the new size
1662  *
1663  * Sets the total size of the memory blocks in @buffer.
1664  */
1665 void
1666 gst_buffer_set_size (GstBuffer * buffer, gssize size)
1667 {
1668   gst_buffer_resize_range (buffer, 0, -1, 0, size);
1669 }
1670
1671 /**
1672  * gst_buffer_resize_range:
1673  * @buffer: a #GstBuffer.
1674  * @idx: an index
1675  * @length: a length
1676  * @offset: the offset adjustment
1677  * @size: the new size or -1 to just adjust the offset
1678  *
1679  * Sets the total size of the @length memory blocks starting at @idx in
1680  * @buffer
1681  *
1682  * Returns: %TRUE if resizing succeeded, %FALSE otherwise.
1683  */
1684 gboolean
1685 gst_buffer_resize_range (GstBuffer * buffer, guint idx, gint length,
1686     gssize offset, gssize size)
1687 {
1688   guint i, len, end;
1689   gsize bsize, bufsize, bufoffs, bufmax;
1690
1691   g_return_val_if_fail (gst_buffer_is_writable (buffer), FALSE);
1692   g_return_val_if_fail (size >= -1, FALSE);
1693
1694   len = GST_BUFFER_MEM_LEN (buffer);
1695   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1696       (length == -1 && idx < len) || (length + idx <= len), FALSE);
1697
1698   if (length == -1)
1699     length = len - idx;
1700
1701   bufsize = gst_buffer_get_sizes_range (buffer, idx, length, &bufoffs, &bufmax);
1702
1703   GST_CAT_LOG (GST_CAT_BUFFER, "trim %p %" G_GSSIZE_FORMAT "-%" G_GSSIZE_FORMAT
1704       " size:%" G_GSIZE_FORMAT " offs:%" G_GSIZE_FORMAT " max:%"
1705       G_GSIZE_FORMAT, buffer, offset, size, bufsize, bufoffs, bufmax);
1706
1707   /* we can't go back further than the current offset or past the end of the
1708    * buffer */
1709   g_return_val_if_fail ((offset < 0 && bufoffs >= -offset) || (offset >= 0
1710           && bufoffs + offset <= bufmax), FALSE);
1711   if (size == -1) {
1712     g_return_val_if_fail (bufsize >= offset, FALSE);
1713     size = bufsize - offset;
1714   }
1715   g_return_val_if_fail (bufmax >= bufoffs + offset + size, FALSE);
1716
1717   /* no change */
1718   if (offset == 0 && size == bufsize)
1719     return TRUE;
1720
1721   end = idx + length;
1722   /* copy and trim */
1723   for (i = idx; i < end; i++) {
1724     GstMemory *mem;
1725     gsize left, noffs;
1726
1727     mem = GST_BUFFER_MEM_PTR (buffer, i);
1728     bsize = mem->size;
1729
1730     noffs = 0;
1731     /* last buffer always gets resized to the remaining size */
1732     if (i + 1 == end)
1733       left = size;
1734     /* shrink buffers before the offset */
1735     else if ((gssize) bsize <= offset) {
1736       left = 0;
1737       noffs = offset - bsize;
1738       offset = 0;
1739     }
1740     /* clip other buffers */
1741     else
1742       left = MIN (bsize - offset, size);
1743
1744     if (offset != 0 || left != bsize) {
1745       if (gst_memory_is_writable (mem)) {
1746         gst_memory_resize (mem, offset, left);
1747       } else {
1748         GstMemory *newmem = NULL;
1749
1750         if (!GST_MEMORY_IS_NO_SHARE (mem))
1751           newmem = gst_memory_share (mem, offset, left);
1752
1753         if (!newmem)
1754           newmem = gst_memory_copy (mem, offset, left);
1755
1756         if (newmem == NULL)
1757           return FALSE;
1758
1759         gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (newmem),
1760             GST_MINI_OBJECT_CAST (buffer));
1761         gst_memory_lock (newmem, GST_LOCK_FLAG_EXCLUSIVE);
1762         GST_BUFFER_MEM_PTR (buffer, i) = newmem;
1763         gst_memory_unlock (mem, GST_LOCK_FLAG_EXCLUSIVE);
1764         gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
1765             GST_MINI_OBJECT_CAST (buffer));
1766         gst_memory_unref (mem);
1767
1768         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
1769       }
1770     }
1771
1772     offset = noffs;
1773     size -= left;
1774   }
1775
1776   return TRUE;
1777 }
1778
1779 /**
1780  * gst_buffer_map:
1781  * @buffer: a #GstBuffer.
1782  * @info: (out caller-allocates): info about the mapping
1783  * @flags: flags for the mapping
1784  *
1785  * Fills @info with the #GstMapInfo of all merged memory blocks in @buffer.
1786  *
1787  * @flags describe the desired access of the memory. When @flags is
1788  * #GST_MAP_WRITE, @buffer should be writable (as returned from
1789  * gst_buffer_is_writable()).
1790  *
1791  * When @buffer is writable but the memory isn't, a writable copy will
1792  * automatically be created and returned. The readonly copy of the
1793  * buffer memory will then also be replaced with this writable copy.
1794  *
1795  * The memory in @info should be unmapped with gst_buffer_unmap() after
1796  * usage.
1797  *
1798  * Returns: %TRUE if the map succeeded and @info contains valid data.
1799  */
1800 gboolean
1801 gst_buffer_map (GstBuffer * buffer, GstMapInfo * info, GstMapFlags flags)
1802 {
1803   return gst_buffer_map_range (buffer, 0, -1, info, flags);
1804 }
1805
1806 /**
1807  * gst_buffer_map_range:
1808  * @buffer: a #GstBuffer.
1809  * @idx: an index
1810  * @length: a length
1811  * @info: (out caller-allocates): info about the mapping
1812  * @flags: flags for the mapping
1813  *
1814  * Fills @info with the #GstMapInfo of @length merged memory blocks
1815  * starting at @idx in @buffer. When @length is -1, all memory blocks starting
1816  * from @idx are merged and mapped.
1817  *
1818  * @flags describe the desired access of the memory. When @flags is
1819  * #GST_MAP_WRITE, @buffer should be writable (as returned from
1820  * gst_buffer_is_writable()).
1821  *
1822  * When @buffer is writable but the memory isn't, a writable copy will
1823  * automatically be created and returned. The readonly copy of the buffer memory
1824  * will then also be replaced with this writable copy.
1825  *
1826  * The memory in @info should be unmapped with gst_buffer_unmap() after usage.
1827  *
1828  * Returns: %TRUE if the map succeeded and @info contains valid
1829  * data.
1830  */
1831 gboolean
1832 gst_buffer_map_range (GstBuffer * buffer, guint idx, gint length,
1833     GstMapInfo * info, GstMapFlags flags)
1834 {
1835   GstMemory *mem, *nmem;
1836   gboolean write, writable;
1837   gsize len;
1838
1839   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1840   g_return_val_if_fail (info != NULL, FALSE);
1841   len = GST_BUFFER_MEM_LEN (buffer);
1842   g_return_val_if_fail ((len == 0 && idx == 0 && length == -1) ||
1843       (length == -1 && idx < len) || (length > 0
1844           && length + idx <= len), FALSE);
1845
1846   GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %u, length %d, flags %04x",
1847       buffer, idx, length, flags);
1848
1849   write = (flags & GST_MAP_WRITE) != 0;
1850   writable = gst_buffer_is_writable (buffer);
1851
1852   /* check if we can write when asked for write access */
1853   if (G_UNLIKELY (write && !writable))
1854     goto not_writable;
1855
1856   if (length == -1)
1857     length = len - idx;
1858
1859   mem = _get_merged_memory (buffer, idx, length);
1860   if (G_UNLIKELY (mem == NULL))
1861     goto no_memory;
1862
1863   /* now try to map */
1864   nmem = gst_memory_make_mapped (mem, info, flags);
1865   if (G_UNLIKELY (nmem == NULL))
1866     goto cannot_map;
1867
1868   /* if we merged or when the map returned a different memory, we try to replace
1869    * the memory in the buffer */
1870   if (G_UNLIKELY (length > 1 || nmem != mem)) {
1871     /* if the buffer is writable, replace the memory */
1872     if (writable) {
1873       _replace_memory (buffer, len, idx, length, gst_memory_ref (nmem));
1874     } else {
1875       if (len > 1) {
1876         GST_CAT_DEBUG (GST_CAT_PERFORMANCE,
1877             "temporary mapping for memory %p in buffer %p", nmem, buffer);
1878       }
1879     }
1880   }
1881   return TRUE;
1882
1883   /* ERROR */
1884 not_writable:
1885   {
1886     GST_WARNING ("write map requested on non-writable buffer");
1887     g_critical ("write map requested on non-writable buffer");
1888     memset (info, 0, sizeof (GstMapInfo));
1889     return FALSE;
1890   }
1891 no_memory:
1892   {
1893     /* empty buffer, we need to return NULL */
1894     GST_DEBUG ("can't get buffer memory");
1895     memset (info, 0, sizeof (GstMapInfo));
1896     return TRUE;
1897   }
1898 cannot_map:
1899   {
1900     GST_DEBUG ("cannot map memory");
1901     memset (info, 0, sizeof (GstMapInfo));
1902     return FALSE;
1903   }
1904 }
1905
1906 /**
1907  * gst_buffer_unmap:
1908  * @buffer: a #GstBuffer.
1909  * @info: a #GstMapInfo
1910  *
1911  * Releases the memory previously mapped with gst_buffer_map().
1912  */
1913 void
1914 gst_buffer_unmap (GstBuffer * buffer, GstMapInfo * info)
1915 {
1916   g_return_if_fail (GST_IS_BUFFER (buffer));
1917   g_return_if_fail (info != NULL);
1918
1919   _gst_buffer_map_info_clear ((GstBufferMapInfo *) info);
1920 }
1921
1922 /**
1923  * gst_buffer_fill:
1924  * @buffer: a #GstBuffer.
1925  * @offset: the offset to fill
1926  * @src: (array length=size) (element-type guint8): the source address
1927  * @size: the size to fill
1928  *
1929  * Copies @size bytes from @src to @buffer at @offset.
1930  *
1931  * Returns: The amount of bytes copied. This value can be lower than @size
1932  *    when @buffer did not contain enough data.
1933  */
1934 gsize
1935 gst_buffer_fill (GstBuffer * buffer, gsize offset, gconstpointer src,
1936     gsize size)
1937 {
1938   gsize i, len, left;
1939   const guint8 *ptr = src;
1940
1941   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1942   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1943   g_return_val_if_fail (src != NULL || size == 0, 0);
1944
1945   GST_CAT_LOG (GST_CAT_BUFFER,
1946       "buffer %p, offset %" G_GSIZE_FORMAT ", size %" G_GSIZE_FORMAT, buffer,
1947       offset, size);
1948
1949   len = GST_BUFFER_MEM_LEN (buffer);
1950   left = size;
1951
1952   for (i = 0; i < len && left > 0; i++) {
1953     GstMapInfo info;
1954     gsize tocopy;
1955     GstMemory *mem;
1956
1957     mem = _get_mapped (buffer, i, &info, GST_MAP_WRITE);
1958     if (info.size > offset) {
1959       /* we have enough */
1960       tocopy = MIN (info.size - offset, left);
1961       memcpy ((guint8 *) info.data + offset, ptr, tocopy);
1962       left -= tocopy;
1963       ptr += tocopy;
1964       offset = 0;
1965     } else {
1966       /* offset past buffer, skip */
1967       offset -= info.size;
1968     }
1969     gst_memory_unmap (mem, &info);
1970   }
1971   return size - left;
1972 }
1973
1974 /**
1975  * gst_buffer_extract:
1976  * @buffer: a #GstBuffer.
1977  * @offset: the offset to extract
1978  * @dest: (out caller-allocates) (array length=size) (element-type guint8):
1979  *     the destination address
1980  * @size: the size to extract
1981  *
1982  * Copies @size bytes starting from @offset in @buffer to @dest.
1983  *
1984  * Returns: The amount of bytes extracted. This value can be lower than @size
1985  *    when @buffer did not contain enough data.
1986  */
1987 gsize
1988 gst_buffer_extract (GstBuffer * buffer, gsize offset, gpointer dest, gsize size)
1989 {
1990   gsize i, len, left;
1991   guint8 *ptr = dest;
1992
1993   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1994   g_return_val_if_fail (dest != NULL, 0);
1995
1996   GST_CAT_LOG (GST_CAT_BUFFER,
1997       "buffer %p, offset %" G_GSIZE_FORMAT ", size %" G_GSIZE_FORMAT, buffer,
1998       offset, size);
1999
2000   len = GST_BUFFER_MEM_LEN (buffer);
2001   left = size;
2002
2003   for (i = 0; i < len && left > 0; i++) {
2004     GstMapInfo info;
2005     gsize tocopy;
2006     GstMemory *mem;
2007
2008     mem = _get_mapped (buffer, i, &info, GST_MAP_READ);
2009     if (info.size > offset) {
2010       /* we have enough */
2011       tocopy = MIN (info.size - offset, left);
2012       memcpy (ptr, (guint8 *) info.data + offset, tocopy);
2013       left -= tocopy;
2014       ptr += tocopy;
2015       offset = 0;
2016     } else {
2017       /* offset past buffer, skip */
2018       offset -= info.size;
2019     }
2020     gst_memory_unmap (mem, &info);
2021   }
2022   return size - left;
2023 }
2024
2025 /**
2026  * gst_buffer_memcmp:
2027  * @buffer: a #GstBuffer.
2028  * @offset: the offset in @buffer
2029  * @mem: (array length=size) (element-type guint8): the memory to compare
2030  * @size: the size to compare
2031  *
2032  * Compares @size bytes starting from @offset in @buffer with the memory in @mem.
2033  *
2034  * Returns: 0 if the memory is equal.
2035  */
2036 gint
2037 gst_buffer_memcmp (GstBuffer * buffer, gsize offset, gconstpointer mem,
2038     gsize size)
2039 {
2040   gsize i, len;
2041   const guint8 *ptr = mem;
2042   gint res = 0;
2043
2044   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
2045   g_return_val_if_fail (mem != NULL, 0);
2046
2047   GST_CAT_LOG (GST_CAT_BUFFER,
2048       "buffer %p, offset %" G_GSIZE_FORMAT ", size %" G_GSIZE_FORMAT, buffer,
2049       offset, size);
2050
2051   if (G_UNLIKELY (gst_buffer_get_size (buffer) < offset + size))
2052     return -1;
2053
2054   len = GST_BUFFER_MEM_LEN (buffer);
2055
2056   for (i = 0; i < len && size > 0 && res == 0; i++) {
2057     GstMapInfo info;
2058     gsize tocmp;
2059     GstMemory *mem;
2060
2061     mem = _get_mapped (buffer, i, &info, GST_MAP_READ);
2062     if (info.size > offset) {
2063       /* we have enough */
2064       tocmp = MIN (info.size - offset, size);
2065       res = memcmp (ptr, (guint8 *) info.data + offset, tocmp);
2066       size -= tocmp;
2067       ptr += tocmp;
2068       offset = 0;
2069     } else {
2070       /* offset past buffer, skip */
2071       offset -= info.size;
2072     }
2073     gst_memory_unmap (mem, &info);
2074   }
2075   return res;
2076 }
2077
2078 /**
2079  * gst_buffer_memset:
2080  * @buffer: a #GstBuffer.
2081  * @offset: the offset in @buffer
2082  * @val: the value to set
2083  * @size: the size to set
2084  *
2085  * Fills @buf with @size bytes with @val starting from @offset.
2086  *
2087  * Returns: The amount of bytes filled. This value can be lower than @size
2088  *    when @buffer did not contain enough data.
2089  */
2090 gsize
2091 gst_buffer_memset (GstBuffer * buffer, gsize offset, guint8 val, gsize size)
2092 {
2093   gsize i, len, left;
2094
2095   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
2096   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
2097
2098   GST_CAT_LOG (GST_CAT_BUFFER,
2099       "buffer %p, offset %" G_GSIZE_FORMAT ", val %02x, size %" G_GSIZE_FORMAT,
2100       buffer, offset, val, size);
2101
2102   len = GST_BUFFER_MEM_LEN (buffer);
2103   left = size;
2104
2105   for (i = 0; i < len && left > 0; i++) {
2106     GstMapInfo info;
2107     gsize toset;
2108     GstMemory *mem;
2109
2110     mem = _get_mapped (buffer, i, &info, GST_MAP_WRITE);
2111     if (info.size > offset) {
2112       /* we have enough */
2113       toset = MIN (info.size - offset, left);
2114       memset ((guint8 *) info.data + offset, val, toset);
2115       left -= toset;
2116       offset = 0;
2117     } else {
2118       /* offset past buffer, skip */
2119       offset -= info.size;
2120     }
2121     gst_memory_unmap (mem, &info);
2122   }
2123   return size - left;
2124 }
2125
2126 /**
2127  * gst_buffer_copy_region:
2128  * @parent: a #GstBuffer.
2129  * @flags: the #GstBufferCopyFlags
2130  * @offset: the offset into parent #GstBuffer at which the new sub-buffer
2131  *          begins.
2132  * @size: the size of the new #GstBuffer sub-buffer, in bytes. If -1, all
2133  *        data is copied.
2134  *
2135  * Creates a sub-buffer from @parent at @offset and @size.
2136  * This sub-buffer uses the actual memory space of the parent buffer.
2137  * This function will copy the offset and timestamp fields when the
2138  * offset is 0. If not, they will be set to #GST_CLOCK_TIME_NONE and
2139  * #GST_BUFFER_OFFSET_NONE.
2140  * If @offset equals 0 and @size equals the total size of @buffer, the
2141  * duration and offset end fields are also copied. If not they will be set
2142  * to #GST_CLOCK_TIME_NONE and #GST_BUFFER_OFFSET_NONE.
2143  *
2144  * Returns: (transfer full) (nullable): the new #GstBuffer or %NULL if copying
2145  *     failed.
2146  */
2147 GstBuffer *
2148 gst_buffer_copy_region (GstBuffer * buffer, GstBufferCopyFlags flags,
2149     gsize offset, gsize size)
2150 {
2151   GstBuffer *copy;
2152
2153   g_return_val_if_fail (buffer != NULL, NULL);
2154
2155   /* create the new buffer */
2156   copy = gst_buffer_new ();
2157
2158   GST_CAT_LOG (GST_CAT_BUFFER, "new region copy %p of %p %" G_GSIZE_FORMAT
2159       "-%" G_GSIZE_FORMAT, copy, buffer, offset, size);
2160
2161   if (!gst_buffer_copy_into (copy, buffer, flags, offset, size))
2162     gst_buffer_replace (&copy, NULL);
2163
2164   return copy;
2165 }
2166
2167 /**
2168  * gst_buffer_append:
2169  * @buf1: (transfer full): the first source #GstBuffer to append.
2170  * @buf2: (transfer full): the second source #GstBuffer to append.
2171  *
2172  * Appends all the memory from @buf2 to @buf1. The result buffer will contain a
2173  * concatenation of the memory of @buf1 and @buf2.
2174  *
2175  * Returns: (transfer full): the new #GstBuffer that contains the memory
2176  *     of the two source buffers.
2177  */
2178 GstBuffer *
2179 gst_buffer_append (GstBuffer * buf1, GstBuffer * buf2)
2180 {
2181   return gst_buffer_append_region (buf1, buf2, 0, -1);
2182 }
2183
2184 /**
2185  * gst_buffer_append_region:
2186  * @buf1: (transfer full): the first source #GstBuffer to append.
2187  * @buf2: (transfer full): the second source #GstBuffer to append.
2188  * @offset: the offset in @buf2
2189  * @size: the size or -1 of @buf2
2190  *
2191  * Appends @size bytes at @offset from @buf2 to @buf1. The result buffer will
2192  * contain a concatenation of the memory of @buf1 and the requested region of
2193  * @buf2.
2194  *
2195  * Returns: (transfer full): the new #GstBuffer that contains the memory
2196  *     of the two source buffers.
2197  */
2198 GstBuffer *
2199 gst_buffer_append_region (GstBuffer * buf1, GstBuffer * buf2, gssize offset,
2200     gssize size)
2201 {
2202   gsize i, len;
2203
2204   g_return_val_if_fail (GST_IS_BUFFER (buf1), NULL);
2205   g_return_val_if_fail (GST_IS_BUFFER (buf2), NULL);
2206
2207   buf1 = gst_buffer_make_writable (buf1);
2208   buf2 = gst_buffer_make_writable (buf2);
2209
2210   gst_buffer_resize (buf2, offset, size);
2211
2212   len = GST_BUFFER_MEM_LEN (buf2);
2213   for (i = 0; i < len; i++) {
2214     GstMemory *mem;
2215
2216     mem = GST_BUFFER_MEM_PTR (buf2, i);
2217     gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
2218         GST_MINI_OBJECT_CAST (buf2));
2219     GST_BUFFER_MEM_PTR (buf2, i) = NULL;
2220     _memory_add (buf1, -1, mem);
2221   }
2222
2223   GST_BUFFER_MEM_LEN (buf2) = 0;
2224   GST_BUFFER_FLAG_SET (buf2, GST_BUFFER_FLAG_TAG_MEMORY);
2225   gst_buffer_unref (buf2);
2226
2227   return buf1;
2228 }
2229
2230 /**
2231  * gst_buffer_get_meta:
2232  * @buffer: a #GstBuffer
2233  * @api: the #GType of an API
2234  *
2235  * Gets the metadata for @api on buffer. When there is no such metadata, %NULL is
2236  * returned. If multiple metadata with the given @api are attached to this
2237  * buffer only the first one is returned.  To handle multiple metadata with a
2238  * given API use gst_buffer_iterate_meta() or gst_buffer_foreach_meta() instead
2239  * and check the `meta->info.api` member for the API type.
2240  *
2241  * Returns: (transfer none) (nullable): the metadata for @api on @buffer.
2242  */
2243 GstMeta *
2244 gst_buffer_get_meta (GstBuffer * buffer, GType api)
2245 {
2246   GstMetaItem *item;
2247   GstMeta *result = NULL;
2248
2249   g_return_val_if_fail (buffer != NULL, NULL);
2250   g_return_val_if_fail (api != 0, NULL);
2251
2252   /* find GstMeta of the requested API */
2253   for (item = GST_BUFFER_META (buffer); item; item = item->next) {
2254     GstMeta *meta = &item->meta;
2255     if (meta->info->api == api) {
2256       result = meta;
2257       break;
2258     }
2259   }
2260   return result;
2261 }
2262
2263 /**
2264  * gst_buffer_get_n_meta:
2265  * @buffer: a #GstBuffer
2266  * @api_type: the #GType of an API
2267  *
2268  * Returns: number of metas of type @api_type on @buffer.
2269  *
2270  * Since: 1.14
2271  */
2272 guint
2273 gst_buffer_get_n_meta (GstBuffer * buffer, GType api_type)
2274 {
2275   gpointer state = NULL;
2276   GstMeta *meta;
2277   guint n = 0;
2278
2279   while ((meta = gst_buffer_iterate_meta_filtered (buffer, &state, api_type)))
2280     ++n;
2281
2282   return n;
2283 }
2284
2285 /**
2286  * gst_buffer_add_meta:
2287  * @buffer: a #GstBuffer
2288  * @info: a #GstMetaInfo
2289  * @params: params for @info
2290  *
2291  * Adds metadata for @info to @buffer using the parameters in @params.
2292  *
2293  * Returns: (transfer none) (nullable): the metadata for the api in @info on @buffer.
2294  */
2295 GstMeta *
2296 gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
2297     gpointer params)
2298 {
2299   GstMetaItem *item;
2300   GstMeta *result = NULL;
2301   gsize size;
2302
2303   g_return_val_if_fail (buffer != NULL, NULL);
2304   g_return_val_if_fail (info != NULL, NULL);
2305   g_return_val_if_fail (gst_buffer_is_writable (buffer), NULL);
2306
2307   /* create a new slice */
2308   size = ITEM_SIZE (info);
2309   /* We warn in gst_meta_register() about metas without
2310    * init function but let's play safe here and prevent
2311    * uninitialized memory
2312    */
2313   if (!info->init_func)
2314     item = g_slice_alloc0 (size);
2315   else
2316     item = g_slice_alloc (size);
2317   result = &item->meta;
2318   result->info = info;
2319   result->flags = GST_META_FLAG_NONE;
2320   GST_CAT_DEBUG (GST_CAT_BUFFER,
2321       "alloc metadata %p (%s) of size %" G_GSIZE_FORMAT, result,
2322       g_type_name (info->type), info->size);
2323
2324   /* call the init_func when needed */
2325   if (info->init_func)
2326     if (!info->init_func (result, params, buffer))
2327       goto init_failed;
2328
2329   item->seq_num = gst_atomic_int64_inc (&meta_seq);
2330   item->next = NULL;
2331
2332   if (!GST_BUFFER_META (buffer)) {
2333     GST_BUFFER_META (buffer) = item;
2334     GST_BUFFER_TAIL_META (buffer) = item;
2335   } else {
2336     GST_BUFFER_TAIL_META (buffer)->next = item;
2337     GST_BUFFER_TAIL_META (buffer) = item;
2338   }
2339
2340   return result;
2341
2342 init_failed:
2343   {
2344     g_slice_free1 (size, item);
2345     return NULL;
2346   }
2347 }
2348
2349 /**
2350  * gst_buffer_remove_meta:
2351  * @buffer: a #GstBuffer
2352  * @meta: a #GstMeta
2353  *
2354  * Removes the metadata for @meta on @buffer.
2355  *
2356  * Returns: %TRUE if the metadata existed and was removed, %FALSE if no such
2357  * metadata was on @buffer.
2358  */
2359 gboolean
2360 gst_buffer_remove_meta (GstBuffer * buffer, GstMeta * meta)
2361 {
2362   GstMetaItem *walk, *prev;
2363
2364   g_return_val_if_fail (buffer != NULL, FALSE);
2365   g_return_val_if_fail (meta != NULL, FALSE);
2366   g_return_val_if_fail (gst_buffer_is_writable (buffer), FALSE);
2367   g_return_val_if_fail (!GST_META_FLAG_IS_SET (meta, GST_META_FLAG_LOCKED),
2368       FALSE);
2369
2370   /* find the metadata and delete */
2371   prev = GST_BUFFER_META (buffer);
2372   for (walk = prev; walk; walk = walk->next) {
2373     GstMeta *m = &walk->meta;
2374     if (m == meta) {
2375       const GstMetaInfo *info = meta->info;
2376
2377       /* remove from list */
2378       if (GST_BUFFER_TAIL_META (buffer) == walk) {
2379         if (prev != walk)
2380           GST_BUFFER_TAIL_META (buffer) = prev;
2381         else
2382           GST_BUFFER_TAIL_META (buffer) = NULL;
2383       }
2384
2385       if (GST_BUFFER_META (buffer) == walk)
2386         GST_BUFFER_META (buffer) = walk->next;
2387       else
2388         prev->next = walk->next;
2389
2390       /* call free_func if any */
2391       if (info->free_func)
2392         info->free_func (m, buffer);
2393
2394       /* and free the slice */
2395       g_slice_free1 (ITEM_SIZE (info), walk);
2396       break;
2397     }
2398     prev = walk;
2399   }
2400   return walk != NULL;
2401 }
2402
2403 /**
2404  * gst_buffer_iterate_meta: (skip)
2405  * @buffer: a #GstBuffer
2406  * @state: (out caller-allocates): an opaque state pointer
2407  *
2408  * Retrieves the next #GstMeta after @current. If @state points
2409  * to %NULL, the first metadata is returned.
2410  *
2411  * @state will be updated with an opaque state pointer
2412  *
2413  * Returns: (transfer none) (nullable): The next #GstMeta or %NULL
2414  * when there are no more items.
2415  */
2416 GstMeta *
2417 gst_buffer_iterate_meta (GstBuffer * buffer, gpointer * state)
2418 {
2419   GstMetaItem **meta;
2420
2421   g_return_val_if_fail (buffer != NULL, NULL);
2422   g_return_val_if_fail (state != NULL, NULL);
2423
2424   meta = (GstMetaItem **) state;
2425   if (*meta == NULL)
2426     /* state NULL, move to first item */
2427     *meta = GST_BUFFER_META (buffer);
2428   else
2429     /* state !NULL, move to next item in list */
2430     *meta = (*meta)->next;
2431
2432   if (*meta)
2433     return &(*meta)->meta;
2434   else
2435     return NULL;
2436 }
2437
2438 /**
2439  * gst_buffer_iterate_meta_filtered: (skip)
2440  * @buffer: a #GstBuffer
2441  * @state: (out caller-allocates): an opaque state pointer
2442  * @meta_api_type: only return #GstMeta of this type
2443  *
2444  * Retrieves the next #GstMeta of type @meta_api_type after the current one
2445  * according to @state. If @state points to %NULL, the first metadata of
2446  * type @meta_api_type is returned.
2447  *
2448  * @state will be updated with an opaque state pointer
2449  *
2450  * Returns: (transfer none) (nullable): The next #GstMeta of type
2451  * @meta_api_type or %NULL when there are no more items.
2452  *
2453  * Since: 1.12
2454  */
2455 GstMeta *
2456 gst_buffer_iterate_meta_filtered (GstBuffer * buffer, gpointer * state,
2457     GType meta_api_type)
2458 {
2459   GstMetaItem **meta;
2460
2461   g_return_val_if_fail (buffer != NULL, NULL);
2462   g_return_val_if_fail (state != NULL, NULL);
2463
2464   meta = (GstMetaItem **) state;
2465   if (*meta == NULL)
2466     /* state NULL, move to first item */
2467     *meta = GST_BUFFER_META (buffer);
2468   else
2469     /* state !NULL, move to next item in list */
2470     *meta = (*meta)->next;
2471
2472   while (*meta != NULL && (*meta)->meta.info->api != meta_api_type)
2473     *meta = (*meta)->next;
2474
2475   if (*meta)
2476     return &(*meta)->meta;
2477   else
2478     return NULL;
2479 }
2480
2481 /**
2482  * gst_buffer_foreach_meta:
2483  * @buffer: a #GstBuffer
2484  * @func: (scope call): a #GstBufferForeachMetaFunc to call
2485  * @user_data: (closure): user data passed to @func
2486  *
2487  * Calls @func with @user_data for each meta in @buffer.
2488  *
2489  * @func can modify the passed meta pointer or its contents. The return value
2490  * of @func defines if this function returns or if the remaining metadata items
2491  * in the buffer should be skipped.
2492  *
2493  * Returns: %FALSE when @func returned %FALSE for one of the metadata.
2494  */
2495 gboolean
2496 gst_buffer_foreach_meta (GstBuffer * buffer, GstBufferForeachMetaFunc func,
2497     gpointer user_data)
2498 {
2499   GstMetaItem *walk, *prev, *next;
2500   gboolean res = TRUE;
2501
2502   g_return_val_if_fail (buffer != NULL, FALSE);
2503   g_return_val_if_fail (func != NULL, FALSE);
2504
2505   /* find the metadata and delete */
2506   prev = GST_BUFFER_META (buffer);
2507   for (walk = prev; walk; walk = next) {
2508     GstMeta *m, *new;
2509
2510     m = new = &walk->meta;
2511     next = walk->next;
2512
2513     res = func (buffer, &new, user_data);
2514
2515     if (new == NULL) {
2516       const GstMetaInfo *info = m->info;
2517
2518       GST_CAT_DEBUG (GST_CAT_BUFFER, "remove metadata %p (%s)", m,
2519           g_type_name (info->type));
2520
2521       g_return_val_if_fail (gst_buffer_is_writable (buffer), FALSE);
2522       g_return_val_if_fail (!GST_META_FLAG_IS_SET (m, GST_META_FLAG_LOCKED),
2523           FALSE);
2524
2525       if (GST_BUFFER_TAIL_META (buffer) == walk) {
2526         if (prev != walk)
2527           GST_BUFFER_TAIL_META (buffer) = prev;
2528         else
2529           GST_BUFFER_TAIL_META (buffer) = NULL;
2530       }
2531
2532       /* remove from list */
2533       if (GST_BUFFER_META (buffer) == walk)
2534         prev = GST_BUFFER_META (buffer) = next;
2535       else
2536         prev->next = next;
2537
2538       /* call free_func if any */
2539       if (info->free_func)
2540         info->free_func (m, buffer);
2541
2542       /* and free the slice */
2543       g_slice_free1 (ITEM_SIZE (info), walk);
2544     } else {
2545       prev = walk;
2546     }
2547     if (!res)
2548       break;
2549   }
2550   return res;
2551 }
2552
2553 /**
2554  * gst_buffer_extract_dup:
2555  * @buffer: a #GstBuffer
2556  * @offset: the offset to extract
2557  * @size: the size to extract
2558  * @dest: (array length=dest_size) (element-type guint8) (out): A pointer where
2559  *  the destination array will be written. Might be %NULL if the size is 0.
2560  * @dest_size: (out): A location where the size of @dest can be written
2561  *
2562  * Extracts a copy of at most @size bytes the data at @offset into
2563  * newly-allocated memory. @dest must be freed using g_free() when done.
2564  *
2565  * Since: 1.0.10
2566  */
2567
2568 void
2569 gst_buffer_extract_dup (GstBuffer * buffer, gsize offset, gsize size,
2570     gpointer * dest, gsize * dest_size)
2571 {
2572   gsize real_size, alloc_size;
2573
2574   real_size = gst_buffer_get_size (buffer);
2575
2576   alloc_size = MIN (real_size - offset, size);
2577   if (alloc_size == 0) {
2578     *dest = NULL;
2579     *dest_size = 0;
2580   } else {
2581     *dest = g_malloc (alloc_size);
2582     *dest_size = gst_buffer_extract (buffer, offset, *dest, size);
2583   }
2584 }
2585
2586 GST_DEBUG_CATEGORY_STATIC (gst_parent_buffer_meta_debug);
2587
2588 /**
2589  * gst_buffer_add_parent_buffer_meta:
2590  * @buffer: (transfer none): a #GstBuffer
2591  * @ref: (transfer none): a #GstBuffer to ref
2592  *
2593  * Adds a #GstParentBufferMeta to @buffer that holds a reference on
2594  * @ref until the buffer is freed.
2595  *
2596  * Returns: (transfer none) (nullable): The #GstParentBufferMeta that was added to the buffer
2597  *
2598  * Since: 1.6
2599  */
2600 GstParentBufferMeta *
2601 gst_buffer_add_parent_buffer_meta (GstBuffer * buffer, GstBuffer * ref)
2602 {
2603   GstParentBufferMeta *meta;
2604
2605   g_return_val_if_fail (GST_IS_BUFFER (ref), NULL);
2606
2607   meta =
2608       (GstParentBufferMeta *) gst_buffer_add_meta (buffer,
2609       GST_PARENT_BUFFER_META_INFO, NULL);
2610
2611   if (!meta)
2612     return NULL;
2613
2614   meta->buffer = gst_buffer_ref (ref);
2615
2616   return meta;
2617 }
2618
2619 static gboolean
2620 _gst_parent_buffer_meta_transform (GstBuffer * dest, GstMeta * meta,
2621     GstBuffer * buffer, GQuark type, gpointer data)
2622 {
2623   GstParentBufferMeta *dmeta, *smeta;
2624
2625   smeta = (GstParentBufferMeta *) meta;
2626
2627   if (GST_META_TRANSFORM_IS_COPY (type)) {
2628     /* copy over the reference to the parent buffer.
2629      * Usually, this meta means we need to keep the parent buffer
2630      * alive because one of the child memories is in use, which
2631      * might not be the case if memory is deep copied or sub-regioned,
2632      * but we can't tell, so keep the meta */
2633     dmeta = gst_buffer_add_parent_buffer_meta (dest, smeta->buffer);
2634     if (!dmeta)
2635       return FALSE;
2636
2637     GST_CAT_DEBUG (gst_parent_buffer_meta_debug,
2638         "copy buffer reference metadata");
2639   } else {
2640     /* return FALSE, if transform type is not supported */
2641     return FALSE;
2642   }
2643   return TRUE;
2644 }
2645
2646 static void
2647 _gst_parent_buffer_meta_free (GstParentBufferMeta * parent_meta,
2648     GstBuffer * buffer)
2649 {
2650   GST_CAT_DEBUG (gst_parent_buffer_meta_debug,
2651       "Dropping reference on buffer %p", parent_meta->buffer);
2652   gst_buffer_unref (parent_meta->buffer);
2653 }
2654
2655 static gboolean
2656 _gst_parent_buffer_meta_init (GstParentBufferMeta * parent_meta,
2657     gpointer params, GstBuffer * buffer)
2658 {
2659   static gsize _init;
2660
2661   if (g_once_init_enter (&_init)) {
2662     GST_DEBUG_CATEGORY_INIT (gst_parent_buffer_meta_debug, "parentbuffermeta",
2663         0, "parentbuffermeta");
2664     g_once_init_leave (&_init, 1);
2665   }
2666
2667   parent_meta->buffer = NULL;
2668
2669   return TRUE;
2670 }
2671
2672 /**
2673  * gst_parent_buffer_meta_api_get_type: (attributes doc.skip=true)
2674  */
2675 GType
2676 gst_parent_buffer_meta_api_get_type (void)
2677 {
2678   static GType type = 0;
2679   static const gchar *tags[] = { GST_META_TAG_MEMORY_REFERENCE_STR, NULL };
2680
2681   if (g_once_init_enter (&type)) {
2682     GType _type = gst_meta_api_type_register ("GstParentBufferMetaAPI", tags);
2683     g_once_init_leave (&type, _type);
2684   }
2685
2686   return type;
2687 }
2688
2689 /**
2690  * gst_parent_buffer_meta_get_info:
2691  *
2692  * Gets the global #GstMetaInfo describing  the #GstParentBufferMeta meta.
2693  *
2694  * Returns: (transfer none): The #GstMetaInfo
2695  *
2696  * Since: 1.6
2697  */
2698 const GstMetaInfo *
2699 gst_parent_buffer_meta_get_info (void)
2700 {
2701   static const GstMetaInfo *meta_info = NULL;
2702
2703   if (g_once_init_enter ((GstMetaInfo **) & meta_info)) {
2704     const GstMetaInfo *meta =
2705         gst_meta_register (gst_parent_buffer_meta_api_get_type (),
2706         "GstParentBufferMeta",
2707         sizeof (GstParentBufferMeta),
2708         (GstMetaInitFunction) _gst_parent_buffer_meta_init,
2709         (GstMetaFreeFunction) _gst_parent_buffer_meta_free,
2710         _gst_parent_buffer_meta_transform);
2711     g_once_init_leave ((GstMetaInfo **) & meta_info, (GstMetaInfo *) meta);
2712   }
2713
2714   return meta_info;
2715 }
2716
2717 GST_DEBUG_CATEGORY_STATIC (gst_reference_timestamp_meta_debug);
2718
2719 /**
2720  * gst_buffer_add_reference_timestamp_meta:
2721  * @buffer: (transfer none): a #GstBuffer
2722  * @reference: (transfer none): identifier for the timestamp reference.
2723  * @timestamp: timestamp
2724  * @duration: duration, or %GST_CLOCK_TIME_NONE
2725  *
2726  * Adds a #GstReferenceTimestampMeta to @buffer that holds a @timestamp and
2727  * optionally @duration based on a specific timestamp @reference. See the
2728  * documentation of #GstReferenceTimestampMeta for details.
2729  *
2730  * Returns: (transfer none) (nullable): The #GstReferenceTimestampMeta that was added to the buffer
2731  *
2732  * Since: 1.14
2733  */
2734 GstReferenceTimestampMeta *
2735 gst_buffer_add_reference_timestamp_meta (GstBuffer * buffer,
2736     GstCaps * reference, GstClockTime timestamp, GstClockTime duration)
2737 {
2738   GstReferenceTimestampMeta *meta;
2739
2740   g_return_val_if_fail (GST_IS_CAPS (reference), NULL);
2741   g_return_val_if_fail (timestamp != GST_CLOCK_TIME_NONE, NULL);
2742
2743   meta =
2744       (GstReferenceTimestampMeta *) gst_buffer_add_meta (buffer,
2745       GST_REFERENCE_TIMESTAMP_META_INFO, NULL);
2746
2747   if (!meta)
2748     return NULL;
2749
2750   meta->reference = gst_caps_ref (reference);
2751   meta->timestamp = timestamp;
2752   meta->duration = duration;
2753
2754   return meta;
2755 }
2756
2757 /**
2758  * gst_buffer_get_reference_timestamp_meta:
2759  * @buffer: a #GstBuffer
2760  * @reference: (allow-none): a reference #GstCaps
2761  *
2762  * Finds the first #GstReferenceTimestampMeta on @buffer that conforms to
2763  * @reference. Conformance is tested by checking if the meta's reference is a
2764  * subset of @reference.
2765  *
2766  * Buffers can contain multiple #GstReferenceTimestampMeta metadata items.
2767  *
2768  * Returns: (transfer none) (nullable): the #GstReferenceTimestampMeta or %NULL when there
2769  * is no such metadata on @buffer.
2770  *
2771  * Since: 1.14
2772  */
2773 GstReferenceTimestampMeta *
2774 gst_buffer_get_reference_timestamp_meta (GstBuffer * buffer,
2775     GstCaps * reference)
2776 {
2777   gpointer state = NULL;
2778   GstMeta *meta;
2779   const GstMetaInfo *info = GST_REFERENCE_TIMESTAMP_META_INFO;
2780
2781   while ((meta = gst_buffer_iterate_meta (buffer, &state))) {
2782     if (meta->info->api == info->api) {
2783       GstReferenceTimestampMeta *rmeta = (GstReferenceTimestampMeta *) meta;
2784
2785       if (!reference)
2786         return rmeta;
2787       if (gst_caps_is_subset (rmeta->reference, reference))
2788         return rmeta;
2789     }
2790   }
2791   return NULL;
2792 }
2793
2794 static gboolean
2795 _gst_reference_timestamp_meta_transform (GstBuffer * dest, GstMeta * meta,
2796     GstBuffer * buffer, GQuark type, gpointer data)
2797 {
2798   GstReferenceTimestampMeta *dmeta, *smeta;
2799
2800   /* we copy over the reference timestamp meta, independent of transformation
2801    * that happens. If it applied to the original buffer, it still applies to
2802    * the new buffer as it refers to the time when the media was captured */
2803   smeta = (GstReferenceTimestampMeta *) meta;
2804   dmeta =
2805       gst_buffer_add_reference_timestamp_meta (dest, smeta->reference,
2806       smeta->timestamp, smeta->duration);
2807   if (!dmeta)
2808     return FALSE;
2809
2810   GST_CAT_DEBUG (gst_reference_timestamp_meta_debug,
2811       "copy reference timestamp metadata from buffer %p to %p", buffer, dest);
2812
2813   return TRUE;
2814 }
2815
2816 static void
2817 _gst_reference_timestamp_meta_free (GstReferenceTimestampMeta * meta,
2818     GstBuffer * buffer)
2819 {
2820   if (meta->reference)
2821     gst_caps_unref (meta->reference);
2822 }
2823
2824 static gboolean
2825 _gst_reference_timestamp_meta_init (GstReferenceTimestampMeta * meta,
2826     gpointer params, GstBuffer * buffer)
2827 {
2828   static gsize _init;
2829
2830   if (g_once_init_enter (&_init)) {
2831     GST_DEBUG_CATEGORY_INIT (gst_reference_timestamp_meta_debug,
2832         "referencetimestampmeta", 0, "referencetimestampmeta");
2833     g_once_init_leave (&_init, 1);
2834   }
2835
2836   meta->reference = NULL;
2837   meta->timestamp = GST_CLOCK_TIME_NONE;
2838   meta->duration = GST_CLOCK_TIME_NONE;
2839
2840   return TRUE;
2841 }
2842
2843 /**
2844  * gst_reference_timestamp_meta_api_get_type: (attributes doc.skip=true)
2845  */
2846 GType
2847 gst_reference_timestamp_meta_api_get_type (void)
2848 {
2849   static GType type = 0;
2850   static const gchar *tags[] = { NULL };
2851
2852   if (g_once_init_enter (&type)) {
2853     GType _type =
2854         gst_meta_api_type_register ("GstReferenceTimestampMetaAPI", tags);
2855     g_once_init_leave (&type, _type);
2856   }
2857
2858   return type;
2859 }
2860
2861 /**
2862  * gst_reference_timestamp_meta_get_info:
2863  *
2864  * Gets the global #GstMetaInfo describing the #GstReferenceTimestampMeta meta.
2865  *
2866  * Returns: (transfer none): The #GstMetaInfo
2867  *
2868  * Since: 1.14
2869  */
2870 const GstMetaInfo *
2871 gst_reference_timestamp_meta_get_info (void)
2872 {
2873   static const GstMetaInfo *meta_info = NULL;
2874
2875   if (g_once_init_enter ((GstMetaInfo **) & meta_info)) {
2876     const GstMetaInfo *meta =
2877         gst_meta_register (gst_reference_timestamp_meta_api_get_type (),
2878         "GstReferenceTimestampMeta",
2879         sizeof (GstReferenceTimestampMeta),
2880         (GstMetaInitFunction) _gst_reference_timestamp_meta_init,
2881         (GstMetaFreeFunction) _gst_reference_timestamp_meta_free,
2882         _gst_reference_timestamp_meta_transform);
2883     g_once_init_leave ((GstMetaInfo **) & meta_info, (GstMetaInfo *) meta);
2884   }
2885
2886   return meta_info;
2887 }
2888
2889 /**
2890  * gst_buffer_add_custom_meta:
2891  * @buffer: (transfer none): a #GstBuffer
2892  * @name: the registered name of the desired custom meta
2893  *
2894  * Creates and adds a #GstCustomMeta for the desired @name. @name must have
2895  * been successfully registered with gst_meta_register_custom().
2896  *
2897  * Returns: (transfer none) (nullable): The #GstCustomMeta that was added to the buffer
2898  *
2899  * Since: 1.20
2900  */
2901 GstCustomMeta *
2902 gst_buffer_add_custom_meta (GstBuffer * buffer, const gchar * name)
2903 {
2904   GstCustomMeta *meta;
2905   const GstMetaInfo *info;
2906
2907   g_return_val_if_fail (name != NULL, NULL);
2908   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
2909
2910   info = gst_meta_get_info (name);
2911
2912   if (info == NULL || !gst_meta_info_is_custom (info))
2913     return NULL;
2914
2915   meta = (GstCustomMeta *) gst_buffer_add_meta (buffer, info, NULL);
2916
2917   return meta;
2918 }
2919
2920 /**
2921  * gst_buffer_get_custom_meta:
2922  * @buffer: a #GstBuffer
2923  * @name: the registered name of the custom meta to retrieve.
2924  *
2925  * Finds the first #GstCustomMeta on @buffer for the desired @name.
2926  *
2927  * Returns: (transfer none) (nullable): the #GstCustomMeta
2928  *
2929  * Since: 1.20
2930  */
2931 GstCustomMeta *
2932 gst_buffer_get_custom_meta (GstBuffer * buffer, const gchar * name)
2933 {
2934   const GstMetaInfo *info;
2935
2936   g_return_val_if_fail (buffer != NULL, NULL);
2937   g_return_val_if_fail (name != NULL, NULL);
2938
2939   info = gst_meta_get_info (name);
2940
2941   if (!info)
2942     return NULL;
2943
2944   if (!gst_meta_info_is_custom (info))
2945     return NULL;
2946
2947   return (GstCustomMeta *) gst_buffer_get_meta (buffer, info->api);
2948 }
2949
2950 /**
2951  * gst_buffer_ref: (skip)
2952  * @buf: a #GstBuffer.
2953  *
2954  * Increases the refcount of the given buffer by one.
2955  *
2956  * Note that the refcount affects the writability
2957  * of @buf and its metadata, see gst_buffer_is_writable().
2958  * It is important to note that keeping additional references to
2959  * GstBuffer instances can potentially increase the number
2960  * of `memcpy` operations in a pipeline.
2961  *
2962  * Returns: (transfer full): @buf
2963  */
2964 GstBuffer *
2965 gst_buffer_ref (GstBuffer * buf)
2966 {
2967   return (GstBuffer *) gst_mini_object_ref (GST_MINI_OBJECT_CAST (buf));
2968 }
2969
2970 /**
2971  * gst_buffer_unref: (skip)
2972  * @buf: (transfer full): a #GstBuffer.
2973  *
2974  * Decreases the refcount of the buffer. If the refcount reaches 0, the buffer
2975  * with the associated metadata and memory will be freed.
2976  */
2977 void
2978 gst_buffer_unref (GstBuffer * buf)
2979 {
2980   gst_mini_object_unref (GST_MINI_OBJECT_CAST (buf));
2981 }
2982
2983 /**
2984  * gst_clear_buffer: (skip)
2985  * @buf_ptr: a pointer to a #GstBuffer reference
2986  *
2987  * Clears a reference to a #GstBuffer.
2988  *
2989  * @buf_ptr must not be %NULL.
2990  *
2991  * If the reference is %NULL then this function does nothing. Otherwise, the
2992  * reference count of the buffer is decreased and the pointer is set to %NULL.
2993  *
2994  * Since: 1.16
2995  */
2996 void
2997 gst_clear_buffer (GstBuffer ** buf_ptr)
2998 {
2999   gst_clear_mini_object ((GstMiniObject **) buf_ptr);
3000 }
3001
3002 /**
3003  * gst_buffer_copy: (skip)
3004  * @buf: a #GstBuffer.
3005  *
3006  * Creates a copy of the given buffer. This will only copy the buffer's
3007  * data to a newly allocated memory if needed (if the type of memory
3008  * requires it), otherwise the underlying data is just referenced.
3009  * Check gst_buffer_copy_deep() if you want to force the data
3010  * to be copied to newly allocated memory.
3011  *
3012  * Returns: (transfer full): a new copy of @buf.
3013  */
3014 GstBuffer *
3015 gst_buffer_copy (const GstBuffer * buf)
3016 {
3017   return GST_BUFFER (gst_mini_object_copy (GST_MINI_OBJECT_CONST_CAST (buf)));
3018 }
3019
3020 /**
3021  * gst_buffer_replace: (skip)
3022  * @obuf: (inout) (transfer full) (nullable): pointer to a pointer to
3023  *     a #GstBuffer to be replaced.
3024  * @nbuf: (transfer none) (allow-none): pointer to a #GstBuffer that will
3025  *     replace the buffer pointed to by @obuf.
3026  *
3027  * Modifies a pointer to a #GstBuffer to point to a different #GstBuffer. The
3028  * modification is done atomically (so this is useful for ensuring thread safety
3029  * in some cases), and the reference counts are updated appropriately (the old
3030  * buffer is unreffed, the new is reffed).
3031  *
3032  * Either @nbuf or the #GstBuffer pointed to by @obuf may be %NULL.
3033  *
3034  * Returns: %TRUE when @obuf was different from @nbuf.
3035  */
3036 gboolean
3037 gst_buffer_replace (GstBuffer ** obuf, GstBuffer * nbuf)
3038 {
3039   return gst_mini_object_replace ((GstMiniObject **) obuf,
3040       (GstMiniObject *) nbuf);
3041 }