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