Using special memory

In some cases, it might be useful to use specially allocated memory (e.g. mmap ()'ed DMA'able memory) in your buffers, and those will require special handling when they are being dereferenced. For this, GStreamer uses the concept of buffer-free functions. Those are special functions pointers that an element can set on buffers that it created itself. The given function will be called when the buffer has been dereferenced, so that the element can clean up or re-use memory internally rather than using the default implementation (which simply calls g_free () on the data pointer).


static void
gst_my_source_buffer_free (GstBuffer *buf)
{
  GstMySource *src = GST_MY_SOURCE (GST_BUFFER_PRIVATE (buf));

  /* do useful things here, like re-queueing the buffer which
   * makes it available for DMA again. The default handler will
   * not free this buffer because of the GST_BUFFER_DONTFREE
   * flag. */
}

static GstData *
gst_my_source_get (GstPad *pad)
{
  GstMySource *src = GST_MY_SOURCE (gst_pad_get_parent (pad));
  GstBuffer *buf;
[..]
  buf = gst_buffer_new ();
  GST_BUFFER_FREE_DATA_FUNC (buf) = gst_my_source_buffer_free;
  GST_BUFFER_PRIVATE (buf) = src;
  GST_BUFFER_FLAG_SET (buf, GST_BUFFER_READONLY | GST_BUFFER_DONTFREE);
[..]

  return GST_DATA (buf);
}
    

Note that this concept should not be used to decrease the number of calls made to functions such as g_malloc () inside your element. We have better ways of doing that elsewhere (GStreamer core, Glib, Glibc, Linux kernel, etc.).