Merge remote-tracking branch 'origin/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, #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   /* unref old buffers */
181   len = GST_BUFFER_MEM_LEN (buffer);
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   for (walk = GST_BUFFER_META (src); walk; walk = walk->next) {
327     GstMeta *meta = &walk->meta;
328     const GstMetaInfo *info = meta->info;
329
330     if (info->copy_func)
331       info->copy_func (dest, meta, src, offset, size);
332   }
333 }
334
335 static GstBuffer *
336 _gst_buffer_copy (GstBuffer * buffer)
337 {
338   GstBuffer *copy;
339
340   g_return_val_if_fail (buffer != NULL, NULL);
341
342   /* create a fresh new buffer */
343   copy = gst_buffer_new ();
344
345   /* we simply copy everything from our parent */
346   gst_buffer_copy_into (copy, buffer, GST_BUFFER_COPY_ALL, 0, -1);
347
348   return copy;
349 }
350
351 /* the default dispose function revives the buffer and returns it to the
352  * pool when there is a pool */
353 static gboolean
354 _gst_buffer_dispose (GstBuffer * buffer)
355 {
356   GstBufferPool *pool;
357
358   /* no pool, do free */
359   if ((pool = buffer->pool) == NULL)
360     return TRUE;
361
362   /* keep the buffer alive */
363   gst_buffer_ref (buffer);
364   /* return the buffer to the pool */
365   GST_CAT_LOG (GST_CAT_BUFFER, "release %p to pool %p", buffer, pool);
366   gst_buffer_pool_release_buffer (pool, buffer);
367
368   return FALSE;
369 }
370
371 static void
372 _gst_buffer_free (GstBuffer * buffer)
373 {
374   GstMetaItem *walk, *next;
375   guint i, len;
376   gsize msize;
377
378   g_return_if_fail (buffer != NULL);
379
380   GST_CAT_LOG (GST_CAT_BUFFER, "finalize %p", buffer);
381
382   /* free metadata */
383   for (walk = GST_BUFFER_META (buffer); walk; walk = next) {
384     GstMeta *meta = &walk->meta;
385     const GstMetaInfo *info = meta->info;
386
387     /* call free_func if any */
388     if (info->free_func)
389       info->free_func (meta, buffer);
390
391     next = walk->next;
392     /* and free the slice */
393     g_slice_free1 (ITEM_SIZE (info), walk);
394   }
395
396   /* get the size, when unreffing the memory, we could also unref the buffer
397    * itself */
398   msize = GST_MINI_OBJECT_SIZE (buffer);
399
400   /* free our memory */
401   len = GST_BUFFER_MEM_LEN (buffer);
402   for (i = 0; i < len; i++)
403     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
404
405   /* we set msize to 0 when the buffer is part of the memory block */
406   if (msize)
407     g_slice_free1 (msize, buffer);
408   else
409     gst_memory_unref (GST_BUFFER_BUFMEM (buffer));
410 }
411
412 static void
413 gst_buffer_init (GstBufferImpl * buffer, gsize size)
414 {
415   gst_mini_object_init (GST_MINI_OBJECT_CAST (buffer), _gst_buffer_type, size);
416
417   buffer->buffer.mini_object.copy =
418       (GstMiniObjectCopyFunction) _gst_buffer_copy;
419   buffer->buffer.mini_object.dispose =
420       (GstMiniObjectDisposeFunction) _gst_buffer_dispose;
421   buffer->buffer.mini_object.free =
422       (GstMiniObjectFreeFunction) _gst_buffer_free;
423
424   GST_BUFFER (buffer)->pool = NULL;
425   GST_BUFFER_PTS (buffer) = GST_CLOCK_TIME_NONE;
426   GST_BUFFER_DTS (buffer) = GST_CLOCK_TIME_NONE;
427   GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
428   GST_BUFFER_OFFSET (buffer) = GST_BUFFER_OFFSET_NONE;
429   GST_BUFFER_OFFSET_END (buffer) = GST_BUFFER_OFFSET_NONE;
430
431   GST_BUFFER_MEM_LEN (buffer) = 0;
432   GST_BUFFER_META (buffer) = NULL;
433 }
434
435 /**
436  * gst_buffer_new:
437  *
438  * Creates a newly allocated buffer without any data.
439  *
440  * MT safe.
441  *
442  * Returns: (transfer full): the new #GstBuffer.
443  */
444 GstBuffer *
445 gst_buffer_new (void)
446 {
447   GstBufferImpl *newbuf;
448
449   newbuf = g_slice_new (GstBufferImpl);
450   GST_CAT_LOG (GST_CAT_BUFFER, "new %p", newbuf);
451
452   gst_buffer_init (newbuf, sizeof (GstBufferImpl));
453
454   return GST_BUFFER_CAST (newbuf);
455 }
456
457 /**
458  * gst_buffer_new_allocate:
459  * @allocator: (allow-none): the #GstAllocator to use, or NULL to use the
460  *     default allocator
461  * @size: the size in bytes of the new buffer's data.
462  * @align: the alignment of the buffer memory
463  *
464  * Tries to create a newly allocated buffer with data of the given size and
465  * alignment from @allocator. If the requested amount of memory can't be
466  * allocated, NULL will be returned. The allocated buffer memory is not cleared.
467  *
468  * When @allocator is NULL, the default memory allocator will be used.
469  *
470  * Allocator buffer memory will be aligned to multiples of (@align + 1) bytes.
471  *
472  * Note that when @size == 0, the buffer will not have memory associated with it.
473  *
474  * MT safe.
475  *
476  * Returns: (transfer full): a new #GstBuffer, or NULL if the memory couldn't
477  *     be allocated.
478  */
479 GstBuffer *
480 gst_buffer_new_allocate (const GstAllocator * allocator, gsize size,
481     gsize align)
482 {
483   GstBuffer *newbuf;
484   GstMemory *mem;
485 #if 0
486   guint8 *data;
487   gsize asize;
488 #endif
489
490 #if 1
491   if (size > 0) {
492     mem = gst_allocator_alloc (allocator, size, align);
493     if (G_UNLIKELY (mem == NULL))
494       goto no_memory;
495   } else {
496     mem = NULL;
497   }
498
499   newbuf = gst_buffer_new ();
500
501   if (mem != NULL)
502     _memory_add (newbuf, -1, mem);
503
504   GST_CAT_LOG (GST_CAT_BUFFER,
505       "new buffer %p of size %" G_GSIZE_FORMAT " from allocator %p", newbuf,
506       size, allocator);
507 #endif
508
509 #if 0
510   asize = sizeof (GstBufferImpl) + size;
511   data = g_slice_alloc (asize);
512   if (G_UNLIKELY (data == NULL))
513     goto no_memory;
514
515   newbuf = GST_BUFFER_CAST (data);
516
517   gst_buffer_init ((GstBufferImpl *) data, asize);
518   if (size > 0) {
519     mem = gst_memory_new_wrapped (0, data + sizeof (GstBufferImpl), NULL,
520         size, 0, size);
521     _memory_add (newbuf, -1, mem);
522   }
523 #endif
524
525 #if 0
526   /* allocate memory and buffer, it might be interesting to do this but there
527    * are many complications. We need to keep the memory mapped to access the
528    * buffer fields and the memory for the buffer might be just very slow. We
529    * also need to do some more magic to get the alignment right. */
530   asize = sizeof (GstBufferImpl) + size;
531   mem = gst_allocator_alloc (allocator, asize, align);
532   if (G_UNLIKELY (mem == NULL))
533     goto no_memory;
534
535   /* map the data part and init the buffer in it, set the buffer size to 0 so
536    * that a finalize won't free the buffer */
537   data = gst_memory_map (mem, &asize, NULL, GST_MAP_WRITE);
538   gst_buffer_init ((GstBufferImpl *) data, 0);
539   gst_memory_unmap (mem, data, asize);
540
541   /* strip off the buffer */
542   gst_memory_resize (mem, sizeof (GstBufferImpl), size);
543
544   newbuf = GST_BUFFER_CAST (data);
545   GST_BUFFER_BUFMEM (newbuf) = mem;
546
547   if (size > 0)
548     _memory_add (newbuf, -1, gst_memory_ref (mem));
549 #endif
550
551   return newbuf;
552
553   /* ERRORS */
554 no_memory:
555   {
556     GST_CAT_WARNING (GST_CAT_BUFFER,
557         "failed to allocate %" G_GSIZE_FORMAT " bytes", size);
558     return NULL;
559   }
560 }
561
562 /**
563  * gst_buffer_new_wrapped_full:
564  * @data: data to wrap
565  * @free_func: function to free @data
566  * @offset: offset in @data of valid data
567  * @size: size of valid data in @data starting at @offset
568  *
569  * Creates a new buffer that wraps the given @data.  Valid data is set
570  * to start at @offset and up to @size.  If no @free_func is provided,
571  * buffer memory is marked READONLY.
572  *
573  * MT safe.
574  *
575  * Returns: (transfer full): a new #GstBuffer
576  */
577 GstBuffer *
578 gst_buffer_new_wrapped_full (gpointer data, GFreeFunc free_func, gsize offset,
579     gsize size)
580 {
581   GstBuffer *newbuf;
582
583   newbuf = gst_buffer_new ();
584   gst_buffer_take_memory (newbuf, -1,
585       gst_memory_new_wrapped (free_func ? 0 : GST_MEMORY_FLAG_READONLY,
586           data, free_func, offset + size, offset, size));
587
588   return newbuf;
589 }
590
591 /**
592  * gst_buffer_new_wrapped:
593  * @data: data to wrap
594  * @size: allocated size of @data
595  *
596  * Creates a new buffer that wraps the given @data. The memory will be freed
597  * with g_free and will be marked writable.
598  *
599  * MT safe.
600  *
601  * Returns: (transfer full): a new #GstBuffer
602  */
603 GstBuffer *
604 gst_buffer_new_wrapped (gpointer data, gsize size)
605 {
606   return gst_buffer_new_wrapped_full (data, g_free, 0, size);
607 }
608
609 /**
610  * gst_buffer_n_memory:
611  * @buffer: a #GstBuffer.
612  *
613  * Get the amount of memory blocks that this buffer has.
614  *
615  * Returns: (transfer full): the amount of memory block in this buffer.
616  */
617 guint
618 gst_buffer_n_memory (GstBuffer * buffer)
619 {
620   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
621
622   return GST_BUFFER_MEM_LEN (buffer);
623 }
624
625 /**
626  * gst_buffer_take_memory:
627  * @buffer: a #GstBuffer.
628  * @idx: the index to add the memory at, or -1 to append it to the end
629  * @mem: (transfer full): a #GstMemory.
630  *
631  * Add the memory block @mem to @buffer at @idx. This function takes ownership
632  * of @mem and thus doesn't increase its refcount.
633  */
634 void
635 gst_buffer_take_memory (GstBuffer * buffer, gint idx, GstMemory * mem)
636 {
637   g_return_if_fail (GST_IS_BUFFER (buffer));
638   g_return_if_fail (gst_buffer_is_writable (buffer));
639   g_return_if_fail (mem != NULL);
640   g_return_if_fail (idx == -1 ||
641       (idx >= 0 && idx <= GST_BUFFER_MEM_LEN (buffer)));
642
643   _memory_add (buffer, idx, mem);
644 }
645
646 static GstMemory *
647 _get_memory (GstBuffer * buffer, guint idx, gboolean write)
648 {
649   GstMemory *mem;
650
651   mem = GST_BUFFER_MEM_PTR (buffer, idx);
652
653   if (G_UNLIKELY (write && !GST_MEMORY_IS_WRITABLE (mem))) {
654     GstMemory *copy;
655     GST_CAT_LOG (GST_CAT_BUFFER,
656         "making writable copy of memory %p in buffer %p", mem, buffer);
657     /* replace with a writable copy */
658     copy = gst_memory_copy (mem, 0, -1);
659     GST_BUFFER_MEM_PTR (buffer, idx) = copy;
660     gst_memory_unref (mem);
661     mem = copy;
662   }
663   return mem;
664 }
665
666 /**
667  * gst_buffer_peek_memory:
668  * @buffer: a #GstBuffer.
669  * @idx: an index
670  * @flags: #GstMapFlags
671  *
672  * Get the memory block in @buffer at @idx for memory access in @flags.
673  * This function does not return a refcount to the memory block. The memory
674  * block stays valid for as long as the caller has a valid reference to @buffer.
675  *
676  * @buffer should be writable when @flags contains #GST_MAP_WRITE. If the memory
677  * at @idx is not writable, a new writable copy will be installed in @buffer and
678  * returned.
679  *
680  * Returns: a #GstMemory at @idx.
681  */
682 GstMemory *
683 gst_buffer_peek_memory (GstBuffer * buffer, guint idx, GstMapFlags flags)
684 {
685   GstMemory *mem;
686   gboolean write;
687
688   write = (flags & GST_MAP_WRITE) != 0;
689
690   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
691   g_return_val_if_fail (idx < GST_BUFFER_MEM_LEN (buffer), NULL);
692
693   /* check if we can write when asked for write access */
694   if (G_UNLIKELY (write && !gst_buffer_is_writable (buffer)))
695     goto not_writable;
696
697   mem = _get_memory (buffer, idx, write);
698
699   return mem;
700
701   /* ERRORS */
702 not_writable:
703   {
704     g_return_val_if_fail (gst_buffer_is_writable (buffer), NULL);
705     return NULL;
706   }
707 }
708
709 /**
710  * gst_buffer_remove_memory_range:
711  * @buffer: a #GstBuffer.
712  * @idx: an index
713  * @length: a length
714  *
715  * Remove @len memory blocks in @buffer starting from @idx.
716  *
717  * @length can be -1, in which case all memory starting from @idx is removed.
718  */
719 void
720 gst_buffer_remove_memory_range (GstBuffer * buffer, guint idx, guint length)
721 {
722   guint len, i, end;
723
724   g_return_if_fail (GST_IS_BUFFER (buffer));
725   g_return_if_fail (gst_buffer_is_writable (buffer));
726
727   len = GST_BUFFER_MEM_LEN (buffer);
728   if (length == -1) {
729     g_return_if_fail (idx < len);
730     length = len - idx;
731   }
732
733   end = idx + length;
734   for (i = idx; i < end; i++)
735     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
736
737   if (end != len) {
738     g_memmove (&GST_BUFFER_MEM_PTR (buffer, idx),
739         &GST_BUFFER_MEM_PTR (buffer, end), (len - end) * sizeof (gpointer));
740   }
741   GST_BUFFER_MEM_LEN (buffer) = len - length;
742 }
743
744 /**
745  * gst_buffer_get_sizes:
746  * @buffer: a #GstBuffer.
747  * @offset: a pointer to the offset
748  * @maxsize: a pointer to the maxsize
749  *
750  * Get the total size of all memory blocks in @buffer.
751  *
752  * When not %NULL, @offset will contain the offset of the data in the first
753  * memory block in @buffer and @maxsize will contain the sum of the size
754  * and @offset and the amount of extra padding on the last memory block.
755  * @offset and @maxsize can be used to resize the buffer with
756  * gst_buffer_resize().
757  *
758  * Returns: the total size of the memory in @buffer.
759  */
760 gsize
761 gst_buffer_get_sizes (GstBuffer * buffer, gsize * offset, gsize * maxsize)
762 {
763   guint len;
764   gsize size;
765   GstMemory *mem;
766
767   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
768
769   len = GST_BUFFER_MEM_LEN (buffer);
770
771   if (G_LIKELY (len == 1)) {
772     /* common case */
773     mem = GST_BUFFER_MEM_PTR (buffer, 0);
774     size = gst_memory_get_sizes (mem, offset, maxsize);
775   } else {
776     guint i;
777     gsize extra, offs;
778
779     size = offs = extra = 0;
780     for (i = 0; i < len; i++) {
781       gsize s, o, ms;
782
783       mem = GST_BUFFER_MEM_PTR (buffer, i);
784       s = gst_memory_get_sizes (mem, &o, &ms);
785
786       if (s) {
787         if (size == 0)
788           /* first size, take accumulated data before as the offset */
789           offs = extra + o;
790         /* add sizes */
791         size += s;
792         /* save the amount of data after this block */
793         extra = ms - (o + s);
794       } else {
795         /* empty block, add as extra */
796         extra += ms;
797       }
798     }
799     if (offset)
800       *offset = offs;
801     if (maxsize)
802       *maxsize = offs + size + extra;
803   }
804   return size;
805 }
806
807 /**
808  * gst_buffer_resize:
809  * @buffer: a #GstBuffer.
810  * @offset: the offset adjustement
811  * @size: the new size or -1 to just adjust the offset
812  *
813  * Set the total size of the buffer
814  */
815 void
816 gst_buffer_resize (GstBuffer * buffer, gssize offset, gssize size)
817 {
818   guint len;
819   guint i;
820   gsize bsize, bufsize, bufoffs, bufmax;
821   GstMemory *mem;
822
823   g_return_if_fail (gst_buffer_is_writable (buffer));
824   g_return_if_fail (size >= -1);
825
826   bufsize = gst_buffer_get_sizes (buffer, &bufoffs, &bufmax);
827
828   GST_CAT_LOG (GST_CAT_BUFFER, "trim %p %" G_GSSIZE_FORMAT "-%" G_GSSIZE_FORMAT
829       " size:%" G_GSIZE_FORMAT " offs:%" G_GSIZE_FORMAT " max:%"
830       G_GSIZE_FORMAT, 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: (out) (allow-none): a location for the size
892  * @maxsize: (out) (allow-none): 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. Both parameters can be %NULL.
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: (transfer none): 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, or -1
993  *
994  * Release the memory previously mapped with gst_buffer_map(). Pass -1 to size
995  * if no update is needed.
996  *
997  * Returns: #TRUE on success. #FALSE can be returned when the new size is larger
998  * than the maxsize of the memory.
999  */
1000 gboolean
1001 gst_buffer_unmap (GstBuffer * buffer, gpointer data, gssize size)
1002 {
1003   gboolean result;
1004   guint len;
1005
1006   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1007   g_return_val_if_fail (size >= -1, FALSE);
1008
1009   len = GST_BUFFER_MEM_LEN (buffer);
1010
1011   if (G_LIKELY (len == 1)) {
1012     GstMemory *mem = GST_BUFFER_MEM_PTR (buffer, 0);
1013
1014     result = gst_memory_unmap (mem, data, size);
1015   } else {
1016     /* this must have been from read-only access. After _map, the buffer either
1017      * only contains 1 memory block or it allocated memory to join memory
1018      * blocks. It's not allowed to add buffers between _map and _unmap. */
1019     g_free (data);
1020     result = TRUE;
1021   }
1022   return result;
1023 }
1024
1025 /**
1026  * gst_buffer_fill:
1027  * @buffer: a #GstBuffer.
1028  * @offset: the offset to fill
1029  * @src: the source address
1030  * @size: the size to fill
1031  *
1032  * Copy @size bytes from @src to @buffer at @offset.
1033  *
1034  * Returns: The amount of bytes copied. This value can be lower than @size
1035  *    when @buffer did not contain enough data.
1036  */
1037 gsize
1038 gst_buffer_fill (GstBuffer * buffer, gsize offset, gconstpointer src,
1039     gsize size)
1040 {
1041   gsize i, len, left;
1042   const guint8 *ptr = src;
1043
1044   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1045   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1046   g_return_val_if_fail (src != NULL, 0);
1047
1048   len = GST_BUFFER_MEM_LEN (buffer);
1049   left = size;
1050
1051   for (i = 0; i < len && left > 0; i++) {
1052     guint8 *data;
1053     gsize ssize, tocopy;
1054     GstMemory *mem;
1055
1056     mem = _get_memory (buffer, i, TRUE);
1057
1058     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_WRITE);
1059     if (ssize > offset) {
1060       /* we have enough */
1061       tocopy = MIN (ssize - offset, left);
1062       memcpy (data + offset, ptr, tocopy);
1063       left -= tocopy;
1064       ptr += tocopy;
1065       offset = 0;
1066     } else {
1067       /* offset past buffer, skip */
1068       offset -= ssize;
1069     }
1070     gst_memory_unmap (mem, data, ssize);
1071   }
1072   return size - left;
1073 }
1074
1075 /**
1076  * gst_buffer_extract:
1077  * @buffer: a #GstBuffer.
1078  * @offset: the offset to extract
1079  * @dest: the destination address
1080  * @size: the size to extract
1081  *
1082  * Copy @size bytes starting from @offset in @buffer to @dest.
1083  *
1084  * Returns: The amount of bytes extracted. This value can be lower than @size
1085  *    when @buffer did not contain enough data.
1086  */
1087 gsize
1088 gst_buffer_extract (GstBuffer * buffer, gsize offset, gpointer dest, gsize size)
1089 {
1090   gsize i, len, left;
1091   guint8 *ptr = dest;
1092
1093   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1094   g_return_val_if_fail (dest != NULL, 0);
1095
1096   len = GST_BUFFER_MEM_LEN (buffer);
1097   left = size;
1098
1099   for (i = 0; i < len && left > 0; i++) {
1100     guint8 *data;
1101     gsize ssize, tocopy;
1102     GstMemory *mem;
1103
1104     mem = GST_BUFFER_MEM_PTR (buffer, i);
1105
1106     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_READ);
1107     if (ssize > offset) {
1108       /* we have enough */
1109       tocopy = MIN (ssize - offset, left);
1110       memcpy (ptr, data + offset, tocopy);
1111       left -= tocopy;
1112       ptr += tocopy;
1113       offset = 0;
1114     } else {
1115       /* offset past buffer, skip */
1116       offset -= ssize;
1117     }
1118     gst_memory_unmap (mem, data, ssize);
1119   }
1120   return size - left;
1121 }
1122
1123 /**
1124  * gst_buffer_memcmp:
1125  * @buffer: a #GstBuffer.
1126  * @offset: the offset in @buffer
1127  * @mem: the memory to compare
1128  * @size: the size to compare
1129  *
1130  * Compare @size bytes starting from @offset in @buffer with the memory in @mem.
1131  *
1132  * Returns: 0 if the memory is equal.
1133  */
1134 gint
1135 gst_buffer_memcmp (GstBuffer * buffer, gsize offset, gconstpointer mem,
1136     gsize size)
1137 {
1138   gsize i, len;
1139   const guint8 *ptr = mem;
1140   gint res = 0;
1141
1142   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1143   g_return_val_if_fail (mem != NULL, 0);
1144
1145   len = GST_BUFFER_MEM_LEN (buffer);
1146
1147   for (i = 0; i < len && size > 0 && res == 0; i++) {
1148     guint8 *data;
1149     gsize ssize, tocmp;
1150     GstMemory *mem;
1151
1152     mem = GST_BUFFER_MEM_PTR (buffer, i);
1153
1154     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_READ);
1155     if (ssize > offset) {
1156       /* we have enough */
1157       tocmp = MIN (ssize - offset, size);
1158       res = memcmp (ptr, data + offset, tocmp);
1159       size -= tocmp;
1160       ptr += tocmp;
1161       offset = 0;
1162     } else {
1163       /* offset past buffer, skip */
1164       offset -= ssize;
1165     }
1166     gst_memory_unmap (mem, data, ssize);
1167   }
1168   return res;
1169 }
1170
1171 /**
1172  * gst_buffer_memset:
1173  * @buffer: a #GstBuffer.
1174  * @offset: the offset in @buffer
1175  * @val: the value to set
1176  * @size: the size to set
1177  *
1178  * Fill @buf with @size bytes with @val starting from @offset.
1179  *
1180  * Returns: The amount of bytes filled. This value can be lower than @size
1181  *    when @buffer did not contain enough data.
1182  */
1183 gsize
1184 gst_buffer_memset (GstBuffer * buffer, gsize offset, guint8 val, gsize size)
1185 {
1186   gsize i, len, left;
1187
1188   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1189   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1190
1191   len = GST_BUFFER_MEM_LEN (buffer);
1192   left = size;
1193
1194   for (i = 0; i < len && left > 0; i++) {
1195     guint8 *data;
1196     gsize ssize, toset;
1197     GstMemory *mem;
1198
1199     mem = GST_BUFFER_MEM_PTR (buffer, i);
1200
1201     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_WRITE);
1202     if (ssize > offset) {
1203       /* we have enough */
1204       toset = MIN (ssize - offset, left);
1205       memset (data + offset, val, toset);
1206       left -= toset;
1207       offset = 0;
1208     } else {
1209       /* offset past buffer, skip */
1210       offset -= ssize;
1211     }
1212     gst_memory_unmap (mem, data, ssize);
1213   }
1214   return size - left;
1215 }
1216
1217 /**
1218  * gst_buffer_copy_region:
1219  * @parent: a #GstBuffer.
1220  * @flags: the #GstBufferCopyFlags
1221  * @offset: the offset into parent #GstBuffer at which the new sub-buffer 
1222  *          begins.
1223  * @size: the size of the new #GstBuffer sub-buffer, in bytes.
1224  *
1225  * Creates a sub-buffer from @parent at @offset and @size.
1226  * This sub-buffer uses the actual memory space of the parent buffer.
1227  * This function will copy the offset and timestamp fields when the
1228  * offset is 0. If not, they will be set to #GST_CLOCK_TIME_NONE and 
1229  * #GST_BUFFER_OFFSET_NONE.
1230  * If @offset equals 0 and @size equals the total size of @buffer, the
1231  * duration and offset end fields are also copied. If not they will be set
1232  * to #GST_CLOCK_TIME_NONE and #GST_BUFFER_OFFSET_NONE.
1233  *
1234  * MT safe.
1235  *
1236  * Returns: (transfer full): the new #GstBuffer or NULL if the arguments were
1237  *     invalid.
1238  */
1239 GstBuffer *
1240 gst_buffer_copy_region (GstBuffer * buffer, GstBufferCopyFlags flags,
1241     gsize offset, gsize size)
1242 {
1243   GstBuffer *copy;
1244
1245   g_return_val_if_fail (buffer != NULL, NULL);
1246
1247   /* create the new buffer */
1248   copy = gst_buffer_new ();
1249
1250   GST_CAT_LOG (GST_CAT_BUFFER, "new region copy %p of %p %" G_GSIZE_FORMAT
1251       "-%" G_GSIZE_FORMAT, copy, buffer, offset, size);
1252
1253   gst_buffer_copy_into (copy, buffer, flags, offset, size);
1254
1255   return copy;
1256 }
1257
1258 static gboolean
1259 _gst_buffer_arr_is_span_fast (GstMemory ** mem[], gsize len[], guint n,
1260     gsize * offset, GstMemory ** parent)
1261 {
1262   GstMemory *mcur, *mprv;
1263   gboolean have_offset = FALSE;
1264   guint count, i;
1265
1266   mcur = mprv = NULL;
1267   for (count = 0; count < n; count++) {
1268     gsize offs, clen;
1269     GstMemory **cmem;
1270
1271     cmem = mem[count];
1272     clen = len[count];
1273
1274     for (i = 0; i < clen; i++) {
1275       if (mcur)
1276         mprv = mcur;
1277       mcur = cmem[i];
1278
1279       if (mprv && mcur) {
1280         /* check is memory is contiguous */
1281         if (!gst_memory_is_span (mprv, mcur, &offs))
1282           return FALSE;
1283
1284         if (!have_offset) {
1285           if (offset)
1286             *offset = offs;
1287           if (parent)
1288             *parent = mprv->parent;
1289
1290           have_offset = TRUE;
1291         }
1292       }
1293     }
1294   }
1295   return have_offset;
1296 }
1297
1298 static GstMemory *
1299 _gst_buffer_arr_span (GstMemory ** mem[], gsize len[], guint n, gsize offset,
1300     gsize size, gboolean writable)
1301 {
1302   GstMemory *span, *parent = NULL;
1303   gsize poffset = 0;
1304
1305   if (!writable
1306       && _gst_buffer_arr_is_span_fast (mem, len, n, &poffset, &parent)) {
1307     if (parent->flags & GST_MEMORY_FLAG_NO_SHARE)
1308       span = gst_memory_copy (parent, offset + poffset, size);
1309     else
1310       span = gst_memory_share (parent, offset + poffset, size);
1311   } else {
1312     gsize count, left;
1313     guint8 *dest, *ptr;
1314
1315     span = gst_allocator_alloc (NULL, size, 0);
1316     dest = gst_memory_map (span, NULL, NULL, GST_MAP_WRITE);
1317
1318     ptr = dest;
1319     left = size;
1320
1321     for (count = 0; count < n; count++) {
1322       gsize i, tocopy, clen, ssize;
1323       guint8 *src;
1324       GstMemory **cmem;
1325
1326       cmem = mem[count];
1327       clen = len[count];
1328
1329       for (i = 0; i < clen && left > 0; i++) {
1330         src = gst_memory_map (cmem[i], &ssize, NULL, GST_MAP_READ);
1331         tocopy = MIN (ssize, left);
1332         if (tocopy > offset) {
1333           memcpy (ptr, src + offset, tocopy - offset);
1334           left -= tocopy;
1335           ptr += tocopy;
1336           offset = 0;
1337         } else {
1338           offset -= tocopy;
1339         }
1340         gst_memory_unmap (cmem[i], src, ssize);
1341       }
1342     }
1343     gst_memory_unmap (span, dest, size);
1344   }
1345   return span;
1346 }
1347
1348 /**
1349  * gst_buffer_is_span_fast:
1350  * @buf1: the first #GstBuffer.
1351  * @buf2: the second #GstBuffer.
1352  *
1353  * Determines whether a gst_buffer_span() can be done without copying
1354  * the contents, that is, whether the data areas are contiguous sub-buffers of
1355  * the same buffer.
1356  *
1357  * MT safe.
1358  * Returns: TRUE if the buffers are contiguous,
1359  * FALSE if a copy would be required.
1360  */
1361 gboolean
1362 gst_buffer_is_span_fast (GstBuffer * buf1, GstBuffer * buf2)
1363 {
1364   GstMemory **mem[2];
1365   gsize len[2];
1366
1367   g_return_val_if_fail (GST_IS_BUFFER (buf1), FALSE);
1368   g_return_val_if_fail (GST_IS_BUFFER (buf2), FALSE);
1369   g_return_val_if_fail (buf1->mini_object.refcount > 0, FALSE);
1370   g_return_val_if_fail (buf2->mini_object.refcount > 0, FALSE);
1371
1372   mem[0] = GST_BUFFER_MEM_ARRAY (buf1);
1373   len[0] = GST_BUFFER_MEM_LEN (buf1);
1374   mem[1] = GST_BUFFER_MEM_ARRAY (buf2);
1375   len[1] = GST_BUFFER_MEM_LEN (buf2);
1376
1377   return _gst_buffer_arr_is_span_fast (mem, len, 2, NULL, NULL);
1378 }
1379
1380 /**
1381  * gst_buffer_span:
1382  * @buf1: the first source #GstBuffer to merge.
1383  * @offset: the offset in the first buffer from where the new
1384  * buffer should start.
1385  * @buf2: the second source #GstBuffer to merge.
1386  * @size: the total size of the new buffer.
1387  *
1388  * Creates a new buffer that consists of part of buf1 and buf2.
1389  * Logically, buf1 and buf2 are concatenated into a single larger
1390  * buffer, and a new buffer is created at the given offset inside
1391  * this space, with a given length.
1392  *
1393  * If the two source buffers are children of the same larger buffer,
1394  * and are contiguous, the new buffer will be a child of the shared
1395  * parent, and thus no copying is necessary. you can use
1396  * gst_buffer_is_span_fast() to determine if a memcpy will be needed.
1397  *
1398  * MT safe.
1399  *
1400  * Returns: (transfer full): the new #GstBuffer that spans the two source
1401  *     buffers, or NULL if the arguments are invalid.
1402  */
1403 GstBuffer *
1404 gst_buffer_span (GstBuffer * buf1, gsize offset, GstBuffer * buf2, gsize size)
1405 {
1406   GstBuffer *newbuf;
1407   GstMemory *span;
1408   GstMemory **mem[2];
1409   gsize len[2], len1, len2;
1410
1411   g_return_val_if_fail (GST_IS_BUFFER (buf1), NULL);
1412   g_return_val_if_fail (GST_IS_BUFFER (buf2), NULL);
1413   g_return_val_if_fail (buf1->mini_object.refcount > 0, NULL);
1414   g_return_val_if_fail (buf2->mini_object.refcount > 0, NULL);
1415   len1 = gst_buffer_get_size (buf1);
1416   len2 = gst_buffer_get_size (buf2);
1417   g_return_val_if_fail (len1 + len2 > offset, NULL);
1418   if (size == -1)
1419     size = len1 + len2 - offset;
1420   else
1421     g_return_val_if_fail (size <= len1 + len2 - offset, NULL);
1422
1423   mem[0] = GST_BUFFER_MEM_ARRAY (buf1);
1424   len[0] = GST_BUFFER_MEM_LEN (buf1);
1425   mem[1] = GST_BUFFER_MEM_ARRAY (buf2);
1426   len[1] = GST_BUFFER_MEM_LEN (buf2);
1427
1428   span = _gst_buffer_arr_span (mem, len, 2, offset, size, FALSE);
1429
1430   newbuf = gst_buffer_new ();
1431   _memory_add (newbuf, -1, span);
1432
1433 #if 0
1434   /* if the offset is 0, the new buffer has the same timestamp as buf1 */
1435   if (offset == 0) {
1436     GST_BUFFER_OFFSET (newbuf) = GST_BUFFER_OFFSET (buf1);
1437     GST_BUFFER_PTS (newbuf) = GST_BUFFER_PTS (buf1);
1438     GST_BUFFER_DTS (newbuf) = GST_BUFFER_DTS (buf1);
1439
1440     /* if we completely merged the two buffers (appended), we can
1441      * calculate the duration too. Also make sure we's not messing with
1442      * invalid DURATIONS */
1443     if (buf1->size + buf2->size == len) {
1444       if (GST_BUFFER_DURATION_IS_VALID (buf1) &&
1445           GST_BUFFER_DURATION_IS_VALID (buf2)) {
1446         /* add duration */
1447         GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf1) +
1448             GST_BUFFER_DURATION (buf2);
1449       }
1450       if (GST_BUFFER_OFFSET_END_IS_VALID (buf2)) {
1451         /* add offset_end */
1452         GST_BUFFER_OFFSET_END (newbuf) = GST_BUFFER_OFFSET_END (buf2);
1453       }
1454     }
1455   }
1456 #endif
1457
1458   return newbuf;
1459 }
1460
1461 /**
1462  * gst_buffer_get_meta:
1463  * @buffer: a #GstBuffer
1464  * @info: a #GstMetaInfo
1465  *
1466  * Get the metadata for the api in @info on buffer. When there is no such
1467  * metadata, NULL is returned.
1468  *
1469  * Note that the result metadata might not be of the implementation @info.
1470  *
1471  * Returns: the metadata for the api in @info on @buffer.
1472  */
1473 GstMeta *
1474 gst_buffer_get_meta (GstBuffer * buffer, const GstMetaInfo * info)
1475 {
1476   GstMetaItem *item;
1477   GstMeta *result = NULL;
1478
1479   g_return_val_if_fail (buffer != NULL, NULL);
1480   g_return_val_if_fail (info != NULL, NULL);
1481
1482   /* find GstMeta of the requested API */
1483   for (item = GST_BUFFER_META (buffer); item; item = item->next) {
1484     GstMeta *meta = &item->meta;
1485     if (meta->info->api == info->api) {
1486       result = meta;
1487       break;
1488     }
1489   }
1490   return result;
1491 }
1492
1493 /**
1494  * gst_buffer_add_meta:
1495  * @buffer: a #GstBuffer
1496  * @info: a #GstMetaInfo
1497  * @params: params for @info
1498  *
1499  * Add metadata for @info to @buffer using the parameters in @params.
1500  *
1501  * Returns: (transfer none): the metadata for the api in @info on @buffer.
1502  */
1503 GstMeta *
1504 gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
1505     gpointer params)
1506 {
1507   GstMetaItem *item;
1508   GstMeta *result = NULL;
1509   gsize size;
1510
1511   g_return_val_if_fail (buffer != NULL, NULL);
1512   g_return_val_if_fail (info != NULL, NULL);
1513
1514   /* create a new slice */
1515   GST_CAT_DEBUG (GST_CAT_BUFFER, "alloc metadata %s of size %" G_GSIZE_FORMAT,
1516       g_type_name (info->type), info->size);
1517
1518   size = ITEM_SIZE (info);
1519   item = g_slice_alloc (size);
1520   result = &item->meta;
1521   result->info = info;
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 }