gstbuffer.c 69.9 KB
Newer Older
1 2 3 4 5
/* GStreamer
 * Copyright (C) 1999,2000 Erik Walthinsen <omega@cse.ogi.edu>
 *                    2000 Wim Taymans <wtay@chello.be>
 *
 * gstbuffer.c: Buffer operations
Erik Walthinsen's avatar
Erik Walthinsen committed
6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
Tim-Philipp Müller's avatar
Tim-Philipp Müller committed
19 20
 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 * Boston, MA 02110-1301, USA.
Erik Walthinsen's avatar
Erik Walthinsen committed
21
 */
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
22

23 24
/**
 * SECTION:gstbuffer
25
 * @title: GstBuffer
Wim Taymans's avatar
Wim Taymans committed
26 27
 * @short_description: Data-passing buffer type
 * @see_also: #GstPad, #GstMiniObject, #GstMemory, #GstMeta, #GstBufferPool
28
 *
Wim Taymans's avatar
Wim Taymans committed
29 30 31
 * Buffers are the basic unit of data transfer in GStreamer. They contain the
 * timing and offset along with other arbitrary metadata that is associated
 * with the #GstMemory blocks that the buffer contains.
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
32 33
 *
 * Buffers are usually created with gst_buffer_new(). After a buffer has been
Wim Taymans's avatar
Wim Taymans committed
34 35 36
 * 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.
37
 * |[<!-- language="C" -->
38
 *   GstBuffer *buffer;
Wim Taymans's avatar
Wim Taymans committed
39
 *   GstMemory *memory;
40 41 42 43
 *   gint size, width, height, bpp;
 *   ...
 *   size = width * height * bpp;
 *   buffer = gst_buffer_new ();
44
 *   memory = gst_allocator_alloc (NULL, size, NULL);
45
 *   gst_buffer_insert_memory (buffer, -1, memory);
46
 *   ...
47
 * ]|
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
48
 *
49 50
 * Alternatively, use gst_buffer_new_allocate() to create a buffer with
 * preallocated data of a given size.
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
51
 *
Wim Taymans's avatar
Wim Taymans committed
52 53 54
 * Buffers can contain a list of #GstMemory objects. You can retrieve how many
 * memory objects with gst_buffer_n_memory() and you can get a pointer
 * to memory with gst_buffer_peek_memory()
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
55
 *
Wim Taymans's avatar
Wim Taymans committed
56
 * A buffer will usually have timestamps, and a duration, but neither of these
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
57
 * are guaranteed (they may be set to #GST_CLOCK_TIME_NONE). Whenever a
Wim Taymans's avatar
Wim Taymans committed
58
 * meaningful value can be given for these, they should be set. The timestamps
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
59 60
 * and duration are measured in nanoseconds (they are #GstClockTime values).
 *
Wim Taymans's avatar
Wim Taymans committed
61 62 63 64 65
 * The buffer DTS refers to the timestamp when the buffer should be decoded and
 * is usually monotonically increasing. The buffer PTS refers to the timestamp when
 * the buffer content should be presented to the user and is not always
 * monotonically increasing.
 *
66 67
 * A buffer can also have one or both of a start and an end offset. These are
 * media-type specific. For video buffers, the start offset will generally be
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
68 69
 * the frame number. For audio buffers, it will be the number of samples
 * produced so far. For compressed data, it could be the byte offset in a
70 71
 * source or destination file. Likewise, the end offset will be the offset of
 * the end of the buffer. These can only be meaningfully interpreted if you
72
 * know the media type of the buffer (the preceding CAPS event). Either or both
73
 * can be set to #GST_BUFFER_OFFSET_NONE.
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
74
 *
75 76
 * gst_buffer_ref() is used to increase the refcount of a buffer. This must be
 * done when you want to keep a handle to the buffer after pushing it to the
Wim Taymans's avatar
Wim Taymans committed
77 78 79
 * next element. The buffer refcount determines the writability of the buffer, a
 * buffer is only writable when the refcount is exactly 1, i.e. when the caller
 * has the only reference to the buffer.
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
80
 *
81
 * To efficiently create a smaller buffer out of an existing one, you can
Wim Taymans's avatar
Wim Taymans committed
82 83
 * use gst_buffer_copy_region(). This method tries to share the memory objects
 * between the two buffers.
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
84
 *
Wim Taymans's avatar
Wim Taymans committed
85 86 87 88
 * 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
 * only be made when it is necessary.
89
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
90 91
 * Several flags of the buffer can be set and unset with the
 * GST_BUFFER_FLAG_SET() and GST_BUFFER_FLAG_UNSET() macros. Use
92
 * GST_BUFFER_FLAG_IS_SET() to test if a certain #GstBufferFlags flag is set.
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
93
 *
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
94
 * Buffers can be efficiently merged into a larger buffer with
95 96
 * gst_buffer_append(). Copying of memory will only be done when absolutely
 * needed.
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
97
 *
Wim Taymans's avatar
Wim Taymans committed
98 99 100
 * 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
 *
101 102
 * An element should either unref the buffer or push it out on a src pad
 * using gst_pad_push() (see #GstPad).
Thomas Vander Stichele's avatar
Thomas Vander Stichele committed
103
 *
104
 * Buffers are usually freed by unreffing them with gst_buffer_unref(). When
Wim Taymans's avatar
Wim Taymans committed
105 106 107
 * the refcount drops to 0, any memory and metadata pointed to by the buffer is
 * unreffed as well. Buffers allocated from a #GstBufferPool will be returned to
 * the pool when the refcount drops to 0.
Jan Schmidt's avatar
Jan Schmidt committed
108 109 110 111 112 113 114 115
 *
 * The #GstParentBufferMeta is a meta which can be attached to a #GstBuffer
 * to hold a reference to another buffer that is only released when the child
 * #GstBuffer is released.
 *
 * 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
116
 * for re-use. (Since 1.6)
Jan Schmidt's avatar
Jan Schmidt committed
117
 *
118
 */
