gstbuffer: Use g_memdup2 instead of g_memdup
[platform/upstream/gstreamer.git] / gst / gstbuffer.c
index 65c915a..d3d0898 100644 (file)
@@ -22,6 +22,7 @@
 
 /**
  * SECTION:gstbuffer
+ * @title: GstBuffer
  * @short_description: Data-passing buffer type
  * @see_also: #GstPad, #GstMiniObject, #GstMemory, #GstMeta, #GstBufferPool
  *
@@ -33,7 +34,8 @@
  * created one will typically allocate memory for it and add it to the buffer.
  * The following example creates a buffer that can hold a given video frame
  * with a given width, height and bits per plane.
- * |[
+ *
+ * ``` C 
  *   GstBuffer *buffer;
  *   GstMemory *memory;
  *   gint size, width, height, bpp;
@@ -43,7 +45,7 @@
  *   memory = gst_allocator_alloc (NULL, size, NULL);
  *   gst_buffer_insert_memory (buffer, -1, memory);
  *   ...
- * ]|
+ * ```
  *
  * Alternatively, use gst_buffer_new_allocate() to create a buffer with
  * preallocated data of a given size.
@@ -83,7 +85,7 @@
  *
  * If a plug-in wants to modify the buffer data or metadata in-place, it should
  * first obtain a buffer that is safe to modify by using
- * gst_buffer_make_writable().  This function is optimized so that a copy will
+ * gst_buffer_make_writable(). This function is optimized so that a copy will
  * only be made when it is necessary.
  *
  * Several flags of the buffer can be set and unset with the
@@ -95,7 +97,7 @@
  * needed.
  *
  * Arbitrary extra metadata can be set on a buffer with gst_buffer_add_meta().
- * Metadata can be retrieved with gst_buffer_get_meta(). See also #GstMeta
+ * Metadata can be retrieved with gst_buffer_get_meta(). See also #GstMeta.
  *
  * An element should either unref the buffer or push it out on a src pad
  * using gst_pad_push() (see #GstPad).
  * Typically, #GstParentBufferMeta is used when the child buffer is directly
  * using the #GstMemory of the parent buffer, and wants to prevent the parent
  * buffer from being returned to a buffer pool until the #GstMemory is available
- * for re-use. (Since 1.6)
- *
+ * for re-use. (Since: 1.6)
  */
+
+#define GST_DISABLE_MINIOBJECT_INLINE_FUNCTIONS
 #include "gst_private.h"
 
 #ifdef HAVE_UNISTD_H
 #include "gstutils.h"
 #include "gstversion.h"
 
-GType _gst_buffer_type = 0;
+/* For g_memdup2 */
+#include "glib-compat-private.h"
 
-typedef struct _GstMetaItem GstMetaItem;
+GType _gst_buffer_type = 0;
 
-struct _GstMetaItem
-{
-  GstMetaItem *next;
-  GstMeta meta;
-};
-#define ITEM_SIZE(info) ((info)->size + sizeof (GstMetaItem))
+/* info->size will be sizeof(FooMeta) which contains a GstMeta at the beginning
+ * too, and then there is again a GstMeta in GstMetaItem, so subtract one. */
+#define ITEM_SIZE(info) ((info)->size + sizeof (GstMetaItem) - sizeof (GstMeta))
 
 #define GST_BUFFER_MEM_MAX         16
 
@@ -149,6 +150,7 @@ struct _GstMetaItem
 #define GST_BUFFER_MEM_PTR(b,i)    (((GstBufferImpl *)(b))->mem[i])
 #define GST_BUFFER_BUFMEM(b)       (((GstBufferImpl *)(b))->bufmem)
 #define GST_BUFFER_META(b)         (((GstBufferImpl *)(b))->item)
+#define GST_BUFFER_TAIL_META(b)    (((GstBufferImpl *)(b))->tail_item)
 
 typedef struct
 {
@@ -166,8 +168,44 @@ typedef struct
   /* FIXME, make metadata allocation more efficient by using part of the
    * GstBufferImpl */
   GstMetaItem *item;
+  GstMetaItem *tail_item;
 } GstBufferImpl;
 
+static gint64 meta_seq;         /* 0 *//* ATOMIC */
+
+/* TODO: use GLib's once https://gitlab.gnome.org/GNOME/glib/issues/1076 lands */
+#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)
+static inline gint64
+gst_atomic_int64_inc (gint64 * atomic)
+{
+  return __sync_fetch_and_add (atomic, 1);
+}
+#elif defined (G_PLATFORM_WIN32)
+#include <windows.h>
+static inline gint64
+gst_atomic_int64_inc (gint64 * atomic)
+{
+  return InterlockedExchangeAdd64 (atomic, 1);
+}
+#else
+#define STR_TOKEN(s) #s
+#define STR(s) STR_TOKEN(s)
+#pragma message "No 64-bit atomic int defined for this " STR(TARGET_CPU) " platform/toolchain!"
+
+#define NO_64BIT_ATOMIC_INT_FOR_PLATFORM
+G_LOCK_DEFINE_STATIC (meta_seq);
+static inline gint64
+gst_atomic_int64_inc (gint64 * atomic)
+{
+  gint64 ret;
+
+  G_LOCK (meta_seq);
+  ret = (*atomic)++;
+  G_UNLOCK (meta_seq);
+
+  return ret;
+}
+#endif
 
 static gboolean
 _is_span (GstMemory ** mem, gsize len, gsize * poffset, GstMemory ** parent)
@@ -204,60 +242,79 @@ _is_span (GstMemory ** mem, gsize len, gsize * poffset, GstMemory ** parent)
 }
 
 static GstMemory *
-_get_merged_memory (GstBuffer * buffer, guint idx, guint length)
+_actual_merged_memory (GstBuffer * buffer, guint idx, guint length)
 {
   GstMemory **mem, *result = NULL;
-
-  GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %u, length %u", buffer, idx,
-      length);
+  GstMemory *parent = NULL;
+  gsize size, poffset = 0;
 
   mem = GST_BUFFER_MEM_ARRAY (buffer);
 
-  if (G_UNLIKELY (length == 0)) {
-    result = NULL;
-  } else if (G_LIKELY (length == 1)) {
-    result = gst_memory_ref (mem[idx]);
-  } else {
-    GstMemory *parent = NULL;
-    gsize size, poffset = 0;
+  size = gst_buffer_get_sizes_range (buffer, idx, length, NULL, NULL);
 
-    size = gst_buffer_get_sizes_range (buffer, idx, length, NULL, NULL);
-
-    if (G_UNLIKELY (_is_span (mem + idx, length, &poffset, &parent))) {
-      if (!GST_MEMORY_IS_NO_SHARE (parent))
-        result = gst_memory_share (parent, poffset, size);
-      if (!result) {
-        GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy for merge %p", parent);
-        result = gst_memory_copy (parent, poffset, size);
-      }
-    } else {
-      gsize i, tocopy, left;
-      GstMapInfo sinfo, dinfo;
-      guint8 *ptr;
-
-      result = gst_allocator_alloc (NULL, size, NULL);
-      gst_memory_map (result, &dinfo, GST_MAP_WRITE);
+  if (G_UNLIKELY (_is_span (mem + idx, length, &poffset, &parent))) {
+    if (!GST_MEMORY_IS_NO_SHARE (parent))
+      result = gst_memory_share (parent, poffset, size);
+    if (!result) {
+      GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "copy for merge %p", parent);
+      result = gst_memory_copy (parent, poffset, size);
+    }
+  } else {
+    gsize i, tocopy, left;
+    GstMapInfo sinfo, dinfo;
+    guint8 *ptr;
+
+    result = gst_allocator_alloc (NULL, size, NULL);
+    if (result == NULL || !gst_memory_map (result, &dinfo, GST_MAP_WRITE)) {
+      GST_CAT_ERROR (GST_CAT_BUFFER, "Failed to map memory writable");
+      if (result)
+        gst_memory_unref (result);
+      return NULL;
+    }
 
-      ptr = dinfo.data;
-      left = size;
+    ptr = dinfo.data;
+    left = size;
 
-      for (i = idx; i < (idx + length) && left > 0; i++) {
-        gst_memory_map (mem[i], &sinfo, GST_MAP_READ);
-        tocopy = MIN (sinfo.size, left);
-        GST_CAT_DEBUG (GST_CAT_PERFORMANCE,
-            "memcpy %" G_GSIZE_FORMAT " bytes for merge %p from memory %p",
-            tocopy, result, mem[i]);
-        memcpy (ptr, (guint8 *) sinfo.data, tocopy);
-        left -= tocopy;
-        ptr += tocopy;
-        gst_memory_unmap (mem[i], &sinfo);
+    for (i = idx; i < (idx + length) && left > 0; i++) {
+      if (!gst_memory_map (mem[i], &sinfo, GST_MAP_READ)) {
+        GST_CAT_ERROR (GST_CAT_BUFFER,
+            "buffer %p, idx %u, length %u failed to map readable", buffer,
+            idx, length);
+        gst_memory_unmap (result, &dinfo);
+        gst_memory_unref (result);
+        return NULL;
       }
-      gst_memory_unmap (result, &dinfo);
+      tocopy = MIN (sinfo.size, left);
+      GST_CAT_DEBUG (GST_CAT_PERFORMANCE,
+          "memcpy %" G_GSIZE_FORMAT " bytes for merge %p from memory %p",
+          tocopy, result, mem[i]);
+      memcpy (ptr, (guint8 *) sinfo.data, tocopy);
+      left -= tocopy;
+      ptr += tocopy;
+      gst_memory_unmap (mem[i], &sinfo);
     }
+    gst_memory_unmap (result, &dinfo);
   }
+
   return result;
 }
 
+static inline GstMemory *
+_get_merged_memory (GstBuffer * buffer, guint idx, guint length)
+{
+  GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %u, length %u", buffer, idx,
+      length);
+
+  if (G_UNLIKELY (length == 0))
+    return NULL;
+
+  if (G_LIKELY (length == 1))
+    return gst_memory_ref (GST_BUFFER_MEM_PTR (buffer, idx));
+
+  return _actual_merged_memory (buffer, idx, length);
+}
+
+
 static void
 _replace_memory (GstBuffer * buffer, guint len, guint idx, guint length,
     GstMemory * mem)
