5.2. Creating a GstElement

The simplest way to create an element is to use gst_element_factory_make (). This function takes a factory name and an element name for the newly created element. The name of the element is something you can use later on to look up the element in a bin, for example. The name will also be used in debug output. You can pass NULL as the name argument to get a unique, default name.

When you don't need the element anymore, you need to unref it using gst_object_unref (). This decreases the reference count for the element by 1. An element has a refcount of 1 when it gets created. An element gets destroyed completely when the refcount is decreased to 0.

The following example [1] shows how to create an element named source from the element factory named fakesrc. It checks if the creation succeeded. After checking, it unrefs the element.


#include <gst/gst.h>

int
main (int   argc,
      char *argv[])
{
  GstElement *element;

  /* init GStreamer */
  gst_init (&argc, &argv);

  /* create element */
  element = gst_element_factory_make ("fakesrc", "source");
  if (!element) {
    g_print ("Failed to create element of type 'fakesrc'\n");
    return -1;
  }

  gst_object_unref (GST_OBJECT (element));

  return 0;
}
    

gst_element_factory_make is actually a shorthand for a combination of two functions. A GstElement object is created from a factory. To create the element, you have to get access to a GstElementFactory object using a unique factory name. This is done with gst_element_factory_find ().

The following code fragment is used to get a factory that can be used to create the fakesrc element, a fake data source. The function gst_element_factory_create () will use the element factory to create an element with the given name.


#include <gst/gst.h>

int
main (int   argc,
      char *argv[])
{
  GstElementFactory *factory;
  GstElement * element;

  /* init GStreamer */
  gst_init (&argc, &argv);

  /* create element, method #2 */
  factory = gst_element_factory_find ("fakesrc");
  if (!factory) {
    g_print ("Failed to find factory of type 'fakesrc'\n");
    return -1;
  }
  element = gst_element_factory_create (factory, "source");
  if (!element) {
    g_print ("Failed to create element, even though its factory exists!\n");
    return -1;
  }

  gst_object_unref (GST_OBJECT (element));

  return 0;
}
    

Notes

[1]

The code for this example is automatically extracted from the documentation and built under examples/manual in the GStreamer tarball.