119
#include "gst_private.h"
Erik Walthinsen's avatar
Erik Walthinsen committed
120

121 122 123 124 125 126 127
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif

128
#include "gstbuffer.h"
129
#include "gstbufferpool.h"
130
#include "gstinfo.h"
131
#include "gstutils.h"
Benjamin Otte's avatar
Benjamin Otte committed
132
#include "gstversion.h"
133

Wim Taymans's avatar
Wim Taymans committed
134
GType _gst_buffer_type = 0;
135

Wim Taymans's avatar
Wim Taymans committed
136
typedef struct _GstMetaItem GstMetaItem;
137

Wim Taymans's avatar
Wim Taymans committed
138
struct _GstMetaItem
139
{
Wim Taymans's avatar
Wim Taymans committed
140 141
  GstMetaItem *next;
  GstMeta meta;
142
};
Wim Taymans's avatar
Wim Taymans committed
143 144 145
#define ITEM_SIZE(info) ((info)->size + sizeof (GstMetaItem))

#define GST_BUFFER_MEM_MAX         16
146

147
#define GST_BUFFER_SLICE_SIZE(b)   (((GstBufferImpl *)(b))->slice_size)
Wim Taymans's avatar
Wim Taymans committed
148 149 150
#define GST_BUFFER_MEM_LEN(b)      (((GstBufferImpl *)(b))->len)
#define GST_BUFFER_MEM_ARRAY(b)    (((GstBufferImpl *)(b))->mem)
#define GST_BUFFER_MEM_PTR(b,i)    (((GstBufferImpl *)(b))->mem[i])
151
#define GST_BUFFER_BUFMEM(b)       (((GstBufferImpl *)(b))->bufmem)
Wim Taymans's avatar
Wim Taymans committed
152
#define GST_BUFFER_META(b)         (((GstBufferImpl *)(b))->item)
153 154 155 156 157

typedef struct
{
  GstBuffer buffer;

158 159
  gsize slice_size;

Wim Taymans's avatar
Wim Taymans committed
160
  /* the memory blocks */
Wim Taymans's avatar
Wim Taymans committed
161 162 163
  guint len;
  GstMemory *mem[GST_BUFFER_MEM_MAX];

164 165 166
  /* memory of the buffer when allocated from 1 chunk */
  GstMemory *bufmem;

Wim Taymans's avatar
Wim Taymans committed
167 168
  /* FIXME, make metadata allocation more efficient by using part of the
   * GstBufferImpl */
169 170 171
  GstMetaItem *item;
} GstBufferImpl;

Wim Taymans's avatar
Wim Taymans committed
172 173

static gboolean
174
_is_span (GstMemory ** mem, gsize len, gsize * poffset, GstMemory ** parent)
Wim Taymans's avatar
Wim Taymans committed
175 176 177
{
  GstMemory *mcur, *mprv;
  gboolean have_offset = FALSE;
178
  gsize i;
Wim Taymans's avatar
Wim Taymans committed
179 180

  mcur = mprv = NULL;
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

  for (i = 0; i < len; i++) {
    if (mcur)
      mprv = mcur;
    mcur = mem[i];

    if (mprv && mcur) {
      gsize poffs;

      /* check if memory is contiguous */
      if (!gst_memory_is_span (mprv, mcur, &poffs))
        return FALSE;

      if (!have_offset) {
        if (poffset)
          *poffset = poffs;
        if (parent)
          *parent = mprv->parent;

        have_offset = TRUE;
Wim Taymans's avatar
Wim Taymans committed
201 202 203 204 205 206 207
      }
    }
  }
  return have_offset;
}

static GstMemory *
208
_get_merged_memory (GstBuffer * buffer, guint idx, guint length)
Wim Taymans's avatar
Wim Taymans committed
209
{
210
  GstMemory **mem, *result = NULL;
Wim Taymans's avatar
Wim Taymans committed
211

Wim Taymans's avatar
Wim Taymans committed
212 213
  GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %u, length %u", buffer, idx,
      length);
Wim Taymans's avatar
Wim Taymans committed
214

215 216
  mem = GST_BUFFER_MEM_ARRAY (buffer);

