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