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
本文版權歸作者所有,歡迎轉載。商業轉載請聯系作者獲得授權,非商業轉載請在文章頁面明顯位置給出原文連接.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM