memory: make writability check into a method
[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   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 (const GstAllocator * allocator, gsize size,
483     gsize align)
484 {
485   GstBuffer *newbuf;
486   GstMemory *mem;
487 #if 0
488   guint8 *data;
489   gsize asize;
490 #endif
491
492 #if 1
493   if (size > 0) {
494     mem = gst_allocator_alloc (allocator, size, align);
495     if (G_UNLIKELY (mem == NULL))
496       goto no_memory;
497   } else {
498     mem = NULL;
499   }
500
501   newbuf = gst_buffer_new ();
502
503   if (mem != NULL)
504     _memory_add (newbuf, -1, mem);
505
506   GST_CAT_LOG (GST_CAT_BUFFER,
507       "new buffer %p of size %" G_GSIZE_FORMAT " from allocator %p", newbuf,
508       size, allocator);
509 #endif
510
511 #if 0
512   asize = sizeof (GstBufferImpl) + size;
513   data = g_slice_alloc (asize);
514   if (G_UNLIKELY (data == NULL))
515     goto no_memory;
516
517   newbuf = GST_BUFFER_CAST (data);
518
519   gst_buffer_init ((GstBufferImpl *) data, asize);
520   if (size > 0) {
521     mem = gst_memory_new_wrapped (0, data + sizeof (GstBufferImpl), NULL,
522         size, 0, size);
523     _memory_add (newbuf, -1, mem);
524   }
525 #endif
526
527 #if 0
528   /* allocate memory and buffer, it might be interesting to do this but there
529    * are many complications. We need to keep the memory mapped to access the
530    * buffer fields and the memory for the buffer might be just very slow. We
531    * also need to do some more magic to get the alignment right. */
532   asize = sizeof (GstBufferImpl) + size;
533   mem = gst_allocator_alloc (allocator, asize, align);
534   if (G_UNLIKELY (mem == NULL))
535     goto no_memory;
536
537   /* map the data part and init the buffer in it, set the buffer size to 0 so
538    * that a finalize won't free the buffer */
539   data = gst_memory_map (mem, &asize, NULL, GST_MAP_WRITE);
540   gst_buffer_init ((GstBufferImpl *) data, 0);
541   gst_memory_unmap (mem, data, asize);
542
543   /* strip off the buffer */
544   gst_memory_resize (mem, sizeof (GstBufferImpl), size);
545
546   newbuf = GST_BUFFER_CAST (data);
547   GST_BUFFER_BUFMEM (newbuf) = mem;
548
549   if (size > 0)
550     _memory_add (newbuf, -1, gst_memory_ref (mem));
551 #endif
552
553   return newbuf;
554
555   /* ERRORS */
556 no_memory:
557   {
558     GST_CAT_WARNING (GST_CAT_BUFFER,
559         "failed to allocate %" G_GSIZE_FORMAT " bytes", size);
560     return NULL;
561   }
562 }
563
564 /**
565  * gst_buffer_new_wrapped_full:
566  * @data: data to wrap
567  * @free_func: function to free @data
568  * @offset: offset in @data of valid data
569  * @size: size of valid data in @data starting at @offset
570  *
571  * Creates a new buffer that wraps the given @data.  Valid data is set
572  * to start at @offset and up to @size.  If no @free_func is provided,
573  * buffer memory is marked READONLY.
574  *
575  * MT safe.
576  *
577  * Returns: (transfer full): a new #GstBuffer
578  */
579 GstBuffer *
580 gst_buffer_new_wrapped_full (gpointer data, GFreeFunc free_func, gsize offset,
581     gsize size)
582 {
583   GstBuffer *newbuf;
584
585   newbuf = gst_buffer_new ();
586   gst_buffer_take_memory (newbuf, -1,
587       gst_memory_new_wrapped (free_func ? 0 : GST_MEMORY_FLAG_READONLY,
588           data, free_func, offset + size, offset, size));
589
590   return newbuf;
591 }
592
593 /**
594  * gst_buffer_new_wrapped:
595  * @data: data to wrap
596  * @size: allocated size of @data
597  *
598  * Creates a new buffer that wraps the given @data. The memory will be freed
599  * with g_free and will be marked writable.
600  *
601  * MT safe.
602  *
603  * Returns: (transfer full): a new #GstBuffer
604  */
605 GstBuffer *
606 gst_buffer_new_wrapped (gpointer data, gsize size)
607 {
608   return gst_buffer_new_wrapped_full (data, g_free, 0, size);
609 }
610
611 /**
612  * gst_buffer_n_memory:
613  * @buffer: a #GstBuffer.
614  *
615  * Get the amount of memory blocks that this buffer has.
616  *
617  * Returns: (transfer full): the amount of memory block in this buffer.
618  */
619 guint
620 gst_buffer_n_memory (GstBuffer * buffer)
621 {
622   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
623
624   return GST_BUFFER_MEM_LEN (buffer);
625 }
626
627 /**
628  * gst_buffer_take_memory:
629  * @buffer: a #GstBuffer.
630  * @idx: the index to add the memory at, or -1 to append it to the end
631  * @mem: (transfer full): a #GstMemory.
632  *
633  * Add the memory block @mem to @buffer at @idx. This function takes ownership
634  * of @mem and thus doesn't increase its refcount.
635  */
636 void
637 gst_buffer_take_memory (GstBuffer * buffer, gint idx, GstMemory * mem)
638 {
639   g_return_if_fail (GST_IS_BUFFER (buffer));
640   g_return_if_fail (gst_buffer_is_writable (buffer));
641   g_return_if_fail (mem != NULL);
642   g_return_if_fail (idx == -1 ||
643       (idx >= 0 && idx <= GST_BUFFER_MEM_LEN (buffer)));
644
645   _memory_add (buffer, idx, mem);
646 }
647
648 static GstMemory *
649 _get_memory (GstBuffer * buffer, guint idx, gboolean write)
650 {
651   GstMemory *mem;
652
653   mem = GST_BUFFER_MEM_PTR (buffer, idx);
654
655   if (G_UNLIKELY (write && !gst_memory_is_writable (mem))) {
656     GstMemory *copy;
657     GST_CAT_LOG (GST_CAT_BUFFER,
658         "making writable copy of memory %p in buffer %p", mem, buffer);
659     /* replace with a writable copy */
660     copy = gst_memory_copy (mem, 0, -1);
661     GST_BUFFER_MEM_PTR (buffer, idx) = copy;
662     gst_memory_unref (mem);
663     mem = copy;
664   }
665   return mem;
666 }
667
668 /**
669  * gst_buffer_peek_memory:
670  * @buffer: a #GstBuffer.
671  * @idx: an index
672  * @flags: #GstMapFlags
673  *
674  * Get the memory block in @buffer at @idx for memory access in @flags.
675  * This function does not return a refcount to the memory block. The memory
676  * block stays valid for as long as the caller has a valid reference to @buffer
677  * and as long as no operations that modify the memory blocks are called, such
678  * as gst_buffer_remove_memory_range(), gst_buffer_take_memory() and gst_buffer_resize().
679  *
680  * @buffer should be writable when @flags contains #GST_MAP_WRITE. If the memory
681  * at @idx is not writable, a new writable copy will be installed in @buffer and
682  * returned.
683  *
684  * Returns: a #GstMemory at @idx.
685  */
686 GstMemory *
687 gst_buffer_peek_memory (GstBuffer * buffer, guint idx, GstMapFlags flags)
688 {
689   GstMemory *mem;
690   gboolean write;
691
692   write = (flags & GST_MAP_WRITE) != 0;
693
694   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
695   g_return_val_if_fail (idx < GST_BUFFER_MEM_LEN (buffer), NULL);
696
697   /* check if we can write when asked for write access */
698   if (G_UNLIKELY (write && !gst_buffer_is_writable (buffer)))
699     goto not_writable;
700
701   mem = _get_memory (buffer, idx, write);
702
703   return mem;
704
705   /* ERRORS */
706 not_writable:
707   {
708     g_return_val_if_fail (gst_buffer_is_writable (buffer), NULL);
709     return NULL;
710   }
711 }
712
713 /**
714  * gst_buffer_remove_memory_range:
715  * @buffer: a #GstBuffer.
716  * @idx: an index
717  * @length: a length
718  *
719  * Remove @len memory blocks in @buffer starting from @idx.
720  *
721  * @length can be -1, in which case all memory starting from @idx is removed.
722  */
723 void
724 gst_buffer_remove_memory_range (GstBuffer * buffer, guint idx, guint length)
725 {
726   guint len, i, end;
727
728   g_return_if_fail (GST_IS_BUFFER (buffer));
729   g_return_if_fail (gst_buffer_is_writable (buffer));
730
731   len = GST_BUFFER_MEM_LEN (buffer);
732   if (length == -1) {
733     g_return_if_fail (idx < len);
734     length = len - idx;
735   }
736
737   end = idx + length;
738   for (i = idx; i < end; i++)
739     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
740
741   if (end != len) {
742     g_memmove (&GST_BUFFER_MEM_PTR (buffer, idx),
743         &GST_BUFFER_MEM_PTR (buffer, end), (len - end) * sizeof (gpointer));
744   }
745   GST_BUFFER_MEM_LEN (buffer) = len - length;
746 }
747
748 /**
749  * gst_buffer_get_sizes:
750  * @buffer: a #GstBuffer.
751  * @offset: a pointer to the offset
752  * @maxsize: a pointer to the maxsize
753  *
754  * Get the total size of all memory blocks in @buffer.
755  *
756  * When not %NULL, @offset will contain the offset of the data in the first
757  * memory block in @buffer and @maxsize will contain the sum of the size
758  * and @offset and the amount of extra padding on the last memory block.
759  * @offset and @maxsize can be used to resize the buffer with
760  * gst_buffer_resize().
761  *
762  * Returns: the total size of the memory in @buffer.
763  */
764 gsize
765 gst_buffer_get_sizes (GstBuffer * buffer, gsize * offset, gsize * maxsize)
766 {
767   guint len;
768   gsize size;
769   GstMemory *mem;
770
771   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
772
773   len = GST_BUFFER_MEM_LEN (buffer);
774
775   if (G_LIKELY (len == 1)) {
776     /* common case */
777     mem = GST_BUFFER_MEM_PTR (buffer, 0);
778     size = gst_memory_get_sizes (mem, offset, maxsize);
779   } else {
780     guint i;
781     gsize extra, offs;
782
783     size = offs = extra = 0;
784     for (i = 0; i < len; i++) {
785       gsize s, o, ms;
786
787       mem = GST_BUFFER_MEM_PTR (buffer, i);
788       s = gst_memory_get_sizes (mem, &o, &ms);
789
790       if (s) {
791         if (size == 0)
792           /* first size, take accumulated data before as the offset */
793           offs = extra + o;
794         /* add sizes */
795         size += s;
796         /* save the amount of data after this block */
797         extra = ms - (o + s);
798       } else {
799         /* empty block, add as extra */
800         extra += ms;
801       }
802     }
803     if (offset)
804       *offset = offs;
805     if (maxsize)
806       *maxsize = offs + size + extra;
807   }
808   return size;
809 }
810
811 /**
812  * gst_buffer_resize:
813  * @buffer: a #GstBuffer.
814  * @offset: the offset adjustement
815  * @size: the new size or -1 to just adjust the offset
816  *
817  * Set the total size of the buffer
818  */
819 void
820 gst_buffer_resize (GstBuffer * buffer, gssize offset, gssize size)
821 {
822   guint len;
823   guint i;
824   gsize bsize, bufsize, bufoffs, bufmax;
825   GstMemory *mem;
826
827   g_return_if_fail (gst_buffer_is_writable (buffer));
828   g_return_if_fail (size >= -1);
829
830   bufsize = gst_buffer_get_sizes (buffer, &bufoffs, &bufmax);
831
832   GST_CAT_LOG (GST_CAT_BUFFER, "trim %p %" G_GSSIZE_FORMAT "-%" G_GSSIZE_FORMAT
833       " size:%" G_GSIZE_FORMAT " offs:%" G_GSIZE_FORMAT " max:%"
834       G_GSIZE_FORMAT, buffer, offset, size, bufsize, bufoffs, bufmax);
835
836   /* we can't go back further than the current offset or past the end of the
837    * buffer */
838   g_return_if_fail ((offset < 0 && bufoffs >= -offset) || (offset >= 0
839           && bufoffs + offset <= bufmax));
840   if (size == -1) {
841     g_return_if_fail (bufsize >= offset);
842     size = bufsize - offset;
843   }
844   g_return_if_fail (bufmax >= bufoffs + offset + size);
845
846   len = GST_BUFFER_MEM_LEN (buffer);
847
848   /* copy and trim */
849   for (i = 0; i < len; i++) {
850     gsize left, noffs;
851
852     mem = GST_BUFFER_MEM_PTR (buffer, i);
853     bsize = gst_memory_get_sizes (mem, NULL, NULL);
854
855     noffs = 0;
856     /* last buffer always gets resized to the remaining size */
857     if (i + 1 == len)
858       left = size;
859     /* shrink buffers before the offset */
860     else if ((gssize) bsize <= offset) {
861       left = 0;
862       noffs = offset - bsize;
863       offset = 0;
864     }
865     /* clip other buffers */
866     else
867       left = MIN (bsize - offset, size);
868
869     if (offset != 0 || left != bsize) {
870       /* we need to clip something */
871       if (gst_memory_is_writable (mem)) {
872         gst_memory_resize (mem, offset, left);
873       } else {
874         GstMemory *tmp;
875
876         if (mem->flags & GST_MEMORY_FLAG_NO_SHARE)
877           tmp = gst_memory_copy (mem, offset, left);
878         else
879           tmp = gst_memory_share (mem, offset, left);
880
881         gst_memory_unref (mem);
882         mem = tmp;
883       }
884     }
885     offset = noffs;
886     size -= left;
887
888     GST_BUFFER_MEM_PTR (buffer, i) = mem;
889   }
890 }
891
892 /**
893  * gst_buffer_map:
894  * @buffer: a #GstBuffer.
895  * @size: (out) (allow-none): a location for the size
896  * @maxsize: (out) (allow-none): a location for the max size
897  * @flags: flags for the mapping
898  *
899  * This function return a pointer to the memory in @buffer. @flags describe the
900  * desired access of the memory. When @flags is #GST_MAP_WRITE, @buffer should
901  * be writable (as returned from gst_buffer_is_writable()).
902  *
903  * @size and @maxsize will contain the current valid number of bytes in the
904  * returned memory area and the total maximum mount of bytes available in the
905  * returned memory area respectively. Both parameters can be %NULL.
906  *
907  * When @buffer is writable but the memory isn't, a writable copy will
908  * automatically be created and returned. The readonly copy of the buffer memory
909  * will then also be replaced with this writable copy.
910  *
911  * When the buffer contains multiple memory blocks, the returned pointer will be
912  * a concatenation of the memory blocks.
913  *
914  * Returns: (transfer none): a pointer to the memory for the buffer.
915  */
916 gpointer
917 gst_buffer_map (GstBuffer * buffer, gsize * size, gsize * maxsize,
918     GstMapFlags flags)
919 {
920   guint len;
921   gpointer data;
922   GstMemory *mem;
923   gboolean write, writable;
924
925   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
926
927   write = (flags & GST_MAP_WRITE) != 0;
928   writable = gst_buffer_is_writable (buffer);
929
930   /* check if we can write when asked for write access */
931   if (G_UNLIKELY (write && !writable))
932     goto not_writable;
933
934   len = GST_BUFFER_MEM_LEN (buffer);
935
936   if (G_UNLIKELY (len == 0)) {
937     /* no memory, return immediately */
938     if (size)
939       *size = 0;
940     if (maxsize)
941       *maxsize = 0;
942     return NULL;
943   }
944
945   if (G_LIKELY (len == 1)) {
946     /* we can take the first one */
947     mem = GST_BUFFER_MEM_PTR (buffer, 0);
948   } else {
949     /* we need to span memory */
950     if (writable) {
951       /* if we can write, we can change the memory with the spanned
952        * memory */
953       mem = _span_memory (buffer, 0, -1, write);
954       _replace_memory (buffer, mem);
955     } else {
956       gsize bsize;
957
958       /* extract all data in new memory, FIXME slow!! */
959       bsize = gst_buffer_get_size (buffer);
960
961       data = g_malloc (bsize);
962       gst_buffer_extract (buffer, 0, data, bsize);
963       if (size)
964         *size = bsize;
965       if (maxsize)
966         *maxsize = bsize;
967       return data;
968     }
969   }
970
971   if (G_UNLIKELY (write && !gst_memory_is_writable (mem))) {
972     GstMemory *copy;
973     /* replace with a writable copy */
974     copy = gst_memory_copy (mem, 0, -1);
975     GST_BUFFER_MEM_PTR (buffer, 0) = copy;
976     gst_memory_unref (mem);
977     mem = copy;
978   }
979
980   data = gst_memory_map (mem, size, maxsize, flags);
981
982   return data;
983
984   /* ERROR */
985 not_writable:
986   {
987     g_return_val_if_fail (gst_buffer_is_writable (buffer), NULL);
988     return NULL;
989   }
990 }
991
992 /**
993  * gst_buffer_unmap:
994  * @buffer: a #GstBuffer.
995  * @data: the previously mapped data
996  * @size: the size of @data, or -1
997  *
998  * Release the memory previously mapped with gst_buffer_map(). Pass -1 to size
999  * if no update is needed.
1000  *
1001  * Returns: #TRUE on success. #FALSE can be returned when the new size is larger
1002  * than the maxsize of the memory.
1003  */
1004 gboolean
1005 gst_buffer_unmap (GstBuffer * buffer, gpointer data, gssize size)
1006 {
1007   gboolean result;
1008   guint len;
1009
1010   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
1011   g_return_val_if_fail (size >= -1, FALSE);
1012
1013   len = GST_BUFFER_MEM_LEN (buffer);
1014
1015   if (G_LIKELY (len == 1)) {
1016     GstMemory *mem = GST_BUFFER_MEM_PTR (buffer, 0);
1017
1018     result = gst_memory_unmap (mem, data, size);
1019   } else {
1020     /* this must have been from read-only access. After _map, the buffer either
1021      * only contains 1 memory block or it allocated memory to join memory
1022      * blocks. It's not allowed to add buffers between _map and _unmap. */
1023     g_free (data);
1024     result = TRUE;
1025   }
1026   return result;
1027 }
1028
1029 /**
1030  * gst_buffer_fill:
1031  * @buffer: a #GstBuffer.
1032  * @offset: the offset to fill
1033  * @src: the source address
1034  * @size: the size to fill
1035  *
1036  * Copy @size bytes from @src to @buffer at @offset.
1037  *
1038  * Returns: The amount of bytes copied. This value can be lower than @size
1039  *    when @buffer did not contain enough data.
1040  */
1041 gsize
1042 gst_buffer_fill (GstBuffer * buffer, gsize offset, gconstpointer src,
1043     gsize size)
1044 {
1045   gsize i, len, left;
1046   const guint8 *ptr = src;
1047
1048   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1049   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1050   g_return_val_if_fail (src != NULL, 0);
1051
1052   len = GST_BUFFER_MEM_LEN (buffer);
1053   left = size;
1054
1055   for (i = 0; i < len && left > 0; i++) {
1056     guint8 *data;
1057     gsize ssize, tocopy;
1058     GstMemory *mem;
1059
1060     mem = _get_memory (buffer, i, TRUE);
1061
1062     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_WRITE);
1063     if (ssize > offset) {
1064       /* we have enough */
1065       tocopy = MIN (ssize - offset, left);
1066       memcpy (data + offset, ptr, tocopy);
1067       left -= tocopy;
1068       ptr += tocopy;
1069       offset = 0;
1070     } else {
1071       /* offset past buffer, skip */
1072       offset -= ssize;
1073     }
1074     gst_memory_unmap (mem, data, ssize);
1075   }
1076   return size - left;
1077 }
1078
1079 /**
1080  * gst_buffer_extract:
1081  * @buffer: a #GstBuffer.
1082  * @offset: the offset to extract
1083  * @dest: the destination address
1084  * @size: the size to extract
1085  *
1086  * Copy @size bytes starting from @offset in @buffer to @dest.
1087  *
1088  * Returns: The amount of bytes extracted. This value can be lower than @size
1089  *    when @buffer did not contain enough data.
1090  */
1091 gsize
1092 gst_buffer_extract (GstBuffer * buffer, gsize offset, gpointer dest, gsize size)
1093 {
1094   gsize i, len, left;
1095   guint8 *ptr = dest;
1096
1097   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1098   g_return_val_if_fail (dest != NULL, 0);
1099
1100   len = GST_BUFFER_MEM_LEN (buffer);
1101   left = size;
1102
1103   for (i = 0; i < len && left > 0; i++) {
1104     guint8 *data;
1105     gsize ssize, tocopy;
1106     GstMemory *mem;
1107
1108     mem = GST_BUFFER_MEM_PTR (buffer, i);
1109
1110     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_READ);
1111     if (ssize > offset) {
1112       /* we have enough */
1113       tocopy = MIN (ssize - offset, left);
1114       memcpy (ptr, data + offset, tocopy);
1115       left -= tocopy;
1116       ptr += tocopy;
1117       offset = 0;
1118     } else {
1119       /* offset past buffer, skip */
1120       offset -= ssize;
1121     }
1122     gst_memory_unmap (mem, data, ssize);
1123   }
1124   return size - left;
1125 }
1126
1127 /**
1128  * gst_buffer_memcmp:
1129  * @buffer: a #GstBuffer.
1130  * @offset: the offset in @buffer
1131  * @mem: the memory to compare
1132  * @size: the size to compare
1133  *
1134  * Compare @size bytes starting from @offset in @buffer with the memory in @mem.
1135  *
1136  * Returns: 0 if the memory is equal.
1137  */
1138 gint
1139 gst_buffer_memcmp (GstBuffer * buffer, gsize offset, gconstpointer mem,
1140     gsize size)
1141 {
1142   gsize i, len;
1143   const guint8 *ptr = mem;
1144   gint res = 0;
1145
1146   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1147   g_return_val_if_fail (mem != NULL, 0);
1148
1149   len = GST_BUFFER_MEM_LEN (buffer);
1150
1151   for (i = 0; i < len && size > 0 && res == 0; i++) {
1152     guint8 *data;
1153     gsize ssize, tocmp;
1154     GstMemory *mem;
1155
1156     mem = GST_BUFFER_MEM_PTR (buffer, i);
1157
1158     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_READ);
1159     if (ssize > offset) {
1160       /* we have enough */
1161       tocmp = MIN (ssize - offset, size);
1162       res = memcmp (ptr, data + offset, tocmp);
1163       size -= tocmp;
1164       ptr += tocmp;
1165       offset = 0;
1166     } else {
1167       /* offset past buffer, skip */
1168       offset -= ssize;
1169     }
1170     gst_memory_unmap (mem, data, ssize);
1171   }
1172   return res;
1173 }
1174
1175 /**
1176  * gst_buffer_memset:
1177  * @buffer: a #GstBuffer.
1178  * @offset: the offset in @buffer
1179  * @val: the value to set
1180  * @size: the size to set
1181  *
1182  * Fill @buf with @size bytes with @val starting from @offset.
1183  *
1184  * Returns: The amount of bytes filled. This value can be lower than @size
1185  *    when @buffer did not contain enough data.
1186  */
1187 gsize
1188 gst_buffer_memset (GstBuffer * buffer, gsize offset, guint8 val, gsize size)
1189 {
1190   gsize i, len, left;
1191
1192   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
1193   g_return_val_if_fail (gst_buffer_is_writable (buffer), 0);
1194
1195   len = GST_BUFFER_MEM_LEN (buffer);
1196   left = size;
1197
1198   for (i = 0; i < len && left > 0; i++) {
1199     guint8 *data;
1200     gsize ssize, toset;
1201     GstMemory *mem;
1202
1203     mem = _get_memory (buffer, i, TRUE);
1204
1205     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_WRITE);
1206     if (ssize > offset) {
1207       /* we have enough */
1208       toset = MIN (ssize - offset, left);
1209       memset (data + offset, val, toset);
1210       left -= toset;
1211       offset = 0;
1212     } else {
1213       /* offset past buffer, skip */
1214       offset -= ssize;
1215     }
1216     gst_memory_unmap (mem, data, ssize);
1217   }
1218   return size - left;
1219 }
1220
1221 /**
1222  * gst_buffer_copy_region:
1223  * @parent: a #GstBuffer.
1224  * @flags: the #GstBufferCopyFlags
1225  * @offset: the offset into parent #GstBuffer at which the new sub-buffer 
1226  *          begins.
1227  * @size: the size of the new #GstBuffer sub-buffer, in bytes.
1228  *
1229  * Creates a sub-buffer from @parent at @offset and @size.
1230  * This sub-buffer uses the actual memory space of the parent buffer.
1231  * This function will copy the offset and timestamp fields when the
1232  * offset is 0. If not, they will be set to #GST_CLOCK_TIME_NONE and 
1233  * #GST_BUFFER_OFFSET_NONE.
1234  * If @offset equals 0 and @size equals the total size of @buffer, the
1235  * duration and offset end fields are also copied. If not they will be set
1236  * to #GST_CLOCK_TIME_NONE and #GST_BUFFER_OFFSET_NONE.
1237  *
1238  * MT safe.
1239  *
1240  * Returns: (transfer full): the new #GstBuffer or NULL if the arguments were
1241  *     invalid.
1242  */
1243 GstBuffer *
1244 gst_buffer_copy_region (GstBuffer * buffer, GstBufferCopyFlags flags,
1245     gsize offset, gsize size)
1246 {
1247   GstBuffer *copy;
1248
1249   g_return_val_if_fail (buffer != NULL, NULL);
1250
1251   /* create the new buffer */
1252   copy = gst_buffer_new ();
1253
1254   GST_CAT_LOG (GST_CAT_BUFFER, "new region copy %p of %p %" G_GSIZE_FORMAT
1255       "-%" G_GSIZE_FORMAT, copy, buffer, offset, size);
1256
1257   gst_buffer_copy_into (copy, buffer, flags, offset, size);
1258
1259   return copy;
1260 }
1261
1262 static gboolean
1263 _gst_buffer_arr_is_span_fast (GstMemory ** mem[], gsize len[], guint n,
1264     gsize * offset, GstMemory ** parent)
1265 {
1266   GstMemory *mcur, *mprv;
1267   gboolean have_offset = FALSE;
1268   guint count, i;
1269
1270   mcur = mprv = NULL;
1271   for (count = 0; count < n; count++) {
1272     gsize offs, clen;
1273     GstMemory **cmem;
1274
1275     cmem = mem[count];
1276     clen = len[count];
1277
1278     for (i = 0; i < clen; i++) {
1279       if (mcur)
1280         mprv = mcur;
1281       mcur = cmem[i];
1282
1283       if (mprv && mcur) {
1284         /* check is memory is contiguous */
1285         if (!gst_memory_is_span (mprv, mcur, &offs))
1286           return FALSE;
1287
1288         if (!have_offset) {
1289           if (offset)
1290             *offset = offs;
1291           if (parent)
1292             *parent = mprv->parent;
1293
1294           have_offset = TRUE;
1295         }
1296       }
1297     }
1298   }
1299   return have_offset;
1300 }
1301
1302 static GstMemory *
1303 _gst_buffer_arr_span (GstMemory ** mem[], gsize len[], guint n, gsize offset,
1304     gsize size, gboolean writable)
1305 {
1306   GstMemory *span, *parent = NULL;
1307   gsize poffset = 0;
1308
1309   if (!writable
1310       && _gst_buffer_arr_is_span_fast (mem, len, n, &poffset, &parent)) {
1311     if (parent->flags & GST_MEMORY_FLAG_NO_SHARE)
1312       span = gst_memory_copy (parent, offset + poffset, size);
1313     else
1314       span = gst_memory_share (parent, offset + poffset, size);
1315   } else {
1316     gsize count, left;
1317     guint8 *dest, *ptr;
1318
1319     span = gst_allocator_alloc (NULL, size, 0);
1320     dest = gst_memory_map (span, NULL, NULL, GST_MAP_WRITE);
1321
1322     ptr = dest;
1323     left = size;
1324
1325     for (count = 0; count < n; count++) {
1326       gsize i, tocopy, clen, ssize;
1327       guint8 *src;
1328       GstMemory **cmem;
1329
1330       cmem = mem[count];
1331       clen = len[count];
1332
1333       for (i = 0; i < clen && left > 0; i++) {
1334         src = gst_memory_map (cmem[i], &ssize, NULL, GST_MAP_READ);
1335         tocopy = MIN (ssize, left);
1336         if (tocopy > offset) {
1337           memcpy (ptr, src + offset, tocopy - offset);
1338           left -= tocopy;
1339           ptr += tocopy;
1340           offset = 0;
1341         } else {
1342           offset -= tocopy;
1343         }
1344         gst_memory_unmap (cmem[i], src, ssize);
1345       }
1346     }
1347     gst_memory_unmap (span, dest, size);
1348   }
1349   return span;
1350 }
1351
1352 /**
1353  * gst_buffer_is_span_fast:
1354  * @buf1: the first #GstBuffer.
1355  * @buf2: the second #GstBuffer.
1356  *
1357  * Determines whether a gst_buffer_span() can be done without copying
1358  * the contents, that is, whether the data areas are contiguous sub-buffers of
1359  * the same buffer.
1360  *
1361  * MT safe.
1362  * Returns: TRUE if the buffers are contiguous,
1363  * FALSE if a copy would be required.
1364  */
1365 gboolean
1366 gst_buffer_is_span_fast (GstBuffer * buf1, GstBuffer * buf2)
1367 {
1368   GstMemory **mem[2];
1369   gsize len[2];
1370
1371   g_return_val_if_fail (GST_IS_BUFFER (buf1), FALSE);
1372   g_return_val_if_fail (GST_IS_BUFFER (buf2), FALSE);
1373   g_return_val_if_fail (buf1->mini_object.refcount > 0, FALSE);
1374   g_return_val_if_fail (buf2->mini_object.refcount > 0, FALSE);
1375
1376   mem[0] = GST_BUFFER_MEM_ARRAY (buf1);
1377   len[0] = GST_BUFFER_MEM_LEN (buf1);
1378   mem[1] = GST_BUFFER_MEM_ARRAY (buf2);
1379   len[1] = GST_BUFFER_MEM_LEN (buf2);
1380
1381   return _gst_buffer_arr_is_span_fast (mem, len, 2, NULL, NULL);
1382 }
1383
1384 /**
1385  * gst_buffer_span:
1386  * @buf1: the first source #GstBuffer to merge.
1387  * @offset: the offset in the first buffer from where the new
1388  * buffer should start.
1389  * @buf2: the second source #GstBuffer to merge.
1390  * @size: the total size of the new buffer.
1391  *
1392  * Creates a new buffer that consists of part of buf1 and buf2.
1393  * Logically, buf1 and buf2 are concatenated into a single larger
1394  * buffer, and a new buffer is created at the given offset inside
1395  * this space, with a given length.
1396  *
1397  * If the two source buffers are children of the same larger buffer,
1398  * and are contiguous, the new buffer will be a child of the shared
1399  * parent, and thus no copying is necessary. you can use
1400  * gst_buffer_is_span_fast() to determine if a memcpy will be needed.
1401  *
1402  * MT safe.
1403  *
1404  * Returns: (transfer full): the new #GstBuffer that spans the two source
1405  *     buffers, or NULL if the arguments are invalid.
1406  */
1407 GstBuffer *
1408 gst_buffer_span (GstBuffer * buf1, gsize offset, GstBuffer * buf2, gsize size)
1409 {
1410   GstBuffer *newbuf;
1411   GstMemory *span;
1412   GstMemory **mem[2];
1413   gsize len[2], len1, len2;
1414
1415   g_return_val_if_fail (GST_IS_BUFFER (buf1), NULL);
1416   g_return_val_if_fail (GST_IS_BUFFER (buf2), NULL);
1417   g_return_val_if_fail (buf1->mini_object.refcount > 0, NULL);
1418   g_return_val_if_fail (buf2->mini_object.refcount > 0, NULL);
1419   len1 = gst_buffer_get_size (buf1);
1420   len2 = gst_buffer_get_size (buf2);
1421   g_return_val_if_fail (len1 + len2 > offset, NULL);
1422   if (size == -1)
1423     size = len1 + len2 - offset;
1424   else
1425     g_return_val_if_fail (size <= len1 + len2 - offset, NULL);
1426
1427   mem[0] = GST_BUFFER_MEM_ARRAY (buf1);
1428   len[0] = GST_BUFFER_MEM_LEN (buf1);
1429   mem[1] = GST_BUFFER_MEM_ARRAY (buf2);
1430   len[1] = GST_BUFFER_MEM_LEN (buf2);
1431
1432   span = _gst_buffer_arr_span (mem, len, 2, offset, size, FALSE);
1433
1434   newbuf = gst_buffer_new ();
1435   _memory_add (newbuf, -1, span);
1436
1437 #if 0
1438   /* if the offset is 0, the new buffer has the same timestamp as buf1 */
1439   if (offset == 0) {
1440     GST_BUFFER_OFFSET (newbuf) = GST_BUFFER_OFFSET (buf1);
1441     GST_BUFFER_PTS (newbuf) = GST_BUFFER_PTS (buf1);
1442     GST_BUFFER_DTS (newbuf) = GST_BUFFER_DTS (buf1);
1443
1444     /* if we completely merged the two buffers (appended), we can
1445      * calculate the duration too. Also make sure we's not messing with
1446      * invalid DURATIONS */
1447     if (buf1->size + buf2->size == len) {
1448       if (GST_BUFFER_DURATION_IS_VALID (buf1) &&
1449           GST_BUFFER_DURATION_IS_VALID (buf2)) {
1450         /* add duration */
1451         GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf1) +
1452             GST_BUFFER_DURATION (buf2);
1453       }
1454       if (GST_BUFFER_OFFSET_END_IS_VALID (buf2)) {
1455         /* add offset_end */
1456         GST_BUFFER_OFFSET_END (newbuf) = GST_BUFFER_OFFSET_END (buf2);
1457       }
1458     }
1459   }
1460 #endif
1461
1462   return newbuf;
1463 }
1464
1465 /**
1466  * gst_buffer_get_meta:
1467  * @buffer: a #GstBuffer
1468  * @info: a #GstMetaInfo
1469  *
1470  * Get the metadata for the api in @info on buffer. When there is no such
1471  * metadata, NULL is returned.
1472  *
1473  * Note that the result metadata might not be of the implementation @info.
1474  *
1475  * Returns: the metadata for the api in @info on @buffer.
1476  */
1477 GstMeta *
1478 gst_buffer_get_meta (GstBuffer * buffer, const GstMetaInfo * info)
1479 {
1480   GstMetaItem *item;
1481   GstMeta *result = NULL;
1482
1483   g_return_val_if_fail (buffer != NULL, NULL);
1484   g_return_val_if_fail (info != NULL, NULL);
1485
1486   /* find GstMeta of the requested API */
1487   for (item = GST_BUFFER_META (buffer); item; item = item->next) {
1488     GstMeta *meta = &item->meta;
1489     if (meta->info->api == info->api) {
1490       result = meta;
1491       break;
1492     }
1493   }
1494   return result;
1495 }
1496
1497 /**
1498  * gst_buffer_add_meta:
1499  * @buffer: a #GstBuffer
1500  * @info: a #GstMetaInfo
1501  * @params: params for @info
1502  *
1503  * Add metadata for @info to @buffer using the parameters in @params.
1504  *
1505  * Returns: (transfer none): the metadata for the api in @info on @buffer.
1506  */
1507 GstMeta *
1508 gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
1509     gpointer params)
1510 {
1511   GstMetaItem *item;
1512   GstMeta *result = NULL;
1513   gsize size;
1514
1515   g_return_val_if_fail (buffer != NULL, NULL);
1516   g_return_val_if_fail (info != NULL, NULL);
1517
1518   /* create a new slice */
1519   size = ITEM_SIZE (info);
1520   item = g_slice_alloc (size);
1521   result = &item->meta;
1522   result->info = info;
1523   result->flags = GST_META_FLAG_NONE;
1524
1525   GST_CAT_DEBUG (GST_CAT_BUFFER,
1526       "alloc metadata %p (%s) of size %" G_GSIZE_FORMAT, result,
1527       g_type_name (info->type), info->size);
1528
1529   /* call the init_func when needed */
1530   if (info->init_func)
1531     if (!info->init_func (result, params, buffer))
1532       goto init_failed;
1533
1534   /* and add to the list of metadata */
1535   item->next = GST_BUFFER_META (buffer);
1536   GST_BUFFER_META (buffer) = item;
1537
1538   return result;
1539
1540 init_failed:
1541   {
1542     g_slice_free1 (size, item);
1543     return NULL;
1544   }
1545 }
1546
1547 /**
1548  * gst_buffer_remove_meta:
1549  * @buffer: a #GstBuffer
1550  * @meta: a #GstMeta
1551  *
1552  * Remove the metadata for @meta on @buffer.
1553  *
1554  * Returns: %TRUE if the metadata existed and was removed, %FALSE if no such
1555  * metadata was on @buffer.
1556  */
1557 gboolean
1558 gst_buffer_remove_meta (GstBuffer * buffer, GstMeta * meta)
1559 {
1560   GstMetaItem *walk, *prev;
1561
1562   g_return_val_if_fail (buffer != NULL, FALSE);
1563   g_return_val_if_fail (meta != NULL, FALSE);
1564
1565   /* find the metadata and delete */
1566   prev = GST_BUFFER_META (buffer);
1567   for (walk = prev; walk; walk = walk->next) {
1568     GstMeta *m = &walk->meta;
1569     if (m == meta) {
1570       const GstMetaInfo *info = meta->info;
1571
1572       /* remove from list */
1573       if (GST_BUFFER_META (buffer) == walk)
1574         GST_BUFFER_META (buffer) = walk->next;
1575       else
1576         prev->next = walk->next;
1577       /* call free_func if any */
1578       if (info->free_func)
1579         info->free_func (m, buffer);
1580
1581       /* and free the slice */
1582       g_slice_free1 (ITEM_SIZE (info), walk);
1583       break;
1584     }
1585     prev = walk;
1586   }
1587   return walk != NULL;
1588 }
1589
1590 /**
1591  * gst_buffer_iterate_meta:
1592  * @buffer: a #GstBuffer
1593  * @state: an opaque state pointer
1594  *
1595  * Retrieve the next #GstMeta after @current. If @state points
1596  * to %NULL, the first metadata is returned.
1597  *
1598  * @state will be updated with an opage state pointer 
1599  *
1600  * Returns: The next #GstMeta or %NULL when there are no more items.
1601  */
1602 GstMeta *
1603 gst_buffer_iterate_meta (GstBuffer * buffer, gpointer * state)
1604 {
1605   GstMetaItem **meta;
1606
1607   g_return_val_if_fail (buffer != NULL, NULL);
1608   g_return_val_if_fail (state != NULL, NULL);
1609
1610   meta = (GstMetaItem **) state;
1611   if (*meta == NULL)
1612     /* state NULL, move to first item */
1613     *meta = GST_BUFFER_META (buffer);
1614   else
1615     /* state !NULL, move to next item in list */
1616     *meta = (*meta)->next;
1617
1618   if (*meta)
1619     return &(*meta)->meta;
1620   else
1621     return NULL;
1622 }
1623
1624 /**
1625  * gst_buffer_foreach_meta:
1626  * @buffer: a #GstBuffer
1627  * @func: (scope call): a #GstBufferForeachMetaFunc to call
1628  * @user_data: (closure): user data passed to @func
1629  *
1630  * Call @func with @user_data for each meta in @buffer.
1631  *
1632  * @func can modify the passed meta pointer or its contents. The return value
1633  * of @func define if this function returns or if the remaining metadata items
1634  * in the buffer should be skipped.
1635  */
1636 void
1637 gst_buffer_foreach_meta (GstBuffer * buffer, GstBufferForeachMetaFunc func,
1638     gpointer user_data)
1639 {
1640   GstMetaItem *walk, *prev, *next;
1641
1642   g_return_if_fail (buffer != NULL);
1643   g_return_if_fail (func != NULL);
1644
1645   /* find the metadata and delete */
1646   prev = GST_BUFFER_META (buffer);
1647   for (walk = prev; walk; walk = next) {
1648     GstMeta *m, *new;
1649     gboolean res;
1650
1651     m = new = &walk->meta;
1652     next = walk->next;
1653
1654     res = func (buffer, &new, user_data);
1655
1656     if (new == NULL) {
1657       const GstMetaInfo *info = m->info;
1658
1659       GST_CAT_DEBUG (GST_CAT_BUFFER, "remove metadata %p (%s)", m,
1660           g_type_name (info->type));
1661
1662       /* remove from list */
1663       if (GST_BUFFER_META (buffer) == walk)
1664         GST_BUFFER_META (buffer) = next;
1665       else
1666         prev->next = next;
1667
1668       /* call free_func if any */
1669       if (info->free_func)
1670         info->free_func (m, buffer);
1671
1672       /* and free the slice */
1673       g_slice_free1 (ITEM_SIZE (info), walk);
1674     }
1675     if (!res)
1676       break;
1677   }
1678 }