1. 程式人生 > >GStreamer基礎教程09 - Appsrc及Appsink

GStreamer基礎教程09 - Appsrc及Appsink

摘要

在我們前面的文章中,我們的Pipline都是使用GStreamer自帶的外掛去產生/消費資料。在實際的情況中,我們的資料來源可能沒有相應的gstreamer外掛,但我們又需要將資料傳送到GStreamer Pipeline中。GStreamer為我們提供了Appsrc以及Appsink外掛,用於處理這種情況,本文將介紹如何使用這些外掛來實現資料與應用程式的互動。

 

Appsrc與Appsink

GStreamer提供了多種方法使得應用程式與GStreamer Pipeline之間可以進行資料互動,我們這裡介紹的是最簡單的一種方式:appsrc與appsink。

  • appsrc:

用於將應用程式的資料傳送到Pipeline中。應用程式負責資料的生成,並將其作為GstBuffer傳輸到Pipeline中。
appsrc有2中模式,拉模式和推模式。在拉模式下,appsrc會在需要資料時,通過指定介面從應用程式中獲取相應資料。在推模式下,則需要由應用程式主動將資料推送到Pipeline中,應用程式可以指定在Pipeline的資料佇列滿時是否阻塞相應呼叫,或通過監聽enough-data和need-data訊號來控制資料的傳送。

  • appsink:

用於從Pipeline中提取資料,併發送到應用程式中。


  appsrc和appsink需要通過特殊的API才能與Pipeline進行資料互動,相應的介面可以檢視官方文件,在編譯的時候還需連線gstreamer-app庫。

 

GstBuffer

  在GStreamer Pipeline中的plugin間傳輸的資料塊被稱為buffer,在GStreamer內部對應於GstBuffer。Buffer由Source Pad產生,並由Sink Pad消耗。一個Buffer只表示一塊資料,不同的buffer可能包含不同大小,不同時間長度的資料。同時,某些Element中可能對Buffer進行拆分或合併,所以GstBuffer中可能包含不止一個記憶體資料,實際的記憶體資料在GStreamer系統中通過GstMemory物件進行描述,因此,GstBuffer可以包含多個GstMemory物件。
  每個GstBuffer都有相應的時間戳以及時間長度,用於描述這個buffer的解碼時間以及顯示時間。

 

示例程式碼

本例在GStreamer基礎教程08 - 多執行緒示例上進行擴充套件,首先使用appsrc替代audiotestsrc用於產生audio資料,另外增加一個新的分支,將tee產生的資料傳送到應用程式,由應用程式決定如何處理收到的資料。Pipeline的示意圖如下:

#include <gst/gst.h>
#include <gst/audio/audio.h>
#include <string.h>

#define CHUNK_SIZE 1024   /* Amount of bytes we are sending in each buffer */
#define SAMPLE_RATE 44100 /* Samples per second we are sending */

/* Structure to contain all our information, so we can pass it to callbacks */
typedef struct _CustomData {
  GstElement *pipeline, *app_source, *tee, *audio_queue, *audio_convert1, *audio_resample, *audio_sink;
  GstElement *video_queue, *audio_convert2, *visual, *video_convert, *video_sink;
  GstElement *app_queue, *app_sink;

  guint64 num_samples;   /* Number of samples generated so far (for timestamp generation) */
  gfloat a, b, c, d;     /* For waveform generation */

  guint sourceid;        /* To control the GSource */

  GMainLoop *main_loop;  /* GLib's Main Loop */
} CustomData;

/* This method is called by the idle GSource in the mainloop, to feed CHUNK_SIZE bytes into appsrc.
 * The idle handler is added to the mainloop when appsrc requests us to start sending data (need-data signal)
 * and is removed when appsrc has enough data (enough-data signal).
 */
