memory: make the allocator refcounted
[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, 0);
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 void
176 _replace_memory (GstBuffer * buffer, GstMemory * mem)
177 {
178   gsize len, i;
179
180   len = GST_BUFFER_MEM_LEN (buffer);
181   /* unref old buffers */
182   for (i = 0; i < len; i++)
183     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
184
185   /* replace with single spanned buffer */
186   GST_BUFFER_MEM_PTR (buffer, 0) = mem;
187   GST_BUFFER_MEM_LEN (buffer) = 1;
188 }
189
190 static inline void
191 _memory_add (GstBuffer * buffer, guint idx, GstMemory * mem)
192 {
193   guint i, len = GST_BUFFER_MEM_LEN (buffer);
194
195   if (G_UNLIKELY (len >= GST_BUFFER_MEM_MAX)) {
196     /* too many buffer, span them. */
197     /* FIXME, there is room for improvement here: We could only try to merge
198      * 2 buffers to make some room. If we can't efficiently merge 2 buffers we
199      * could try to only merge the two smallest buffers to avoid memcpy, etc. */
200     _replace_memory (buffer, _span_memory (buffer, 0, -1, FALSE));
201     /* we now have 1 single spanned buffer */
202     len = 1;
203   }
204
205   if (idx == -1)
206     idx = len;
207
208   for (i = len; i > idx; i--) {
209     /* move buffers to insert, FIXME, we need to insert first and then merge */
210     GST_BUFFER_MEM_PTR (buffer, i) = GST_BUFFER_MEM_PTR (buffer, i - 1);
211   }
212   /* and insert the new buffer */
213   GST_BUFFER_MEM_PTR (buffer, idx) = mem;
214   GST_BUFFER_MEM_LEN (buffer) = len + 1;
215 }
216
217 GST_DEFINE_MINI_OBJECT_TYPE (GstBuffer, gst_buffer);
218
219 void
220 _priv_gst_buffer_initialize (void)
221 {
222   _gst_buffer_type = gst_buffer_get_type ();
223 }
224
225 /**
226  * gst_buffer_copy_into:
227  * @dest: a destination #GstBuffer
228  * @src: a source #GstBuffer
229  * @flags: flags indicating what metadata fields should be copied.
230  * @offset: offset to copy from
231  * @size: total size to copy. If -1, all data is copied.
232  *
233  * Copies the information from @src into @dest.
234  *
235  * @flags indicate which fields will be copied.
236  */
237 void
238 gst_buffer_copy_into (GstBuffer * dest, GstBuffer * src,
239     GstBufferCopyFlags flags, gsize offset, gsize size)
240 {
241   GstMetaItem *walk;
242   gsize bufsize;
243
244   g_return_if_fail (dest != NULL);
245   g_return_if_fail (src != NULL);
246
247   /* nothing to copy if the buffers are the same */
248   if (G_UNLIKELY (dest == src))
249     return;
250
251   g_return_if_fail (gst_buffer_is_writable (dest));
252
253   bufsize = gst_buffer_get_size (src);
254   g_return_if_fail (bufsize >= offset);
255   if (size == -1)
256     size = bufsize - offset;
257   g_return_if_fail (bufsize >= offset + size);
258
259   GST_CAT_LOG (GST_CAT_BUFFER, "copy %p to %p, offset %" G_GSIZE_FORMAT
260       "-%" G_GSIZE_FORMAT "/%" G_GSIZE_FORMAT, src, dest, offset, size,
261       bufsize);
262
263   if (flags & GST_BUFFER_COPY_FLAGS) {
264     /* copy flags */
265     GST_MINI_OBJECT_FLAGS (dest) = GST_MINI_OBJECT_FLAGS (src);
266   }
267
268   if (flags & GST_BUFFER_COPY_TIMESTAMPS) {
269     if (offset == 0) {
270       GST_BUFFER_PTS (dest) = GST_BUFFER_PTS (src);
271       GST_BUFFER_DTS (dest) = GST_BUFFER_DTS (src);
272       GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
273       if (size == bufsize) {
274         GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
275         GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
276       }
277     } else {
278       GST_BUFFER_PTS (dest) = GST_CLOCK_TIME_NONE;
279       GST_BUFFER_DTS (dest) = GST_CLOCK_TIME_NONE;
280       GST_BUFFER_DURATION (dest) = GST_CLOCK_TIME_NONE;
281       GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET_NONE;
282       GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_NONE;
283     }
284   }
285
286   if (flags & GST_BUFFER_COPY_MEMORY) {
287     GstMemory *mem;
288     gsize skip, left, len, i, bsize;
289
290     len = GST_BUFFER_MEM_LEN (src);
291     left = size;
292     skip = offset;
293
294     /* copy and make regions of the memory */
295     for (i = 0; i < len && left > 0; i++) {
296       mem = GST_BUFFER_MEM_PTR (src, i);
297       bsize = gst_memory_get_sizes (mem, NULL, NULL);
298
299       if (bsize <= skip) {
300         /* don't copy buffer */
301         skip -= bsize;
302       } else {
303         gsize tocopy;
304
305         tocopy = MIN (bsize - skip, left);
306         if (mem->flags & GST_MEMORY_FLAG_NO_SHARE) {
307           /* no share, always copy then */
308           mem = gst_memory_copy (mem, skip, tocopy);
309           skip = 0;
310         } else if (tocopy < bsize) {
311           /* we need to clip something */
312           mem = gst_memory_share (mem, skip, tocopy);
313           skip = 0;
314         } else {
315           mem = gst_memory_ref (mem);
316         }
317         _memory_add (dest, -1, mem);
318         left -= tocopy;
319       }
320     }
321     if (flags & GST_BUFFER_COPY_MERGE) {
322       _replace_memory (dest, _span_memory (dest, 0, size, FALSE));
323     }
324   }
325
326   if (flags & GST_BUFFER_COPY_META) {
327     for (walk = GST_BUFFER_META (src); walk; walk = walk->next) {
328       GstMeta *meta = &walk->meta;
329       const GstMetaInfo *info = meta->info;
330
331       if (info->copy_func)
332         info->copy_func (dest, meta, src, offset, size);
333     }
334   }
335 }
336
337 static GstBuffer *
338 _gst_buffer_copy (GstBuffer * buffer)
339 {
340   GstBuffer *copy;
341
342   g_return_val_if_fail (buffer != NULL, NULL);
343
344   /* create a fresh new buffer */
345   copy = gst_buffer_new ();
346
347   /* we simply copy everything from our parent */
348   gst_buffer_copy_into (copy, buffer, GST_BUFFER_COPY_ALL, 0, -1);
349
350   return copy;
351 }
352
353 /* the default dispose function revives the buffer and returns it to the
354  * pool when there is a pool */
355 static gboolean
356 _gst_buffer_dispose (GstBuffer * buffer)
357 {
358   GstBufferPool *pool;
359
360   /* no pool, do free */
361   if ((pool = buffer->pool) == NULL)
362     return TRUE;
363
364   /* keep the buffer alive */
365   gst_buffer_ref (buffer);
366   /* return the buffer to the pool */
367   GST_CAT_LOG (GST_CAT_BUFFER, "release %p to pool %p", buffer, pool);
368   gst_buffer_pool_release_buffer (pool, buffer);
369
370   return FALSE;
371 }
372
373 static void
374 _gst_buffer_free (GstBuffer * buffer)
375 {
376   GstMetaItem *walk, *next;
377   guint i, len;
378   gsize msize;
379
380   g_return_if_fail (buffer != NULL);
381
382   GST_CAT_LOG (GST_CAT_BUFFER, "finalize %p", buffer);
383
384   /* free metadata */
385   for (walk = GST_BUFFER_META (buffer); walk; walk = next) {
386     GstMeta *meta = &walk->meta;
387     const GstMetaInfo *info = meta->info;
388
389     /* call free_func if any */
390     if (info->free_func)
391       info->free_func (meta, buffer);
392
393     next = walk->next;
394     /* and free the slice */
395     g_slice_free1 (ITEM_SIZE (info), walk);
396   }
397
398   /* get the size, when unreffing the memory, we could also unref the buffer
399    * itself */
400   msize = GST_MINI_OBJECT_SIZE (buffer);
401
402   /* free our memory */
403   len = GST_BUFFER_MEM_LEN (buffer);
404   for (i = 0; i < len; i++)
405     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
406
407   /* we set msize to 0 when the buffer is part of the memory block */
408   if (msize)
409     g_slice_free1 (msize, buffer);
410   else
411     gst_memory_unref (GST_BUFFER_BUFMEM (buffer));
412 }
413
414 static void
415 gst_buffer_init (GstBufferImpl * buffer, gsize size)
416 {
417   gst_mini_object_init (GST_MINI_OBJECT_CAST (buffer), _gst_buffer_type, size);
418
419   buffer->buffer.mini_object.copy =
420       (GstMiniObjectCopyFunction) _gst_buffer_copy;
421   buffer->buffer.mini_object.dispose =
422       (GstMiniObjectDisposeFunction) _gst_buffer_dispose;
423   buffer->buffer.mini_object.free =
424       (GstMiniObjectFreeFunction) _gst_buffer_free;
425
426   GST_BUFFER (buffer)->pool = NULL;
427   GST_BUFFER_PTS (buffer) = GST_CLOCK_TIME_NONE;
428   GST_BUFFER_DTS (buffer) = GST_CLOCK_TIME_NONE;
429   GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
430   GST_BUFFER_OFFSET (buffer) = GST_BUFFER_OFFSET_NONE;
431   GST_BUFFER_OFFSET_END (buffer) = GST_BUFFER_OFFSET_NONE;
432
433   GST_BUFFER_MEM_LEN (buffer) = 0;
434   GST_BUFFER_META (buffer) = NULL;
435 }
436
437 /**
438  * gst_buffer_new:
439  *
440  * Creates a newly allocated buffer without any data.
441  *
442  * MT safe.
443  *
444  * Returns: (transfer full): the new #GstBuffer.
445  */
446 GstBuffer *
447 gst_buffer_new (void)
448 {
449   GstBufferImpl *newbuf;
450
451   newbuf = g_slice_new (GstBufferImpl);
452   GST_CAT_LOG (GST_CAT_BUFFER, "new %p", newbuf);
453
454   gst_buffer_init (newbuf, sizeof (GstBufferImpl));
455
456   return GST_BUFFER_CAST (newbuf);
457 }
458
459 /**
460  * gst_buffer_new_allocate:
461  * @allocator: (allow-none): the #GstAllocator to use, or NULL to use the
462  *     default allocator
463  * @size: the size in bytes of the new buffer's data.
464  * @align: the alignment of the buffer memory
465  *
466  * Tries to create a newly allocated buffer with data of the given size and
467  * alignment from @allocator. If the requested amount of memory can't be
468  * allocated, NULL will be returned. The allocated buffer memory is not cleared.
469  *
470  * When @allocator is NULL, the default memory allocator will be used.
471  *
472  * Allocator buffer memory will be aligned to multiples of (@align + 1) bytes.
473  *
474  * Note that when @size == 0, the buffer will not have memory associated with it.
475  *
476  * MT safe.
477  *
478  * Returns: (transfer full): a new #GstBuffer, or NULL if the memory couldn't
479  *     be allocated.
480  */
481 GstBuffer *
482 gst_buffer_new_allocate (GstAllocator * allocator, gsize size, gsize align)
483 {
484   GstBuffer *newbuf;
485   GstMemory *mem;
486 #if 0
487   guint8 *data;
488   gsize asize;
489 #endif
490
491 #if 1
492   if (size > 0) {
493     mem = gst_allocator_alloc (allocator, size, align);
494     if (G_UNLIKELY (mem == NULL))
495       goto no_memory;
496   } else {
497     mem = NULL;
498   }
499
500   newbuf = gst_buffer_new ();
501
502   if (mem != NULL)
503     _memory_add (newbuf, -1, mem);
504
505   GST_CAT_LOG (GST_CAT_BUFFER,
506       "new buffer %p of size %" G_GSIZE_FORMAT " from allocator %p", newbuf,
507       size, allocator);
508 #endif
509
510 #if 0
511   asize = sizeof (GstBufferImpl) + size;
512   data = g_slice_alloc (asize);
513   if (G_UNLIKELY (data == NULL))
514     goto no_memory;
515
516   newbuf = GST_BUFFER_CAST (data);
517
518   gst_buffer_init ((GstBufferImpl *) data, asize);
519   if (size > 0) {
520     mem = gst_memory_new_wrapped (0, data + sizeof (GstBufferImpl), NULL,
521         size, 0, size);
522     _memory_add (newbuf, -1, mem);
523   }
524 #endif
525
526 #if 0
527   /* allocate memory and buffer, it might be interesting to do this but there
528    * are many complications. We need to keep the memory mapped to access the
529    * buffer fields and the memory for the buffer might be just very slow. We
530    * also need to do some more magic to get the alignment right. */
531   asize = sizeof (GstBufferImpl) + size;
532   mem = gst_allocator_alloc (allocator, asize, align);
533   if (G_UNLIKELY (mem == NULL))
534     goto no_memory;
535
536   /* map the data part and init the buffer in it, set the buffer size to 0 so
537    * that a finalize won't free the buffer */
538   data = gst_memory_map (mem, &asize, NULL, GST_MAP_WRITE);
539   gst_buffer_init ((GstBufferImpl *) data, 0);
540   gst_memory_unmap (mem);
541
542   /* strip off the buffer */
543   gst_memory_resize (mem, sizeof (GstBufferImpl), size);
544
545   newbuf = GST_BUFFER_CAST (data);
546   GST_BUFFER_BUFMEM (newbuf) = mem;
547
548   if (size > 0)
549     _memory_add (newbuf, -1, gst_memory_ref (mem));
550 #endif
551
552   return newbuf;
553
554   /* ERRORS */
555 no_memory:
556   {
557     GST_CAT_WARNING (GST_CAT_BUFFER,
558         "failed to allocate %" G_GSIZE_FORMAT " bytes", size);
559     return NULL;
560   }
561 }
562
563 /**
564  * gst_buffer_new_wrapped_full:
565  * @data: data to wrap
566  * @free_func: function to free @data
567  * @offset: offset in @data of valid data
568  * @size: size of valid data in @data starting at @offset
569  *
570  * Creates a new buffer that wraps the given @data.  Valid data is set
571  * to start at @offset and up to @size.  If no @free_func is provided,
572  * buffer memory is marked READONLY.
573  *
574  * MT safe.
575  *
576  * Returns: (transfer full): a new #GstBuffer
577  */
578 GstBuffer *
579 gst_buffer_new_wrapped_full (gpointer data, GFreeFunc free_func, gsize offset,
580     gsize size)
581 {
582   GstBuffer *newbuf;
583
584   newbuf = gst_buffer_new ();
585   gst_buffer_take_memory (newbuf, -1,
586       gst_memory_new_wrapped (free_func ? 0 : GST_MEMORY_FLAG_READONLY,
587           data, free_func, offset + size, offset, size));
588
589   return newbuf;
590 }
591
592 /**
593  * gst_buffer_new_wrapped:
594  * @data: data to wrap
595  * @size: allocated size of @data
596  *
597  * Creates a new buffer that wraps the given @data. The memory will be freed
598  * with g_free and will be marked writable.
599  *
600  * MT safe.
601  *
602  * Returns: (transfer full): a new #GstBuffer
603  */
604 GstBuffer *
605 gst_buffer_new_wrapped (gpointer data, gsize size)
606 {
607   return gst_buffer_new_wrapped_full (data, g_free, 0, size);
608 }
609
610 /**
611  * gst_buffer_n_memory:
612  * @buffer: a #GstBuffer.
613  *
614  * Get the amount of memory blocks that this buffer has.
615  *
616  * Returns: (transfer full): the amount of memory block in this buffer.
617  */
618 guint
619 gst_buffer_n_memory (GstBuffer * buffer)
620 {
621   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
622
623   return GST_BUFFER_MEM_LEN (buffer);
624 }
625
626 /**
627  * gst_buffer_take_memory:
628  * @buffer: a #GstBuffer.
629  * @idx: the index to add the memory at, or -1 to append it to the end
630  * @mem: (transfer full): a #GstMemory.
631  *
632  * Add the memory block @mem to @buffer at @idx. This function takes ownership
633  * of @mem and thus doesn't increase its refcount.
634  */
635 void
636 gst_buffer_take_memory (GstBuffer * buffer, gint idx, GstMemory * mem)
637 {
638   g_return_if_fail (GST_IS_BUFFER (buffer));
639   g_return_if_fail (gst_buffer_is_writable (buffer));
640   g_return_if_fail (mem != NULL);
641   g_return_if_fail (idx == -1 ||
642       (idx >= 0 && idx <= GST_BUFFER_MEM_LEN (buffer)));
643
644   _memory_add (buffer, idx, mem);
645 }
646
647 static GstMemory *
648 _get_memory (GstBuffer * buffer, guint idx, gboolean write)
649 {
650   GstMemory *mem;
651
652   mem = GST_BUFFER_MEM_PTR (buffer, idx);
653
654   if (G_UNLIKELY (write && !gst_memory_is_writable (mem))) {
655     GstMemory *copy;
656     GST_CAT_LOG (GST_CAT_BUFFER,
657         "making writable copy of memory %p in buffer %p", mem, buffer);
658     /* replace with a writable copy */
659     copy = gst_memory_copy (mem, 0, -1);
660     GST_BUFFER_MEM_PTR (buffer, idx) = copy;
661     gst_memory_unref (mem);
662     mem = copy;
663   }
664   return mem;
665 }
666
667 /**
668  * gst_buffer_peek_memory:
669  * @buffer: a #GstBuffer.
670  * @idx: an index
671  * @flags: #GstMapFlags
672  *
673  * Get the memory block in @buffer at @idx for memory access in @flags.
674  * This function does not return a refcount to the memory block. The memory
675  * block stays valid for as long as the caller has a valid reference to @buffer
676  * and as long as no operations that modify the memory blocks are called, such
677  * as gst_buffer_remove_memory_range(), gst_buffer_take_memory() and gst_buffer_resize().
678  *
679  * @buffer should be writable when @flags contains #GST_MAP_WRITE. If the memory
680  * at @idx is not writable, a new writable copy will be installed in @buffer and
681  * returned.
682  *
683  * Returns: a #GstMemory at @idx.
684  */
685 GstMemory *
686 gst_buffer_peek_memory (GstBuffer * buffer, guint idx, GstMapFlags flags)
687 {
688   GstMemory *mem;
689   gboolean write;
690
691   write = (flags & GST_MAP_WRITE) != 0;
692
693   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
694   g_return_val_if_fail (idx < GST_BUFFER_MEM_LEN (buffer), NULL);
695
696   /* check if we can write when asked for write access */
697   if (G_UNLIKELY (write && !gst_buffer_is_writable (buffer)))
698     goto not_writable;
699
700   mem = _get_memory (buffer, idx, write);
701
702   return mem;
703
704   /* ERRORS */
705 not_writable:
706   {
707     g_return_val_if_fail (gst_buffer_is_writable (buffer), NULL);
708     return NULL;
709   }
710 }
711
712 /**
713  * gst_buffer_remove_memory_range:
714  * @buffer: a #GstBuffer.
715  * @idx: an index
716  * @length: a length
717  *
718  * Remove @len memory blocks in @buffer starting from @idx.
719  *
720  * @length can be -1, in which case all memory starting from @idx is removed.
721  */
722 void
723 gst_buffer_remove_memory_range (GstBuffer * buffer, guint idx, guint length)
724 {
725   guint len, i, end;
726
727   g_return_if_fail (GST_IS_BUFFER (buffer));
728   g_return_if_fail (gst_buffer_is_writable (buffer));
729
730   len = GST_BUFFER_MEM_LEN (buffer);
731   if (length == -1) {
732     g_return_if_fail (idx < len);
733     length = len - idx;
734   }
735
736   end = idx + length;
737   for (i = idx; i < end; i++)
738     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
739
740   if (end != len) {
741     g_memmove (&GST_BUFFER_MEM_PTR (buffer, idx),
742         &GST_BUFFER_MEM_PTR (buffer, end), (len - end) * sizeof (gpointer));
743   }
744   GST_BUFFER_MEM_LEN (buffer) = len - length;
745 }
746
747 /**
748  * gst_buffer_get_merged_memory:
749  * @buffer: a #GstBuffer.
750  *
751  * Return a #GstMemory object that contains all the memory in @buffer. If there
752  * was only one memory in @buffer, it will be returned directly, otherwise all
753  * memory objects will be merged into one object that will be returned.
754  *
755  * Returns: a #GstMemory with the merged memory in @buffer. This function can
756  * return %NULL if there is no memory in @buffer. Use gst_memory_unref() after
757  * usage.
758  */
759 static GstMemory *
760 gst_buffer_get_merged_memory (GstBuffer * buffer)
761 {
762   guint len;
763   GstMemory *mem;
764
765   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
766
767   len = GST_BUFFER_MEM_LEN (buffer);
768
769   if (G_UNLIKELY (len == 0)) {
770     /* no memory */
771     mem = NULL;
772   } else if (G_LIKELY (len == 1)) {
773     /* we can take the first one */
774     mem = GST_BUFFER_MEM_PTR (buffer, 0);
775     gst_memory_ref (mem);
776   } else {
777     /* we need to span memory */
778     mem = _span_memory (buffer, 0, -1, FALSE);
779   }
780   return mem;
781 }
782
783 /**
784  * gst_buffer_get_sizes:
785  * @buffer: a #GstBuffer.
786  * @offset: a pointer to the offset
787  * @maxsize: a pointer to the maxsize
788  *
789  * Get the total size of all memory blocks in @buffer.
790  *
791  * When not %NULL, @offset will contain the offset of the data in the first
792  * memory block in @buffer and @maxsize will contain the sum of the size
793  * and @offset and the amount of extra padding on the last memory block.
794  * @offset and @maxsize can be used to resize the buffer with
795  * gst_buffer_resize().
796  *
797  * Returns: the total size of the memory in @buffer.
798  */
799 gsize
800 gst_buffer_get_sizes (GstBuffer * buffer, gsize * offset, gsize * maxsize)
801 {
802   guint len;
803   gsize size;
804   GstMemory *mem;
805
806   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
807
808   len = GST_BUFFER_MEM_LEN (buffer);
809
810   if (G_LIKELY (len == 1)) {
811     /* common case */
812     mem = GST_BUFFER_MEM_PTR (buffer, 0);
813     size = gst_memory_get_sizes (mem, offset, maxsize);
814   } else {
815     guint i;
816     gsize extra, offs;
817
818     size = offs = extra = 0;
819     for (i = 0; i < len; i++) {
820       gsize s, o, ms;
821
822       mem = GST_BUFFER_MEM_PTR (buffer, i);
823       s = gst_memory_get_sizes (mem, &o, &ms);
824
825       if (s) {
826         if (size == 0)
827           /* first size, take accumulated data before as the offset */
828           offs = extra + o;
829         /* add sizes */
830         size += s;
831         /* save the amount of data after this block */
832         extra = ms - (o + s);
833       } else {
834         /* empty block, add as extra */
835         extra += ms;
836       }
837     }
838     if (offset)
839       *offset = offs;
840     if (maxsize)
841       *maxsize = offs + size + extra;
842   }
843   return size;
844 }
845
846 /**
847  * gst_buffer_resize:
848  * @buffer: a #GstBuffer.
849  * @offset: the offset adjustement
850  * @size: the new size or -1 to just adjust the offset
851  *
852  * Set the total size of the buffer
853  */
854 void
855 gst_buffer_resize (GstBuffer * buffer, gssize offset, gssize size)
856 {
857   guint len;
858   guint i;
859   gsize bsize, bufsize, bufoffs, bufmax;
860   GstMemory *mem;
861
862   g_return_if_fail (gst_buffer_is_writable (buffer));
863   g_return_if_fail (size >= -1);
864
865   bufsize = gst_buffer_get_sizes (buffer, &bufoffs, &bufmax);
866
867   GST_CAT_LOG (GST_CAT_BUFFER, "trim %p %" G_GSSIZE_FORMAT "-%" G_GSSIZE_FORMAT
868       " size:%" G_GSIZE_FORMAT " offs:%" G_GSIZE_FORMAT " max:%"
869       G_GSIZE_FORMAT, buffer, offset, size, bufsize, bufoffs, bufmax);
870
871   /* we can't go back further than the current offset or past the end of the
872    * buffer */
873   g_return_if_fail ((offset < 0 && bufoffs >= -offset) || (offset >= 0
874           && bufoffs + offset <= bufmax));
875   if (size == -1) {
876     g_return_if_fail (bufsize >= offset);
877     size = bufsize - offset;
878   }
879   g_return_if_fail (bufmax >= bufoffs + offset + size);
880
881   len = GST_BUFFER_MEM_LEN (buffer);
882
883   /* copy and trim */
884   for (i = 0; i < len; i++) {
885     gsize left, noffs;
886
887     mem = GST_BUFFER_MEM_PTR (buffer, i);
888     bsize = gst_memory_get_sizes (mem, NULL, NULL);
889
890     noffs = 0;
891     /* last buffer always gets resized to the remaining size */
892     if (i + 1 == len)
893       left = size;
894     /* shrink buffers before the offset */
895     else if ((gssize) bsize <= offset) {
896       left = 0;
897       noffs = offset - bsize;
898       offset = 0;
899     }
900     /* clip other buffers */
901     else
902       left = MIN (bsize - offset, size);
903
904     if (offset != 0 || left != bsize) {
905       /* we need to clip something */
906       if (gst_memory_is_writable (mem)) {
907         gst_memory_resize (mem, offset, left);
908       } else {
909         GstMemory *tmp;
910
911         if (mem->flags & GST_MEMORY_FLAG_NO_SHARE)
912           tmp = gst_memory_copy (mem, offset, left);
913         else
914           tmp = gst_memory_share (mem, offset, left);
915
916         gst_memory_unref (mem);
917         mem = tmp;
918       }
919     }
920     offset = noffs;
921     size -= left;
922
923     GST_BUFFER_MEM_PTR (buffer, i) = mem;
924   }
925 }
926
927 /**
928  * gst_buffer_map:
929  * @buffer: a #GstBuffer.
930  * @info: (out): info about the mapping
931  * @flags: flags for the mapping
932  *
933  * This function fills @info with a pointer to the merged memory in @buffer.
934  * @flags describe the desired access of the memory. When @flags is
935  * #GST_MAP_WRITE, @buffer should be writable (as returned from
936  * gst_buffer_is_writable()).
937  *
938  * When @buffer is writable but the memory isn't, a writable copy will
939  * automatically be created and returned. The readonly copy of the buffer memory
940  * will then also be replaced with this writable copy.
941  *
942  * When the buffer contains multiple memory blocks, the returned pointer will be
943  * a concatenation of the memory blocks.
944  *
945  * Returns: (transfer full): %TRUE if the map succeeded and @info contains valid
946  * data.
947  */
948 gboolean
949 gst_buffer_map (GstBuffer * buffer, GstMapInfo * info, GstMapFlags flags)
950 {
951   GstMemory *mem;
952   gboolean write, writable;
953
954   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
955   g_return_val_if_fail (info != NULL, FALSE);
956
957   write = (flags & GST_MAP_WRITE) != 0;
958   writable = gst_buffer_is_writable (buffer);
959
960   /* check if we can write when asked for write access */
961   if (G_UNLIKELY (write && !writable))
962     goto not_writable;
963
964   mem = gst_buffer_get_merged_memory (buffer);
965   if (G_UNLIKELY (mem == NULL))
966     goto no_memory;
967
968   /* now try to map */
969   mem = gst_memory_make_mapped (mem, info, flags);
970   if (G_UNLIKELY (mem == NULL))
971     goto cannot_map;
972
973   /* if the buffer is writable, replace the memory */
974   if (writable)
975     _replace_memory (buffer, gst_memory_ref (mem));
976
977   return TRUE;
978
979   /* ERROR */
980 not_writable:
981   {
982     g_critical ("write map requested on non-writable buffer");
983     return FALSE;
984   }
985 no_memory:
986   {
987     /* empty buffer, we need to return NULL */
988     GST_DEBUG_OBJECT (buffer, "can't get buffer memory");
989     info->memory = NULL;
990     info->data = NULL;
991     info->size = 0;
992     info->maxsize = 0;
993     return TRUE;
994   }
995 cannot_map:
996   {
997     GST_DEBUG_OBJECT (buffer, "cannot map memory");
998     gst_memory_unref (mem);
999     return FALSE;
1000   }
1001 }
1002
1003 /**
1004  * gst_buffer_unmap:
1005  * @buffer: a #GstBuffer.
1006  * @info: a #GstMapInfo
1007  *
1008  * Release the memory previously mapped with gst_buffer_map().
1009  */
1010 void
1011 gst_buffer_unmap (GstBuffer * buffer, GstMapInfo * info)
1012 {
1013   g_return_if_fail (GST_IS_BUFFER (buffer));
1014   g_return_if_fail (info != NULL);
1015
1016   if (info->memory) {
1017     gst_memory_unmap (info->memory, info);
1018     gst_memory_unref (info->memory);
1019   }
1020 }
1021
1022 /**
1023  * gst_buffer_fill:
1024  * @buffer: a #GstBuffer.
1025  * @offset: the offset to fill
1026  * @src: the source address
1027  * @size: the size to fill
1028  *
1029  * Copy @size bytes from @src to @buffer at @offset.
1030  *
1031  * Returns: The amount of bytes copied. This value can be lower than @size
1032  *    when @buffer did not contain enough data.
1033  */
1034 gsize
1035 gst_buffer_fill (GstBuffer * buffer, gsize offset, gconstpointer src,
1036     gsize size)
1037 {
1038   gsize i, len, left;
1039   const guint8 *ptr = src;
1040
1041   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1042   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1043   g_return_val_if_fail (src != NULL, 0);
1044
1045   len = GST_BUFFER_MEM_LEN (buffer);
1046   left = size;
1047
1048   for (i = 0; i < len && left > 0; i++) {
1049     GstMapInfo info;
1050     gsize tocopy;
1051     GstMemory *mem;
1052
1053     mem = _get_memory (buffer, i, TRUE);
1054
1055     gst_memory_map (mem, &info, GST_MAP_WRITE);
1056     if (info.size > offset) {
1057       /* we have enough */
1058       tocopy = MIN (info.size - offset, left);
1059       memcpy ((guint8 *) info.data + offset, ptr, tocopy);
1060       left -= tocopy;
1061       ptr += tocopy;
1062       offset = 0;
1063     } else {
1064       /* offset past buffer, skip */
1065       offset -= info.size;
1066     }
1067     gst_memory_unmap (mem, &info);
1068   }
1069   return size - left;
1070 }
1071
1072 /**
1073  * gst_buffer_extract:
1074  * @buffer: a #GstBuffer.
1075  * @offset: the offset to extract
1076  * @dest: the destination address
1077  * @size: the size to extract
1078  *
1079  * Copy @size bytes starting from @offset in @buffer to @dest.
1080  *
1081  * Returns: The amount of bytes extracted. This value can be lower than @size
1082  *    when @buffer did not contain enough data.
1083  */
1084 gsize
1085 gst_buffer_extract (GstBuffer * buffer, gsize offset, gpointer dest, gsize size)
1086 {
1087   gsize i, len, left;
1088   guint8 *ptr = dest;
1089
1090   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1091   g_return_val_if_fail (dest != NULL, 0);
1092
1093   len = GST_BUFFER_MEM_LEN (buffer);
1094   left = size;
1095
1096   for (i = 0; i < len && left > 0; i++) {
1097     GstMapInfo info;
1098     gsize tocopy;
1099     GstMemory *mem;
1100
1101     mem = GST_BUFFER_MEM_PTR (buffer, i);
1102
1103     gst_memory_map (mem, &info, GST_MAP_READ);
1104     if (info.size > offset) {
1105       /* we have enough */
1106       tocopy = MIN (info.size - offset, left);
1107       memcpy (ptr, (guint8 *) info.data + offset, tocopy);
1108       left -= tocopy;
1109       ptr += tocopy;
1110       offset = 0;
1111     } else {
1112       /* offset past buffer, skip */
1113       offset -= info.size;
1114     }
1115     gst_memory_unmap (mem, &info);
1116   }
1117   return size - left;
1118 }
1119
1120 /**
1121  * gst_buffer_memcmp:
1122  * @buffer: a #GstBuffer.
1123  * @offset: the offset in @buffer
1124  * @mem: the memory to compare
1125  * @size: the size to compare
1126  *
1127  * Compare @size bytes starting from @offset in @buffer with the memory in @mem.
1128  *
1129  * Returns: 0 if the memory is equal.
1130  */
1131 gint
1132 gst_buffer_memcmp (GstBuffer * buffer, gsize offset, gconstpointer mem,
1133     gsize size)
1134 {
1135   gsize i, len;
1136   const guint8 *ptr = mem;
1137   gint res = 0;
1138
1139   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1140   g_return_val_if_fail (mem != NULL, 0);
1141
1142   len = GST_BUFFER_MEM_LEN (buffer);
1143
1144   for (i = 0; i < len && size > 0 && res == 0; i++) {
1145     GstMapInfo info;
1146     gsize tocmp;
1147     GstMemory *mem;
1148
1149     mem = GST_BUFFER_MEM_PTR (buffer, i);
1150
1151     gst_memory_map (mem, &info, GST_MAP_READ);
1152     if (info.size > offset) {
1153       /* we have enough */
1154       tocmp = MIN (info.size - offset, size);
1155       res = memcmp (ptr, (guint8 *) info.data + offset, tocmp);
1156       size -= tocmp;
1157       ptr += tocmp;
1158       offset = 0;
1159     } else {
1160       /* offset past buffer, skip */
1161       offset -= info.size;
1162     }
1163     gst_memory_unmap (mem, &info);
1164   }
1165   return res;
1166 }
1167
1168 /**
1169  * gst_buffer_memset:
1170  * @buffer: a #GstBuffer.
1171  * @offset: the offset in @buffer
1172  * @val: the value to set
1173  * @size: the size to set
1174  *
1175  * Fill @buf with @size bytes with @val starting from @offset.
1176  *
1177  * Returns: The amount of bytes filled. This value can be lower than @size
1178  *    when @buffer did not contain enough data.
1179  */
1180 gsize
1181 gst_buffer_memset (GstBuffer * buffer, gsize offset, guint8 val, gsize size)
1182 {
1183   gsize i, len, left;
1184
1185   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1186   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1187
1188   len = GST_BUFFER_MEM_LEN (buffer);
1189   left = size;
1190
1191   for (i = 0; i < len && left > 0; i++) {
1192     GstMapInfo info;
1193     gsize toset;
1194     GstMemory *mem;
1195
1196     mem = _get_memory (buffer, i, TRUE);
1197
1198     gst_memory_map (mem, &info, GST_MAP_WRITE);
1199     if (info.size > offset) {
1200       /* we have enough */
1201       toset = MIN (info.size - offset, left);
1202       memset ((guint8 *) info.data + offset, val, toset);
1203       left -= toset;
1204       offset = 0;
1205     } else {
1206       /* offset past buffer, skip */
1207       offset -= info.size;
1208     }
1209     gst_memory_unmap (mem, &info);
1210   }
1211   return size - left;
1212 }
1213
1214 /**
1215  * gst_buffer_copy_region:
1216  * @parent: a #GstBuffer.
1217  * @flags: the #GstBufferCopyFlags
1218  * @offset: the offset into parent #GstBuffer at which the new sub-buffer 
1219  *          begins.
1220  * @size: the size of the new #GstBuffer sub-buffer, in bytes.
1221  *
1222  * Creates a sub-buffer from @parent at @offset and @size.
1223  * This sub-buffer uses the actual memory space of the parent buffer.
1224  * This function will copy the offset and timestamp fields when the
1225  * offset is 0. If not, they will be set to #GST_CLOCK_TIME_NONE and 
1226  * #GST_BUFFER_OFFSET_NONE.
1227  * If @offset equals 0 and @size equals the total size of @buffer, the
1228  * duration and offset end fields are also copied. If not they will be set
1229  * to #GST_CLOCK_TIME_NONE and #GST_BUFFER_OFFSET_NONE.
1230  *
1231  * MT safe.
1232  *
1233  * Returns: (transfer full): the new #GstBuffer or NULL if the arguments were
1234  *     invalid.
1235  */
1236 GstBuffer *
1237 gst_buffer_copy_region (GstBuffer * buffer, GstBufferCopyFlags flags,
1238     gsize offset, gsize size)
1239 {
1240   GstBuffer *copy;
1241
1242   g_return_val_if_fail (buffer != NULL, NULL);
1243
1244   /* create the new buffer */
1245   copy = gst_buffer_new ();
1246
1247   GST_CAT_LOG (GST_CAT_BUFFER, "new region copy %p of %p %" G_GSIZE_FORMAT
1248       "-%" G_GSIZE_FORMAT, copy, buffer, offset, size);
1249
1250   gst_buffer_copy_into (copy, buffer, flags, offset, size);
1251
1252   return copy;
1253 }
1254
1255 static gboolean
1256 _gst_buffer_arr_is_span_fast (GstMemory ** mem[], gsize len[], guint n,
1257     gsize * offset, GstMemory ** parent)
1258 {
1259   GstMemory *mcur, *mprv;
1260   gboolean have_offset = FALSE;
1261   guint count, i;
1262
1263   mcur = mprv = NULL;
1264   for (count = 0; count < n; count++) {
1265     gsize offs, clen;
1266     GstMemory **cmem;
1267
1268     cmem = mem[count];
1269     clen = len[count];
1270
1271     for (i = 0; i < clen; i++) {
1272       if (mcur)
1273         mprv = mcur;
1274       mcur = cmem[i];
1275
1276       if (mprv && mcur) {
1277         /* check is memory is contiguous */
1278         if (!gst_memory_is_span (mprv, mcur, &offs))
1279           return FALSE;
1280
1281         if (!have_offset) {
1282           if (offset)
1283             *offset = offs;
1284           if (parent)
1285             *parent = mprv->parent;
1286
1287           have_offset = TRUE;
1288         }
1289       }
1290     }
1291   }
1292   return have_offset;
1293 }
1294
1295 static GstMemory *
1296 _gst_buffer_arr_span (GstMemory ** mem[], gsize len[], guint n, gsize offset,
1297     gsize size, gboolean writable)
1298 {
1299   GstMemory *span, *parent = NULL;
1300   gsize poffset = 0;
1301
1302   if (!writable
1303       && _gst_buffer_arr_is_span_fast (mem, len, n, &poffset, &parent)) {
1304     if (parent->flags & GST_MEMORY_FLAG_NO_SHARE)
1305       span = gst_memory_copy (parent, offset + poffset, size);
1306     else
1307       span = gst_memory_share (parent, offset + poffset, size);
1308   } else {
1309     gsize count, left;
1310     GstMapInfo dinfo;
1311     guint8 *ptr;
1312
1313     span = gst_allocator_alloc (NULL, size, 0);
1314     gst_memory_map (span, &dinfo, GST_MAP_WRITE);
1315
1316     ptr = dinfo.data;
1317     left = size;
1318
1319     for (count = 0; count < n; count++) {
1320       GstMapInfo sinfo;
1321       gsize i, tocopy, clen;
1322       GstMemory **cmem;
1323
1324       cmem = mem[count];
1325       clen = len[count];
1326
1327       for (i = 0; i < clen && left > 0; i++) {
1328         gst_memory_map (cmem[i], &sinfo, GST_MAP_READ);
1329         tocopy = MIN (sinfo.size, left);
1330         if (tocopy > offset) {
1331           memcpy (ptr, (guint8 *) sinfo.data + offset, tocopy - offset);
1332           left -= tocopy;
1333           ptr += tocopy;
1334           offset = 0;
1335         } else {
1336           offset -= tocopy;
1337         }
1338         gst_memory_unmap (cmem[i], &sinfo);
1339       }
1340     }
1341     gst_memory_unmap (span, &dinfo);
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_PTS (newbuf) = GST_BUFFER_PTS (buf1);
1436     GST_BUFFER_DTS (newbuf) = GST_BUFFER_DTS (buf1);
1437
1438     /* if we completely merged the two buffers (appended), we can
1439      * calculate the duration too. Also make sure we's not messing with
1440      * invalid DURATIONS */
1441     if (buf1->size + buf2->size == len) {
1442       if (GST_BUFFER_DURATION_IS_VALID (buf1) &&
1443           GST_BUFFER_DURATION_IS_VALID (buf2)) {
1444         /* add duration */
1445         GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf1) +
1446             GST_BUFFER_DURATION (buf2);
1447       }
1448       if (GST_BUFFER_OFFSET_END_IS_VALID (buf2)) {
1449         /* add offset_end */
1450         GST_BUFFER_OFFSET_END (newbuf) = GST_BUFFER_OFFSET_END (buf2);
1451       }
1452     }
1453   }
1454 #endif
1455
1456   return newbuf;
1457 }
1458
1459 /**
1460  * gst_buffer_get_meta:
1461  * @buffer: a #GstBuffer
1462  * @info: a #GstMetaInfo
1463  *
1464  * Get the metadata for the api in @info on buffer. When there is no such
1465  * metadata, NULL is returned.
1466  *
1467  * Note that the result metadata might not be of the implementation @info.
1468  *
1469  * Returns: the metadata for the api in @info on @buffer.
1470  */
1471 GstMeta *
1472 gst_buffer_get_meta (GstBuffer * buffer, const GstMetaInfo * info)
1473 {
1474   GstMetaItem *item;
1475   GstMeta *result = NULL;
1476
1477   g_return_val_if_fail (buffer != NULL, NULL);
1478   g_return_val_if_fail (info != NULL, NULL);
1479
1480   /* find GstMeta of the requested API */
1481   for (item = GST_BUFFER_META (buffer); item; item = item->next) {
1482     GstMeta *meta = &item->meta;
1483     if (meta->info->api == info->api) {
1484       result = meta;
1485       break;
1486     }
1487   }
1488   return result;
1489 }
1490
1491 /**
1492  * gst_buffer_add_meta:
1493  * @buffer: a #GstBuffer
1494  * @info: a #GstMetaInfo
1495  * @params: params for @info
1496  *
1497  * Add metadata for @info to @buffer using the parameters in @params.
1498  *
1499  * Returns: (transfer none): the metadata for the api in @info on @buffer.
1500  */
1501 GstMeta *
1502 gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
1503     gpointer params)
1504 {
1505   GstMetaItem *item;
1506   GstMeta *result = NULL;
1507   gsize size;
1508
1509   g_return_val_if_fail (buffer != NULL, NULL);
1510   g_return_val_if_fail (info != NULL, NULL);
1511
1512   /* create a new slice */
1513   size = ITEM_SIZE (info);
1514   item = g_slice_alloc (size);
1515   result = &item->meta;
1516   result->info = info;
1517   result->flags = GST_META_FLAG_NONE;
1518
1519   GST_CAT_DEBUG (GST_CAT_BUFFER,
1520       "alloc metadata %p (%s) of size %" G_GSIZE_FORMAT, result,
1521       g_type_name (info->type), info->size);
1522
1523   /* call the init_func when needed */
1524   if (info->init_func)
1525     if (!info->init_func (result, params, buffer))
1526       goto init_failed;
1527
1528   /* and add to the list of metadata */
1529   item->next = GST_BUFFER_META (buffer);
1530   GST_BUFFER_META (buffer) = item;
1531
1532   return result;
1533
1534 init_failed:
1535   {
1536     g_slice_free1 (size, item);
1537     return NULL;
1538   }
1539 }
1540
1541 /**
1542  * gst_buffer_remove_meta:
1543  * @buffer: a #GstBuffer
1544  * @meta: a #GstMeta
1545  *
1546  * Remove the metadata for @meta on @buffer.
1547  *
1548  * Returns: %TRUE if the metadata existed and was removed, %FALSE if no such
1549  * metadata was on @buffer.
1550  */
1551 gboolean
1552 gst_buffer_remove_meta (GstBuffer * buffer, GstMeta * meta)
1553 {
1554   GstMetaItem *walk, *prev;
1555
1556   g_return_val_if_fail (buffer != NULL, FALSE);
1557   g_return_val_if_fail (meta != NULL, FALSE);
1558
1559   /* find the metadata and delete */
1560   prev = GST_BUFFER_META (buffer);
1561   for (walk = prev; walk; walk = walk->next) {
1562     GstMeta *m = &walk->meta;
1563     if (m == meta) {
1564       const GstMetaInfo *info = meta->info;
1565
1566       /* remove from list */
1567       if (GST_BUFFER_META (buffer) == walk)
1568         GST_BUFFER_META (buffer) = walk->next;
1569       else
1570         prev->next = walk->next;
1571       /* call free_func if any */
1572       if (info->free_func)
1573         info->free_func (m, buffer);
1574
1575       /* and free the slice */
1576       g_slice_free1 (ITEM_SIZE (info), walk);
1577       break;
1578     }
1579     prev = walk;
1580   }
1581   return walk != NULL;
1582 }
1583
1584 /**
1585  * gst_buffer_iterate_meta:
1586  * @buffer: a #GstBuffer
1587  * @state: an opaque state pointer
1588  *
1589  * Retrieve the next #GstMeta after @current. If @state points
1590  * to %NULL, the first metadata is returned.
1591  *
1592  * @state will be updated with an opage state pointer 
1593  *
1594  * Returns: The next #GstMeta or %NULL when there are no more items.
1595  */
1596 GstMeta *
1597 gst_buffer_iterate_meta (GstBuffer * buffer, gpointer * state)
1598 {
1599   GstMetaItem **meta;
1600
1601   g_return_val_if_fail (buffer != NULL, NULL);
1602   g_return_val_if_fail (state != NULL, NULL);
1603
1604   meta = (GstMetaItem **) state;
1605   if (*meta == NULL)
1606     /* state NULL, move to first item */
1607     *meta = GST_BUFFER_META (buffer);
1608   else
1609     /* state !NULL, move to next item in list */
1610     *meta = (*meta)->next;
1611
1612   if (*meta)
1613     return &(*meta)->meta;
1614   else
1615     return NULL;
1616 }
1617
1618 /**
1619  * gst_buffer_foreach_meta:
1620  * @buffer: a #GstBuffer
1621  * @func: (scope call): a #GstBufferForeachMetaFunc to call
1622  * @user_data: (closure): user data passed to @func
1623  *
1624  * Call @func with @user_data for each meta in @buffer.
1625  *
1626  * @func can modify the passed meta pointer or its contents. The return value
1627  * of @func define if this function returns or if the remaining metadata items
1628  * in the buffer should be skipped.
1629  */
1630 void
1631 gst_buffer_foreach_meta (GstBuffer * buffer, GstBufferForeachMetaFunc func,
1632     gpointer user_data)
1633 {
1634   GstMetaItem *walk, *prev, *next;
1635
1636   g_return_if_fail (buffer != NULL);
1637   g_return_if_fail (func != NULL);
1638
1639   /* find the metadata and delete */
1640   prev = GST_BUFFER_META (buffer);
1641   for (walk = prev; walk; walk = next) {
1642     GstMeta *m, *new;
1643     gboolean res;
1644
1645     m = new = &walk->meta;
1646     next = walk->next;
1647
1648     res = func (buffer, &new, user_data);
1649
1650     if (new == NULL) {
1651       const GstMetaInfo *info = m->info;
1652
1653       GST_CAT_DEBUG (GST_CAT_BUFFER, "remove metadata %p (%s)", m,
1654           g_type_name (info->type));
1655
1656       /* remove from list */
1657       if (GST_BUFFER_META (buffer) == walk)
1658         GST_BUFFER_META (buffer) = next;
1659       else
1660         prev->next = next;
1661
1662       /* call free_func if any */
1663       if (info->free_func)
1664         info->free_func (m, buffer);
1665
1666       /* and free the slice */
1667       g_slice_free1 (ITEM_SIZE (info), walk);
1668     }
1669     if (!res)
1670       break;
1671   }
1672 }