前言
本文是GStreamer学习笔记,也可以看成是对原文的意译。
这些教程描述了理解其余教程所需的GStreamer主题。
GStreamer教程:
环境
系统环境
Distributor ID: Ubuntu
Description: Ubuntu 18.04.4 LTS
Release: 18.04
Codename: bionic
Linux version : 5.3.0-46-generic ( buildd@lcy01-amd64-013 )
Gcc version: 7.5.0 ( Ubuntu 7.5.0-3ubuntu1~18.04 )
软件信息
version :
GStreamer-1.0
正文
1. 目标
使用 GStreamer 构建的管道不需要完全关闭。数据可以随时以多种方式注入管道并从中提取。本教程显示:
- 如何将外部数据注入通用 GStreamer 管道。
- 如何从通用 GStreamer 管道中提取数据。
- 如何访问和操作这些数据。
回放教程 3:缩短管道解释了如何在基于 playbin 的管道中实现相同的目标。
2. 介绍
应用程序可以通过多种方式与流经 GStreamer 管道的数据进行交互。本教程描述了最简单的一个,因为它使用了为此唯一目的而创建的元素。
用于将应用程序数据注入 GStreamer 管道的元素是 appsrc
,用于将 GStreamer 数据提取回应用程序的元素是appsink
。为避免混淆名称,请从 GStreamer 的角度考虑:appsrc
它只是一个常规源,它提供从天而降的数据(实际上是由应用程序提供的)。appsink
是一个常规接收器,流经 GStreamer 管道的数据在其中死亡(实际上它由应用程序恢复)。
appsrc
并且appsink
用途广泛,以至于他们提供了自己的 API(请参阅他们的文档),可以通过链接 gstreamer-app
库来访问这些 API。然而,在本教程中,我们将使用更简单的方法并通过信号控制它们。
appsrc
可以在多种模式下工作:在拉模式下,它会在每次需要时向应用程序请求数据。在推送模式下,应用程序以自己的节奏推送数据。此外,在推送模式下,应用程序可以选择在已经提供足够数据时阻塞在推送功能中,或者它可以监听 enough-data
和need-data
信号来控制流量。这个例子实现了后一种方法。有关其他方法的信息可以在appsrc
文档中找到。
2.1 缓冲器
数据以称为缓冲区的块的形式通过 GStreamer 管道。由于这个例子生产和消费数据,我们需要了解 GstBuffer
s。
Source Pads 产生缓冲区,由 Sink Pads 消耗;GStreamer 获取这些缓冲区并将它们从一个元素传递到另一个元素。
缓冲区只是代表一个数据单元,不要假设所有缓冲区都具有相同的大小或代表相同的时间量。你也不应该假设如果一个缓冲区进入一个元素,一个缓冲区就会出来。元素可以随意处理接收到的缓冲区。GstBuffer
s 也可能包含多个实际内存缓冲区。实际的内存缓冲区是使用 GstMemory
对象抽象出来的,一个GstBuffer
可以包含多个GstMemory
对象。
每个缓冲区都有附加的时间戳和持续时间,它们描述了应该在什么时刻解码、渲染或显示缓冲区的内容。时间戳是一个非常复杂和微妙的主题,但这个简化的愿景现在应该足够了。
例如,一个filesrc
(读取文件的 GStreamer 元素)生成带有“ANY”上限且没有时间戳信息的缓冲区。解复用后(参见基础教程 3: 动态管道)缓冲区可以有一些特定的上限,例如“video/x-h264”。解码后,每个缓冲区将包含一个带有原始大写字母的视频帧(例如,“video/x-raw-yuv”)和指示何时显示该帧的非常精确的时间戳。
2.2 本教程
本教程以两种方式扩展了基础教程 7: 多线程和Pad可用性:首先,将audiotestsrc
替换为appsrc
将生成音频数据的 。其次,将一个新分支添加到 tee
,所以数据进入音频接收器和波形显示也复制到appsink
. 将appsink
信息上传回应用程序,然后应用程序只会通知用户已收到数据,但它显然可以执行更复杂的任务。
3. 一个粗略的波形发生器
basic-tutorial-8.c
#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;
}
编译运行
gcc basic-tutorial-8.c -o basic-tutorial-8 `pkg-config --cflags --libs gstreamer-1.0 gstreamer-audio-1.0`
./basic-tutorial-8
可能遇到的问题
$ gcc basic-tutorial-8.c -o basic-tutorial-8 `pkg-config --cflags --libs gstreamer-1.0 gstreamer-audio-1.0`
basic-tutorial-8.c: In function ‘main’:
basic-tutorial-8.c:204:21: warning: implicit declaration of function ‘gst_element_request_pad_simple’; did you mean ‘gst_element_request_pad’? [-Wimplicit-function-declaration]
tee_audio_pad = gst_element_request_pad_simple(data.tee, "src_%u");
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gst_element_request_pad
basic-tutorial-8.c:204:19: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
tee_audio_pad = gst_element_request_pad_simple(data.tee, "src_%u");
^
basic-tutorial-8.c:207:19: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
tee_video_pad = gst_element_request_pad_simple(data.tee, "src_%u");
^
basic-tutorial-8.c:210:17: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
tee_app_pad = gst_element_request_pad_simple(data.tee, "src_%u");
^
/tmp/ccLg1fcn.o: In function `main':
basic-tutorial-8.c:(.text+0xb20): undefined reference to `gst_element_request_pad_simple'
basic-tutorial-8.c:(.text+0xb84): undefined reference to `gst_element_request_pad_simple'
basic-tutorial-8.c:(.text+0xbe8): undefined reference to `gst_element_request_pad_simple'
collect2: error: ld returned 1 exit status
解决方案:将gst_element_request_pad_simple
替换成gst_element_get_request_pad
参考:gst_element_request_pad_simple
Note that this function was introduced in GStreamer 1.20 in order to provide a better name to gst_element_get_request_pad. Prior to 1.20, users should use gst_element_get_request_pad which provides the same functionality.
4. 演练
创建管道的代码(第 131 到 205 行)是基础教程 7: 多线程和Pad可用性的放大版本。它涉及实例化所有元素,将元素与 Always Pads 链接,并手动链接tee
元素的 Request Pads。
关于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 可以检查是否可以与下游元素链接(即下游元素是否能够理解这种数据)。该属性必须是一个GstCaps
对象,它可以很容易地从带有gst_caps_from_string()
.
然后我们连接到need-data
和enough-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);
关于appsink
配置,我们连接到 new-sample
每次接收器接收缓冲区时发出的信号。此外,需要通过该 emit-signals
属性启用信号发射,因为默认情况下它是禁用的。
像往常一样启动管道、等待消息和最终清理。让我们回顾一下我们刚刚注册的回调:
/* 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 空闲函数,它会向它g_idle_add()
提供数据,appsrc
直到它再次满为止。GLib 空闲函数是 GLib 将在其“空闲”时从其主循环调用的方法,即当它没有更高优先级的任务要执行时。显然,它需要一个 GLibGMainLoop
实例化和运行。
这只是appsrc
允许的多种方法之一。特别是,缓冲区不需要appsrc
使用 GLib 从主线程馈入,并且您不需要使用need-data
and enough-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
当内部队列足够满时调用此函数,因此我们停止推送数据。这里我们简单的通过 using 去掉 idle 函数g_source_remove()
(idle 函数实现为 a 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);
这是 feed 的功能appsrc
。GLib 有时会调用它并且速率超出我们的控制范围,但我们知道当它的工作完成时(当队列appsrc
已满时)我们将禁用它。
它的第一个任务是使用 gst_buffer_new_and_alloc()
.
我们使用变量计算到目前为止我们生成的样本数 ,因此我们可以使用宏 inCustomData.num_samples
为这个缓冲区加时间戳。GST_BUFFER_TIMESTAMP
GstBuffer
由于我们正在生成相同大小的缓冲区,因此它们的持续时间是相同的,并且使用GST_BUFFER_DURATION
in设置GstBuffer
。
gst_util_uint64_scale()
是一个实用函数,可以缩放(乘除)可能很大的数字,而不必担心溢出。
可以使用 GST_BUFFER_DATA 访问缓冲区的字节 GstBuffer
(注意不要写超出缓冲区的末尾:您分配了它,所以您知道它的大小)。
我们将跳过波形生成,因为它超出了本教程的范围(它只是一种生成漂亮迷幻波形的有趣方式)。
/* 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);
一旦我们准备好缓冲区,我们将它appsrc
与 动作信号一起传递给它(参见播放教程 1:Playbin 使用push-buffer
末尾的信息框),然后 它因为我们不再需要它。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_BUFFER_DATA
数据大小。请记住,此缓冲区不必与我们在函数中生成的缓冲区匹配,路径中的任何元素都可能以任何方式更改缓冲区(此示例中未显示:在 apprc 和 appsink 之间的路径中只有一个tee,并且它不会更改缓冲区的内容)
然后我们gst_buffer_unref()
缓冲,本教程就完成了。
5. 结论
本教程展示了应用程序如何:
appsrc
使用该元素将数据注入管道。appsink
使用该元素从管道中检索数据。- 通过访问
GstBuffer
.
在基于 playbin 的管道中,相同的目标以略微不同的方式实现。回放教程 3:缩短管道展示了如何做到这一点。