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