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的示意图如下:

GStreamer基础教程09 - Appsrc及Appsink_第1张图片

#include 
#include 
#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/
本文版权归作者所有,欢迎转载。商业转载请联系作者获得授权,非商业转载请在文章页面明显位置给出原文连接.

你可能感兴趣的:(GStreamer基础教程09 - Appsrc及Appsink)