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