static gboolean push_data (CustomData *data) {
  GstBuffer *buffer;
  GstFlowReturn ret;
  int i;
  GstMapInfo map;
  gint16 *raw;
  gint num_samples = CHUNK_SIZE / 2; /* Because each sample is 16 bits */
  gfloat freq;

  /* Create a new empty buffer */
  buffer = gst_buffer_new_and_alloc (CHUNK_SIZE);

  /* Set its timestamp and duration */
  GST_BUFFER_TIMESTAMP (buffer) = gst_util_uint64_scale (data->num_samples, GST_SECOND, SAMPLE_RATE);
  GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale (num_samples, GST_SECOND, SAMPLE_RATE);

  /* Generate some psychodelic waveforms */
  gst_buffer_map (buffer, &map, GST_MAP_WRITE);
  raw = (gint16 *)map.data;
  data->c += data->d;
  data->d -= data->c / 1000;
  freq = 1100 + 1000 * data->d;
  for (i = 0; i < num_samples; i++) {
    data->a += data->b;
    data->b -= data->a / freq;
    raw[i] = (gint16)(500 * data->a);
  }
  gst_buffer_unmap (buffer, &map);
  data->num_samples += num_samples;

  /* Push the buffer into the appsrc */
  g_signal_emit_by_name (data->app_source, "push-buffer", buffer, &ret);

  /* Free the buffer now that we are done with it */
  gst_buffer_unref (buffer);

  if (ret != GST_FLOW_OK) {
    /* We got some error, stop sending data */
    return FALSE;
  }

  return TRUE;
}

/* This signal callback triggers when appsrc needs data. Here, we add an idle handler
 * to the mainloop to start pushing data into the appsrc */
static void start_feed (GstElement *source, guint size, CustomData *data) {
  if (data->sourceid == 0) {
    g_print ("Start feeding\n");
    data->sourceid = g_idle_add ((GSourceFunc) push_data, data);
  }
}

/* This callback triggers when appsrc has enough data and we can stop sending.
 * We remove the idle handler from the mainloop */
static void stop_feed (GstElement *source, CustomData *data) {
  if (data->sourceid != 0) {
    g_print ("Stop feeding\n");
    g_source_remove (data->sourceid);
    data->sourceid = 0;
  }
}

/* The appsink has received a buffer */
static GstFlowReturn new_sample (GstElement *sink, CustomData *data) {
  GstSample *sample;

  /* Retrieve the buffer */
  g_signal_emit_by_name (sink, "pull-sample", &sample);
  if (sample) {
    /* The only thing we do in this example is print a * to indicate a received buffer */
    g_print ("*");
    gst_sample_unref (sample);
    return GST_FLOW_OK;
  }

  return GST_FLOW_ERROR;
}

/* This function is called when an error message is posted on the bus */
static void error_cb (GstBus *bus, GstMessage *msg, CustomData *data) {
  GError *err;
  gchar *debug_info;

  /* Print error details on the screen */
  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);

  g_main_loop_quit (data->main_loop);
}

