GStreamer——教程——基础教程8:Short-cutting the pipeline

基本教程8:Short-cutting the pipeline(缩短pipeline)

目标

GStreamer构造的pipeline不需要完全封闭,有几种方式允许用户在任意时间向pipeline注入或提取数据。本教程将展示:

  • 如何将外部数据注入通用的GStreamer pipeline。

  • 如何从通用的GStreamer pipeline中提取数据。

  • 如何访问和操作从GStreamer pipeline中取出的数据。

Playback tutorial 3: Short-cutting the pipeline解释中使用基于playbin的pipeline以另外一种方式实现了相同的目标。

介绍

应用程序可以通过几种方式与GStreamer管道中流动的数据进行交互。本教程描述了最简单的一种方式,因为它使用了专为这个目的创建的元素。

用于将应用程序数据注入GStreamer管道的元素是appsrc,而其对应元素,用于将GStreamer数据提取回应用程序的是appsink。为了避免混淆名称,可以从GStreamer的角度来考虑:appsrc只是一个普通的源,它提供的数据仿佛是从天而降(实际上是由应用程序提供的)。appsink是一个普通的接收器,GStreamer管道中流动的数据最终流向此处(实际上被应用程序回收)。

appsrc和appsink非常灵活,它们提供了自己的API(参见它们的文档),可以通过链接到gstreamer-app库来访问。然而,在本教程中,我们将使用更简单的方式,通过信号来控制它们。

appsrc可以在多种模式下工作:在拉取模式下,每当需要时,它会从应用程序请求数据。在推送模式下,应用程序按照自己的节奏推送数据。此外,在推送模式下,应用程序可以选择在推送函数中被阻塞,当已经提供了足够的数据时,或者它可以监听enough-data和need-data信号来控制流量。本示例实现了后一种方法。有关其他方法的信息可以在appsrc文档中找到。

Buffers

数据以称为buffers(缓冲区)的块的形式通过GStreamer管道传输。由于本例生产和消费数据,我们有必要了解GstBuffer。

Source pads生产buffer,而sink pads消费buffer,GStreamer接受这些buffer并将它们从一个element传递到另一个element。

buffer 简单地代表了一个数据单元,不要假设所有缓冲区都会有相同的大小,或者代表相同的时间量。你也不应当假设:如果单个缓冲区进入一个元素,就会有单个缓冲区出来。元素可以随意处理收到的缓冲区。GstBuffers 也可能包含不止一个实际的内存缓冲区。实际的内存缓冲区使用GstMemory 对象进行抽象,一个 GstBuffer 可以包含多个 GstMemory 对象。

每个buffer都附带有时间戳和持续时间,描述在哪个时刻应该解码、渲染或显示buffer的内容。时间戳是一个非常复杂和微妙的主题,但这个简化的观点目前应该足够了。

举例来说,一个filesrc(可以读取文件的GStreamer element)插件生产的buffer具有ANY类型的caps和无时间戳信息。 而经过解复用(参见基本教程3:动态管道) 之后,缓冲区可能具有一些特定的能力,例如“video/x-h264”。解码后,每个缓冲区将包含一个带有原始能力(例如,“video/x-raw-yuv”)的单一视频帧,并且非常精确的时间戳指示何时应显示该帧。

教程

本教程扩展了基本教程7:多线程和Pad可用性两种方法:首先,aaudiotesetsrcappsrc取代,音频数据将由appsrc产生。其次,tee插件增加了一个分支,因此流入audio sink和波形显示的数据也被复制了一份传给appsinkappsink会将信息回传到应用程序中,在本教程中仅仅是通知用户收到了新的数据,但是显然appsink可以处理更复杂的任务。

一种粗波形发生器

将此代码复制到名为basic-tutorial-8.c文本文件中(或找到它 在您的GStreamer安装中)。

#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 custom 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_request_pad_simple (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_request_pad_simple (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_request_pad_simple (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;
}

需要帮忙吗?

如果您需要帮助来编译此代码,请参阅为您的平台构建教程部分:LinuxMac OS XWindows,或在Linux上使用此特定命令:

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

如果您需要帮助来运行此代码,请参阅为您的平台运行教程部分:LinuxMac OS XWindows

本教程通过声卡播放变频的可听音调,并打开一个带有音调波形表示的窗口。波形应该是正弦曲线,但由于窗口的刷新可能不会出现。

所需库:gstreamer-1.0

工作流

创建管道的代码(第131到205行)是基本教程7:多线程和Pad可用性 的放大版本基本教程7:多线程和Pad可用性 。 它涉及实例化所有elements,自动连接所有具有Always Pads的elements,手动连接从tee中申请的Request Pads

关于appsrcappsink元素的配置:

