GStreamer基础教程04 - 动态连接Pipeline

摘要

在以前的文章中,我们了解到了2种播放文件的方式:一种是在知道了文件的类型及编码方式后,手动创建所需Element并构造Pipeline;另一种是直接使用playbin,由playbin内部动态创建所需Element并连接Pipeline。很明显使用playbin的方式更加灵活,我们不需要在一开始就创建各种Pipeline,只需由playbin内部根据文件类型,自动构造Pipeline。 在了解了Pad的作用后,本文通过一个例子来了解如何通过Pad事件动态的连接Pipeline,为了解playbin内部是如何动态创建Pipeline打下基础。

 

动态连接Pipeline

在本章的例子中,我们在将Pipeline设置为PLAYING状态之前,不会将所有的Element都连接起来,这种处理方式是可以的,但需要额外的处理。如果在设置PLAYING状态后不做任何操作,数据无法到达Sink,Pipeline会直接抛出一个错误并退出。如果在收到相应事件后,对其进行处理,并将Pipeline连接起来,Pipeline就可以正常工作。

我们常见的媒体,音频和视频都是通过某一种容器格式被包含中同一个文件中。播放时,我们需要将音视频数据分离出来,通常将具备这种功能的模块称为分离器(demuxer)。

GStreamer针对常见的容器提供了相应的demuxer,如果一个容器文件中包含多种媒体数据(例如:一路视频,两路音频),这种情况下,demuxer会为些数据分别创建不同的Source Pad,每一个Source Pad可以被认为一个处理分支,可以创建多个分支分别处理相应的数据。

gst-launch-1.0 filesrc location=sintel_trailer-480p.ogv ! oggdemux name=demux ! queue ! vorbisdec ! autoaudiosink demux. ! queue ! theoradec ! videoconvert ! autovideosink
通过上面的命令播放文件时,会创建具有2个分支的Pipeline:

使用demuxer需要注意的一点是:demuxer只有在收到足够的数据时才能确定容器中包含哪些媒体信息,因此demuxer开始没有Source Pad,所以其他的Element无法在Pipeline创建时就连接到demuxer。
解决这种问题的办法是:在创建Pipeline时,我们只将Source Element到demuxer之间的Elements连接好,然后设置Pipeline状态为PLAYING,当demuxer收到足够的数据可以确定文件总包含哪些媒体流时,demuxer会创建相应的Source Pad,并通过事件告诉应用程序。我们可以通过监听demuxer的事件,在新的Source Pad被创建时,我们根据数据类型,创建相应的Element,再将其连接到Source Pad,形成完整的Pipeline。

 

示例代码

为了简化逻辑,我们在本示例中会忽略视频的Source Pad,仅连接音频的Source Pad。

#include <gst/gst.h>

/* Structure to contain all our information, so we can pass it to callbacks */
typedef struct _CustomData {
  GstElement *pipeline;
  GstElement *source;
  GstElement *convert;
  GstElement *sink;
} CustomData;

/* Handler for the pad-added signal */
static void pad_added_handler (GstElement *src, GstPad *pad, CustomData *data);

