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