@@ -275,11 +332,15 @@ _replace_memory (GstBuffer * buffer, guint len, guint idx, guint length,
     GstMemory *old = GST_BUFFER_MEM_PTR (buffer, i);
 
     gst_memory_unlock (old, GST_LOCK_FLAG_EXCLUSIVE);
+    gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (old),
+        GST_MINI_OBJECT_CAST (buffer));
     gst_memory_unref (old);
   }
 
   if (mem != NULL) {
     /* replace with single memory */
+    gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (mem),
+        GST_MINI_OBJECT_CAST (buffer));
     gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
     GST_BUFFER_MEM_PTR (buffer, idx) = mem;
     idx++;
@@ -294,6 +355,77 @@ _replace_memory (GstBuffer * buffer, guint len, guint idx, guint length,
   GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
 }
 
+/**
+ * gst_buffer_get_flags:
+ * @buffer: a #GstBuffer
+ *
+ * Gets the #GstBufferFlags flags set on this buffer.
+ *
+ * Returns: the flags set on this buffer.
+ *
+ * Since: 1.10
+ */
+GstBufferFlags
+gst_buffer_get_flags (GstBuffer * buffer)
+{
+  return (GstBufferFlags) GST_BUFFER_FLAGS (buffer);
+}
+
+/**
+ * gst_buffer_has_flags:
+ * @buffer: a #GstBuffer
+ * @flags: the #GstBufferFlags flag to check.
+ *
+ * Gives the status of a specific flag on a buffer.
+ *
+ * Returns: %TRUE if all flags in @flags are found on @buffer.
+ *
+ * Since: 1.10
+ */
+gboolean
+gst_buffer_has_flags (GstBuffer * buffer, GstBufferFlags flags)
+{
+  return GST_BUFFER_FLAG_IS_SET (buffer, flags);
+}
+
+/**
+ * gst_buffer_set_flags:
+ * @buffer: a #GstBuffer
+ * @flags: the #GstBufferFlags to set.
+ *
+ * Sets one or more buffer flags on a buffer.
+ *
+ * Returns: %TRUE if @flags were successfully set on buffer.
+ *
+ * Since: 1.10
+ */
+gboolean
+gst_buffer_set_flags (GstBuffer * buffer, GstBufferFlags flags)
+{
+  GST_BUFFER_FLAG_SET (buffer, flags);
+  return TRUE;
+}
+
+/**
+ * gst_buffer_unset_flags:
+ * @buffer: a #GstBuffer
+ * @flags: the #GstBufferFlags to clear
+ *
+ * Clears one or more buffer flags.
+ *
+ * Returns: true if @flags is successfully cleared from buffer.
+ *
+ * Since: 1.10
+ */
+gboolean
+gst_buffer_unset_flags (GstBuffer * buffer, GstBufferFlags flags)
+{
+  GST_BUFFER_FLAG_UNSET (buffer, flags);
+  return TRUE;
+}
+
+
+
 /* transfer full for return and transfer none for @mem */
 static inline GstMemory *
 _memory_get_exclusive_reference (GstMemory * mem)
@@ -351,6 +483,8 @@ _memory_add (GstBuffer * buffer, gint idx, GstMemory * mem)
   /* and insert the new buffer */
   GST_BUFFER_MEM_PTR (buffer, idx) = mem;
   GST_BUFFER_MEM_LEN (buffer) = len + 1;
+  gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (mem),
+      GST_MINI_OBJECT_CAST (buffer));
 
   GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
 }
@@ -361,12 +495,17 @@ void
 _priv_gst_buffer_initialize (void)
 {
   _gst_buffer_type = gst_buffer_get_type ();
+
+#ifdef NO_64BIT_ATOMIC_INT_FOR_PLATFORM
+  GST_CAT_WARNING (GST_CAT_PERFORMANCE,
+      "No 64-bit atomic int defined for this platform/toolchain!");
+#endif
 }
 
 /**
  * gst_buffer_get_max_memory:
  *
- * Get the maximum amount of memory blocks that a buffer can hold. This is a
+ * Gets the maximum amount of memory blocks that a buffer can hold. This is a
  * compile time constant that can be queried with the function.
  *
  * When more memory blocks are added, existing memory blocks will be merged
@@ -472,7 +611,7 @@ gst_buffer_copy_into (GstBuffer * dest, GstBuffer * src,
     for (i = 0; i < len && left > 0; i++) {
       GstMemory *mem = GST_BUFFER_MEM_PTR (src, i);
 
-      bsize = gst_memory_get_sizes (mem, NULL, NULL);
+      bsize = mem->size;
 
       if (bsize <= skip) {
         /* don't copy buffer */
@@ -595,7 +734,7 @@ _gst_buffer_copy (const GstBuffer * buffer)
  * gst_buffer_copy_deep:
  * @buf: a #GstBuffer.
  *
- * Create a copy of the given buffer. This will make a newly allocated
+ * Creates a copy of the given buffer. This will make a newly allocated
  * copy of the data the source buffer contains.
  *
  * Returns: (transfer full): a new copy of @buf.
@@ -662,6 +801,8 @@ _gst_buffer_free (GstBuffer * buffer)
   len = GST_BUFFER_MEM_LEN (buffer);
   for (i = 0; i < len; i++) {
     gst_memory_unlock (GST_BUFFER_MEM_PTR (buffer, i), GST_LOCK_FLAG_EXCLUSIVE);
+    gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (GST_BUFFER_MEM_PTR
+            (buffer, i)), GST_MINI_OBJECT_CAST (buffer));
     gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
   }
 
@@ -702,8 +843,6 @@ gst_buffer_init (GstBufferImpl * buffer, gsize size)
  *
  * Creates a newly allocated buffer without any data.
  *
- * MT safe.
- *
  * Returns: (transfer full): the new #GstBuffer.
  */
 GstBuffer *
@@ -734,10 +873,7 @@ gst_buffer_new (void)
  *
  * Note that when @size == 0, the buffer will not have memory associated with it.
  *