217
  if (G_UNLIKELY (length == 0)) {
218
    result = NULL;
219 220
  } else if (G_LIKELY (length == 1)) {
    result = gst_memory_ref (mem[idx]);
Wim Taymans's avatar
Wim Taymans committed
221
  } else {
222
    GstMemory *parent = NULL;
223
    gsize size, poffset = 0;
Wim Taymans's avatar
Wim Taymans committed
224

225
    size = gst_buffer_get_sizes_range (buffer, idx, length, NULL, NULL);
Wim Taymans's avatar
Wim Taymans committed
226

227
    if (G_UNLIKELY (_is_span (mem + idx, length, &poffset, &parent))) {
228 229 230
      if (!GST_MEMORY_IS_NO_SHARE (parent))
        result = gst_memory_share (parent, poffset, size);
      if (!result) {
231 232 233 234 235 236 237 238 239
        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);
240 241 242 243 244 245
      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;
      }
Wim Taymans's avatar
Wim Taymans committed
246

247 248
      ptr = dinfo.data;
      left = size;
Wim Taymans's avatar
Wim Taymans committed
249

250
      for (i = idx; i < (idx + length) && left > 0; i++) {
251 252 253 254 255 256 257 258
        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;
        }
Wim Taymans's avatar
Wim Taymans committed
259 260
        tocopy = MIN (sinfo.size, left);
        GST_CAT_DEBUG (GST_CAT_PERFORMANCE,
Wim Taymans's avatar
Wim Taymans committed
261 262
            "memcpy %" G_GSIZE_FORMAT " bytes for merge %p from memory %p",
            tocopy, result, mem[i]);
Wim Taymans's avatar
Wim Taymans committed
263 264 265
        memcpy (ptr, (guint8 *) sinfo.data, tocopy);
        left -= tocopy;
        ptr += tocopy;
266
        gst_memory_unmap (mem[i], &sinfo);
Wim Taymans's avatar
Wim Taymans committed
267
      }
268
      gst_memory_unmap (result, &dinfo);
Wim Taymans's avatar
Wim Taymans committed
269
    }
270
  }
271
  return result;
272 273
}

Wim Taymans's avatar
Wim Taymans committed
274
static void
275 276
_replace_memory (GstBuffer * buffer, guint len, guint idx, guint length,
    GstMemory * mem)
Wim Taymans's avatar
Wim Taymans committed
277
{
278
  gsize end, i;
279

280
  end = idx + length;
Wim Taymans's avatar
Wim Taymans committed
281

Wim Taymans's avatar
Wim Taymans committed
282 283 284
  GST_CAT_LOG (GST_CAT_BUFFER,
      "buffer %p replace %u-%" G_GSIZE_FORMAT " with memory %p", buffer, idx,
      end, mem);
285

286
  /* unref old memory */
Wim Taymans's avatar
Wim Taymans committed
287
  for (i = idx; i < end; i++) {
288 289 290 291
    GstMemory *old = GST_BUFFER_MEM_PTR (buffer, i);

    gst_memory_unlock (old, GST_LOCK_FLAG_EXCLUSIVE);
    gst_memory_unref (old);
Wim Taymans's avatar
Wim Taymans committed
292
  }
293

Wim Taymans's avatar
Wim Taymans committed
294 295
  if (mem != NULL) {
    /* replace with single memory */
Wim Taymans's avatar
Wim Taymans committed
296
    gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
Wim Taymans's avatar
Wim Taymans committed
297 298 299 300 301 302
    GST_BUFFER_MEM_PTR (buffer, idx) = mem;
    idx++;
    length--;
  }

  if (end < len) {
303
    memmove (&GST_BUFFER_MEM_PTR (buffer, idx),
304 305
        &GST_BUFFER_MEM_PTR (buffer, end), (len - end) * sizeof (gpointer));
  }
Wim Taymans's avatar
Wim Taymans committed
306
  GST_BUFFER_MEM_LEN (buffer) = len - length;
307
  GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
308 309
}

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
/**
 * gst_buffer_get_flags:
 * @buffer: a #GstBuffer
 *
 * Get 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_flag_is_set:
 * @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;
}



381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
/* transfer full for return and transfer none for @mem */
static inline GstMemory *
_memory_get_exclusive_reference (GstMemory * mem)
{
  GstMemory *ret = NULL;

  if (gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE)) {
    ret = gst_memory_ref (mem);
  } else {
    /* we cannot take another exclusive lock as the memory is already
     * locked WRITE + EXCLUSIVE according to part-miniobject.txt */
    ret = gst_memory_copy (mem, 0, -1);

    if (ret) {
      if (!gst_memory_lock (ret, GST_LOCK_FLAG_EXCLUSIVE)) {
        gst_memory_unref (ret);
        ret = NULL;
      }
    }
  }

  if (!ret)
    GST_CAT_WARNING (GST_CAT_BUFFER, "Failed to acquire an exclusive lock for "
        "memory %p", mem);

  return ret;
}

