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