buffer: more fixes
[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
27  *
28  * Buffers are the basic unit of data transfer in GStreamer.  The #GstBuffer
29  * type provides all the state necessary to define a region of memory as part
30  * of a stream.  Sub-buffers are also supported, allowing a smaller region of a
31  * buffer to become its own buffer, with mechanisms in place to ensure that
32  * 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 set the size of the
36  * buffer data.  The following example creates a buffer that can hold a given
37  * video frame 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  *   gint size, width, height, bpp;
43  *   ...
44  *   size = width * height * bpp;
45  *   buffer = gst_buffer_new ();
46  *   GST_BUFFER_SIZE (buffer) = size;
47  *   GST_BUFFER_MALLOCDATA (buffer) = g_malloc (size);
48  *   GST_BUFFER_DATA (buffer) = GST_BUFFER_MALLOCDATA (buffer);
49  *   ...
50  *   </programlisting>
51  * </example>
52  *
53  * Alternatively, use gst_buffer_new_and_alloc()
54  * to create a buffer with preallocated data of a given size.
55  *
56  * The data pointed to by the buffer can be retrieved with the GST_BUFFER_DATA()
57  * macro. The size of the data can be found with GST_BUFFER_SIZE(). For buffers
58  * of size 0, the data pointer is undefined (usually NULL) and should never be used.
59  *
60  * If an element knows what pad you will push the buffer out on, it should use
61  * gst_pad_alloc_buffer() instead to create a buffer.  This allows downstream
62  * elements to provide special buffers to write in, like hardware buffers.
63  *
64  * A buffer has a pointer to a #GstCaps describing the media type of the data
65  * in the buffer. Attach caps to the buffer with gst_buffer_set_caps(); this
66  * is typically done before pushing out a buffer using gst_pad_push() so that
67  * the downstream element knows the type of the buffer.
68  *
69  * A buffer will usually have a timestamp, and a duration, but neither of these
70  * are guaranteed (they may be set to #GST_CLOCK_TIME_NONE). Whenever a
71  * meaningful value can be given for these, they should be set. The timestamp
72  * and duration are measured in nanoseconds (they are #GstClockTime values).
73  *
74  * A buffer can also have one or both of a start and an end offset. These are
75  * media-type specific. For video buffers, the start offset will generally be
76  * the frame number. For audio buffers, it will be the number of samples
77  * produced so far. For compressed data, it could be the byte offset in a
78  * source or destination file. Likewise, the end offset will be the offset of
79  * the end of the buffer. These can only be meaningfully interpreted if you
80  * know the media type of the buffer (the #GstCaps set on it). Either or both
81  * can be set to #GST_BUFFER_OFFSET_NONE.
82  *
83  * gst_buffer_ref() is used to increase the refcount of a buffer. This must be
84  * done when you want to keep a handle to the buffer after pushing it to the
85  * next element.
86  *
87  * To efficiently create a smaller buffer out of an existing one, you can
88  * use gst_buffer_create_sub().
89  *
90  * If a plug-in wants to modify the buffer data in-place, it should first obtain
91  * a buffer that is safe to modify by using gst_buffer_make_writable().  This
92  * function is optimized so that a copy will only be made when it is necessary.
93  *
94  * A plugin that only wishes to modify the metadata of a buffer, such as the
95  * offset, timestamp or caps, should use gst_buffer_make_metadata_writable(),
96  * which will create a subbuffer of the original buffer to ensure the caller
97  * has sole ownership, and not copy the buffer data.
98  *
99  * Several flags of the buffer can be set and unset with the
100  * GST_BUFFER_FLAG_SET() and GST_BUFFER_FLAG_UNSET() macros. Use
101  * GST_BUFFER_FLAG_IS_SET() to test if a certain #GstBufferFlag is set.
102  *
103  * Buffers can be efficiently merged into a larger buffer with
104  * gst_buffer_merge() and gst_buffer_span() if the gst_buffer_is_span_fast()
105  * function returns TRUE.
106  *
107  * An element should either unref the buffer or push it out on a src pad
108  * using gst_pad_push() (see #GstPad).
109  *
110  * Buffers are usually freed by unreffing them with gst_buffer_unref(). When
111  * the refcount drops to 0, any data pointed to by GST_BUFFER_MALLOCDATA() will
112  * also be freed.
113  *
114  * Last reviewed on August 11th, 2006 (0.10.10)
115  */
116 #include "gst_private.h"
117
118 #ifdef HAVE_UNISTD_H
119 #include <unistd.h>
120 #endif
121 #ifdef HAVE_STDLIB_H
122 #include <stdlib.h>
123 #endif
124
125 #include "gstbuffer.h"
126 #include "gstbufferpool.h"
127 #include "gstinfo.h"
128 #include "gstutils.h"
129 #include "gstminiobject.h"
130 #include "gstversion.h"
131
132 GType _gst_buffer_type = 0;
133
134 typedef struct _GstMetaItem GstMetaItem;
135
136 struct _GstMetaItem
137 {
138   GstMetaItem *next;
139   GstMeta meta;
140 };
141
142 #define ITEM_SIZE(info) ((info)->size + sizeof (GstMetaItem))
143
144 /* buffer alignment in bytes
145  * an alignment of 8 would be the same as malloc() guarantees
146  */
147 #ifdef HAVE_POSIX_MEMALIGN
148 #if defined(BUFFER_ALIGNMENT_MALLOC)
149 static size_t _gst_buffer_data_alignment = 8;
150 #elif defined(BUFFER_ALIGNMENT_PAGESIZE)
151 static size_t _gst_buffer_data_alignment = 0;
152 #elif defined(BUFFER_ALIGNMENT)
153 static size_t _gst_buffer_data_alignment = BUFFER_ALIGNMENT;
154 #else
155 #error "No buffer alignment configured"
156 #endif
157 #endif /* HAVE_POSIX_MEMALIGN */
158
159 void
160 _gst_buffer_initialize (void)
161 {
162   if (G_LIKELY (_gst_buffer_type == 0)) {
163     _gst_buffer_type = gst_mini_object_register ("GstBuffer");
164 #ifdef HAVE_GETPAGESIZE
165 #ifdef BUFFER_ALIGNMENT_PAGESIZE
166     _gst_buffer_data_alignment = getpagesize ();
167 #endif
168 #endif
169   }
170 }
171
172 /**
173  * gst_buffer_copy_into:
174  * @dest: a destination #GstBuffer
175  * @src: a source #GstBuffer
176  * @flags: flags indicating what metadata fields should be copied.
177  * @offset: offset to copy from
178  * @size: total size to copy
179  *
180  * Copies the information from @src into @dest.
181  *
182  * @flags indicate which fields will be copied.
183  */
184 void
185 gst_buffer_copy_into (GstBuffer * dest, GstBuffer * src,
186     GstBufferCopyFlags flags, gsize offset, gsize size)
187 {
188   GstMetaItem *walk;
189   gsize bufsize;
190
191   g_return_if_fail (dest != NULL);
192   g_return_if_fail (src != NULL);
193
194   /* nothing to copy if the buffers are the same */
195   if (G_UNLIKELY (dest == src))
196     return;
197
198   bufsize = gst_buffer_get_size (src);
199   if (size == -1)
200     size = bufsize - offset;
201   g_return_if_fail (bufsize >= offset + size);
202
203 #if GST_VERSION_NANO == 1
204   /* we enable this extra debugging in git versions only for now */
205   g_warn_if_fail (gst_buffer_is_writable (dest));
206 #endif
207
208   GST_CAT_LOG (GST_CAT_BUFFER, "copy %p to %p", src, dest);
209
210   if (flags & GST_BUFFER_COPY_FLAGS) {
211     guint mask;
212
213     /* copy relevant flags */
214     mask = GST_BUFFER_FLAG_PREROLL | GST_BUFFER_FLAG_IN_CAPS |
215         GST_BUFFER_FLAG_DELTA_UNIT | GST_BUFFER_FLAG_DISCONT |
216         GST_BUFFER_FLAG_GAP | GST_BUFFER_FLAG_MEDIA1 |
217         GST_BUFFER_FLAG_MEDIA2 | GST_BUFFER_FLAG_MEDIA3;
218     GST_MINI_OBJECT_FLAGS (dest) |= GST_MINI_OBJECT_FLAGS (src) & mask;
219   }
220
221   if (flags & GST_BUFFER_COPY_TIMESTAMPS) {
222     if (offset == 0) {
223       GST_BUFFER_TIMESTAMP (dest) = GST_BUFFER_TIMESTAMP (src);
224       GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
225       if (size == gst_buffer_get_size (src)) {
226         GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
227         GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
228       }
229     } else {
230       GST_BUFFER_TIMESTAMP (dest) = GST_CLOCK_TIME_NONE;
231       GST_BUFFER_DURATION (dest) = GST_CLOCK_TIME_NONE;
232       GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET_NONE;
233       GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_NONE;
234     }
235   }
236
237   if (flags & GST_BUFFER_COPY_CAPS) {
238     gst_caps_replace (&GST_BUFFER_CAPS (dest), GST_BUFFER_CAPS (src));
239   }
240
241   if (flags & GST_BUFFER_COPY_MEMORY) {
242     GPtrArray *sarr = (GPtrArray *) src->memory;
243     GPtrArray *darr = (GPtrArray *) dest->memory;
244     guint i, len;
245
246     len = sarr->len;
247
248     for (i = 0; i < len; i++) {
249       GstMemory *mem, *dmem;
250       gsize msize;
251
252       mem = g_ptr_array_index (sarr, i);
253       msize = gst_memory_get_sizes (mem, NULL);
254
255       if (i + 1 == len) {
256         /* last chunk */
257         dmem = gst_memory_sub (mem, offset, size);
258       } else if (offset) {
259         if (msize > offset) {
260           dmem = gst_memory_sub (mem, offset, msize - offset);
261           offset = 0;
262         } else {
263           offset -= msize;
264           dmem = NULL;
265         }
266       } else
267         dmem = gst_memory_ref (mem);
268
269       if (dmem)
270         g_ptr_array_add (darr, dmem);
271     }
272   }
273
274   for (walk = src->priv; walk; walk = walk->next) {
275     GstMeta *meta = &walk->meta;
276     const GstMetaInfo *info = meta->info;
277
278     if (info->copy_func)
279       info->copy_func (dest, meta, (GstBuffer *) src, offset, size);
280   }
281 }
282
283 static GstBuffer *
284 _gst_buffer_copy (GstBuffer * buffer)
285 {
286   GstBuffer *copy;
287
288   g_return_val_if_fail (buffer != NULL, NULL);
289
290   /* create a fresh new buffer */
291   copy = gst_buffer_new ();
292
293   /* we simply copy everything from our parent */
294   gst_buffer_copy_into (copy, buffer, GST_BUFFER_COPY_ALL, 0, -1);
295
296   return copy;
297 }
298
299 /* the default dispose function revives the buffer and returns it to the
300  * pool when there is a pool */
301 static void
302 _gst_buffer_dispose (GstBuffer * buffer)
303 {
304   GstBufferPool *pool;
305
306   if ((pool = buffer->pool) != NULL) {
307     /* keep the buffer alive */
308     gst_buffer_ref (buffer);
309     /* return the buffer to the pool */
310     GST_CAT_LOG (GST_CAT_BUFFER, "release %p to pool %p", buffer, pool);
311     gst_buffer_pool_release_buffer (pool, buffer);
312   }
313 }
314
315 static void
316 _gst_buffer_free (GstBuffer * buffer)
317 {
318   GstMetaItem *walk, *next;
319
320   g_return_if_fail (buffer != NULL);
321
322   GST_CAT_LOG (GST_CAT_BUFFER, "finalize %p", buffer);
323
324   gst_caps_replace (&GST_BUFFER_CAPS (buffer), NULL);
325
326   /* free metadata */
327   for (walk = buffer->priv; walk; walk = next) {
328     GstMeta *meta = &walk->meta;
329     const GstMetaInfo *info = meta->info;
330
331     /* call free_func if any */
332     if (info->free_func)
333       info->free_func (meta, buffer);
334
335     next = walk->next;
336     /* and free the slice */
337     g_slice_free1 (ITEM_SIZE (info), walk);
338   }
339
340   /* free our data, unrefs the memory too */
341   g_ptr_array_free (buffer->memory, TRUE);
342
343   g_slice_free1 (GST_MINI_OBJECT_SIZE (buffer), buffer);
344 }
345
346 static void
347 gst_buffer_init (GstBuffer * buffer, gsize size)
348 {
349   gst_mini_object_init (GST_MINI_OBJECT_CAST (buffer), _gst_buffer_type, size);
350
351   buffer->mini_object.copy = (GstMiniObjectCopyFunction) _gst_buffer_copy;
352   buffer->mini_object.dispose =
353       (GstMiniObjectDisposeFunction) _gst_buffer_dispose;
354   buffer->mini_object.free = (GstMiniObjectFreeFunction) _gst_buffer_free;
355
356   GST_BUFFER_TIMESTAMP (buffer) = GST_CLOCK_TIME_NONE;
357   GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
358   GST_BUFFER_OFFSET (buffer) = GST_BUFFER_OFFSET_NONE;
359   GST_BUFFER_OFFSET_END (buffer) = GST_BUFFER_OFFSET_NONE;
360
361   /* FIXME, do more efficient with array in the buffer memory itself */
362   buffer->memory =
363       g_ptr_array_new_with_free_func ((GDestroyNotify) gst_memory_unref);
364 }
365
366 /**
367  * gst_buffer_new:
368  *
369  * Creates a newly allocated buffer without any data.
370  *
371  * MT safe.
372  *
373  * Returns: (transfer full): the new #GstBuffer.
374  */
375 GstBuffer *
376 gst_buffer_new (void)
377 {
378   GstBuffer *newbuf;
379
380   newbuf = g_slice_new0 (GstBuffer);
381   GST_CAT_LOG (GST_CAT_BUFFER, "new %p", newbuf);
382
383   gst_buffer_init (newbuf, sizeof (GstBuffer));
384
385   return newbuf;
386 }
387
388 /**
389  * gst_buffer_new_and_alloc:
390  * @size: the size in bytes of the new buffer's data.
391  *
392  * Creates a newly allocated buffer with data of the given size.
393  * The buffer memory is not cleared. If the requested amount of
394  * memory can't be allocated, the program will abort. Use
395  * gst_buffer_try_new_and_alloc() if you want to handle this case
396  * gracefully or have gotten the size to allocate from an untrusted
397  * source such as a media stream.
398  *
399  * Note that when @size == 0, the buffer data pointer will be NULL.
400  *
401  * MT safe.
402  *
403  * Returns: (transfer full): the new #GstBuffer.
404  */
405 GstBuffer *
406 gst_buffer_new_and_alloc (guint size)
407 {
408   GstBuffer *newbuf;
409
410   newbuf = gst_buffer_new ();
411
412   if (size > 0) {
413     gst_buffer_take_memory (newbuf, gst_memory_new_alloc (size,
414             _gst_buffer_data_alignment));
415   }
416
417   GST_CAT_LOG (GST_CAT_BUFFER, "new %p of size %d", newbuf, size);
418
419   return newbuf;
420 }
421
422 /**
423  * gst_buffer_try_new_and_alloc:
424  * @size: the size in bytes of the new buffer's data.
425  *
426  * Tries to create a newly allocated buffer with data of the given size. If
427  * the requested amount of memory can't be allocated, NULL will be returned.
428  * The buffer memory is not cleared.
429  *
430  * Note that when @size == 0, the buffer will not have memory associated with it.
431  *
432  * MT safe.
433  *
434  * Returns: (transfer full): a new #GstBuffer, or NULL if the memory couldn't
435  *     be allocated.
436  */
437 GstBuffer *
438 gst_buffer_try_new_and_alloc (guint size)
439 {
440   GstBuffer *newbuf;
441   GstMemory *mem;
442
443   if (size > 0) {
444     mem = gst_memory_new_alloc (size, _gst_buffer_data_alignment);
445     if (G_UNLIKELY (mem == NULL))
446       goto no_memory;
447   } else {
448     mem = NULL;
449   }
450
451   newbuf = gst_buffer_new ();
452
453   if (mem != NULL)
454     gst_buffer_take_memory (newbuf, mem);
455
456   GST_CAT_LOG (GST_CAT_BUFFER, "new %p of size %d", newbuf, size);
457
458   return newbuf;
459
460   /* ERRORS */
461 no_memory:
462   {
463     GST_CAT_WARNING (GST_CAT_BUFFER, "failed to allocate %d bytes", size);
464     return NULL;
465   }
466 }
467
468 /**
469  * gst_buffer_n_memory:
470  * @buffer: a #GstBuffer.
471  *
472  * Get the amount of memory blocks that this buffer has.
473  *
474  * Returns: (transfer full): the amount of memory block in this buffer.
475  */
476 guint
477 gst_buffer_n_memory (GstBuffer * buffer)
478 {
479   GPtrArray *arr;
480
481   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
482
483   arr = (GPtrArray *) buffer->memory;
484
485   return arr->len;
486 }
487
488 /**
489  * gst_buffer_take_memory:
490  * @buffer: a #GstBuffer.
491  * @mem: a #GstMemory.
492  *
493  * Add the memory block @mem to @buffer. This function takes ownership of @mem
494  * and thus doesn't increase its refcount.
495  */
496 void
497 gst_buffer_take_memory (GstBuffer * buffer, GstMemory * mem)
498 {
499   GPtrArray *arr;
500
501   g_return_if_fail (GST_IS_BUFFER (buffer));
502   g_return_if_fail (gst_buffer_is_writable (buffer));
503   g_return_if_fail (mem != NULL);
504
505   arr = (GPtrArray *) buffer->memory;
506   g_ptr_array_add (arr, mem);
507 }
508
509 /**
510  * gst_buffer_peek_memory:
511  * @buffer: a #GstBuffer.
512  * @idx: an index
513  *
514  * Get the memory block in @buffer at @idx. This function does not return a
515  * refcount to the memory block. The memory block stays valid for as long as the
516  * caller has a valid reference to @buffer.
517  *
518  * Returns: a #GstMemory at @idx.
519  */
520 GstMemory *
521 gst_buffer_peek_memory (GstBuffer * buffer, guint idx)
522 {
523   GstMemory *mem;
524   GPtrArray *arr;
525
526   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
527   arr = (GPtrArray *) buffer->memory;
528   g_return_val_if_fail (idx < arr->len, NULL);
529
530   mem = g_ptr_array_index (arr, idx);
531
532   return mem;
533 }
534
535 /**
536  * gst_buffer_remove_memory:
537  * @buffer: a #GstBuffer.
538  * @idx: an index
539  *
540  * Remove the memory block in @buffer at @idx.
541  */
542 void
543 gst_buffer_remove_memory (GstBuffer * buffer, guint idx)
544 {
545   GPtrArray *arr;
546
547   g_return_if_fail (GST_IS_BUFFER (buffer));
548   g_return_if_fail (gst_buffer_is_writable (buffer));
549   arr = (GPtrArray *) buffer->memory;
550   g_return_if_fail (idx < arr->len);
551
552   g_ptr_array_remove_index (arr, idx);
553 }
554
555 /**
556  * gst_buffer_get_size:
557  * @buffer: a #GstBuffer.
558  *
559  * Get the total size of all memory blocks in @buffer.
560  *
561  * Returns: the total size of the memory in @buffer.
562  */
563 gsize
564 gst_buffer_get_size (GstBuffer * buffer)
565 {
566   GPtrArray *arr = (GPtrArray *) buffer->memory;
567   guint i, size, len;
568
569   g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
570
571   len = arr->len;
572
573   size = 0;
574   for (i = 0; i < len; i++) {
575     size += gst_memory_get_sizes (g_ptr_array_index (arr, i), NULL);
576   }
577   return size;
578 }
579
580 /**
581  * gst_buffer_set_size:
582  * @buffer: a #GstBuffer.
583  * @size: the new size
584  *
585  * Set the total size of the buffer
586  */
587 void
588 gst_buffer_set_size (GstBuffer * buffer, gsize size)
589 {
590   /* FIXME */
591   g_warning ("gst_buffer_set_size not imlpemented");
592 }
593
594 /**
595  * gst_buffer_map:
596  * @buffer: a #GstBuffer.
597  * @size: a location for the size
598  * @maxsize: a location for the max size
599  * @flags: flags for the mapping
600  *
601  * This function return a pointer to the memory in @buffer. @flags describe the
602  * desired access of the memory. When @flags is #GST_MAP_WRITE, @buffer should
603  * be writable (as returned from gst_buffer_is_writable()).
604  *
605  * @size and @maxsize will contain the current valid number of bytes in the
606  * returned memory area and the total maximum mount of bytes available in the
607  * returned memory area respectively.
608  *
609  * When @buffer is writable but the memory isn't, a writable copy will
610  * automatically be created and returned. The readonly copy of the buffer memory
611  * will then also be replaced with this writable copy.
612  *
613  * When the buffer contains multiple memory blocks, the returned pointer will be
614  * a concatenation of the memory blocks.
615  *
616  * Returns: a pointer to the memory for the buffer.
617  */
618 gpointer
619 gst_buffer_map (GstBuffer * buffer, gsize * size, gsize * maxsize,
620     GstMapFlags flags)
621 {
622   GPtrArray *arr;
623   guint len;
624   gpointer data;
625
626   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
627
628   arr = (GPtrArray *) buffer->memory;
629   len = arr->len;
630
631   if (G_UNLIKELY ((flags & GST_MAP_WRITE) && !gst_buffer_is_writable (buffer)))
632     goto not_writable;
633
634   if (G_LIKELY (len == 1)) {
635     GstMemory *mem;
636
637     mem = g_ptr_array_index (arr, 0);
638
639     if (flags & GST_MAP_WRITE) {
640       if (G_UNLIKELY (!GST_MEMORY_IS_WRITABLE (mem))) {
641         GstMemory *copy;
642
643         /* replace with a writable copy */
644         copy = gst_memory_copy (mem, 0, gst_memory_get_sizes (mem, NULL));
645         g_ptr_array_index (arr, 0) = copy;
646         gst_memory_unref (mem);
647         mem = copy;
648       }
649     }
650
651     data = gst_memory_map (mem, size, maxsize, flags);
652   } else {
653     data = NULL;
654   }
655   return data;
656
657   /* ERROR */
658 not_writable:
659   {
660     g_return_val_if_fail (gst_buffer_is_writable (buffer), NULL);
661     return NULL;
662   }
663 }
664
665 /**
666  * gst_buffer_unmap:
667  * @buffer: a #GstBuffer.
668  * @data: the previously mapped data
669  * @size: the size of @data
670  *
671  * Release the memory previously mapped with gst_buffer_map().
672  *
673  * Returns: #TRUE on success. #FALSE can be returned when the new size is larger
674  * than the maxsize of the memory.
675  */
676 gboolean
677 gst_buffer_unmap (GstBuffer * buffer, gpointer data, gsize size)
678 {
679   GPtrArray *arr;
680   gboolean result;
681   guint len;
682
683   g_return_val_if_fail (GST_IS_BUFFER (buffer), FALSE);
684
685   arr = (GPtrArray *) buffer->memory;
686   len = arr->len;
687
688   if (G_LIKELY (len == 1)) {
689     GstMemory *mem = g_ptr_array_index (arr, 0);
690
691     result = gst_memory_unmap (mem, data, size);
692   } else {
693     result = FALSE;
694   }
695   return result;
696 }
697
698 /**
699  * gst_buffer_fill:
700  * @buffer: a #GstBuffer.
701  * @offset: the offset to fill
702  * @src: the source address
703  * @size: the size to fill
704  *
705  * Copy @size bytes fro @src to @buffer at @offset.
706  */
707 void
708 gst_buffer_fill (GstBuffer * buffer, gsize offset, gconstpointer src,
709     gsize size)
710 {
711   GPtrArray *arr = (GPtrArray *) buffer->memory;
712   gsize i, len;
713   const guint8 *ptr = src;
714
715   len = arr->len;
716
717   for (i = 0; i < len && size > 0; i++) {
718     guint8 *data;
719     gsize ssize, tocopy;
720     GstMemory *mem;
721
722     mem = g_ptr_array_index (arr, i);
723
724     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_WRITE);
725     if (ssize > offset) {
726       /* we have enough */
727       tocopy = MIN (ssize - offset, size);
728       memcpy (data + offset, ptr, tocopy);
729       size -= tocopy;
730       ptr += tocopy;
731       offset = 0;
732     } else {
733       /* offset past buffer, skip */
734       offset -= ssize;
735     }
736     gst_memory_unmap (mem, data, ssize);
737   }
738 }
739
740 /**
741  * gst_buffer_extract:
742  * @buffer: a #GstBuffer.
743  * @offset: the offset to extract
744  * @dest: the destination address
745  * @size: the size to extract
746  *
747  * Copy @size bytes starting from @offset in @buffer to @dest.
748  */
749 void
750 gst_buffer_extract (GstBuffer * buffer, gsize offset, gpointer dest, gsize size)
751 {
752   GPtrArray *arr = (GPtrArray *) buffer->memory;
753   gsize i, len;
754   guint8 *ptr = dest;
755
756   len = arr->len;
757
758   for (i = 0; i < len && size > 0; i++) {
759     guint8 *data;
760     gsize ssize, tocopy;
761     GstMemory *mem;
762
763     mem = g_ptr_array_index (arr, i);
764
765     data = gst_memory_map (mem, &ssize, NULL, GST_MAP_READ);
766     if (ssize > offset) {
767       /* we have enough */
768       tocopy = MIN (ssize - offset, size);
769       memcpy (ptr, data + offset, tocopy);
770       size -= tocopy;
771       ptr += tocopy;
772       offset = 0;
773     } else {
774       /* offset past buffer, skip */
775       offset -= ssize;
776     }
777     gst_memory_unmap (mem, data, ssize);
778   }
779 }
780
781 /**
782  * gst_buffer_get_caps:
783  * @buffer: a #GstBuffer.
784  *
785  * Gets the media type of the buffer. This can be NULL if there
786  * is no media type attached to this buffer.
787  *
788  * Returns: (transfer full): a reference to the #GstCaps. unref after usage.
789  * Returns NULL if there were no caps on this buffer.
790  */
791 /* this is not made atomic because if the buffer were reffed from multiple
792  * threads, it would have a refcount > 2 and thus be immutable.
793  */
794 GstCaps *
795 gst_buffer_get_caps (GstBuffer * buffer)
796 {
797   GstCaps *ret;
798
799   g_return_val_if_fail (buffer != NULL, NULL);
800
801   ret = GST_BUFFER_CAPS (buffer);
802
803   if (ret)
804     gst_caps_ref (ret);
805
806   return ret;
807 }
808
809 /**
810  * gst_buffer_set_caps:
811  * @buffer: a #GstBuffer.
812  * @caps: (transfer none): a #GstCaps.
813  *
814  * Sets the media type on the buffer. The refcount of the caps will
815  * be increased and any previous caps on the buffer will be
816  * unreffed.
817  */
818 /* this is not made atomic because if the buffer were reffed from multiple
819  * threads, it would have a refcount > 2 and thus be immutable.
820  */
821 void
822 gst_buffer_set_caps (GstBuffer * buffer, GstCaps * caps)
823 {
824   g_return_if_fail (buffer != NULL);
825   g_return_if_fail (caps == NULL || GST_CAPS_IS_SIMPLE (caps));
826
827 #if GST_VERSION_NANO == 1
828   /* we enable this extra debugging in git versions only for now */
829   g_warn_if_fail (gst_buffer_is_writable (buffer));
830   /* FIXME: would be nice to also check if caps are fixed here, but expensive */
831 #endif
832
833   gst_caps_replace (&GST_BUFFER_CAPS (buffer), caps);
834 }
835
836 /**
837  * gst_buffer_create_sub:
838  * @parent: a #GstBuffer.
839  * @offset: the offset into parent #GstBuffer at which the new sub-buffer 
840  *          begins.
841  * @size: the size of the new #GstBuffer sub-buffer, in bytes.
842  *
843  * Creates a sub-buffer from @parent at @offset and @size.
844  * This sub-buffer uses the actual memory space of the parent buffer.
845  * This function will copy the offset and timestamp fields when the
846  * offset is 0. If not, they will be set to #GST_CLOCK_TIME_NONE and 
847  * #GST_BUFFER_OFFSET_NONE.
848  * If @offset equals 0 and @size equals the total size of @buffer, the
849  * duration and offset end fields are also copied. If not they will be set
850  * to #GST_CLOCK_TIME_NONE and #GST_BUFFER_OFFSET_NONE.
851  *
852  * MT safe.
853  *
854  * Returns: (transfer full): the new #GstBuffer or NULL if the arguments were
855  *     invalid.
856  */
857 GstBuffer *
858 gst_buffer_create_sub (GstBuffer * buffer, gsize offset, gsize size)
859 {
860   GstBuffer *subbuffer;
861   gsize bufsize;
862
863   g_return_val_if_fail (buffer != NULL, NULL);
864   g_return_val_if_fail (buffer->mini_object.refcount > 0, NULL);
865
866   bufsize = gst_buffer_get_size (buffer);
867   g_return_val_if_fail (bufsize >= offset + size, NULL);
868
869   /* create the new buffer */
870   subbuffer = gst_buffer_new ();
871
872   GST_CAT_LOG (GST_CAT_BUFFER, "new subbuffer %p of %p", subbuffer, buffer);
873
874   gst_buffer_copy_into (subbuffer, buffer, GST_BUFFER_COPY_ALL, offset, size);
875
876   return subbuffer;
877 }
878
879 /**
880  * gst_buffer_is_span_fast:
881  * @buf1: the first #GstBuffer.
882  * @buf2: the second #GstBuffer.
883  *
884  * Determines whether a gst_buffer_span() can be done without copying
885  * the contents, that is, whether the data areas are contiguous sub-buffers of
886  * the same buffer.
887  *
888  * MT safe.
889  * Returns: TRUE if the buffers are contiguous,
890  * FALSE if a copy would be required.
891  */
892 gboolean
893 gst_buffer_is_span_fast (GstBuffer * buf1, GstBuffer * buf2)
894 {
895   GPtrArray *arr1, *arr2;
896
897   g_return_val_if_fail (buf1 != NULL && buf2 != NULL, FALSE);
898   g_return_val_if_fail (buf1->mini_object.refcount > 0, FALSE);
899   g_return_val_if_fail (buf2->mini_object.refcount > 0, FALSE);
900
901   arr1 = (GPtrArray *) buf1->memory;
902   arr2 = (GPtrArray *) buf2->memory;
903
904   return gst_memory_is_span ((GstMemory **) arr1->pdata, arr1->len,
905       (GstMemory **) arr2->pdata, arr2->len, NULL, NULL);
906 }
907
908 /**
909  * gst_buffer_span:
910  * @buf1: the first source #GstBuffer to merge.
911  * @offset: the offset in the first buffer from where the new
912  * buffer should start.
913  * @buf2: the second source #GstBuffer to merge.
914  * @len: the total length of the new buffer.
915  *
916  * Creates a new buffer that consists of part of buf1 and buf2.
917  * Logically, buf1 and buf2 are concatenated into a single larger
918  * buffer, and a new buffer is created at the given offset inside
919  * this space, with a given length.
920  *
921  * If the two source buffers are children of the same larger buffer,
922  * and are contiguous, the new buffer will be a child of the shared
923  * parent, and thus no copying is necessary. you can use
924  * gst_buffer_is_span_fast() to determine if a memcpy will be needed.
925  *
926  * MT safe.
927  *
928  * Returns: (transfer full): the new #GstBuffer that spans the two source
929  *     buffers, or NULL if the arguments are invalid.
930  */
931 GstBuffer *
932 gst_buffer_span (GstBuffer * buf1, gsize offset, GstBuffer * buf2, gsize len)
933 {
934   GstBuffer *newbuf;
935   GPtrArray *arr1, *arr2;
936   GstMemory *mem;
937
938   g_return_val_if_fail (buf1 != NULL && buf2 != NULL, NULL);
939   g_return_val_if_fail (buf1->mini_object.refcount > 0, NULL);
940   g_return_val_if_fail (buf2->mini_object.refcount > 0, NULL);
941   g_return_val_if_fail (len > 0, NULL);
942   g_return_val_if_fail (len <= gst_buffer_get_size (buf1) +
943       gst_buffer_get_size (buf2) - offset, NULL);
944
945   newbuf = gst_buffer_new ();
946
947   arr1 = (GPtrArray *) buf1->memory;
948   arr2 = (GPtrArray *) buf2->memory;
949
950   mem = gst_memory_span ((GstMemory **) arr1->pdata, arr1->len, offset,
951       (GstMemory **) arr2->pdata, arr2->len, len);
952   gst_buffer_take_memory (newbuf, mem);
953
954 #if 0
955   /* if the offset is 0, the new buffer has the same timestamp as buf1 */
956   if (offset == 0) {
957     GST_BUFFER_OFFSET (newbuf) = GST_BUFFER_OFFSET (buf1);
958     GST_BUFFER_TIMESTAMP (newbuf) = GST_BUFFER_TIMESTAMP (buf1);
959
960     /* if we completely merged the two buffers (appended), we can
961      * calculate the duration too. Also make sure we's not messing with
962      * invalid DURATIONS */
963     if (buf1->size + buf2->size == len) {
964       if (GST_BUFFER_DURATION_IS_VALID (buf1) &&
965           GST_BUFFER_DURATION_IS_VALID (buf2)) {
966         /* add duration */
967         GST_BUFFER_DURATION (newbuf) = GST_BUFFER_DURATION (buf1) +
968             GST_BUFFER_DURATION (buf2);
969       }
970       if (GST_BUFFER_OFFSET_END_IS_VALID (buf2)) {
971         /* add offset_end */
972         GST_BUFFER_OFFSET_END (newbuf) = GST_BUFFER_OFFSET_END (buf2);
973       }
974     }
975   }
976 #endif
977
978   return newbuf;
979 }
980
981 /**
982  * gst_buffer_get_meta:
983  * @buffer: a #GstBuffer
984  * @info: a #GstMetaInfo
985  *
986  * Get the metadata for the api in @info on buffer. When there is no such
987  * metadata, NULL is returned.
988  *
989  * Note that the result metadata might not be of the implementation @info.
990  *
991  * Returns: the metadata for the api in @info on @buffer.
992  */
993 GstMeta *
994 gst_buffer_get_meta (GstBuffer * buffer, const GstMetaInfo * info)
995 {
996   GstMetaItem *item;
997   GstMeta *result = NULL;
998
999   g_return_val_if_fail (buffer != NULL, NULL);
1000   g_return_val_if_fail (info != NULL, NULL);
1001
1002   /* find GstMeta of the requested API */
1003   for (item = buffer->priv; item; item = item->next) {
1004     GstMeta *meta = &item->meta;
1005     if (meta->info->api == info->api) {
1006       result = meta;
1007       break;
1008     }
1009   }
1010   return result;
1011 }
1012
1013 /**
1014  * gst_buffer_add_meta:
1015  * @buffer: a #GstBuffer
1016  * @info: a #GstMetaInfo
1017  * @params: params for @info
1018  *
1019  * Add metadata for @info to @buffer using the parameters in @params.
1020  *
1021  * Returns: the metadata for the api in @info on @buffer.
1022  */
1023 GstMeta *
1024 gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
1025     gpointer params)
1026 {
1027   GstMetaItem *item;
1028   GstMeta *result = NULL;
1029   gsize size;
1030
1031   g_return_val_if_fail (buffer != NULL, NULL);
1032   g_return_val_if_fail (info != NULL, NULL);
1033
1034   /* create a new slice */
1035   GST_CAT_DEBUG (GST_CAT_BUFFER, "alloc metadata of size %" G_GSIZE_FORMAT,
1036       info->size);
1037
1038   size = ITEM_SIZE (info);
1039   item = g_slice_alloc (size);
1040   result = &item->meta;
1041   result->info = info;
1042
1043   /* call the init_func when needed */
1044   if (info->init_func)
1045     if (!info->init_func (result, params, buffer))
1046       goto init_failed;
1047
1048   /* and add to the list of metadata */
1049   item->next = buffer->priv;
1050   buffer->priv = item;
1051
1052   return result;
1053
1054 init_failed:
1055   {
1056     g_slice_free1 (size, item);
1057     return NULL;
1058   }
1059 }
1060
1061 /**
1062  * gst_buffer_remove_meta:
1063  * @buffer: a #GstBuffer
1064  * @info: a #GstMetaInfo
1065  *
1066  * Remove the metadata for @info on @buffer.
1067  *
1068  * Returns: %TRUE if the metadata existed and was removed, %FALSE if no such
1069  * metadata was on @buffer.
1070  */
1071 gboolean
1072 gst_buffer_remove_meta (GstBuffer * buffer, GstMeta * meta)
1073 {
1074   GstMetaItem *walk, *prev;
1075
1076   g_return_val_if_fail (buffer != NULL, FALSE);
1077   g_return_val_if_fail (meta != NULL, FALSE);
1078
1079   /* find the metadata and delete */
1080   prev = buffer->priv;
1081   for (walk = prev; walk; walk = walk->next) {
1082     GstMeta *m = &walk->meta;
1083     if (m == meta) {
1084       const GstMetaInfo *info = meta->info;
1085
1086       /* remove from list */
1087       if (buffer->priv == walk)
1088         buffer->priv = walk->next;
1089       else
1090         prev->next = walk->next;
1091       /* call free_func if any */
1092       if (info->free_func)
1093         info->free_func (m, buffer);
1094
1095       /* and free the slice */
1096       g_slice_free1 (ITEM_SIZE (info), walk);
1097       break;
1098     }
1099     prev = walk;
1100   }
1101   return walk != NULL;
1102 }
1103
1104 /**
1105  * gst_buffer_iterate_meta:
1106  * @buffer: a #GstBuffer
1107  * @state: an opaque state pointer
1108  *
1109  * Retrieve the next #GstMeta after @current. If @state points
1110  * to %NULL, the first metadata is returned.
1111  *
1112  * @state will be updated with an opage state pointer 
1113  *
1114  * Returns: The next #GstMeta or %NULL when there are no more items.
1115  */
1116 GstMeta *
1117 gst_buffer_iterate_meta (GstBuffer * buffer, gpointer * state)
1118 {
1119   GstMetaItem **meta;
1120
1121   g_return_val_if_fail (buffer != NULL, NULL);
1122   g_return_val_if_fail (state != NULL, NULL);
1123
1124   meta = (GstMetaItem **) state;
1125   if (*meta == NULL)
1126     /* state NULL, move to first item */
1127     *meta = buffer->priv;
1128   else
1129     /* state !NULL, move to next item in list */
1130     *meta = (*meta)->next;
1131
1132   if (*meta)
1133     return &(*meta)->meta;
1134   else
1135     return NULL;
1136 }