int main(int argc, char *argv[]) {
  CustomData data;
  GstPad *tee_audio_pad, *tee_video_pad, *tee_app_pad;
  GstPad *queue_audio_pad, *queue_video_pad, *queue_app_pad;
  GstAudioInfo info;
  GstCaps *audio_caps;
  GstBus *bus;

  /* Initialize cumstom data structure */
  memset (&data, 0, sizeof (data));
  data.b = 1; /* For waveform generation */
  data.d = 1;

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

  /* Create the elements */
  data.app_source = gst_element_factory_make ("appsrc", "audio_source");
  data.tee = gst_element_factory_make ("tee", "tee");
  data.audio_queue = gst_element_factory_make ("queue", "audio_queue");
  data.audio_convert1 = gst_element_factory_make ("audioconvert", "audio_convert1");
  data.audio_resample = gst_element_factory_make ("audioresample", "audio_resample");
  data.audio_sink = gst_element_factory_make ("autoaudiosink", "audio_sink");
  data.video_queue = gst_element_factory_make ("queue", "video_queue");
  data.audio_convert2 = gst_element_factory_make ("audioconvert", "audio_convert2");
  data.visual = gst_element_factory_make ("wavescope", "visual");
  data.video_convert = gst_element_factory_make ("videoconvert", "video_convert");
  data.video_sink = gst_element_factory_make ("autovideosink", "video_sink");
  data.app_queue = gst_element_factory_make ("queue", "app_queue");
  data.app_sink = gst_element_factory_make ("appsink", "app_sink");

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

  if (!data.pipeline || !data.app_source || !data.tee || !data.audio_queue || !data.audio_convert1 ||
      !data.audio_resample || !data.audio_sink || !data.video_queue || !data.audio_convert2 || !data.visual ||
      !data.video_convert || !data.video_sink || !data.app_queue || !data.app_sink) {
    g_printerr ("Not all elements could be created.\n");
    return -1;
  }

  /* Configure wavescope */
  g_object_set (data.visual, "shader", 0, "style", 0, NULL);

  /* Configure appsrc */
  gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16, SAMPLE_RATE, 1, NULL);
  audio_caps = gst_audio_info_to_caps (&info);
  g_object_set (data.app_source, "caps", audio_caps, "format", GST_FORMAT_TIME, NULL);
  g_signal_connect (data.app_source, "need-data", G_CALLBACK (start_feed), &data);
  g_signal_connect (data.app_source, "enough-data", G_CALLBACK (stop_feed), &data);

  /* Configure appsink */
  g_object_set (data.app_sink, "emit-signals", TRUE, "caps", audio_caps, NULL);
  g_signal_connect (data.app_sink, "new-sample", G_CALLBACK (new_sample), &data);
  gst_caps_unref (audio_caps);

  /* Link all elements that can be automatically linked because they have "Always" pads */
  gst_bin_add_many (GST_BIN (data.pipeline), data.app_source, data.tee, data.audio_queue, data.audio_convert1, data.audio_resample,
      data.audio_sink, data.video_queue, data.audio_convert2, data.visual, data.video_convert, data.video_sink, data.app_queue,
      data.app_sink, NULL);
  if (gst_element_link_many (data.app_source, data.tee, NULL) != TRUE ||
      gst_element_link_many (data.audio_queue, data.audio_convert1, data.audio_resample, data.audio_sink, NULL) != TRUE ||
      gst_element_link_many (data.video_queue, data.audio_convert2, data.visual, data.video_convert, data.video_sink, NULL) != TRUE ||
      gst_element_link_many (data.app_queue, data.app_sink, NULL) != TRUE) {
    g_printerr ("Elements could not be linked.\n");
    gst_object_unref (data.pipeline);
    return -1;
  }

  /* Manually link the Tee, which has "Request" pads */
  tee_audio_pad = gst_element_get_request_pad (data.tee, "src_%u");
  g_print ("Obtained request pad %s for audio branch.\n", gst_pad_get_name (tee_audio_pad));
  queue_audio_pad = gst_element_get_static_pad (data.audio_queue, "sink");
  tee_video_pad = gst_element_get_request_pad (data.tee, "src_%u");
  g_print ("Obtained request pad %s for video branch.\n", gst_pad_get_name (tee_video_pad));
  queue_video_pad = gst_element_get_static_pad (data.video_queue, "sink");
  tee_app_pad = gst_element_get_request_pad (data.tee, "src_%u");
  g_print ("Obtained request pad %s for app branch.\n", gst_pad_get_name (tee_app_pad));
  queue_app_pad = gst_element_get_static_pad (data.app_queue, "sink");
  if (gst_pad_link (tee_audio_pad, queue_audio_pad) != GST_PAD_LINK_OK ||
      gst_pad_link (tee_video_pad, queue_video_pad) != GST_PAD_LINK_OK ||
      gst_pad_link (tee_app_pad, queue_app_pad) != GST_PAD_LINK_OK) {
    g_printerr ("Tee could not be linked\n");
    gst_object_unref (data.pipeline);
    return -1;
  }
  gst_object_unref (queue_audio_pad);
  gst_object_unref (queue_video_pad);
  gst_object_unref (queue_app_pad);

  /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
  bus = gst_element_get_bus (data.pipeline);
  gst_bus_add_signal_watch (bus);
  g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data);
  gst_object_unref (bus);

  /* Start playing the pipeline */
  gst_element_set_state (data.pipeline, GST_STATE_PLAYING);

  /* Create a GLib Main Loop and set it to run */
  data.main_loop = g_main_loop_new (NULL, FALSE);
  g_main_loop_run (data.main_loop);

  /* Release the request pads from the Tee, and unref them */
  gst_element_release_request_pad (data.tee, tee_audio_pad);
  gst_element_release_request_pad (data.tee, tee_video_pad);
  gst_element_release_request_pad (data.tee, tee_app_pad);
  gst_object_unref (tee_audio_pad);
  gst_object_unref (tee_video_pad);
  gst_object_unref (tee_app_pad);

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