Wim Taymans's avatar
Wim Taymans committed
409
static inline void
410
_memory_add (GstBuffer * buffer, gint idx, GstMemory * mem)
Wim Taymans's avatar
Wim Taymans committed
411
{
412
  guint i, len = GST_BUFFER_MEM_LEN (buffer);
413

414
  GST_CAT_LOG (GST_CAT_BUFFER, "buffer %p, idx %d, mem %p", buffer, idx, mem);
Wim Taymans's avatar
Wim Taymans committed
415

416
  if (G_UNLIKELY (len >= GST_BUFFER_MEM_MAX)) {
Wim Taymans's avatar
Wim Taymans committed
417 418 419 420
    /* too many buffer, span them. */
    /* FIXME, there is room for improvement here: We could only try to merge
     * 2 buffers to make some room. If we can't efficiently merge 2 buffers we
     * could try to only merge the two smallest buffers to avoid memcpy, etc. */
421 422
    GST_CAT_DEBUG (GST_CAT_PERFORMANCE, "memory array overflow in buffer %p",
        buffer);
423
    _replace_memory (buffer, len, 0, len, _get_merged_memory (buffer, 0, len));
424 425 426
    /* we now have 1 single spanned buffer */
    len = 1;
  }
427 428 429 430 431 432 433 434 435 436

  if (idx == -1)
    idx = len;

  for (i = len; i > idx; i--) {
    /* move buffers to insert, FIXME, we need to insert first and then merge */
    GST_BUFFER_MEM_PTR (buffer, i) = GST_BUFFER_MEM_PTR (buffer, i - 1);
  }
  /* and insert the new buffer */
  GST_BUFFER_MEM_PTR (buffer, idx) = mem;
Wim Taymans's avatar
Wim Taymans committed
437
  GST_BUFFER_MEM_LEN (buffer) = len + 1;
438

439
  GST_BUFFER_FLAG_SET (buffer, GST_BUFFER_FLAG_TAG_MEMORY);
Wim Taymans's avatar
Wim Taymans committed
440
}
441

442
GST_DEFINE_MINI_OBJECT_TYPE (GstBuffer, gst_buffer);
Wim Taymans's avatar
Wim Taymans committed
443

444
void
445
_priv_gst_buffer_initialize (void)
Wim Taymans's avatar
Wim Taymans committed
446
{
Wim Taymans's avatar
Wim Taymans committed
447
  _gst_buffer_type = gst_buffer_get_type ();
448 449
}

450 451 452 453 454 455 456 457 458 459 460
/**
 * gst_buffer_get_max_memory:
 *
 * Get 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
 * together to make room for the new block.
 *
 * Returns: the maximum amount of memory blocks that a buffer can hold.
 *
461
 * Since: 1.2
462 463 464 465 466 467 468
 */
guint
gst_buffer_get_max_memory (void)
{
  return GST_BUFFER_MEM_MAX;
}

469
/**
Wim Taymans's avatar
Wim Taymans committed
470
 * gst_buffer_copy_into:
471 472 473
 * @dest: a destination #GstBuffer
 * @src: a source #GstBuffer
 * @flags: flags indicating what metadata fields should be copied.
Wim Taymans's avatar
Wim Taymans committed
474
 * @offset: offset to copy from
Edward Hervey's avatar
Edward Hervey committed
475
 * @size: total size to copy. If -1, all data is copied.
476
 *
Wim Taymans's avatar
Wim Taymans committed
477
 * Copies the information from @src into @dest.
478
 *
479 480 481
 * If @dest already contains memory and @flags contains GST_BUFFER_COPY_MEMORY,
 * the memory from @src will be appended to @dest.
 *
Wim Taymans's avatar
Wim Taymans committed
482
 * @flags indicate which fields will be copied.
483 484
 *
 * Returns: %TRUE if the copying succeeded, %FALSE otherwise.
485
 */
486
gboolean
Wim Taymans's avatar
Wim Taymans committed
487
gst_buffer_copy_into (GstBuffer * dest, GstBuffer * src,
Wim Taymans's avatar
Wim Taymans committed
488
    GstBufferCopyFlags flags, gsize offset, gsize size)
489
{
Wim Taymans's avatar
Wim Taymans committed
490
  GstMetaItem *walk;
Wim Taymans's avatar
Wim Taymans committed
491
  gsize bufsize;
492
  gboolean region = FALSE;
493

494 495
  g_return_val_if_fail (dest != NULL, FALSE);
  g_return_val_if_fail (src != NULL, FALSE);
496

Wim Taymans's avatar
Wim Taymans committed
497 498
  /* nothing to copy if the buffers are the same */
  if (G_UNLIKELY (dest == src))
499
    return TRUE;
Wim Taymans's avatar
Wim Taymans committed
500

501
  g_return_val_if_fail (gst_buffer_is_writable (dest), FALSE);
502

Wim Taymans's avatar
Wim Taymans committed
503
  bufsize = gst_buffer_get_size (src);
504
  g_return_val_if_fail (bufsize >= offset, FALSE);
505 506
  if (offset > 0)
    region = TRUE;
Wim Taymans's avatar
Wim Taymans committed
507 508
  if (size == -1)
    size = bufsize - offset;
509 510
  if (size < bufsize)
    region = TRUE;
511
  g_return_val_if_fail (bufsize >= offset + size, FALSE);
512

Wim Taymans's avatar
Wim Taymans committed
513 514 515
  GST_CAT_LOG (GST_CAT_BUFFER, "copy %p to %p, offset %" G_GSIZE_FORMAT
      "-%" G_GSIZE_FORMAT "/%" G_GSIZE_FORMAT, src, dest, offset, size,
      bufsize);
516 517

  if (flags & GST_BUFFER_COPY_FLAGS) {
518
    /* copy flags */
519 520 521 522 523
    guint flags_mask = ~GST_BUFFER_FLAG_TAG_MEMORY;

    GST_MINI_OBJECT_FLAGS (dest) =
        (GST_MINI_OBJECT_FLAGS (src) & flags_mask) |
        (GST_MINI_OBJECT_FLAGS (dest) & ~flags_mask);
524 525 526
  }

  if (flags & GST_BUFFER_COPY_TIMESTAMPS) {
Wim Taymans's avatar
Wim Taymans committed
527
    if (offset == 0) {
Wim Taymans's avatar
Wim Taymans committed
528 529
      GST_BUFFER_PTS (dest) = GST_BUFFER_PTS (src);
      GST_BUFFER_DTS (dest) = GST_BUFFER_DTS (src);
Wim Taymans's avatar
Wim Taymans committed
530
      GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET (src);
Wim Taymans's avatar
Wim Taymans committed
531
      if (size == bufsize) {
Wim Taymans's avatar
Wim Taymans committed
532 533 534 535
        GST_BUFFER_DURATION (dest) = GST_BUFFER_DURATION (src);
        GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_END (src);
      }
    } else {
Wim Taymans's avatar
Wim Taymans committed
536 537
      GST_BUFFER_PTS (dest) = GST_CLOCK_TIME_NONE;
      GST_BUFFER_DTS (dest) = GST_CLOCK_TIME_NONE;
Wim Taymans's avatar
Wim Taymans committed
538 539 540 541
      GST_BUFFER_DURATION (dest) = GST_CLOCK_TIME_NONE;
      GST_BUFFER_OFFSET (dest) = GST_BUFFER_OFFSET_NONE;
      GST_BUFFER_OFFSET_END (dest) = GST_BUFFER_OFFSET_NONE;
    }
542
  }
543

Wim Taymans's avatar
Wim Taymans committed
544
  if (flags & GST_BUFFER_COPY_MEMORY) {
545
    gsize skip, left, len, dest_len, i, bsize;
546 547 548
    gboolean deep;

    deep = flags & GST_BUFFER_COPY_DEEP;
Wim Taymans's avatar
Wim Taymans committed
549

Wim Taymans's avatar
Wim Taymans committed
550
    len = GST_BUFFER_MEM_LEN (src);
551
    dest_len = GST_BUFFER_MEM_LEN (dest);
Wim Taymans's avatar
Wim Taymans committed
552
    left = size;
553
    skip = offset;
Wim Taymans's avatar
Wim Taymans committed
554

Wim Taymans's avatar
Wim Taymans committed
555
    /* copy and make regions of the memory */
Wim Taymans's avatar
Wim Taymans committed
556
    for (i = 0; i < len && left > 0; i++) {
557 558
      GstMemory *mem = GST_BUFFER_MEM_PTR (src, i);

559
      bsize = gst_memory_get_sizes (mem, NULL, NULL);
Wim Taymans's avatar
Wim Taymans committed
560

561
      if (bsize <= skip) {
Wim Taymans's avatar
Wim Taymans committed
562
        /* don't copy buffer */
563
        skip -= bsize;
Wim Taymans's avatar
Wim Taymans committed
564
      } else {
565
        GstMemory *newmem = NULL;
Wim Taymans's avatar
Wim Taymans committed
566 567
        gsize tocopy;

568
        tocopy = MIN (bsize - skip, left);
569

570
        if (tocopy < bsize && !deep && !GST_MEMORY_IS_NO_SHARE (mem)) {
571
          /* we need to clip something */
572
          newmem = gst_memory_share (mem, skip, tocopy);
573 574
          if (newmem) {
            gst_memory_lock (newmem, GST_LOCK_FLAG_EXCLUSIVE);
575
            skip = 0;
576
          }
577 578
        }

579
        if (deep || GST_MEMORY_IS_NO_SHARE (mem) || (!newmem && tocopy < bsize)) {
580 581
          /* deep copy or we're not allowed to share this memory
           * between buffers, always copy then */
582
          newmem = gst_memory_copy (mem, skip, tocopy);
583 584 585 586
          if (newmem) {
            gst_memory_lock (newmem, GST_LOCK_FLAG_EXCLUSIVE);
            skip = 0;
          }
587
        } else if (!newmem) {
588
          newmem = _memory_get_exclusive_reference (mem);
Wim Taymans's avatar
Wim Taymans committed
589
        }
590

591
        if (!newmem) {
592 593 594
          gst_buffer_remove_memory_range (dest, dest_len, -1);
          return FALSE;
        }
595

596
        _memory_add (dest, -1, newmem);
Wim Taymans's avatar
Wim Taymans committed
597 598
        left -= tocopy;
      }
Wim Taymans's avatar
Wim Taymans committed
599
    }
Wim Taymans's avatar
Wim Taymans committed
600
    if (flags & GST_BUFFER_COPY_MERGE) {
601 602
      GstMemory *mem;

603
      len = GST_BUFFER_MEM_LEN (dest);
604 605 606 607 608 609
      mem = _get_merged_memory (dest, 0, len);
      if (!mem) {
        gst_buffer_remove_memory_range (dest, dest_len, -1);
        return FALSE;
      }
      _replace_memory (dest, len, 0, len, mem);
Wim Taymans's avatar
Wim Taymans committed
610
    }
Wim Taymans's avatar
Wim Taymans committed
611 612
  }

Wim Taymans's avatar
Wim Taymans committed
613
  if (flags & GST_BUFFER_COPY_META) {
614 615 616
    /* NOTE: GstGLSyncMeta copying relies on the meta
     *       being copied now, after the buffer data,
     *       so this has to happen last */
Wim Taymans's avatar
Wim Taymans committed
617 618 619
    for (walk = GST_BUFFER_META (src); walk; walk = walk->next) {
      GstMeta *meta = &walk->meta;
      const GstMetaInfo *info = meta->info;
620

621 622 623 624 625 626 627 628 629 630 631
      /* Don't copy memory metas if we only copied part of the buffer, didn't
       * copy memories or merged memories. In all these cases the memory
       * structure has changed and the memory meta becomes meaningless.
       */
      if ((region || !(flags & GST_BUFFER_COPY_MEMORY)
              || (flags & GST_BUFFER_COPY_MERGE))
          && gst_meta_api_type_has_tag (info->api, _gst_meta_tag_memory)) {
        GST_CAT_DEBUG (GST_CAT_BUFFER,
            "don't copy memory meta %p of API type %s", meta,
            g_type_name (info->api));
      } else if (info->transform_func) {
632 633
        GstMetaTransformCopy copy_data;

634
        copy_data.region = region;
635 636 637
        copy_data.offset = offset;
        copy_data.size = size;

638 639 640 641 642 643
        if (!info->transform_func (dest, meta, src,
                _gst_meta_transform_copy, &copy_data)) {
          GST_CAT_ERROR (GST_CAT_BUFFER,
              "failed to copy meta %p of API type %s", meta,
              g_type_name (info->api));
        }
644
      }
Wim Taymans's avatar
Wim Taymans committed
645
    }
646
  }
647 648

  return TRUE;
649 650
}

