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