跳转至

时间管理

目标

本教程介绍如何使用 GStreamer 时间相关工具。 特别:

  • 如何查询管道以获取流位置或持续时间等信息。

  • 如何搜索 (跳转) 到流中的其他位置 (时间)。

介绍

GstQuery 是一种允许向元素或填充请求一条信息的机制。在此示例中,我们询问管道是否允许查找(某些源(如实时流)不允许查找)。如果允许,则在电影运行了 10 秒后,我们使用 seek 跳到其他位置。

在前面的教程中,一旦我们设置并运行了管道,我们的 main 函数就坐着等待接收 ERROR 或 EOS 通过总线。这里,我们修改这个函数,周期性地唤醒 并查询 pipeline 以获取 stream 位置,以便我们可以在 屏幕。这类似于媒体播放器执行的作,更新 用户界面。

最后,每当流持续时间发生变化时,都会查询并更新流持续时间。

跳转示例

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

#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://gstreamer.freedesktop.org/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, &current)) {
          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、Mac OS X 或 Windows 上,或在 Linux 上使用以下特定命令:

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

如果您需要运行此代码的帮助,请参阅适用于您的平台的运行教程部分:Linux、Mac OS X 或 Windows 的

本教程将打开一个窗口并显示一部电影,并附带音频。媒体是从 Internet 获取的,因此该窗口可能需要几秒钟才能显示,具体取决于您的连接速度。播放影片 10 秒后,它会跳到新位置

必需安装的库: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,我们已经在基础教程 1:Hello world! 中看到过。 然而 playbin 本身就是一个 pipeline,在这种情况下,它是 pipeline 中唯一的元素,因此我们直接使用 playbin 元素。我们将跳过细节:剪辑的 URI 通过 URI 属性提供给 playbin,并且 pipeline 设置为播放状态。

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 毫秒的超时,因此,如果 在十分之一秒内未收到任何消息,该函数将返回 NULL 的 UI。我们将使用此逻辑来更新我们的 “UI”。

请注意,所需的超时必须指定为 GstClockTime,因此以纳秒为单位。表示不同时间单位的数字应乘以 GST_SECOND 或 GST_MSECOND 等宏。这也使您的代码更具可读性。

如果我们收到一条消息,我们在 handle_message 函数中处理它(下一小节),否则:

用户界面刷新

/* We got no message, this means the timeout expired */
if (data.playing) {

如果管道处于 PLAYING 状态,则该刷新屏幕了。如果我们没有处于 PLAYING 状态,我们就不想做任何事情,因为大多数查询都会失败。

我们每秒大约到达这里 10 次,对于我们的 UI 来说,这个刷新率已经足够好了。我们将在屏幕上打印当前媒体位置,我们可以通过查询管道来了解。这涉及几个步骤,这些步骤将在下一小节中介绍,但是,由于位置和持续时间是足够常见的查询,因此 GstElement 提供了更简单的现成替代方案:

/* Query the current position of the stream */
if (!gst_element_query_position (data.pipeline, GST_FORMAT_TIME, &current)) {
  g_printerr ("Could not query current position.\n");
}

gst_element_query_position() 隐藏了 query 对象的管理,直接为我们提供了结果。

/* 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 表示我们以时间单位指定目的地。其他 seek 格式使用不同的单位。

然后是 GstSeekFlags,让我们回顾一下最常见的:

  • GST_SEEK_FLAG_FLUSH:这会在执行查找之前丢弃管道中当前的所有数据。在重新填充管道并开始显示新数据时,可能会暂停一下,但会大大提高应用程序的“响应能力”。如果未提供此标志,则“过时”数据可能会显示一段时间,直到新位置出现在管道的末尾。

  • GST_SEEK_FLAG_KEY_UNIT:对于大多数编码的视频流,无法搜索到任意位置,而只能搜索到某些称为 Key Frames (关键帧) 的帧。使用此标志时,搜索实际上会移动到最近的关键帧,并立即开始生成数据。如果未使用此标志,管道将在内部移动到最近的关键帧(它没有其他选择),但在数据到达请求的位置之前不会显示数据。最后一种选择更准确,但可能需要更长的时间。

  • GST_SEEK_FLAG_ACCURATE:某些媒体剪辑没有提供足够的索引信息,这意味着搜索任意位置非常耗时。在这些情况下,GStreamer 通常会估计要搜索的位置,并且通常工作正常。如果此精度对于您的情况来说不够好(您看到搜索没有到达您要求的确切时间),请提供此标志。请注意,计算搜索位置可能需要更长的时间(在某些文件中很长)。

最后,我们提供要搜索的位置。由于我们请求GST_FORMAT_TIME,该值必须以纳秒为单位,因此为了简单起见,我们以秒为单位表示时间,然后乘以 GST_SECOND。

消息泵

handle_message 函数处理通过管道总线接收的所有消息。ERROR 和 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);

查找和时间查询通常只有在 PAUSED 或 PLAYING 状态,因为所有元素都有机会接收信息并配置自己。在这里,我们使用 playing 变量来跟踪管道是否处于 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() 创建一个 “seeking” 类型的新查询对象,格式为 GST_FORMAT_TIME。这表明我们通过指定要移动到的新时间来对 seek 感兴趣。我们也可以请求 GST_FORMAT_BYTES,然后查找源文件中的特定字节位置,但这通常不太有用。

然后,此查询对象将传递给管道 gst_element_query() 中。结果存储在同一个查询中,可以使用 gst_query_parse_seeking() 轻松检索。它提取一个布尔值,指示是否允许查找,以及可以查找的范围。

完成后,不要忘记取消引用 query 对象。

就是这样!有了这些知识,就可以构建一个媒体播放器,它根据当前流位置定期更新滑块,并允许通过移动滑块进行搜索!

总结

本教程展示了:

  • 如何使用 GstQuery 查询管道以获取信息

  • 如何使用 gst_element_query_position() 和 gst_element_query_duration() 获取位置和持续时间等常见信息

  • 如何使用 gst_element_seek_simple() 在流中查找任意位置

  • 在哪些状态下可以执行所有这些作。

下一个教程将介绍如何将 GStreamer 与 Graphical User Interface 工具包集成。

请记住,本页附带了本教程,您应该可以找到本教程的完整源代码以及构建本教程所需的任何附件。

评论