GStreamer基礎教程05 - 播放時間控制

John.Leng發表於2019-07-24

簡介

在多媒體應用中,我們通常需要查詢媒體檔案的總時間、當前播放位置,以及跳轉到指定的時間點。GStreamer提供了相應的介面來實現此功能,在本文中,我們將通過示例瞭解如何查詢時間資訊,以及如何進行跳轉到指定位置。

 

GStreamer查詢機制

GStreamer提供了GstQuery的查詢機制,用於查詢Element或Pad的相應資訊。例如:查詢當前的播放速率,產生的延遲,是否支援跳轉等。可檢視GstQuery文件瞭解所支援的型別。

要查詢所需的資訊,首先需要構造一個查詢的型別,然後使用Element或Pad的查詢介面獲取資料,最終再解析相應結果。 下面的例子介紹瞭如何使用GstQuery查詢Pipeline的總時間:

   GstQuery *query = gst_query_new_duration (GST_FORMAT_TIME);
   gboolean res = gst_element_query (pipeline, query);
   if (res) {
     gint64 duration;
     gst_query_parse_duration (query, NULL, &duration);
     g_print ("duration = %"GST_TIME_FORMAT, GST_TIME_ARGS (duration));
   } else {
     g_print ("duration query failed...");
   }
   gst_query_unref (query);

示例程式碼

在本示例中,我們通過查詢Pipeline是否支援跳轉(seeking),如果支援跳轉(有些媒體不支援跳轉,例如實時視訊),我們會在播放10秒後跳轉到其他位置。
在以前的示例中,我們在Pipeline開始執行後,只等待ERROR和EOS訊息,然後退出。本例中,我們會在訊息等在中設定等待超時時間,超時後,我們會去查詢當前播放的時間,用於顯示,這與播放器的進度條類似。