int main(int argc, char *argv[]) {
  CustomData data;
  GstBus *bus;
  GstMessage *msg;
  GstStateChangeReturn ret;
  gboolean terminate = FALSE;

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

  /* Create the elements */
  data.source = gst_element_factory_make ("uridecodebin", "source");
  data.convert = gst_element_factory_make ("audioconvert", "convert");
  data.sink = gst_element_factory_make ("autoaudiosink", "sink");

  /* Create the empty pipeline */
  data.pipeline = gst_pipeline_new ("test-pipeline");

  if (!data.pipeline || !data.source || !data.convert || !data.sink) {
    g_printerr ("Not all elements could be created.\n");
    return -1;
  }

  /* Build the pipeline. Note that we are NOT linking the source at this
   * point. We will do it later. */
  gst_bin_add_many (GST_BIN (data.pipeline), data.source, data.convert , data.sink, NULL);
  if (!gst_element_link (data.convert, data.sink)) {
    g_printerr ("Elements could not be linked.\n");
    gst_object_unref (data.pipeline);
    return -1;
  }

  /* Set the URI to play */
  g_object_set (data.source, "uri", "https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm", NULL);

  /* Connect to the pad-added signal */
  g_signal_connect (data.source, "pad-added", G_CALLBACK (pad_added_handler), &data);

  /* Start playing */
  ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING);
  if (ret == GST_STATE_CHANGE_FAILURE) {
    g_printerr ("Unable to set the pipeline to the playing state.\n");
    gst_object_unref (data.pipeline);
    return -1;
  }

  /* Listen to the bus */
  bus = gst_element_get_bus (data.pipeline);
  do {
    msg = gst_bus_timed_pop_filtered (bus, GST_CLOCK_TIME_NONE,
        GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS);

    /* Parse message */
    if (msg != NULL) {
      GError *err;
      gchar *debug_info;

      switch (GST_MESSAGE_TYPE (msg)) {
        case GST_MESSAGE_ERROR:
          gst_message_parse_error (msg, &err, &debug_info);
          g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
          g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
          g_clear_error (&err);
          g_free (debug_info);
          terminate = TRUE;
          break;
        case GST_MESSAGE_EOS:
          g_print ("End-Of-Stream reached.\n");
          terminate = TRUE;
          break;
        case GST_MESSAGE_STATE_CHANGED:
          /* We are only interested in state-changed messages from the pipeline */
          if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data.pipeline)) {
            GstState old_state, new_state, pending_state;
            gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
            g_print ("Pipeline state changed from %s to %s:\n",
                gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
          }
          break;
        default:
          /* We should not reach here */
          g_printerr ("Unexpected message received.\n");
          break;
      }
      gst_message_unref (msg);
    }
  } while (!terminate);

  /* Free resources */
  gst_object_unref (bus);
  gst_element_set_state (data.pipeline, GST_STATE_NULL);
  gst_object_unref (data.pipeline);
  return 0;
}

/* This function will be called by the pad-added signal */
static void pad_added_handler (GstElement *src, GstPad *new_pad, CustomData *data) {
  GstPad *sink_pad = gst_element_get_static_pad (data->convert, "sink");
  GstPadLinkReturn ret;
  GstCaps *new_pad_caps = NULL;
  GstStructure *new_pad_struct = NULL;
  const gchar *new_pad_type = NULL;

  g_print ("Received new pad '%s' from '%s':\n", GST_PAD_NAME (new_pad), GST_ELEMENT_NAME (src));

  /* If our converter is already linked, we have nothing to do here */
  if (gst_pad_is_linked (sink_pad)) {
    g_print ("We are already linked. Ignoring.\n");
    goto exit;
  }

  /* Check the new pad's type */
  new_pad_caps = gst_pad_get_current_caps (new_pad);
  new_pad_struct = gst_caps_get_structure (new_pad_caps, 0);
  new_pad_type = gst_structure_get_name (new_pad_struct);
  if (!g_str_has_prefix (new_pad_type, "audio/x-raw")) {
    g_print ("It has type '%s' which is not raw audio. Ignoring.\n", new_pad_type);
    goto exit;
  }

  /* Attempt the link */
  ret = gst_pad_link (new_pad, sink_pad);
  if (GST_PAD_LINK_FAILED (ret)) {
    g_print ("Type is '%s' but link failed.\n", new_pad_type);
  } else {
    g_print ("Link succeeded (type '%s').\n", new_pad_type);
  }

exit:
  /* Unreference the new pad's caps, if we got them */
  if (new_pad_caps != NULL)
    gst_caps_unref (new_pad_caps);

  /* Unreference the sink pad */
  gst_object_unref (sink_pad);
}

将源码保存为basic-tutorial-4.c,执行下列命令可得到编译结果:
gcc basic-tutorial-4.c -o basic-tutorial-4 `pkg-config --cflags --libs gstreamer-1.0`

 

源码分析