/* 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,它指定了appsrc将生成的数据类型,以便GStreamer可以检查它是否能够和下游elements连接(下游elements能否处理这种数据)。caps属性值必须是GstCaps对象,GstCaps对象可以使用gst_caps_from_string()解析一个字符串对象来构建。

我们连接了appsrcneed-dataenough-data信号,它们将在appsrc内部队列数据不足或快满时分别被触发。本教程使用这两个信号分别启动/停止信号发生过程。

/* 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);

我们连接了appsinnew-sample信号,每当appsink到数据的时候就会触发这个信号。与appsrc不同,appsinkemit-signals属性的默认值为false,因此我们需要将它设置为true以便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的内部队列缺乏数据的时候就会触发上述回调,在这个回调函数中唯一做的事就是使用g_idle_add()注册了一个GLib空闲函数,在空闲函数中将不断向appsrc的传递数据只知道它的内部队列队满。GLib空闲函数是当它的主循环处于“空闲”状态时将被调用的方法,也就是说当前没有更高优先级的任务需要执行。调用GLib空闲函数需要用户线初始化并启动一个GMainLoop(推荐阅读GMainLoop以获得更多关于GMainLoop的信息)。

这时appsrc允许的多种方法中的一个。事实上buffer并不需要使用GLib从主线程传递给appsrc,也不一定需要使用need-dataenough-data信号来与appsrc同步(据说是最方便的)。

我们维护g_idle_add()返回的sourceid,稍后需要禁用它。

/* 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;
  }
}

这个函数当appsrc内部的队列满的时候调用,所以我们需要停止发送数据。这里我们简单地用g_source_remove()来把idle函数注销。

/* 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;
  GstMapInfo map;
  int i;
  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 */
  if (gst_buffer_map (buf, &map, GST_MAP_READ)) {
    gint16 *raw = (gint16 *) map.data;

    /* create samples here */

    /* unmap buffer when done */
    gst_buffer_unmap (buf, &map);
  }

这是为appsrc提供数据的函数。GLib会在我们无法控制的时间点和速率调用它,但我们知道当appsrc的任务完成时(即appsrc中的队列满了)我们将禁用它。

它的首要任务是使用gst_buffer_new_and_alloc()创建一个新的缓冲区,大小为给定值(在这个例子中,我们随意设置为1024字节)。

我们用CustomData.num_samples变量来统计到目前为止生成的样本数,以便我们可以使用GstBuffer中的GST_BUFFER_TIMESTAMP宏来为此缓冲区添加时间戳。

由于我们产生的缓冲区大小相同,它们的长度也相同,使用GstBuffer中的GST_BUFFER_DURATION进行设置。

gst_util_uint64_scale()是一个实用函数,它可以放大(乘法和除法)可能很大的数字,而不必担心溢出。

为了访问缓冲区的内存,你首先需要用gst_buffer_map()映射它,这将在成功时给你一个指针和一个GstMapInfo结构内的大小。小心不要写入缓冲区的末尾:你已经分配了它,所以你知道它的字节和样本大小。

我们将跳过波形生成部分,因为它不在本教程的范围内(它只是生成漂亮迷幻波形的一种有趣方式)。

/* 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);

需要注意的是,gst_app_src_push_buffer()也是gstreamer-app-1.0库的一部分,它可能是一个更好的函数,用于将缓冲区推入appsrc,而不是上面的信号发射,因为它具有适当的类型签名,因此更难出错。然而,请注意,如果你使用gst_app_src_push_buffer(),它会接管传入的缓冲区的所有权,所以在这种情况下,你不必在推送后取消引用它。

一旦我们准备好了buffer,我们就用推送buffer操作信号将其传递给appsrc(参见回放教程1:Playbin用法末尾的信息框),然后用gst_buffer_unref()取消引用它,因为我们不再需要它了。

/* 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接收到缓冲区时被调用的函数。我们使用pull-sample操作信号来检索缓冲区,然后在屏幕上打印一些指示器。

需要注意的是,gst_app_src_pull_sample()也是gstreamer-app-1.0库的一部分,它可能是一个更好的函数,用于从appsink中提取样本/缓冲区,而不是上面的信号发射,因为它具有适当的类型签名,因此更难出错。

为了获取数据指针,我们需要像上面一样使用gst_buffer_map(),它将用指向数据的指针和数据字节大小填充一个GstMapInfo辅助结构。完成数据处理后,别忘了再次使用gst_buffer_unmap()取消映射缓冲区。

请记住,这个缓冲区不必与我们push_data函数中生成的缓冲区匹配,路径中的任何元素都可能以任何方式更改了缓冲区(在这个例子中不会:在appsrc和appsink之间的路径中只有一个tee,而tee不会改变缓冲区的内容)。

然后我们使用gst_sample_unref()取消引用检索到的样本,本教程到此结束。

结论

本教程展示了应用程序如何:

  • 如何使用appsrc元素向pipeline插入数据。
  • 如何使用appsink元素从pipeline中检索数据。

  • 如何通过GstBuffer操作从pipeline中取出的数据。

播放教程3:缩短管道中使用基于playbin的pipeline以另外一种方式实现了相同的目标。

很高兴你在这里,很快就会见到你!

  • 22
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值