#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_CHANGED);

    /* 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 ("End-Of-Stream reached.\n");
      data->terminate = TRUE;
      break;
    case GST_MESSAGE_DURATION_CHANGED:
      /* 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);
}
View Code

將原始碼儲存為basic-tutorial-5.c,執行下列命令可得到編譯結果:
gcc basic-tutorial-5.c -o basic-tutorial-5 `pkg-config --cflags --libs gstreamer-1.0`

原始碼分析

示例前部分內容與其他示例類似,構造Pipeline並使其進入PLAYING狀態。之後開始監聽Bus上的訊息。

msg = gst_bus_timed_pop_filtered (bus, 100 * GST_MSECOND,
    GST_MESSAGE_STATE_CHANGED | GST_MESSAGE_ERROR | GST_MESSAGE_EOS | GST_MESSAGE_DURATION_CHANGED);

與以前的示例相比,我們在gst_bus_timed_pop_filtered ()中加入了超時時間(100毫秒),這使得此函式如果在100毫秒內沒有收到任何訊息就會返回超時(msg == NULL),我們會在超時中去更新當前時間,如果返回相應訊息(msg != NULL),我們在handle_message中處理相應訊息。

GStreamer內部有統一的時間型別(GstClockTime),時間計算方式為:GstClockTime = 數值 x 時間單位。GStreamer提供了3種時間單位(巨集定義):GST_SECOND(秒),GST_MSECOND(毫秒),GST_NSECOND(納秒)。例如:
10秒: 10 * GST_SECOND
100毫秒:100 * GST_MSECOND
100納秒:100 * GST_NSECOND

 

重新整理播放時間

/* We got no message, this means the timeout expired */
if (data.playing) {
/* 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");
}
/* 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");
  }
}

我們首先判斷Pipeline的狀態,僅在PLAYING狀態時才更新當前時間,在非PLAYING狀態時查詢可能失敗。這部分邏輯每秒大概會執行10次,頻率足夠用於介面的重新整理。這裡我們只將查詢到的時間輸出到終端。
GstElement封裝了相應的介面分別用於查詢當前時間(gst_element_query_position)和總時間(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 幫助我們方便地將GstClockTime的值轉換為: ”時:分:秒“格式的字串輸出。

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

我們同時在超時處理中判斷是否需要進行seek操作(在播放到10s時,自動跳轉到30s),這裡我們直接在Pipeline物件上使用gst_element_seek_simple()來執行跳轉操作。
gst_element_seek_simple所需要的引數為:

  • element : 需要執行seek操作的Element,這裡是Pipeline。
  • format:執行seek的型別,這裡使用GST_FORMAT_TIME表示我們基於時間的方式進行跳轉。其他支援的型別可以檢視 GstFormat
  • seek_flags :通過標識指定seek的行為。 常用的標識如下,其他支援的flag詳見GstSeekFlags。 
    • GST_SEEK_FLAG_FLUSH:在執行seek前,清除Pipeline中所有buffer中快取的資料。這可能導致Pipeline在填充的新資料被顯示之前出現短暫的等待,但能提高應用更快的響應速度。如果不指定這個標誌,Pipeline中的所有快取資料會依次輸出,然後才會播放跳轉的位置,會導致一定的延遲。
    • GST_SEEK_FLAG_KEY_UNIT:對於大多數的視訊,如果跳轉的位置不是關鍵幀,需要依次解碼該幀所依賴的幀(I幀及P幀)後,才能解碼此非關鍵幀。使用這個標識後,seek會自動從最近的I幀開始播放。這個標識降低了seek的精度,提高了seek的效率。
    • GST_SEEK_FLAG_ACCURATE:一些媒體檔案沒有提供足夠的索引資訊,在這種檔案中執行seek操作會非常耗時,針對這類檔案,GStreamer通過內部計算得到需要跳轉的位置,大部分的計算結果都是正確的。如果seek的位置不能達到所需精度時,可以增加此標識。但需要注意的是,使用此標識可能會導致seek耗費更多時間來尋找精確的位置。
  • seek_pos :需要跳轉的位置,前面指定了seek的型別為時間,所以這裡是30秒。

訊息處理

我們在handle_message介面中處理所有Pipeline上的訊息,ERROR和EOS與以前示例處理方式相同,此例中新增了以下內容:

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

跳轉和時間查詢操作僅在PUASED和PLAYING狀態時才能得到正確的結果,因為所有的Element只能在這2個狀態才能接收處理seek和query的指令。這裡會儲存播放的狀態便於後續使用,並且在進入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作為引數,表明我們需要知道當前的檔案是否支援通過時間進行跳轉。我們同樣可以使用GST_FORMAT_BYTES作為引數,用於查詢是否可以根據檔案的偏移量來就行跳轉,但這種使用方式不常見。
  • 接著,將查詢物件傳入gst_element_query()查詢,並得到結果。
  • 最後,通過gst_query_parse_seeking()解析是否支援跳轉及所支援的範圍。

一定需要記住在使用完後釋放查詢物件

 

總結

在本教程中,我們學習了:

  • 如何通過GstQuery查詢Pipeline上的資訊。
  • 如何通過gst_element_query_position()和gst_element_query_duration() 查詢當前時間和總時間。
  • 如何通過gst_element_seek_simple()操作跳轉到任意位置。
  • 在哪些狀態可以執行查詢和跳轉操作。

後續我們將介紹如何獲取媒體檔案中的後設資料(Metadata)。

引用

https://gstreamer.freedesktop.org/documentation/tutorials/basic/time-management.html?gi-language=c
https://gstreamer.freedesktop.org/documentation/additional/design/query.html?gi-language=c
https://gstreamer.freedesktop.org/documentation/gstreamer/gstquery.html?gi-language=c

 

作者:John.Leng
本文版權歸作者所有,歡迎轉載。商業轉載請聯絡作者獲得授權,非商業轉載請在文章頁面明顯位置給出原文連線.

相關文章