儲存以上程式碼,執行下列編譯命令即可得到可執行程式:

gcc basic-tutorial-9.c -o basic-tutorial-9 `pkg-config --cflags --libs gstreamer-1.0 gstreamer-audio-1.0 `

Note:本例在編譯時沒有連線gstreamer-app-1.0的庫是因為我們使用的是通過訊號的方式,由appsrc自動處理buffer,所以無需在編譯時連線相應庫。在原始碼分析部分會詳述。

 

原始碼分析

  與上一示例相同,首先對所需Element進行例項化,同時將Element的Always Pad連線起來,並與tee的Request Pad相連。此外我們還對appsrc及appsink進行了相應的配置:

/* Configure appsrc */
gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16, SAMPLE_RATE, 1, NULL);
audio_caps = gst_audio_info_to_caps (&info);
g_object_set (data.app_source, "caps", audio_caps, NULL);
g_signal_connect (data.app_source, "need-data", G_CALLBACK (start_feed), &data);
g_signal_connect (data.app_source, "enough-data", G_CALLBACK (stop_feed), &data);

  首先需要對appsrc的caps進行設定,指定我們會產生何種型別的資料,這樣GStreamer會在連線階段檢查後續的Element是否支援此資料型別。這裡的 caps必須為GstCaps物件,我們可以通過gst_caps_from_string()或gst_audio_info_to_caps ()得到相應的例項。
  我們同時監聽了“need-data”與“enough-data”事件,這2個事件由appsrc在需要資料和緩衝區滿時觸發,使用這2個事件可以方便的控制何時產生資料與停止資料。

 

/* Configure appsink */
g_object_set (data.app_sink, "emit-signals", TRUE, "caps", audio_caps, NULL);
g_signal_connect (data.app_sink, "new-sample", G_CALLBACK (new_sample), &data);
gst_caps_unref (audio_caps);

  對於appsink,我們監聽“new-sample”事件,用於appsink在收到資料時的處理。同時我們需要顯式的使能“new-sample”事件,因為這個事件預設是處於關閉狀態。

  Pipeline的播放,停止及訊息處理與其他示例相同,不再複述。我們接下來將檢視我們監聽事件的回撥函式。

 

/* This signal callback triggers when appsrc needs data. Here, we add an idle handler
 * to the mainloop to start pushing data into the appsrc */
static void start_feed (GstElement *source, guint size, CustomData *data) {
  if (data->sourceid == 0) {
    g_print ("Start feeding\n");
    data->sourceid = g_idle_add ((GSourceFunc) push_data, data);
  }
}

  appsrc會在其內部的資料佇列即將缺乏資料時呼叫此回撥函式,這裡我們通過註冊一個GLib的idle函式來向appsrc填充資料,GLib的主迴圈在“idle”狀態時會迴圈呼叫 push_data,用於向appsrc填充資料。這只是一種向appsrc填充資料的方式,我們可以在任意執行緒中想appsrc填充資料。
  我們儲存了g_idle_add()的返回值,以便後續用於停止資料寫入。

/* This callback triggers when appsrc has enough data and we can stop sending.
 * We remove the idle handler from the mainloop */
static void stop_feed (GstElement *source, CustomData *data) {
  if (data->sourceid != 0) {
    g_print ("Stop feeding\n");
    g_source_remove (data->sourceid);
    data->sourceid = 0;
  }
}

  stop_feed函式會在appsrc內部資料佇列滿時被呼叫。這裡我們僅僅通過g_source_remove() 將先前註冊的idle處理函式從GLib的主迴圈中移除(idle處理函式是被實現為一個GSource)。

 

/* This method is called by the idle GSource in the mainloop, to feed CHUNK_SIZE bytes into appsrc.
 * The ide handler is added to the mainloop when appsrc requests us to start sending data (need-data signal)
 * and is removed when appsrc has enough data (enough-data signal).
 */
