GStreamer官方教程系列
Basic tutorial 4: Time management
原文:https://gstreamer.freedesktop.org/documentation/tutorials/basic/time-management.html?gi-language=c
目标
本教程会展示怎么使用GStreamer时间相关设施。特别是:
- 如何询问管道以获取诸如流位置或长度之类的信息。
- 如何寻找(跳跃)到一个流中不同的位置(时间)。
引言
GstQuery是一种询问一个元件或一个pad以获取一条信息的机制。本例中,我们询问管道寻找是否是允许的(一些源,像直播流,不允许寻找)。如果允许,每当视频播放了10s就使用寻找跳到另一个位置。
在之前的教程中,一旦我们将管道设置完毕并播放,我们的主函数就等待直到错误或EOS经过总线。在这里,我们修改函数来周期性地唤醒壁并询问管道以获取流位置信息,这样我们就能将其打印在屏幕上。这就和一个媒体播放器作的差不多,定时更新用户接口。
最后,询问流长度并当其变化时更新信息。
Seeking example
代码basic-tutorial-4.c如下所示。
#include <gst/gst.h>
/* Structure to contain all our information, so we can pass it around */
typedef struct _CustomData {
GstElement *playbin; /* Our one and only element */
gboolean playing; /* Are we in the PLAYING state? */
gboolean terminate; /* Should we terminate execution? */
gboolean seek_enabled; /* Is seeking enabled for this media? */
gboolean seek_done; /* Have we performed the seek already? */
gint64 duration; /* How long does this media last, in nanoseconds */
} CustomData;
/* Forward definition of the message processing function */
static void handle_message (CustomData *data, GstMessage *msg);
int main(int argc, char *argv[]) {
CustomData data;
GstBus *bus;
GstMessage *msg;
GstStateChangeReturn ret;
data.playing = FALSE;
data.terminate = FALSE;
data.seek_enabled = FALSE;
data.seek_done = FALSE;
data.duration = GST_CLOCK_TIME_NONE;
/* Initialize GStreamer */
gst_init (&argc, &argv);
/* Create the elements */
data.playbin = gst_element_factory_make ("playbin", "playbin");
if (!data.playbin) {
g_printerr ("Not all elements could be created.\n");
return -1;
}
/* Set the URI to play */
g_object_set (data.playbin, "uri", "https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm", NULL);
/* Start playing */
ret = gst_element_set_state (data.playbin, 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.playbin);
return -1;
}
/* Listen to the bus */
bus = gst_element_get_bus (data.playbin);
do {
msg = gst_bus_timed_pop_filtered (bus, 100 * GST_MSECOND,
GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_DURATION);
/* Parse message */
if (msg != NULL) {
handle_message (&data, msg);
} else {
/* We got no message, this means the timeout expired */
if (data.playing) {
gint64 current = -1;
/* Query the current position of the stream */
if (!gst_element_query_position (data.playbin, GST_FORMAT_TIME, ¤t)) {
g_printerr ("Could not query current position.\n");
}
/* If we didn't know it yet, query the stream duration */
if (!GST_CLOCK_TIME_IS_VALID (data.duration)) {
if (!gst_element_query_duration (data.playbin, GST_FORMAT_TIME, &data.duration)) {
g_printerr ("Could not query current duration.\n");
}
}
/* Print current position and total duration */
g_print ("Position %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\r",
GST_TIME_ARGS (current), GST_TIME_ARGS (data.duration));
/* If seeking is enabled, we have not done it yet, and the time is right, seek */
if (data.seek_enabled && !data.seek_done && current > 10 * GST_SECOND) {
g_print ("\nReached 10s, performing seek...\n");
gst_element_seek_simple (data.playbin, GST_FORMAT_TIME,
GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, 30 * GST_SECOND);
data.seek_done = TRUE;
}
}
}
} while (!data.terminate);
/* Free resources */
gst_object_unref (bus);
gst_element_set_state (data.playbin, GST_STATE_NULL);
gst_object_unref (data.playbin);
return 0;
}
static void handle_message (CustomData *data, GstMessage *msg) {
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);
data->terminate = TRUE;
break;
case GST_MESSAGE_EOS:
g_print ("\nEnd-Of-Stream reached.\n");
data->terminate = TRUE;
break;
case GST_MESSAGE_DURATION:
/* The duration has changed, mark the current one as invalid */
data->duration = GST_CLOCK_TIME_NONE;
break;
case GST_MESSAGE_STATE_CHANGED: {
GstState old_state, new_state, pending_state;
gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->playbin)) {
g_print ("Pipeline state changed from %s to %s:\n",
gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
/* Remember whether we are in the PLAYING state or not */
data->playing = (new_state == GST_STATE_PLAYING);
if (data->playing) {
/* We just moved to PLAYING. Check if seeking is possible */
GstQuery *query;
gint64 start, end;
query = gst_query_new_seeking (GST_FORMAT_TIME);
if (gst_element_query (data->playbin, query)) {
gst_query_parse_seeking (query, NULL, &data->seek_enabled, &start, &end);
if (data->seek_enabled) {
g_print ("Seeking is ENABLED from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT "\n",
GST_TIME_ARGS (start), GST_TIME_ARGS (end));
} else {
g_print ("Seeking is DISABLED for this stream.\n");
}
}
else {
g_printerr ("Seeking query failed.");
}
gst_query_unref (query);
}
}
} break;
default:
/* We should not reach here */
g_printerr ("Unexpected message received.\n");
break;
}
gst_message_unref (msg);
}
Linux平台编译命令:gcc basic-tutorial-4.c -o basic-tutorial-4 `pkg-config --cflags --libs gstreamer-1.0`
讲解
/* Structure to contain all our information, so we can pass it around */
typedef struct _CustomData {
GstElement *playbin; /* Our one and only element */
gboolean playing; /* Are we in the PLAYING state? */
gboolean terminate; /* Should we terminate execution? */
gboolean seek_enabled; /* Is seeking enabled for this media? */
gboolean seek_done; /* Have we performed the seek already? */
gint64 duration; /* How long does this media last, in nanoseconds */
} CustomData;
/* Forward definition of the message processing function */
static void handle_message (CustomData *data, GstMessage *msg);
我们开始定义一个结构来包含我们需要的信息,这样我们就可以将其传递给其他函数。特别是,本例中我们将消息处理代码放到了其单独的位置handle_message函数中,因为它变得太长了。
我们构建了一个由一个元件playbin构成的管道,我们在Basic tutorial 1: Hello world!中已经见识过了。然而,playbin自己就是一个管道,在本例中它是管道当中的唯一的一个元件,因此我们直接使用playbin元件。我们会跳过细节:URI通过URI属性赋值给playbin,管道设置为播放状态。
msg = gst_bus_timed_pop_filtered (bus, 100 * GST_MSECOND,
GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_DURATION);
之前我们没有向gst_bus_timed_pop_filtered()中添加超时,意味着它在收到消息前不会返回。现在我们添加了一个100毫秒的超时,所以,如果0.1s内没有收到消息,函数返回NULL。我们将使用这个逻辑来更新我们的UI。
注意,预期的超时必须指定为一个GstClockTime,因此,这是纳秒形式的。数字表示不同的时间单位,需要乘以宏像GST_SECOND或者GST_MSECOND。这也让你的代码更加可读。
如果我们获取了一个消息,我们在handle_message函数中处理它。
用户界面刷新
/* We got no message, this means the timeout expired */
if (data.playing) {
如果管道在播放状态下,需要刷新屏幕。如果不是在播放状态下,我们不做任何操作,因为大多数询问会失败。
我们到这行大概每秒10次,这对我们的UI来说是一个很好的刷新率。我们将在屏幕上打印昂欠的媒体位置,我们可以通过询问管道来获取媒体位置。这包含了一些接下来会讲解的步骤,但是,因为位置和长度问询是非常普遍的问询,GstElement提供了更加简单的,现成的可选项:
/* Query the current position of the stream */
if (!gst_element_query_position (data.pipeline, GST_FORMAT_TIME, ¤t)) {
g_printerr ("Could not query current position.\n");
}
gst_element_query_position()隐藏了对问询对象的管理并直接提供了结果。
/* If we didn't know it yet, query the stream duration */
if (!GST_CLOCK_TIME_IS_VALID (data.duration)) {
if (!gst_element_query_duration (data.pipeline, GST_FORMAT_TIME, &data.duration)) {
g_printerr ("Could not query current duration.\n");
}
}
现在就可以通过另一个GstElement帮助函数gst_element_query_duration()知道流的长度。
/* Print current position and total duration */
g_print ("Position %" GST_TIME_FORMAT " / %" GST_TIME_FORMAT "\r",
GST_TIME_ARGS (current), GST_TIME_ARGS (data.duration));
注意GST_TIME_FORMAT和GST_TIME_ARGS等宏的使用来提供对用户友好的GStreamer时间展示。
/* If seeking is enabled, we have not done it yet, and the time is right, seek */
if (data.seek_enabled && !data.seek_done && current > 10 * GST_SECOND) {
g_print ("\nReached 10s, performing seek...\n");
gst_element_seek_simple (data.pipeline, GST_FORMAT_TIME,
GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, 30 * GST_SECOND);
data.seek_done = TRUE;
}
现在我们执行寻找操作,简单地通过调用gst_element_seek_simple()。大量寻找操作之中的复杂内容被隐藏在了这个方法中。
让我们来回顾参数。
GST_FORMAT_TIME表明我们在用时间单位来指定目标。其他寻找格式使用其他的单位。
然后就是GstSeekFlags,我们来看一些最常用的:
- GST_SEEK_FLAG_FLUSH:这会在寻找前抛弃所有管道中的数据。可能会暂停一会,因为管道重新填满数据并且新的数据开始出现,但是大大提高了应用的相应能力。如果没有提供该标志,过时的数据可能会展示一会直到新的位置出像在管道的末端。
- GST_SEEK_FLAG_KEY_UNIT:对大多数编码视频流,寻找任意位置是不可能的,这只能在一些称为关键帧的特殊帧上使用。当该标志被使用,管道会移动到最近的关键帧然后开始产生数据。如果该标志位没有给定,管道会内部移动到最近的关键帧(它没有别的选择)但是数据不会展示直到达到指定的位置。最后的选项可能更加精准,但是可能花费更长的时间。
- GST_SEEK_FLAG_ACCURATE:一些媒体并不提供足够的索引信息,这意味着寻找任意位置是非常消耗时间的。在这些情况下,GStreamer通常会预估要寻找的位置,通常这能获得很好的结果。如果这对你来说不够精准(你看到并没有精准地跳到你需要的位置),那么添加该标志位。注意,这可能需要更长的时间来计算位置(在某些文件中会非常长)。
最后,我们提供了一个寻找的位置。由于我们需要GST_FORMAT_TIME,这个值必须是纳秒的格式因此我们用秒来表现,为了简化,需要乘以GST_SECOND来获取纳秒。
消息泵
handle_message函数处理所有从管道总线接收到的消息。错误和EOS的处理和之前的教程一样,我们直接跳到有意思的部分:
case GST_MESSAGE_DURATION:
/* The duration has changed, mark the current one as invalid */
data->duration = GST_CLOCK_TIME_NONE;
break;
这个消息会在流长度变化时发送到总线上。我们在这里简单地将现在的流长度标记为无效的,这样之后就会重新查询流长度。
case GST_MESSAGE_STATE_CHANGED: {
GstState old_state, new_state, pending_state;
gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);
if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->pipeline)) {
g_print ("Pipeline state changed from %s to %s:\n",
gst_element_state_get_name (old_state), gst_element_state_get_name (new_state));
/* Remember whether we are in the PLAYING state or not */
data->playing = (new_state == GST_STATE_PLAYING);
寻找和时间问询通常会在暂停或播放状态下获得一个有效的恢复,因为所有的元件都有机会接受信息并配置自身。这里,我们使用playing变量来追踪管道是否在播放状态。同样,如果我们刚进入播放状态,我们进行第一次询问操作。我们询问管道在这个流上查找操作是否被允许:
if (data->playing) {
/* We just moved to PLAYING. Check if seeking is possible */
GstQuery *query;
gint64 start, end;
query = gst_query_new_seeking (GST_FORMAT_TIME);
if (gst_element_query (data->pipeline, query)) {
gst_query_parse_seeking (query, NULL, &data->seek_enabled, &start, &end);
if (data->seek_enabled) {
g_print ("Seeking is ENABLED from %" GST_TIME_FORMAT " to %" GST_TIME_FORMAT "\n",
GST_TIME_ARGS (start), GST_TIME_ARGS (end));
} else {
g_print ("Seeking is DISABLED for this stream.\n");
}
}
else {
g_printerr ("Seeking query failed.");
}
gst_query_unref (query);
}
gst_query_new_seeking()以GST_FORMAT_TIME格式创建一个新的“seeking”类型的问询对象。这表明我们只关心寻找到一个我们想要跳到的新的时间点。我们也可以要求GST_FORMAT_BYTES格式,这样就会查找源文件中的一个比特位置,但通常这并没有什么用。
这个问询对象之后通过gst_element_query()传递给管道。结果会存储在这个问询对象中,并且可以通过gst_query_parse_seeking()来简单地检索到。这会抽取一个布尔量表明寻找是否被允许,和一个寻找所允许的范围。
不要忘记用完后减去引用计数unref。
就是这样!有了这些知识,媒体播放器就可以基于现在的流时间来定期更新滑动条的位置,并且可以通过滑动滑动条来定位播放位置。
总结
本教程展示了:
- 怎么使用QstQuery来询问管道以获取信息。
- 怎么使用gst_element_query_position()和gst_element_query_duration()来获取常用的信息诸如位置和时长。
- 如何使用gst_element_seek_simple()来寻找一个任意的位置。
- 在哪个状态下,可以执行所有这些操作。