/* Create the elements */
data.source = gst_element_factory_make ("uridecodebin", "source");
data.convert = gst_element_factory_make ("audioconvert", "convert");
data.sink = gst_element_factory_make ("autoaudiosink", "sink");

首先创建了所需的Element:

  • uridecodebin会中内部实例化所需的Elements(source,demuxer,decoder)将URI所指向的媒体文件中的各种媒体数据分别提取出来。因为其包含了demuxer,所以Source Pad在初始化阶段无法访问,只有在收到相应事件后去动态连接Pad。
  • audioconvert用于在不同的音频数据格式之间进行转换。由于不同的声卡支持的数据类型不尽相同,所以在某些平台需要对音频数据类型进行转换。
  • autoaudiosink会自动查找声卡设备,并将音频数据传输到声卡上进行输出。
if (!gst_element_link (data.convert, data.sink)) {
  g_printerr ("Elements could not be linked.\n");
  gst_object_unref (data.pipeline);
  return -1;
}

接着将converter和sink连接起来,注意,这里我们没有连接source与convert,是因为uridecode bin在Pipeline初始阶段还没有Source Pad。

/* Set the URI to play */
g_object_set (data.source, "uri", "https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm", NULL);

这里设置了播放文件的uri,uridecodebin会自动解析该地址,并读取媒体数据。

 

监听事件

/* Connect to the pad-added signal */
g_signal_connect (data.source, "pad-added", G_CALLBACK (pad_added_handler), &data);

GSignals在GStreamer中扮演着至关重要的角色。信号使你能在你所关心到事件发生后得到通知。在GLib中的信号通过信号名来进行识别,每个GObject对象都有其自己的信号。
在上面这行代码中,我们通过g_signal_connect将pad_added_handler回调连接到uridecodebin的“pad-added”信号上,同时附带回调函数的私有参数。GStreamer不会处理我们传入到data指针,只会将其作为参数传递给回调函数,这是传递私有数据给回调函数的常用方式。
一个GstElement可能会发出多个信号,可以使用gst-inspect工具查看具体到信号及参数。

在我们连接了“pad-added”的信号后,我们就可以将Pipeline的状态设置为PLAYING并按原有方式处理自己所关心到消息。

 

回调处理

当Source Element收集到足够到信息,能产生数据时,它会创建Source Pad并且触发“pad-added”信号。这时,我们的回调函数就会被调用。