651
static GstBuffer *
652
gst_buffer_copy_with_flags (const GstBuffer * buffer, GstBufferCopyFlags flags)
Wim Taymans's avatar
Wim Taymans committed
653
{
654
  GstBuffer *copy;
Erik Walthinsen's avatar
Erik Walthinsen committed
655

Wim Taymans's avatar
Wim Taymans committed
656 657
  g_return_val_if_fail (buffer != NULL, NULL);

658
  /* create a fresh new buffer */
659
  copy = gst_buffer_new ();
660

661 662 663
  /* copy what the 'flags' want from our parent */
  /* FIXME why we can't pass const to gst_buffer_copy_into() ? */
  if (!gst_buffer_copy_into (copy, (GstBuffer *) buffer, flags, 0, -1))
664
    gst_buffer_replace (&copy, NULL);
Erik Walthinsen's avatar
Erik Walthinsen committed
665

666 667
  if (copy)
    GST_BUFFER_FLAG_UNSET (copy, GST_BUFFER_FLAG_TAG_MEMORY);
668

669 670
  return copy;
}
671

672 673 674 675 676 677 678 679 680 681 682 683 684 685
static GstBuffer *
_gst_buffer_copy (const GstBuffer * buffer)
{
  return gst_buffer_copy_with_flags (buffer, GST_BUFFER_COPY_ALL);
}

/**
 * gst_buffer_copy_deep:
 * @buf: a #GstBuffer.
 *
 * Create 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.
686
 *
Nicolas Dufresne's avatar
Nicolas Dufresne committed
687
 * Since: 1.6
688 689 690 691 692 693 694 695
 */
GstBuffer *
gst_buffer_copy_deep (const GstBuffer * buffer)
{
  return gst_buffer_copy_with_flags (buffer,
      GST_BUFFER_COPY_ALL | GST_BUFFER_COPY_DEEP);
}

696 697
/* the default dispose function revives the buffer and returns it to the
 * pool when there is a pool */
698
static gboolean
699 700 701 702
_gst_buffer_dispose (GstBuffer * buffer)
{
  GstBufferPool *pool;

703 704 705 706 707 708 709 710 711 712 713
  /* no pool, do free */
  if ((pool = buffer->pool) == NULL)
    return TRUE;

  /* keep the buffer alive */
  gst_buffer_ref (buffer);
  /* return the buffer to the pool */
  GST_CAT_LOG (GST_CAT_BUFFER, "release %p to pool %p", buffer, pool);
  gst_buffer_pool_release_buffer (pool, buffer);

  return FALSE;
714 715
}