static gboolean push_data (CustomData *data) {
  GstBuffer *buffer;
  GstFlowReturn ret;
  int i;
  gint16 *raw;
  gint num_samples = CHUNK_SIZE / 2; /* Because each sample is 16 bits */
  gfloat freq;

  /* Create a new empty buffer */
  buffer = gst_buffer_new_and_alloc (CHUNK_SIZE);

  /* Set its timestamp and duration */
  GST_BUFFER_TIMESTAMP (buffer) = gst_util_uint64_scale (data->num_samples, GST_SECOND, SAMPLE_RATE);
  GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale (num_samples, GST_SECOND, SAMPLE_RATE);

  /* Generate some psychodelic waveforms */
  raw = (gint16 *)GST_BUFFER_DATA (buffer);

  此函式會將真實的資料填充到appsrc的資料佇列中,首先通過gst_buffer_new_and_alloc()分配一個GstBuffer物件,然後通過產生的取樣數量計算這塊buffre所對應的時間戳及事件長度。
  gst_util_uint64_scale(val, num, denom)函式用於計算 val * num / denom,此函式內部會對資料範圍進行檢測,避免溢位的問題。
  GstBuffer的資料指標可以通過GST_BUFFER_DATA 巨集獲取,在寫資料時需要避免超出記憶體分配大小。本文將跳過audio波形生成的函式,其內容不是本文介紹的重點。

 

/* Push the buffer into the appsrc */
g_signal_emit_by_name (data->app_source, "push-buffer", buffer, &ret);

/* Free the buffer now that we are done with it */
gst_buffer_unref (buffer);

  在我們準備好資料後,我們這裡通過“push-buffer”事件通知appsrc資料就緒,並釋放我們申請的buffer。 另外一種方式為通過呼叫gst_app_src_push_buffer() 向appsrc填充資料,這種方式就需要在編譯時連結gstreamer-app-1.0庫,同時gst_app_src_push_buffer() 會接管GstBuffer的所有權,呼叫者無需釋放buffer。在所有資料都發送完成後,我們可以呼叫gst_app_src_end_of_stream()向Pipeline寫入EOS事件。

/* The appsink has received a buffer */
static GstFlowReturn new_sample (GstElement *sink, CustomData *data) {
  GstSample *sample;
  /* Retrieve the buffer */
  g_signal_emit_by_name (sink, "pull-sample", &sample);
  if (sample) {
    /* The only thing we do in this example is print a * to indicate a received buffer */
    g_print ("*");
    gst_sample_unref (sample);
    return GST_FLOW_OK;
  }
  return GST_FLOW_ERROR;
}

  當appsink得到資料時會呼叫new_sample函式,我們使用“pull-sample”訊號提取sample,這裡僅輸出一個”*“表明此函式被呼叫。除此之外,我們同樣可以使用gst_app_sink_pull_sample ()獲取Sample。得到GstSample之後,我們可以通過gst_sample_get_buffer()得到Sample中所包含的GstBuffer,再使用GST_BUFFER_DATA, GST_BUFFER_SIZE 等介面訪問其中的資料。使用完後,得到的GstSample同樣需要通過gst_sample_unref()進行釋放。
  需要注意的是,在某些Pipeline裡得到的GstBuffer可能會和source中填充的GstBuffer有所差異,因為Pipeline中的Element可能對Buffer進行各種處理(此例中不存在此種情況,因為在appsrc與appsink之間只存在一個tee)。

 

總結

在本文中,我們介紹了:

  • 如何通過appsrc向Pipeline中寫入資料
  • 如何通過appsink取得Pipeline中的資料
  • 如何獲取/填充GstBuffer中對應的資料

後續我們將繼續學習有關GStreamer的其他知識。

 

引用

https://gstreamer.freedesktop.org/documentation/tutorials/basic/short-cutting-the-pipeline.html?gi-language=c

  

作者:John.Leng 出處:http://www.cnblogs.com/xleng/ 本文版權歸作者所有,歡迎轉載。商業轉載請聯絡作者獲得授權,非商業轉載請在文章頁面明顯位置給出原文連線.