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