716
static void
717
_gst_buffer_free (GstBuffer * buffer)
718
{
Wim Taymans's avatar
Wim Taymans committed
719
  GstMetaItem *walk, *next;
Wim Taymans's avatar
Wim Taymans committed
720 721
  guint i, len;
  gsize msize;
722

723 724 725
  g_return_if_fail (buffer != NULL);

  GST_CAT_LOG (GST_CAT_BUFFER, "finalize %p", buffer);
726

727
  /* free metadata */
728
  for (walk = GST_BUFFER_META (buffer); walk; walk = next) {
Wim Taymans's avatar
Wim Taymans committed
729 730
    GstMeta *meta = &walk->meta;
    const GstMetaInfo *info = meta->info;
731 732 733 734

    /* call free_func if any */
    if (info->free_func)
      info->free_func (meta, buffer);
735

736
    next = walk->next;
737 738
    /* and free the slice */
    g_slice_free1 (ITEM_SIZE (info), walk);
739 740
  }

Wim Taymans's avatar
Wim Taymans committed
741 742
  /* get the size, when unreffing the memory, we could also unref the buffer
   * itself */
743
  msize = GST_BUFFER_SLICE_SIZE (buffer);
Wim Taymans's avatar
Wim Taymans committed
744 745 746

  /* free our memory */
  len = GST_BUFFER_MEM_LEN (buffer);
Wim Taymans's avatar
Wim Taymans committed
747 748
  for (i = 0; i < len; i++) {
    gst_memory_unlock (GST_BUFFER_MEM_PTR (buffer, i), GST_LOCK_FLAG_EXCLUSIVE);
Wim Taymans's avatar
Wim Taymans committed
749
    gst_memory_unref (GST_BUFFER_MEM_PTR (buffer, i));
Wim Taymans's avatar
Wim Taymans committed
750
  }
Wim Taymans's avatar
Wim Taymans committed
751

752
  /* we set msize to 0 when the buffer is part of the memory block */
753 754 755 756
  if (msize) {
#ifdef USE_POISONING
    memset (buffer, 0xff, msize);
#endif
Wim Taymans's avatar
Wim Taymans committed
757
    g_slice_free1 (msize, buffer);
758
  } else {
759
    gst_memory_unref (GST_BUFFER_BUFMEM (buffer));
760
  }
Wim Taymans's avatar
Wim Taymans committed
761 762 763
}

static void
764
gst_buffer_init (GstBufferImpl * buffer, gsize size)
Wim Taymans's avatar
Wim Taymans committed
765
{
766
  gst_mini_object_init (GST_MINI_OBJECT_CAST (buffer), 0, _gst_buffer_type,
767 768 769
      (GstMiniObjectCopyFunction) _gst_buffer_copy,
      (GstMiniObjectDisposeFunction) _gst_buffer_dispose,
      (GstMiniObjectFreeFunction) _gst_buffer_free);
Wim Taymans's avatar
Wim Taymans committed
770

771 772
  GST_BUFFER_SLICE_SIZE (buffer) = size;

Wim Taymans's avatar
Wim Taymans committed
773
  GST_BUFFER (buffer)->pool = NULL;
Wim Taymans's avatar
Wim Taymans committed
774 775
  GST_BUFFER_PTS (buffer) = GST_CLOCK_TIME_NONE;
  GST_BUFFER_DTS (buffer) = GST_CLOCK_TIME_NONE;
Wim Taymans's avatar
Wim Taymans committed
776 777 778
  GST_BUFFER_DURATION (buffer) = GST_CLOCK_TIME_NONE;
  GST_BUFFER_OFFSET (buffer) = GST_BUFFER_OFFSET_NONE;
  GST_BUFFER_OFFSET_END (buffer) = GST_BUFFER_OFFSET_NONE;
Wim Taymans's avatar
Wim Taymans committed
779

Wim Taymans's avatar
Wim Taymans committed
780 781
  GST_BUFFER_MEM_LEN (buffer) = 0;
  GST_BUFFER_META (buffer) = NULL;
782 783
}

784
/**
785
 * gst_buffer_new:
786
 *
787
 * Creates a newly allocated buffer without any data.
788
 *
789
 * MT safe.
790 791
 *
 * Returns: (transfer full): the new #GstBuffer.
792
 */
793
GstBuffer *
794
gst_buffer_new (void)
Wim Taymans's avatar
Wim Taymans committed
795
{
796
  GstBufferImpl *newbuf;
797

Wim Taymans's avatar
Wim Taymans committed
798
  newbuf = g_slice_new (GstBufferImpl);
799
  GST_CAT_LOG (GST_CAT_BUFFER, "new %p", newbuf);
800

801
  gst_buffer_init (newbuf, sizeof (GstBufferImpl));
802

803
  return GST_BUFFER_CAST (newbuf);
Erik Walthinsen's avatar
Erik Walthinsen committed
804 805
}

806
/**
807
 * gst_buffer_new_allocate:
808
 * @allocator: (transfer none) (allow-none): the #GstAllocator to use, or %NULL to use the
809
 *     default allocator
Wim Taymans's avatar
Wim Taymans committed
810
 * @size: the size in bytes of the new buffer's data.
811
 * @params: (transfer none) (allow-none): optional parameters
812 813
 *
 * Tries to create a newly allocated buffer with data of the given size and
814
 * extra parameters from @allocator. If the requested amount of memory can't be
815
 * allocated, %NULL will be returned. The allocated buffer memory is not cleared.
816
 *
817
 * When @allocator is %NULL, the default memory allocator will be used.
818
 *
Wim Taymans's avatar
Wim Taymans committed
819
 * Note that when @size == 0, the buffer will not have memory associated with it.
820 821 822
 *
 * MT safe.
 *
823 824
 * Returns: (transfer full) (nullable): a new #GstBuffer, or %NULL if
 *     the memory couldn't be allocated.
825 826
 */
GstBuffer *
827 828
gst_buffer_new_allocate (GstAllocator * allocator, gsize size,
    GstAllocationParams * params)
829 830
{
  GstBuffer *newbuf;
Wim Taymans's avatar
Wim Taymans committed
831
  GstMemory *mem;
Wim Taymans's avatar
Wim Taymans committed
832 833 834 835
#if 0
  guint8 *data;
  gsize asize;
#endif
836

Wim Taymans's avatar
Wim Taymans committed
837
#if 1
838
  if (size > 0) {
839
    mem = gst_allocator_alloc (allocator, size, params);
840 841 842 843
    if (G_UNLIKELY (mem == NULL))
      goto no_memory;
  } else {
    mem = NULL;
844
  }
Wim Taymans's avatar
Wim Taymans committed
845 846

  newbuf = gst_buffer_new ();
847

848 849 850 851
  if (mem != NULL) {
    gst_memory_lock (mem, GST_LOCK_FLAG_EXCLUSIVE);
    _memory_add (newbuf, -1, mem);
  }
852

Josep Torra's avatar
Josep Torra committed
853 854
  GST_CAT_LOG (GST_CAT_BUFFER,
      "new buffer %p of size %" G_GSIZE_FORMAT " from allocator %p", newbuf,
Wim Taymans's avatar
Wim Taymans committed
855
      size, allocator);
Wim Taymans's avatar
Wim Taymans committed
856 857 858 859 860 861 862 863 864 865 866 867 868 869
#endif

#if 0
  asize = sizeof (GstBufferImpl) + size;
  data = g_slice_alloc (asize);
  if (G_UNLIKELY (data == NULL))
    goto no_memory;

  newbuf = GST_BUFFER_CAST (data);

  gst_buffer_init ((GstBufferImpl *) data, asize);
  if (size > 0) {
    mem = gst_memory_new_wrapped (0, data + sizeof (GstBufferImpl), NULL,
        size, 0, size);
Wim Taymans's avatar
Wim Taymans committed
870
    _memory_add (newbuf, -1, mem, TRUE);
Wim Taymans's avatar
Wim Taymans committed
871 872 873 874
  }
#endif

#if 0
875 876 877 878
  /* allocate memory and buffer, it might be interesting to do this but there
   * are many complications. We need to keep the memory mapped to access the
   * buffer fields and the memory for the buffer might be just very slow. We
   * also need to do some more magic to get the alignment right. */
Wim Taymans's avatar
Wim Taymans committed
879
  asize = sizeof (GstBufferImpl) + size;
880
  mem = gst_allocator_alloc (allocator, asize, align);
Wim Taymans's avatar
Wim Taymans committed
881 882 883 884 885 886 887
  if (G_UNLIKELY (mem == NULL))
    goto no_memory;

  /* map the data part and init the buffer in it, set the buffer size to 0 so
   * that a finalize won't free the buffer */
  data = gst_memory_map (mem, &asize, NULL, GST_MAP_WRITE);
  gst_buffer_init ((GstBufferImpl *) data, 0);
Wim Taymans's avatar
Wim Taymans committed
888
  gst_memory_unmap (mem);
Wim Taymans's avatar
Wim Taymans committed
889 890

  /* strip off the buffer */
Wim Taymans's avatar
Wim Taymans committed
891
  gst_memory_resize (mem, sizeof (GstBufferImpl), size);
Wim Taymans's avatar
Wim Taymans committed
892 893

  newbuf = GST_BUFFER_CAST (data);
894
  GST_BUFFER_BUFMEM (newbuf) = mem;
Wim Taymans's avatar
Wim Taymans committed
895 896

  if (size > 0)
Wim Taymans's avatar
Wim Taymans committed
897
    _memory_add (newbuf, -1, gst_memory_ref (mem), TRUE);
Wim Taymans's avatar
Wim Taymans committed
898
#endif
899
  GST_BUFFER_FLAG_UNSET (newbuf, GST_BUFFER_FLAG_TAG_MEMORY);
Wim Taymans's avatar
Wim Taymans committed
900 901

  return newbuf;
902 903 904 905

  /* ERRORS */
no_memory:
  {
Josep Torra's avatar
Josep Torra committed
906 907
    GST_CAT_WARNING (GST_CAT_BUFFER,
        "failed to allocate %" G_GSIZE_FORMAT " bytes", size);
908 909
    return NULL;
  }
Erik Walthinsen's avatar
Erik Walthinsen committed
910 911
}

912 913
/**
 * gst_buffer_new_wrapped_full:
914
 * @flags: #GstMemoryFlags
915
 * @data: (array length=size) (element-type guint8) (transfer none): data to wrap
916 917 918
 * @maxsize: allocated size of @data
 * @offset: offset in @data
 * @size: size of valid data
919 920
 * @user_data: (allow-none): user_data
 * @notify: (allow-none) (scope async) (closure user_data): called with @user_data when the memory is freed
921
 *
922 923 924
 * Allocate 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.