- * MT safe.
- *
- * Returns: (transfer full) (nullable): a new #GstBuffer, or %NULL if
- *     the memory couldn't be allocated.
+ * Returns: (transfer full) (nullable): a new #GstBuffer
  */
 GstBuffer *
 gst_buffer_new_allocate (GstAllocator * allocator, gsize size,
@@ -835,7 +971,7 @@ no_memory:
  * @user_data: (allow-none): user_data
  * @notify: (allow-none) (scope async) (closure user_data): called with @user_data when the memory is freed
  *
- * Allocate a new buffer that wraps the given memory. @data must point to
+ * Allocates a new buffer that wraps the given memory. @data must point to
  * @maxsize of memory, the wrapped buffer will have the region from @offset and
  * @size visible.
  *
@@ -871,9 +1007,7 @@ gst_buffer_new_wrapped_full (GstMemoryFlags flags, gpointer data,
  * @size: allocated size of @data
  *
  * Creates a new buffer that wraps the given @data. The memory will be freed
- * with g_free and will be marked writable.
- *
- * MT safe.
+ * with g_free() and will be marked writable.
  *
  * Returns: (transfer full): a new #GstBuffer
  */
@@ -884,13 +1018,57 @@ gst_buffer_new_wrapped (gpointer data, gsize size)
 }
 
 /**
+ * gst_buffer_new_wrapped_bytes:
+ * @bytes: (transfer none): a #GBytes to wrap
+ *
+ * Creates a new #GstBuffer that wraps the given @bytes. The data inside
+ * @bytes cannot be %NULL and the resulting buffer will be marked as read only.
+ *
+ * Returns: (transfer full): a new #GstBuffer wrapping @bytes
+ *
+ * Since: 1.16
+ */
+GstBuffer *
+gst_buffer_new_wrapped_bytes (GBytes * bytes)
+{
+  guint8 *bytes_data;
+  gsize size;
+
+  g_return_val_if_fail (bytes != NULL, NULL);
+  bytes_data = (guint8 *) g_bytes_get_data (bytes, &size);
+  g_return_val_if_fail (bytes_data != NULL, NULL);
+
+  return gst_buffer_new_wrapped_full (GST_MEMORY_FLAG_READONLY, bytes_data,
+      size, 0, size, g_bytes_ref (bytes), (GDestroyNotify) g_bytes_unref);
+}
+
+/**
+ * gst_buffer_new_memdup:
+ * @data: (array length=size) (element-type guint8) (transfer none): data to copy into new buffer
+ * @size: size of @data in bytes
+ *
+ * Creates a new buffer of size @size and fills it with a copy of @data.
+ *
+ * Returns: (transfer full): a new #GstBuffer
+ *
+ * Since: 1.20
+ */
+GstBuffer *
+gst_buffer_new_memdup (gconstpointer data, gsize size)
+{
+  gpointer data2 = g_memdup2 (data, size);
+
+  return gst_buffer_new_wrapped_full (0, data2, size, 0, size, data2, g_free);
+}
+
+/**
  * gst_buffer_n_memory:
  * @buffer: a #GstBuffer.
  *
- * Get the amount of memory blocks that this buffer has. This amount is never
+ * Gets the amount of memory blocks that this buffer has. This amount is never
  * larger than what gst_buffer_get_max_memory() returns.
  *
- * Returns: (transfer full): the amount of memory block in this buffer.
+ * Returns: the number of memory blocks this buffer is made of.
  */
 guint
 gst_buffer_n_memory (GstBuffer * buffer)
@@ -905,7 +1083,7 @@ gst_buffer_n_memory (GstBuffer * buffer)
  * @buffer: a #GstBuffer.
  * @mem: (transfer full): a #GstMemory.
  *
- * Prepend the memory block @mem to @buffer. This function takes
+ * Prepends the memory block @mem to @buffer. This function takes
  * ownership of @mem and thus doesn't increase its refcount.
  *
  * This function is identical to gst_buffer_insert_memory() with an index of 0.
@@ -922,7 +1100,7 @@ gst_buffer_prepend_memory (GstBuffer * buffer, GstMemory * mem)
  * @buffer: a #GstBuffer.
  * @mem: (transfer full): a #GstMemory.
  *
- * Append the memory block @mem to @buffer. This function takes
+ * Appends the memory block @mem to @buffer. This function takes
  * ownership of @mem and thus doesn't increase its refcount.
  *
  * This function is identical to gst_buffer_insert_memory() with an index of -1.
@@ -940,7 +1118,7 @@ gst_buffer_append_memory (GstBuffer * buffer, GstMemory * mem)
  * @idx: the index to add the memory at, or -1 to append it to the end
  * @mem: (transfer full): a #GstMemory.
  *
- * Insert the memory block @mem to @buffer at @idx. This function takes ownership
+ * Inserts the memory block @mem into @buffer at @idx. This function takes ownership
  * of @mem and thus doesn't increase its refcount.
  *
  * Only gst_buffer_get_max_memory() can be added to a buffer. If more memory is
@@ -976,10 +1154,14 @@ _get_mapped (GstBuffer * buffer, guint idx, GstMapInfo * info,
 
   if (mapped != mem) {
     /* memory changed, lock new memory */
+    gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (mapped),
+        GST_MINI_OBJECT_CAST (buffer));
     gst_memory_lock (mapped, GST_LOCK_FLAG_EXCLUSIVE);
     GST_BUFFER_MEM_PTR (buffer, idx) = mapped;
     /* unlock old memory */
     gst_memory_unlock (mem, GST_LOCK_FLAG_EXCLUSIVE);
+    gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
+        GST_MINI_OBJECT_CAST (buffer));
     GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
   }
   gst_memory_unref (mem);