static void pad_added_handler (GstElement *src, GstPad *new_pad, CustomData *data) {

这里是我们实现到回调函数,为什么我们的回调函数需要定义成这种格式呢?
因为我们的回调函数是为了处理信号所携带到信息,所以必须用符合信号的数据类型,否则不能正确到处理相应数据。通过gst-inspect查看uridecodebin可以看到信号所需要到回调函数格式:

$ gst-inspect-1.0 uridecodebin
...
Element Signals:
  "pad-added" :  void user_function (GstElement* object,
                                     GstPad* arg0,
                                     gpointer user_data);
...                              
  • src指针,指向触发这个事件的GstElement对象实例,这里是uridecodebin。GStreamer中的信号处理函数的第一个参数均为触发事件到对象指针。
  • new_pad指针,指向被创建的src中被创建的GstPad对象实例。这通常是我们需要连接的Pad。
  • data指针,指向我们在连接信号时所传的CustomData对象。
GstPad *sink_pad = gst_element_get_static_pad (data->convert, "sink");

我们首先从CustomData中取得convert指针,并通过gst_element_get_static_pad()获取其Sink Pad。我们需要将这个Sink Pad连接到uridecodebin新创建的new_pad中。

/* If our converter is already linked, we have nothing to do here */
if (gst_pad_is_linked (sink_pad)) {
  g_print ("We are already linked. Ignoring.\n");
  goto exit;
}

由于uridecodebin可能会创建多个Pad,在每次有Pad被创建时,我们的回调函数都会被调用。上面这段代码就是为了避免重复连接Pad。

/* Check the new pad's type */
new_pad_caps = gst_pad_get_current_caps (new_pad, NULL);
new_pad_struct = gst_caps_get_structure (new_pad_caps, 0);
new_pad_type = gst_structure_get_name (new_pad_struct);
if (!g_str_has_prefix (new_pad_type, "audio/x-raw")) {
  g_print ("It has type '%s' which is not raw audio. Ignoring.\n", new_pad_type);
  goto exit;
}

由于我们在当前示例中只处理audio相关的数据(我们开始只创建了autoaudiosink),所以我们这里对Pad所产生的数据类型进行了过滤,对于非音频Pad(视频及字幕)直接忽略。
gst_pad_get_current_caps()可以获取当前Pad的能力(这里是new_pad输出数据的能力),所有的能力被存储在GstCaps结构体中。Pad所支持的所有Caps可以通过gst_pad_query_caps()得到,由于一个Pad可能包含多个Caps,因此GstCaps可以包含一个或多个GstStructure,每个都代表所支持的不同数据的能力。通过gst_pad_get_current_caps()获取到的当前Caps只会包含一个GstStructure用于表示唯一的数据类型,如果无法获取到当前所使用到Caps,该函数会直接返回NULL。
由于我们已知在本例中new_pad只包含一个音频Cap,所以我们直接通过gst_caps_get_structure()来取得第一个GstStructure。接着再通过gst_structure_get_name() 获取该Cap支持的数据类型,如果不是音频(audio/x-raw),我们直接忽略。

/* Attempt the link */
ret = gst_pad_link (new_pad, sink_pad);
if (GST_PAD_LINK_FAILED (ret)) {
  g_print ("Type is '%s' but link failed.\n", new_pad_type);
} else {
  g_print ("Link succeeded (type '%s').\n", new_pad_type);
}

对于音频的Source Pad,我们使用gst_pad_link()将其与Sink Pad进行连接,使用方式与gst_element_link()相同,指定Source和Sink Pad,其所属的Element必须位于同一个Bin或Pipeline。

到目前为止,我们完成了Pipeline的建立,数据会继续在后续的Element中进行音频的播放,直到产生ERROR或EOS。

 

GStreamer的状态

我们已经知道Pipeline在我们将状态设置为PLAYING之前是不会进入播放状态,实际上PLAYING状态只是GStreamer状态中的一个,GStreamer总共包含4个状态:

  1. NULL:NULL状态是所有Element被创建后的初始状态。
  2. READY:READY状态表明GStreamer已经完成所需资源的检查,可以进入PAUSED状态。
  3. PAUSED:Element处于暂停状态,表明其可以开始接收数据。Sink Element在接收了一个buffer后就会进入等待状态。
  4. PLAYING:Element处于播放状态,时钟处于运行中,数据被依次处理。

GStreamer的状态必须按上面的顺序进行切换,例如:不能直接从NULL切换到PLAYING状态,NULL必须依次切换到READY,PAUSED后才能切换到PLAYING状态,当我们直接设置Pipeline的状态为PLAYING时,GStreamer内部会依次为我们切换到PLAYING状态。

case GST_MESSAGE_STATE_CHANGED:
  /* We are only interested in state-changed messages from the pipeline */
  if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data.pipeline)) {
    GstState old_state, new_state, pending_state;
    gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
    g_print ("Pipeline state changed from %s to %s:\n",
        gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
  }
  break;

 

总结

在本教程中,我们学习了:

  • 如何通过GSignals在事件发生时得到通知。
  • 如何直接连接位于两个Element中的Pad。
  • GStreamer中的四种状态。
  • 如何动态连接Pipeline。
  • 后续文章将继续介绍GStreamer时间控制的知识。

引用

https://gstreamer.freedesktop.org/documentation/tutorials/basic/dynamic-pipelines.html?gi-language=c
https://gstreamer.freedesktop.org/documentation/additional/design/states.html?gi-language=c

 

作者:John.Leng
本文版权归作者所有,欢迎转载。商业转载请联系作者获得授权,非商业转载请在文章页面明显位置给出原文连接.
posted @ 2019-07-16 13:06  John.Leng  阅读(12417)  评论(0编辑  收藏  举报