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