@@ -992,20 +1174,17 @@ _get_mapped (GstBuffer * buffer, guint idx, GstMapInfo * info,
  * @buffer: a #GstBuffer.
  * @idx: an index
  *
- * Get the memory block at @idx in @buffer. The memory block stays valid until
+ * Gets the memory block at @idx in @buffer. The memory block stays valid until
  * the memory block in @buffer is removed, replaced or merged, typically with
  * any call that modifies the memory in @buffer.
  *
- * Returns: (transfer none): the #GstMemory at @idx.
+ * Returns: (transfer none) (nullable): the #GstMemory at @idx.
  */
 GstMemory *
 gst_buffer_peek_memory (GstBuffer * buffer, guint idx)
 {
-  guint len;
-
   g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
-  len = GST_BUFFER_MEM_LEN (buffer);
-  g_return_val_if_fail (idx < len, NULL);
+  g_return_val_if_fail (idx < GST_BUFFER_MEM_LEN (buffer), NULL);
 
   return GST_BUFFER_MEM_PTR (buffer, idx);
 }
@@ -1015,10 +1194,10 @@ gst_buffer_peek_memory (GstBuffer * buffer, guint idx)
  * @buffer: a #GstBuffer.
  * @idx: an index
  *
- * Get the memory block at index @idx in @buffer.
+ * Gets the memory block at index @idx in @buffer.
  *
- * Returns: (transfer full): a #GstMemory that contains the data of the
- * memory block at @idx. Use gst_memory_unref () after usage.
+ * Returns: (transfer full) (nullable): a #GstMemory that contains the data of the
+ * memory block at @idx.
  */
 GstMemory *
 gst_buffer_get_memory (GstBuffer * buffer, guint idx)
@@ -1030,11 +1209,10 @@ gst_buffer_get_memory (GstBuffer * buffer, guint idx)
  * gst_buffer_get_all_memory:
  * @buffer: a #GstBuffer.
  *
- * Get all the memory block in @buffer. The memory blocks will be merged
+ * Gets all the memory blocks in @buffer. The memory blocks will be merged
  * into one large #GstMemory.
  *
- * Returns: (transfer full): a #GstMemory that contains the merged memory.
- * Use gst_memory_unref () after usage.
+ * Returns: (transfer full) (nullable): a #GstMemory that contains the merged memory.
  */
 GstMemory *
 gst_buffer_get_all_memory (GstBuffer * buffer)
@@ -1048,13 +1226,13 @@ gst_buffer_get_all_memory (GstBuffer * buffer)
  * @idx: an index
  * @length: a length
  *
- * Get @length memory blocks in @buffer starting at @idx. The memory blocks will
+ * Gets @length memory blocks in @buffer starting at @idx. The memory blocks will
  * be merged into one large #GstMemory.
  *
  * If @length is -1, all memory starting from @idx is merged.
  *
- * Returns: (transfer full): a #GstMemory that contains the merged data of @length
- *    blocks starting at @idx. Use gst_memory_unref () after usage.
+ * Returns: (transfer full) (nullable): a #GstMemory that contains the merged data of @length
+ *    blocks starting at @idx.
  */
 GstMemory *
 gst_buffer_get_memory_range (GstBuffer * buffer, guint idx, gint length)
@@ -1105,7 +1283,7 @@ gst_buffer_replace_all_memory (GstBuffer * buffer, GstMemory * mem)
  * gst_buffer_replace_memory_range:
  * @buffer: a #GstBuffer.
  * @idx: an index
- * @length: a length should not be 0
+ * @length: a length, should not be 0
  * @mem: (transfer full): a #GstMemory
  *
  * Replaces @length memory blocks in @buffer starting at @idx with @mem.
@@ -1141,7 +1319,7 @@ gst_buffer_replace_memory_range (GstBuffer * buffer, guint idx, gint length,
  * @buffer: a #GstBuffer.
  * @idx: an index
  *
- * Remove the memory block in @b at index @i.
+ * Removes the memory block in @b at index @i.
  */
 void
 gst_buffer_remove_memory (GstBuffer * buffer, guint idx)
@@ -1153,12 +1331,13 @@ gst_buffer_remove_memory (GstBuffer * buffer, guint idx)
  * gst_buffer_remove_all_memory:
  * @buffer: a #GstBuffer.
  *
- * Remove all the memory blocks in @buffer.
+ * Removes all the memory blocks in @buffer.
  */
 void
 gst_buffer_remove_all_memory (GstBuffer * buffer)
 {
-  gst_buffer_remove_memory_range (buffer, 0, -1);
+  if (GST_BUFFER_MEM_LEN (buffer))
+    gst_buffer_remove_memory_range (buffer, 0, -1);
 }
 
 /**
@@ -1167,7 +1346,7 @@ gst_buffer_remove_all_memory (GstBuffer * buffer)
  * @idx: an index
  * @length: a length
  *
- * Remove @length memory blocks in @buffer starting from @idx.
+ * Removes @length memory blocks in @buffer starting from @idx.
  *
  * @length can be -1, in which case all memory starting from @idx is removed.
  */
@@ -1200,7 +1379,7 @@ gst_buffer_remove_memory_range (GstBuffer * buffer, guint idx, gint length)
  * @length: (out): pointer to length
  * @skip: (out): pointer to skip
  *
- * Find the memory blocks that span @size bytes starting from @offset
+ * Finds the memory blocks that span @size bytes starting from @offset
  * in @buffer.
  *
  * When this function returns %TRUE, @idx will contain the index of the first
@@ -1233,7 +1412,7 @@ gst_buffer_find_memory (GstBuffer * buffer, gsize offset, gsize size,
     gsize s;
 
     mem = GST_BUFFER_MEM_PTR (buffer, i);
-    s = gst_memory_get_sizes (mem, NULL, NULL);
+    s = mem->size;
 
     if (s <= offset) {
       /* block before offset, or empty block, skip */
@@ -1268,9 +1447,9 @@ gst_buffer_find_memory (GstBuffer * buffer, gsize offset, gsize size,
  * gst_buffer_is_memory_range_writable:
  * @buffer: a #GstBuffer.
  * @idx: an index
- * @length: a length should not be 0
+ * @length: a length, should not be 0
  *
- * Check if @length memory blocks in @buffer starting from @idx are writable.
+ * Checks if @length memory blocks in @buffer starting from @idx are writable.
  *
  * @length can be -1 to check all the memory blocks after @idx.
  *
@@ -1311,7 +1490,7 @@ gst_buffer_is_memory_range_writable (GstBuffer * buffer, guint idx, gint length)
  * gst_buffer_is_all_memory_writable:
  * @buffer: a #GstBuffer.
  *
- * Check if all memory blocks in @buffer are writable.
+ * Checks if all memory blocks in @buffer are writable.
  *
  * Note that this function does not check if @buffer is writable, use
  * gst_buffer_is_writable() to check that if needed.
@@ -1332,7 +1511,7 @@ gst_buffer_is_all_memory_writable (GstBuffer * buffer)
  * @offset: (out) (allow-none): a pointer to the offset
  * @maxsize: (out) (allow-none): a pointer to the maxsize
  *
- * Get the total size of the memory blocks in @b.
+ * Gets the total size of the memory blocks in @buffer.
  *
  * When not %NULL, @offset will contain the offset of the data in the
  * first memory block in @buffer and @maxsize will contain the sum of
@@ -1352,14 +1531,23 @@ gst_buffer_get_sizes (GstBuffer * buffer, gsize * offset, gsize * maxsize)
  * gst_buffer_get_size:
  * @buffer: a #GstBuffer.
  *
- * Get the total size of the memory blocks in @buffer.
+ * Gets the total size of the memory blocks in @buffer.
  *
  * Returns: total size of the memory blocks in @buffer.
  */
 gsize
 gst_buffer_get_size (GstBuffer * buffer)
 {
-  return gst_buffer_get_sizes_range (buffer, 0, -1, NULL, NULL);
+  guint i;
+  gsize size, len;
+
+  g_return_val_if_fail (GST_IS_BUFFER (buffer), 0);
+
+  /* FAST PATH */
+  len = GST_BUFFER_MEM_LEN (buffer);
+  for (i = 0, size = 0; i < len; i++)
+    size += GST_BUFFER_MEM_PTR (buffer, i)->size;
+  return size;
 }
 
 /**
@@ -1370,7 +1558,7 @@ gst_buffer_get_size (GstBuffer * buffer)
  * @offset: (out) (allow-none): a pointer to the offset
  * @maxsize: (out) (allow-none): a pointer to the maxsize
  *
- * Get the total size of @length memory blocks stating from @idx in @buffer.
+ * Gets the total size of @length memory blocks stating from @idx in @buffer.
  *
  * When not %NULL, @offset will contain the offset of the data in the
  * memory block in @buffer at @idx and @maxsize will contain the sum of the size
@@ -1401,6 +1589,16 @@ gst_buffer_get_sizes_range (GstBuffer * buffer, guint idx, gint length,
     /* common case */
     mem = GST_BUFFER_MEM_PTR (buffer, idx);
     size = gst_memory_get_sizes (mem, offset, maxsize);
+  } else if (offset == NULL && maxsize == NULL) {
+    /* FAST PATH ! */
+    guint i, end;
+
+    size = 0;
+    end = idx + length;
+    for (i = idx; i < end; i++) {
+      mem = GST_BUFFER_MEM_PTR (buffer, i);
+      size += mem->size;
+    }
   } else {
     guint i, end;
     gsize extra, offs;
@@ -1440,7 +1638,7 @@ gst_buffer_get_sizes_range (GstBuffer * buffer, guint idx, gint length,
  * @offset: the offset adjustment
  * @size: the new size or -1 to just adjust the offset
  *
- * Set the offset and total size of the memory blocks in @buffer.
+ * Sets the offset and total size of the memory blocks in @buffer.
  */
 void
 gst_buffer_resize (GstBuffer * buffer, gssize offset, gssize size)
@@ -1453,7 +1651,7 @@ gst_buffer_resize (GstBuffer * buffer, gssize offset, gssize size)
  * @buffer: a #GstBuffer.
  * @size: the new size
  *
- * Set the total size of the memory blocks in @buffer.
+ * Sets the total size of the memory blocks in @buffer.
  */
 void
 gst_buffer_set_size (GstBuffer * buffer, gssize size)
@@ -1469,7 +1667,7 @@ gst_buffer_set_size (GstBuffer * buffer, gssize size)
  * @offset: the offset adjustment
  * @size: the new size or -1 to just adjust the offset
  *
- * Set the total size of the @length memory blocks starting at @idx in
+ * Sets the total size of the @length memory blocks starting at @idx in
  * @buffer
  *
  * Returns: %TRUE if resizing succeeded, %FALSE otherwise.
@@ -1518,7 +1716,7 @@ gst_buffer_resize_range (GstBuffer * buffer, guint idx, gint length,
     gsize left, noffs;
 
     mem = GST_BUFFER_MEM_PTR (buffer, i);
-    bsize = gst_memory_get_sizes (mem, NULL, NULL);
+    bsize = mem->size;
 
     noffs = 0;
     /* last buffer always gets resized to the remaining size */
@@ -1549,9 +1747,13 @@ gst_buffer_resize_range (GstBuffer * buffer, guint idx, gint length,
         if (newmem == NULL)
           return FALSE;
 
+        gst_mini_object_add_parent (GST_MINI_OBJECT_CAST (newmem),
+            GST_MINI_OBJECT_CAST (buffer));
         gst_memory_lock (newmem, GST_LOCK_FLAG_EXCLUSIVE);
         GST_BUFFER_MEM_PTR (buffer, i) = newmem;
         gst_memory_unlock (mem, GST_LOCK_FLAG_EXCLUSIVE);
+        gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
+            GST_MINI_OBJECT_CAST (buffer));
         gst_memory_unref (mem);
 
         GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
@@ -1568,11 +1770,10 @@ gst_buffer_resize_range (GstBuffer * buffer, guint idx, gint length,
 /**
  * gst_buffer_map:
  * @buffer: a #GstBuffer.
- * @info: (out): info about the mapping
+ * @info: (out caller-allocates): info about the mapping
  * @flags: flags for the mapping
  *
- * This function fills @info with the #GstMapInfo of all merged memory
- * blocks in @buffer.
+ * Fills @info with the #GstMapInfo of all merged memory blocks in @buffer.
  *
  * @flags describe the desired access of the memory. When @flags is
  * #GST_MAP_WRITE, @buffer should be writable (as returned from
@@ -1598,10 +1799,10 @@ gst_buffer_map (GstBuffer * buffer, GstMapInfo * info, GstMapFlags flags)
  * @buffer: a #GstBuffer.
  * @idx: an index
  * @length: a length
- * @info: (out): info about the mapping
+ * @info: (out caller-allocates): info about the mapping
  * @flags: flags for the mapping
  *
- * This function fills @info with the #GstMapInfo of @length merged memory blocks
+ * Fills @info with the #GstMapInfo of @length merged memory blocks
  * starting at @idx in @buffer. When @length is -1, all memory blocks starting
  * from @idx are merged and mapped.
  *
@@ -1673,7 +1874,7 @@ gst_buffer_map_range (GstBuffer * buffer, guint idx, gint length,
   /* ERROR */
 not_writable:
   {
-    GST_WARNING_OBJECT (buffer, "write map requested on non-writable buffer");
+    GST_WARNING ("write map requested on non-writable buffer");
     g_critical ("write map requested on non-writable buffer");
     memset (info, 0, sizeof (GstMapInfo));
     return FALSE;
@@ -1681,13 +1882,13 @@ not_writable:
 no_memory:
   {
     /* empty buffer, we need to return NULL */
-    GST_DEBUG_OBJECT (buffer, "can't get buffer memory");
+    GST_DEBUG ("can't get buffer memory");
     memset (info, 0, sizeof (GstMapInfo));
     return TRUE;
   }
 cannot_map:
   {
-    GST_DEBUG_OBJECT (buffer, "cannot map memory");
+    GST_DEBUG ("cannot map memory");
     memset (info, 0, sizeof (GstMapInfo));
     return FALSE;
   }
@@ -1698,7 +1899,7 @@ cannot_map:
  * @buffer: a #GstBuffer.
  * @info: a #GstMapInfo
  *
- * Release the memory previously mapped with gst_buffer_map().
+ * Releases the memory previously mapped with gst_buffer_map().
  */
 void
 gst_buffer_unmap (GstBuffer * buffer, GstMapInfo * info)
@@ -1721,7 +1922,7 @@ gst_buffer_unmap (GstBuffer * buffer, GstMapInfo * info)
  * @src: (array length=size) (element-type guint8): the source address
  * @size: the size to fill
  *
- * Copy @size bytes from @src to @buffer at @offset.
+ * Copies @size bytes from @src to @buffer at @offset.
  *
  * Returns: The amount of bytes copied. This value can be lower than @size
  *    when @buffer did not contain enough data.
@@ -1770,10 +1971,11 @@ gst_buffer_fill (GstBuffer * buffer, gsize offset, gconstpointer src,
  * gst_buffer_extract:
  * @buffer: a #GstBuffer.
  * @offset: the offset to extract
- * @dest: the destination address
+ * @dest: (out caller-allocates) (array length=size) (element-type guint8):
+ *     the destination address
  * @size: the size to extract
  *
- * Copy @size bytes starting from @offset in @buffer to @dest.
+ * Copies @size bytes starting from @offset in @buffer to @dest.
  *
  * Returns: The amount of bytes extracted. This value can be lower than @size
  *    when @buffer did not contain enough data.
@@ -1823,7 +2025,7 @@ gst_buffer_extract (GstBuffer * buffer, gsize offset, gpointer dest, gsize size)
  * @mem: (array length=size) (element-type guint8): the memory to compare
  * @size: the size to compare
  *
- * Compare @size bytes starting from @offset in @buffer with the memory in @mem.
+ * Compares @size bytes starting from @offset in @buffer with the memory in @mem.
  *
  * Returns: 0 if the memory is equal.
  */
@@ -1876,7 +2078,7 @@ gst_buffer_memcmp (GstBuffer * buffer, gsize offset, gconstpointer mem,
  * @val: the value to set
  * @size: the size to set
  *
- * Fill @buf with @size bytes with @val starting from @offset.
+ * Fills @buf with @size bytes with @val starting from @offset.
  *
  * Returns: The amount of bytes filled. This value can be lower than @size
  *    when @buffer did not contain enough data.
@@ -1935,8 +2137,6 @@ gst_buffer_memset (GstBuffer * buffer, gsize offset, guint8 val, gsize size)
  * duration and offset end fields are also copied. If not they will be set
  * to #GST_CLOCK_TIME_NONE and #GST_BUFFER_OFFSET_NONE.
  *
- * MT safe.
- *
  * Returns: (transfer full): the new #GstBuffer or %NULL if the arguments were
  *     invalid.
  */
@@ -1965,7 +2165,7 @@ gst_buffer_copy_region (GstBuffer * buffer, GstBufferCopyFlags flags,
  * @buf1: (transfer full): the first source #GstBuffer to append.
  * @buf2: (transfer full): the second source #GstBuffer to append.
  *
- * Append all the memory from @buf2 to @buf1. The result buffer will contain a
+ * Appends all the memory from @buf2 to @buf1. The result buffer will contain a
  * concatenation of the memory of @buf1 and @buf2.
  *
  * Returns: (transfer full): the new #GstBuffer that contains the memory
@@ -1984,7 +2184,7 @@ gst_buffer_append (GstBuffer * buf1, GstBuffer * buf2)
  * @offset: the offset in @buf2
  * @size: the size or -1 of @buf2
  *
- * Append @size bytes at @offset from @buf2 to @buf1. The result buffer will
+ * Appends @size bytes at @offset from @buf2 to @buf1. The result buffer will
  * contain a concatenation of the memory of @buf1 and the requested region of
  * @buf2.
  *
@@ -2010,6 +2210,8 @@ gst_buffer_append_region (GstBuffer * buf1, GstBuffer * buf2, gssize offset,
     GstMemory *mem;
 
     mem = GST_BUFFER_MEM_PTR (buf2, i);
+    gst_mini_object_remove_parent (GST_MINI_OBJECT_CAST (mem),
+        GST_MINI_OBJECT_CAST (buf2));
     GST_BUFFER_MEM_PTR (buf2, i) = NULL;
     _memory_add (buf1, -1, mem);
   }
@@ -2026,14 +2228,13 @@ gst_buffer_append_region (GstBuffer * buf1, GstBuffer * buf2, gssize offset,
  * @buffer: a #GstBuffer
  * @api: the #GType of an API
  *
- * Get the metadata for @api on buffer. When there is no such metadata, %NULL is
+ * Gets the metadata for @api on buffer. When there is no such metadata, %NULL is
  * returned. If multiple metadata with the given @api are attached to this
  * buffer only the first one is returned.  To handle multiple metadata with a
  * given API use gst_buffer_iterate_meta() or gst_buffer_foreach_meta() instead
- * and check the meta->info.api member for the API type.
+ * and check the `meta->info.api` member for the API type.
  *
- * Returns: (transfer none) (nullable): the metadata for @api on
- * @buffer.
+ * Returns: (transfer none) (nullable): the metadata for @api on @buffer.
  */
 GstMeta *
 gst_buffer_get_meta (GstBuffer * buffer, GType api)
@@ -2056,14 +2257,36 @@ gst_buffer_get_meta (GstBuffer * buffer, GType api)
 }
 
 /**
+ * gst_buffer_get_n_meta:
+ * @buffer: a #GstBuffer
+ * @api_type: the #GType of an API
+ *
+ * Returns: number of metas of type @api_type on @buffer.
+ *
+ * Since: 1.14
+ */
+guint
+gst_buffer_get_n_meta (GstBuffer * buffer, GType api_type)
+{
+  gpointer state = NULL;
+  GstMeta *meta;
+  guint n = 0;
+
+  while ((meta = gst_buffer_iterate_meta_filtered (buffer, &state, api_type)))
+    ++n;
+
+  return n;
+}
+
+/**
  * gst_buffer_add_meta:
  * @buffer: a #GstBuffer
  * @info: a #GstMetaInfo
  * @params: params for @info
  *
- * Add metadata for @info to @buffer using the parameters in @params.
+ * Adds metadata for @info to @buffer using the parameters in @params.
  *
- * Returns: (transfer none): the metadata for the api in @info on @buffer.
+ * Returns: (transfer none) (nullable): the metadata for the api in @info on @buffer.
  */
 GstMeta *
 gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
@@ -2079,11 +2302,17 @@ gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
 
   /* create a new slice */
   size = ITEM_SIZE (info);
-  item = g_slice_alloc (size);
+  /* We warn in gst_meta_register() about metas without
+   * init function but let's play safe here and prevent
+   * uninitialized memory
+   */
+  if (!info->init_func)
+    item = g_slice_alloc0 (size);
+  else
+    item = g_slice_alloc (size);
   result = &item->meta;
   result->info = info;
   result->flags = GST_META_FLAG_NONE;
-
   GST_CAT_DEBUG (GST_CAT_BUFFER,
       "alloc metadata %p (%s) of size %" G_GSIZE_FORMAT, result,
       g_type_name (info->type), info->size);
@@ -2093,9 +2322,16 @@ gst_buffer_add_meta (GstBuffer * buffer, const GstMetaInfo * info,
     if (!info->init_func (result, params, buffer))
       goto init_failed;
 
-  /* and add to the list of metadata */
-  item->next = GST_BUFFER_META (buffer);
-  GST_BUFFER_META (buffer) = item;
+  item->seq_num = gst_atomic_int64_inc (&meta_seq);
+  item->next = NULL;
+
+  if (!GST_BUFFER_META (buffer)) {
+    GST_BUFFER_META (buffer) = item;
+    GST_BUFFER_TAIL_META (buffer) = item;
+  } else {
+    GST_BUFFER_TAIL_META (buffer)->next = item;
+    GST_BUFFER_TAIL_META (buffer) = item;
+  }
 
   return result;
 
@@ -2111,7 +2347,7 @@ init_failed:
  * @buffer: a #GstBuffer
  * @meta: a #GstMeta
  *
- * Remove the metadata for @meta on @buffer.
+ * Removes the metadata for @meta on @buffer.
  *
  * Returns: %TRUE if the metadata existed and was removed, %FALSE if no such
  * metadata was on @buffer.
@@ -2135,10 +2371,18 @@ gst_buffer_remove_meta (GstBuffer * buffer, GstMeta * meta)
       const GstMetaInfo *info = meta->info;
 
       /* remove from list */
+      if (GST_BUFFER_TAIL_META (buffer) == walk) {
+        if (prev != walk)
+          GST_BUFFER_TAIL_META (buffer) = prev;
+        else
+          GST_BUFFER_TAIL_META (buffer) = NULL;
+      }
+
       if (GST_BUFFER_META (buffer) == walk)
         GST_BUFFER_META (buffer) = walk->next;
       else
         prev->next = walk->next;
+
       /* call free_func if any */
       if (info->free_func)
         info->free_func (m, buffer);
@@ -2153,11 +2397,11 @@ gst_buffer_remove_meta (GstBuffer * buffer, GstMeta * meta)
 }
 
 /**
- * gst_buffer_iterate_meta:
+ * gst_buffer_iterate_meta: (skip)
  * @buffer: a #GstBuffer
- * @state: an opaque state pointer
+ * @state: (out caller-allocates): an opaque state pointer
  *
- * Retrieve the next #GstMeta after @current. If @state points
+ * Retrieves the next #GstMeta after @current. If @state points
  * to %NULL, the first metadata is returned.
  *
  * @state will be updated with an opaque state pointer
@@ -2188,15 +2432,58 @@ gst_buffer_iterate_meta (GstBuffer * buffer, gpointer * state)
 }
 
 /**
+ * gst_buffer_iterate_meta_filtered: (skip)
+ * @buffer: a #GstBuffer
+ * @state: (out caller-allocates): an opaque state pointer
+ * @meta_api_type: only return #GstMeta of this type
+ *
+ * Retrieves the next #GstMeta of type @meta_api_type after the current one
+ * according to @state. If @state points to %NULL, the first metadata of
+ * type @meta_api_type is returned.
+ *
+ * @state will be updated with an opaque state pointer
+ *
+ * Returns: (transfer none) (nullable): The next #GstMeta of type
+ * @meta_api_type or %NULL when there are no more items.
+ *
+ * Since: 1.12
+ */
+GstMeta *
+gst_buffer_iterate_meta_filtered (GstBuffer * buffer, gpointer * state,
+    GType meta_api_type)
+{
+  GstMetaItem **meta;
+
+  g_return_val_if_fail (buffer != NULL, NULL);
+  g_return_val_if_fail (state != NULL, NULL);
+
+  meta = (GstMetaItem **) state;
+  if (*meta == NULL)
+    /* state NULL, move to first item */
+    *meta = GST_BUFFER_META (buffer);
+  else
+    /* state !NULL, move to next item in list */
+    *meta = (*meta)->next;
+
+  while (*meta != NULL && (*meta)->meta.info->api != meta_api_type)
+    *meta = (*meta)->next;
+
+  if (*meta)
+    return &(*meta)->meta;
+  else
+    return NULL;
+}
+
+/**
  * gst_buffer_foreach_meta:
  * @buffer: a #GstBuffer
  * @func: (scope call): a #GstBufferForeachMetaFunc to call
  * @user_data: (closure): user data passed to @func
  *
- * Call @func with @user_data for each meta in @buffer.
+ * Calls @func with @user_data for each meta in @buffer.
  *
  * @func can modify the passed meta pointer or its contents. The return value
- * of @func define if this function returns or if the remaining metadata items
+ * of @func defines if this function returns or if the remaining metadata items
  * in the buffer should be skipped.
  *
  * Returns: %FALSE when @func returned %FALSE for one of the metadata.
@@ -2231,9 +2518,16 @@ gst_buffer_foreach_meta (GstBuffer * buffer, GstBufferForeachMetaFunc func,
       g_return_val_if_fail (!GST_META_FLAG_IS_SET (m, GST_META_FLAG_LOCKED),
           FALSE);
 
+      if (GST_BUFFER_TAIL_META (buffer) == walk) {
+        if (prev != walk)
+          GST_BUFFER_TAIL_META (buffer) = prev;
+        else
+          GST_BUFFER_TAIL_META (buffer) = NULL;
+      }
+
       /* remove from list */
       if (GST_BUFFER_META (buffer) == walk)
-        GST_BUFFER_META (buffer) = next;
+        prev = GST_BUFFER_META (buffer) = next;
       else
         prev->next = next;
 
@@ -2243,6 +2537,8 @@ gst_buffer_foreach_meta (GstBuffer * buffer, GstBufferForeachMetaFunc func,
 
       /* and free the slice */
       g_slice_free1 (ITEM_SIZE (info), walk);
+    } else {
+      prev = walk;
     }
     if (!res)
       break;
@@ -2256,7 +2552,7 @@ gst_buffer_foreach_meta (GstBuffer * buffer, GstBufferForeachMetaFunc func,
  * @offset: the offset to extract
  * @size: the size to extract
  * @dest: (array length=dest_size) (element-type guint8) (out): A pointer where
- *  the destination array will be written.
+ *  the destination array will be written. Might be %NULL if the size is 0.
  * @dest_size: (out): A location where the size of @dest can be written
  *
  * Extracts a copy of at most @size bytes the data at @offset into
@@ -2269,26 +2565,31 @@ void
 gst_buffer_extract_dup (GstBuffer * buffer, gsize offset, gsize size,
     gpointer * dest, gsize * dest_size)
 {
-  gsize real_size;
+  gsize real_size, alloc_size;
 
   real_size = gst_buffer_get_size (buffer);
 
-  *dest = g_malloc (MIN (real_size - offset, size));
-
-  *dest_size = gst_buffer_extract (buffer, offset, *dest, size);
+  alloc_size = MIN (real_size - offset, size);
+  if (alloc_size == 0) {
+    *dest = NULL;
+    *dest_size = 0;
+  } else {
+    *dest = g_malloc (alloc_size);
+    *dest_size = gst_buffer_extract (buffer, offset, *dest, size);
+  }
 }
 
-GST_DEBUG_CATEGORY (gst_parent_buffer_meta_debug);
+GST_DEBUG_CATEGORY_STATIC (gst_parent_buffer_meta_debug);
 
 /**
  * gst_buffer_add_parent_buffer_meta:
  * @buffer: (transfer none): a #GstBuffer
  * @ref: (transfer none): a #GstBuffer to ref
  *
- * Add a #GstParentBufferMeta to @buffer that holds a reference on
+ * Adds a #GstParentBufferMeta to @buffer that holds a reference on
  * @ref until the buffer is freed.
  *
- * Returns: (transfer none): The #GstParentBufferMeta that was added to the buffer
+ * Returns: (transfer none) (nullable): The #GstParentBufferMeta that was added to the buffer
  *
  * Since: 1.6
  */
@@ -2351,11 +2652,11 @@ static gboolean
 _gst_parent_buffer_meta_init (GstParentBufferMeta * parent_meta,
     gpointer params, GstBuffer * buffer)
 {
-  static volatile gsize _init;
+  static gsize _init;
 
   if (g_once_init_enter (&_init)) {
-    GST_DEBUG_CATEGORY_INIT (gst_parent_buffer_meta_debug, "glbufferrefmeta", 0,
-        "glbufferrefmeta");
+    GST_DEBUG_CATEGORY_INIT (gst_parent_buffer_meta_debug, "parentbuffermeta",
+        0, "parentbuffermeta");
     g_once_init_leave (&_init, 1);
   }
 
@@ -2364,10 +2665,13 @@ _gst_parent_buffer_meta_init (GstParentBufferMeta * parent_meta,
   return TRUE;
 }
 
+/**
+ * gst_parent_buffer_meta_api_get_type: (attributes doc.skip=true)
+ */
 GType
 gst_parent_buffer_meta_api_get_type (void)
 {
-  static volatile GType type = 0;
+  static GType type = 0;
   static const gchar *tags[] = { NULL };
 
   if (g_once_init_enter (&type)) {
@@ -2381,7 +2685,7 @@ gst_parent_buffer_meta_api_get_type (void)
 /**
  * gst_parent_buffer_meta_get_info:
  *
- * Get the global #GstMetaInfo describing  the #GstParentBufferMeta meta.
+ * Gets the global #GstMetaInfo describing  the #GstParentBufferMeta meta.
  *
  * Returns: (transfer none): The #GstMetaInfo
  *
@@ -2392,7 +2696,7 @@ gst_parent_buffer_meta_get_info (void)
 {
   static const GstMetaInfo *meta_info = NULL;
 
-  if (g_once_init_enter (&meta_info)) {
+  if (g_once_init_enter ((GstMetaInfo **) & meta_info)) {
     const GstMetaInfo *meta =
         gst_meta_register (gst_parent_buffer_meta_api_get_type (),
         "GstParentBufferMeta",
@@ -2400,8 +2704,334 @@ gst_parent_buffer_meta_get_info (void)
         (GstMetaInitFunction) _gst_parent_buffer_meta_init,
         (GstMetaFreeFunction) _gst_parent_buffer_meta_free,
         _gst_parent_buffer_meta_transform);
-    g_once_init_leave (&meta_info, meta);
+    g_once_init_leave ((GstMetaInfo **) & meta_info, (GstMetaInfo *) meta);
   }
 
   return meta_info;
 }
+
+GST_DEBUG_CATEGORY_STATIC (gst_reference_timestamp_meta_debug);
+
+/**
+ * gst_buffer_add_reference_timestamp_meta:
+ * @buffer: (transfer none): a #GstBuffer
+ * @reference: (transfer none): identifier for the timestamp reference.
+ * @timestamp: timestamp
+ * @duration: duration, or %GST_CLOCK_TIME_NONE
+ *
+ * Adds a #GstReferenceTimestampMeta to @buffer that holds a @timestamp and
+ * optionally @duration based on a specific timestamp @reference. See the
+ * documentation of #GstReferenceTimestampMeta for details.
+ *
+ * Returns: (transfer none) (nullable): The #GstReferenceTimestampMeta that was added to the buffer
+ *
+ * Since: 1.14
+ */
+GstReferenceTimestampMeta *
+gst_buffer_add_reference_timestamp_meta (GstBuffer * buffer,
+    GstCaps * reference, GstClockTime timestamp, GstClockTime duration)
+{
+  GstReferenceTimestampMeta *meta;
+
+  g_return_val_if_fail (GST_IS_CAPS (reference), NULL);
+  g_return_val_if_fail (timestamp != GST_CLOCK_TIME_NONE, NULL);
+
+  meta =
+      (GstReferenceTimestampMeta *) gst_buffer_add_meta (buffer,
+      GST_REFERENCE_TIMESTAMP_META_INFO, NULL);
+
+  if (!meta)
+    return NULL;
+
+  meta->reference = gst_caps_ref (reference);
+  meta->timestamp = timestamp;
+  meta->duration = duration;
+
+  return meta;
+}
+
+/**
+ * gst_buffer_get_reference_timestamp_meta:
+ * @buffer: a #GstBuffer
+ * @reference: (allow-none): a reference #GstCaps
+ *
+ * Finds the first #GstReferenceTimestampMeta on @buffer that conforms to
+ * @reference. Conformance is tested by checking if the meta's reference is a
+ * subset of @reference.
+ *
+ * Buffers can contain multiple #GstReferenceTimestampMeta metadata items.
+ *
+ * Returns: (transfer none) (nullable): the #GstReferenceTimestampMeta or %NULL when there
+ * is no such metadata on @buffer.
+ *
+ * Since: 1.14
+ */
+GstReferenceTimestampMeta *
+gst_buffer_get_reference_timestamp_meta (GstBuffer * buffer,
+    GstCaps * reference)
+{
+  gpointer state = NULL;
+  GstMeta *meta;
+  const GstMetaInfo *info = GST_REFERENCE_TIMESTAMP_META_INFO;
+
+  while ((meta = gst_buffer_iterate_meta (buffer, &state))) {
+    if (meta->info->api == info->api) {
+      GstReferenceTimestampMeta *rmeta = (GstReferenceTimestampMeta *) meta;
+
+      if (!reference)
+        return rmeta;
+      if (gst_caps_is_subset (rmeta->reference, reference))
+        return rmeta;
+    }
+  }
+  return NULL;
+}
+
+static gboolean
+_gst_reference_timestamp_meta_transform (GstBuffer * dest, GstMeta * meta,
+    GstBuffer * buffer, GQuark type, gpointer data)
+{
+  GstReferenceTimestampMeta *dmeta, *smeta;
+
+  /* we copy over the reference timestamp meta, independent of transformation
+   * that happens. If it applied to the original buffer, it still applies to
+   * the new buffer as it refers to the time when the media was captured */
+  smeta = (GstReferenceTimestampMeta *) meta;
+  dmeta =
+      gst_buffer_add_reference_timestamp_meta (dest, smeta->reference,
+      smeta->timestamp, smeta->duration);
+  if (!dmeta)
+    return FALSE;
+
+  GST_CAT_DEBUG (gst_reference_timestamp_meta_debug,
+      "copy reference timestamp metadata from buffer %p to %p", buffer, dest);
+
+  return TRUE;
+}
+
+static void
+_gst_reference_timestamp_meta_free (GstReferenceTimestampMeta * meta,
+    GstBuffer * buffer)
+{
+  if (meta->reference)
+    gst_caps_unref (meta->reference);
+}
+
+static gboolean
+_gst_reference_timestamp_meta_init (GstReferenceTimestampMeta * meta,
+    gpointer params, GstBuffer * buffer)
+{
+  static gsize _init;
+
+  if (g_once_init_enter (&_init)) {
+    GST_DEBUG_CATEGORY_INIT (gst_reference_timestamp_meta_debug,
+        "referencetimestampmeta", 0, "referencetimestampmeta");
+    g_once_init_leave (&_init, 1);
+  }
+
+  meta->reference = NULL;
+  meta->timestamp = GST_CLOCK_TIME_NONE;
+  meta->duration = GST_CLOCK_TIME_NONE;
+
+  return TRUE;
+}
+
+/**
+ * gst_reference_timestamp_meta_api_get_type: (attributes doc.skip=true)
+ */
+GType
+gst_reference_timestamp_meta_api_get_type (void)
+{
+  static GType type = 0;
+  static const gchar *tags[] = { NULL };
+
+  if (g_once_init_enter (&type)) {
+    GType _type =
+        gst_meta_api_type_register ("GstReferenceTimestampMetaAPI", tags);
+    g_once_init_leave (&type, _type);
+  }
+
+  return type;
+}
+
+/**
+ * gst_reference_timestamp_meta_get_info:
+ *
+ * Gets the global #GstMetaInfo describing the #GstReferenceTimestampMeta meta.
+ *
+ * Returns: (transfer none): The #GstMetaInfo
+ *
+ * Since: 1.14
+ */
+const GstMetaInfo *
+gst_reference_timestamp_meta_get_info (void)
+{
+  static const GstMetaInfo *meta_info = NULL;
+
+  if (g_once_init_enter ((GstMetaInfo **) & meta_info)) {
+    const GstMetaInfo *meta =
+        gst_meta_register (gst_reference_timestamp_meta_api_get_type (),
+        "GstReferenceTimestampMeta",
+        sizeof (GstReferenceTimestampMeta),
+        (GstMetaInitFunction) _gst_reference_timestamp_meta_init,
+        (GstMetaFreeFunction) _gst_reference_timestamp_meta_free,
+        _gst_reference_timestamp_meta_transform);
+    g_once_init_leave ((GstMetaInfo **) & meta_info, (GstMetaInfo *) meta);
+  }
+
+  return meta_info;
+}
+
+/**
+ * gst_buffer_add_custom_meta:
+ * @buffer: (transfer none): a #GstBuffer
+ * @name: the registered name of the desired custom meta
+ *
+ * Creates and adds a #GstCustomMeta for the desired @name. @name must have
+ * been successfully registered with gst_meta_register_custom().
+ *
+ * Returns: (transfer none) (nullable): The #GstCustomMeta that was added to the buffer
+ *
+ * Since: 1.20
+ */
+GstCustomMeta *
+gst_buffer_add_custom_meta (GstBuffer * buffer, const gchar * name)
+{
+  GstCustomMeta *meta;
+  const GstMetaInfo *info;
+
+  g_return_val_if_fail (name != NULL, NULL);
+  g_return_val_if_fail (GST_IS_BUFFER (buffer), NULL);
+
+  info = gst_meta_get_info (name);
+
+  if (info == NULL || !gst_meta_info_is_custom (info))
+    return NULL;
+
+  meta = (GstCustomMeta *) gst_buffer_add_meta (buffer, info, NULL);
+
+  return meta;
+}
+
+/**
+ * gst_buffer_get_custom_meta:
+ * @buffer: a #GstBuffer
+ * @name: the registered name of the custom meta to retrieve.
+ *
+ * Finds the first #GstCustomMeta on @buffer for the desired @name.
+ *
+ * Returns: (transfer none) (nullable): the #GstCustomMeta
+ *
+ * Since: 1.20
+ */
+GstCustomMeta *
+gst_buffer_get_custom_meta (GstBuffer * buffer, const gchar * name)
+{
+  const GstMetaInfo *info;
+
+  g_return_val_if_fail (buffer != NULL, NULL);
+  g_return_val_if_fail (name != NULL, NULL);
+
+  info = gst_meta_get_info (name);
+
+  if (!info)
+    return NULL;
+
+  if (!gst_meta_info_is_custom (info))
+    return NULL;
+
+  return (GstCustomMeta *) gst_buffer_get_meta (buffer, info->api);
+}
+
+/**
+ * gst_buffer_ref: (skip)
+ * @buf: a #GstBuffer.
+ *
+ * Increases the refcount of the given buffer by one.
+ *
+ * Note that the refcount affects the writability
+ * of @buf and its metadata, see gst_buffer_is_writable().
+ * It is important to note that keeping additional references to
+ * GstBuffer instances can potentially increase the number
+ * of `memcpy` operations in a pipeline.
+ *
+ * Returns: (transfer full): @buf
+ */
+GstBuffer *
+gst_buffer_ref (GstBuffer * buf)
+{
+  return (GstBuffer *) gst_mini_object_ref (GST_MINI_OBJECT_CAST (buf));
+}
+
+/**
+ * gst_buffer_unref: (skip)
+ * @buf: (transfer full): a #GstBuffer.
+ *
+ * Decreases the refcount of the buffer. If the refcount reaches 0, the buffer
+ * with the associated metadata and memory will be freed.
+ */
+void
+gst_buffer_unref (GstBuffer * buf)
+{
+  gst_mini_object_unref (GST_MINI_OBJECT_CAST (buf));
+}
+
+/**
+ * gst_clear_buffer: (skip)
+ * @buf_ptr: a pointer to a #GstBuffer reference
+ *
+ * Clears a reference to a #GstBuffer.
+ *
+ * @buf_ptr must not be %NULL.
+ *
+ * If the reference is %NULL then this function does nothing. Otherwise, the
+ * reference count of the buffer is decreased and the pointer is set to %NULL.
+ *
+ * Since: 1.16
+ */
+void
+gst_clear_buffer (GstBuffer ** buf_ptr)
+{
+  gst_clear_mini_object ((GstMiniObject **) buf_ptr);
+}
+
+/**
+ * gst_buffer_copy: (skip)
+ * @buf: a #GstBuffer.
+ *
+ * Creates a copy of the given buffer. This will only copy the buffer's
+ * data to a newly allocated memory if needed (if the type of memory
+ * requires it), otherwise the underlying data is just referenced.
+ * Check gst_buffer_copy_deep() if you want to force the data
+ * to be copied to newly allocated memory.
+ *
+ * Returns: (transfer full): a new copy of @buf.
+ */
+GstBuffer *
+gst_buffer_copy (const GstBuffer * buf)
+{
+  return GST_BUFFER (gst_mini_object_copy (GST_MINI_OBJECT_CONST_CAST (buf)));
+}
+
+/**
+ * gst_buffer_replace: (skip)
+ * @obuf: (inout) (transfer full) (nullable): pointer to a pointer to
+ *     a #GstBuffer to be replaced.
+ * @nbuf: (transfer none) (allow-none): pointer to a #GstBuffer that will
+ *     replace the buffer pointed to by @obuf.
+ *
+ * Modifies a pointer to a #GstBuffer to point to a different #GstBuffer. The
+ * modification is done atomically (so this is useful for ensuring thread safety
+ * in some cases), and the reference counts are updated appropriately (the old
+ * buffer is unreffed, the new is reffed).
+ *
+ * Either @nbuf or the #GstBuffer pointed to by @obuf may be %NULL.
+ *
+ * Returns: %TRUE when @obuf was different from @nbuf.
+ */
+gboolean
+gst_buffer_replace (GstBuffer ** obuf, GstBuffer * nbuf)
+{
+  return gst_mini_object_replace ((GstMiniObject **) obuf,
+      (GstMiniObject *) nbuf);
+}