本教程介紹瞭如何整合 GStreamer 到一個圖形用戶界面(GUI)工具包像GStreamer的集成GTK +。基本上,當GUI與用戶交互時,GStreamer須要關心媒體的播放。最有趣的部分是這兩個庫的互動:指示GStreamer輸出視頻到GTK +的窗口和轉發用戶的操做到GStreamer。html
特別是,您將瞭解到:web
如何告訴GStreamer將視頻輸出到一個特定的窗口(而不是建立本身的窗口)。windows
如何根據由GStreamer發送的信息而不斷刷新用戶圖形界面。數組
如何從GStreamer的多個線程中更新用戶圖形界面。app
有一種機制來只訂閱您感興趣的信息,而不是全部的信息都被告知,。less
咱們將使用GTK + 工具包創建一個媒體播放器,但這些概念也適用於其餘工具包,如 QT,例如。基本的 GTK+ 知識將有助於理解本教程。ide
主要的一點是告訴GStreamer輸出視頻到咱們選擇的窗口。具體的機制依賴於操做系統(或者更確切地說是窗口系統),但GStreamer中提供了一個抽象層,具備平臺獨立性。這種獨立性是經過在
XOverlay
接口,它容許應用程序告訴視頻接收器(video sink)一個應該獲得渲染的窗口的句柄。函數
![]() |
圖形對象的接口 GObject的 |
另外一個問題是,GUI工具包一般只容許經過主(或應用程序)的線程操做的圖形化的「小部件」,,而GStreamer的一般產生多個線程來採起不一樣的任務護理。調用GTK + 從內回調函數一般會失敗,由於回調調用線程,這並不須要是主線程中執行。這個問題能夠經過發佈一條消息到GStreamer的總線上,而後由主線程的回調來響應該消息。oop
最後,到目前爲止,咱們已經註冊了一個能夠獲取每次出如今總線上的消息的 方法 handle_message
,這迫使咱們要分析每一個消息,看它是不是咱們感興趣的。在本教程中不一樣的方法用於爲各類消息註冊一個回調,因此有較少的分析和總體更少的代碼。
讓咱們來編寫一個基於playbin2,具備圖形用戶界面、很是簡單的媒體播放器!
將此代碼複製到名爲的文本文件
。basic-tutorial-5.c
#include <string.h> #include <gtk/gtk.h> #include <gst/gst.h> #include <gst/interfaces/xoverlay.h> #include <gdk/gdk.h> #if defined (GDK_WINDOWING_X11) #include <gdk/gdkx.h> #elif defined (GDK_WINDOWING_WIN32) #include <gdk/gdkwin32.h> #elif defined (GDK_WINDOWING_QUARTZ) #include <gdk/gdkquartz.h> #endif /* Structure to contain all our information, so we can pass it around */ typedef struct _CustomData { GstElement *playbin2; /* Our one and only pipeline */ GtkWidget *slider; /* Slider widget to keep track of current position */ GtkWidget *streams_list; /* Text widget to display info about the streams */ gulong slider_update_signal_id; /* Signal ID for the slider update signal */ GstState state; /* Current state of the pipeline */ gint64 duration; /* Duration of the clip, in nanoseconds */ } CustomData; /* This function is called when the GUI toolkit creates the physical window that will hold the video. * At this point we can retrieve its handler (which has a different meaning depending on the windowing system) * and pass it to GStreamer through the XOverlay interface. */ static void realize_cb (GtkWidget *widget, CustomData *data) { GdkWindow *window = gtk_widget_get_window (widget); guintptr window_handle; if (!gdk_window_ensure_native (window)) g_error ("Couldn't create native window needed for GstXOverlay!"); /* Retrieve window handler from GDK */ #if defined (GDK_WINDOWING_WIN32) window_handle = (guintptr)GDK_WINDOW_HWND (window); #elif defined (GDK_WINDOWING_QUARTZ) window_handle = gdk_quartz_window_get_nsview (window); #elif defined (GDK_WINDOWING_X11) window_handle = GDK_WINDOW_XID (window); #endif /* Pass it to playbin2, which implements XOverlay and will forward it to the video sink */ gst_x_overlay_set_window_handle (GST_X_OVERLAY (data->playbin2), window_handle); } /* This function is called when the PLAY button is clicked */ static void play_cb (GtkButton *button, CustomData *data) { gst_element_set_state (data->playbin2, GST_STATE_PLAYING); } /* This function is called when the PAUSE button is clicked */ static void pause_cb (GtkButton *button, CustomData *data) { gst_element_set_state (data->playbin2, GST_STATE_PAUSED); } /* This function is called when the STOP button is clicked */ static void stop_cb (GtkButton *button, CustomData *data) { gst_element_set_state (data->playbin2, GST_STATE_READY); } /* This function is called when the main window is closed */ static void delete_event_cb (GtkWidget *widget, GdkEvent *event, CustomData *data) { stop_cb (NULL, data); gtk_main_quit (); } /* This function is called everytime the video window needs to be redrawn (due to damage/exposure, * rescaling, etc). GStreamer takes care of this in the PAUSED and PLAYING states, otherwise, * we simply draw a black rectangle to avoid garbage showing up. */ static gboolean expose_cb (GtkWidget *widget, GdkEventExpose *event, CustomData *data) { if (data->state < GST_STATE_PAUSED) { GtkAllocation allocation; GdkWindow *window = gtk_widget_get_window (widget); cairo_t *cr; /* Cairo is a 2D graphics library which we use here to clean the video window. * It is used by GStreamer for other reasons, so it will always be available to us. */ gtk_widget_get_allocation (widget, &allocation); cr = gdk_cairo_create (window); cairo_set_source_rgb (cr, 0, 0, 0); cairo_rectangle (cr, 0, 0, allocation.width, allocation.height); cairo_fill (cr); cairo_destroy (cr); } return FALSE; } /* This function is called when the slider changes its position. We perform a seek to the * new position here. */ static void slider_cb (GtkRange *range, CustomData *data) { gdouble value = gtk_range_get_value (GTK_RANGE (data->slider)); gst_element_seek_simple (data->playbin2, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, (gint64)(value * GST_SECOND)); } /* This creates all the GTK+ widgets that compose our application, and registers the callbacks */ static void create_ui (CustomData *data) { GtkWidget *main_window; /* The uppermost window, containing all other windows */ GtkWidget *video_window; /* The drawing area where the video will be shown */ GtkWidget *main_box; /* VBox to hold main_hbox and the controls */ GtkWidget *main_hbox; /* HBox to hold the video_window and the stream info text widget */ GtkWidget *controls; /* HBox to hold the buttons and the slider */ GtkWidget *play_button, *pause_button, *stop_button; /* Buttons */ main_window = gtk_window_new (GTK_WINDOW_TOPLEVEL); g_signal_connect (G_OBJECT (main_window), "delete-event", G_CALLBACK (delete_event_cb), data); video_window = gtk_drawing_area_new (); gtk_widget_set_double_buffered (video_window, FALSE); g_signal_connect (video_window, "realize", G_CALLBACK (realize_cb), data); g_signal_connect (video_window, "expose_event", G_CALLBACK (expose_cb), data); play_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_PLAY); g_signal_connect (G_OBJECT (play_button), "clicked", G_CALLBACK (play_cb), data); pause_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_PAUSE); g_signal_connect (G_OBJECT (pause_button), "clicked", G_CALLBACK (pause_cb), data); stop_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_STOP); g_signal_connect (G_OBJECT (stop_button), "clicked", G_CALLBACK (stop_cb), data); data->slider = gtk_hscale_new_with_range (0, 100, 1); gtk_scale_set_draw_value (GTK_SCALE (data->slider), 0); data->slider_update_signal_id = g_signal_connect (G_OBJECT (data->slider), "value-changed", G_CALLBACK (slider_cb), data); data->streams_list = gtk_text_view_new (); gtk_text_view_set_editable (GTK_TEXT_VIEW (data->streams_list), FALSE); controls = gtk_hbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (controls), play_button, FALSE, FALSE, 2); gtk_box_pack_start (GTK_BOX (controls), pause_button, FALSE, FALSE, 2); gtk_box_pack_start (GTK_BOX (controls), stop_button, FALSE, FALSE, 2); gtk_box_pack_start (GTK_BOX (controls), data->slider, TRUE, TRUE, 2); main_hbox = gtk_hbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (main_hbox), video_window, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (main_hbox), data->streams_list, FALSE, FALSE, 2); main_box = gtk_vbox_new (FALSE, 0); gtk_box_pack_start (GTK_BOX (main_box), main_hbox, TRUE, TRUE, 0); gtk_box_pack_start (GTK_BOX (main_box), controls, FALSE, FALSE, 0); gtk_container_add (GTK_CONTAINER (main_window), main_box); gtk_window_set_default_size (GTK_WINDOW (main_window), 640, 480); gtk_widget_show_all (main_window); } /* This function is called periodically to refresh the GUI */ static gboolean refresh_ui (CustomData *data) { GstFormat fmt = GST_FORMAT_TIME; gint64 current = -1; /* We do not want to update anything unless we are in the PAUSED or PLAYING states */ if (data->state < GST_STATE_PAUSED) return TRUE; /* 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->playbin2, &fmt, &data->duration)) { g_printerr ("Could not query current duration.\n"); } else { /* Set the range of the slider to the clip duration, in SECONDS */ gtk_range_set_range (GTK_RANGE (data->slider), 0, (gdouble)data->duration / GST_SECOND); } } if (gst_element_query_position (data->playbin2, &fmt, ¤t)) { /* Block the "value-changed" signal, so the slider_cb function is not called * (which would trigger a seek the user has not requested) */ g_signal_handler_block (data->slider, data->slider_update_signal_id); /* Set the position of the slider to the current pipeline positoin, in SECONDS */ gtk_range_set_value (GTK_RANGE (data->slider), (gdouble)current / GST_SECOND); /* Re-enable the signal */ g_signal_handler_unblock (data->slider, data->slider_update_signal_id); } return TRUE; } /* This function is called when new metadata is discovered in the stream */ static void tags_cb (GstElement *playbin2, gint stream, CustomData *data) { /* We are possibly in a GStreamer working thread, so we notify the main * thread of this event through a message in the bus */ gst_element_post_message (playbin2, gst_message_new_application (GST_OBJECT (playbin2), gst_structure_new ("tags-changed", NULL))); } /* 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); /* Set the pipeline to READY (which stops playback) */ gst_element_set_state (data->playbin2, GST_STATE_READY); } /* This function is called when an End-Of-Stream message is posted on the bus. * We just set the pipeline to READY (which stops playback) */ static void eos_cb (GstBus *bus, GstMessage *msg, CustomData *data) { g_print ("End-Of-Stream reached.\n"); gst_element_set_state (data->playbin2, GST_STATE_READY); } /* This function is called when the pipeline changes states. We use it to * keep track of the current state. */ static void state_changed_cb (GstBus *bus, GstMessage *msg, CustomData *data) { 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->playbin2)) { data->state = new_state; g_print ("State set to %s\n", gst_element_state_get_name (new_state)); if (old_state == GST_STATE_READY && new_state == GST_STATE_PAUSED) { /* For extra responsiveness, we refresh the GUI as soon as we reach the PAUSED state */ refresh_ui (data); } } } /* Extract metadata from all the streams and write it to the text widget in the GUI */ static void analyze_streams (CustomData *data) { gint i; GstTagList *tags; gchar *str, *total_str; guint rate; gint n_video, n_audio, n_text; GtkTextBuffer *text; /* Clean current contents of the widget */ text = gtk_text_view_get_buffer (GTK_TEXT_VIEW (data->streams_list)); gtk_text_buffer_set_text (text, "", -1); /* Read some properties */ g_object_get (data->playbin2, "n-video", &n_video, NULL); g_object_get (data->playbin2, "n-audio", &n_audio, NULL); g_object_get (data->playbin2, "n-text", &n_text, NULL); for (i = 0; i < n_video; i++) { tags = NULL; /* Retrieve the stream's video tags */ g_signal_emit_by_name (data->playbin2, "get-video-tags", i, &tags); if (tags) { total_str = g_strdup_printf ("video stream %d:\n", i); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); gst_tag_list_get_string (tags, GST_TAG_VIDEO_CODEC, &str); total_str = g_strdup_printf (" codec: %s\n", str ? str : "unknown"); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); g_free (str); gst_tag_list_free (tags); } } for (i = 0; i < n_audio; i++) { tags = NULL; /* Retrieve the stream's audio tags */ g_signal_emit_by_name (data->playbin2, "get-audio-tags", i, &tags); if (tags) { total_str = g_strdup_printf ("\naudio stream %d:\n", i); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); if (gst_tag_list_get_string (tags, GST_TAG_AUDIO_CODEC, &str)) { total_str = g_strdup_printf (" codec: %s\n", str); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); g_free (str); } if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &str)) { total_str = g_strdup_printf (" language: %s\n", str); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); g_free (str); } if (gst_tag_list_get_uint (tags, GST_TAG_BITRATE, &rate)) { total_str = g_strdup_printf (" bitrate: %d\n", rate); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); } gst_tag_list_free (tags); } } for (i = 0; i < n_text; i++) { tags = NULL; /* Retrieve the stream's subtitle tags */ g_signal_emit_by_name (data->playbin2, "get-text-tags", i, &tags); if (tags) { total_str = g_strdup_printf ("\nsubtitle stream %d:\n", i); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &str)) { total_str = g_strdup_printf (" language: %s\n", str); gtk_text_buffer_insert_at_cursor (text, total_str, -1); g_free (total_str); g_free (str); } gst_tag_list_free (tags); } } } /* This function is called when an "application" message is posted on the bus. * Here we retrieve the message posted by the tags_cb callback */ static void application_cb (GstBus *bus, GstMessage *msg, CustomData *data) { if (g_strcmp0 (gst_structure_get_name (msg->structure), "tags-changed") == 0) { /* If the message is the "tags-changed" (only one we are currently issuing), update * the stream info GUI */ analyze_streams (data); } } int main(int argc, char *argv[]) { CustomData data; GstStateChangeReturn ret; GstBus *bus; /* Initialize GTK */ gtk_init (&argc, &argv); /* Initialize GStreamer */ gst_init (&argc, &argv); /* Initialize our data structure */ memset (&data, 0, sizeof (data)); data.duration = GST_CLOCK_TIME_NONE; /* Create the elements */ data.playbin2 = gst_element_factory_make ("playbin2", "playbin2"); if (!data.playbin2) { g_printerr ("Not all elements could be created.\n"); return -1; } /* Set the URI to play */ g_object_set (data.playbin2, "uri", "http://docs.gstreamer.com/media/sintel_trailer-480p.webm", NULL); /* Connect to interesting signals in playbin2 */ g_signal_connect (G_OBJECT (data.playbin2), "video-tags-changed", (GCallback) tags_cb, &data); g_signal_connect (G_OBJECT (data.playbin2), "audio-tags-changed", (GCallback) tags_cb, &data); g_signal_connect (G_OBJECT (data.playbin2), "text-tags-changed", (GCallback) tags_cb, &data); /* Create the GUI */ create_ui (&data); /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */ bus = gst_element_get_bus (data.playbin2); gst_bus_add_signal_watch (bus); g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data); g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback)eos_cb, &data); g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, &data); g_signal_connect (G_OBJECT (bus), "message::application", (GCallback)application_cb, &data); gst_object_unref (bus); /* Start playing */ ret = gst_element_set_state (data.playbin2, 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.playbin2); return -1; } /* Register a function that GLib will call every second */ g_timeout_add_seconds (1, (GSourceFunc)refresh_ui, &data); /* Start the GTK main loop. We will not regain control until gtk_main_quit is called. */ gtk_main (); /* Free resources */ gst_element_set_state (data.playbin2, GST_STATE_NULL); gst_object_unref (data.playbin2); return 0; }
關於本教程的結構,咱們不打算使用提早的函數定義了:函數將被定義在使用以前。此外,爲了解釋清楚,其中的代碼片斷顯示的順序不會永遠與程序順序相匹配。使用行號來在完整代碼中定位片斷。
#include <gdk/gdk.h> #if defined (GDK_WINDOWING_X11) #include <gdk/gdkx.h> #elif defined (GDK_WINDOWING_WIN32) #include <gdk/gdkwin32.h> #elif defined (GDK_WINDOWING_QUARTZ) #include <gdk/gdkquartzwindow.h> #endif
值得關注的第一件事是,咱們再也不是徹底獨立於平臺的。咱們須要包含適當的GDK標題的窗口系統。幸運的是,沒有那麼多的可支持視窗系統,因此這三行每每就夠了:X11適用於Linux,Win32適用於Windows和Quartz適用於Mac OSX系統。
本教程是由回調函數組成,這些回調將是從GStreamer的或GTK +調用的,因此讓咱們來回顧一下主函數,註冊全部這些回調。
int main(int argc, char *argv[]) { CustomData data; GstStateChangeReturn ret; GstBus *bus; /* Initialize GTK */ gtk_init (&argc, &argv); /* Initialize GStreamer */ gst_init (&argc, &argv); /* Initialize our data structure */ memset (&data, 0, sizeof (data)); data.duration = GST_CLOCK_TIME_NONE; /* Create the elements */ data.playbin2 = gst_element_factory_make ("playbin2", "playbin2"); if (!data.playbin2) { g_printerr ("Not all elements could be created.\n"); return -1; } /* Set the URI to play */ g_object_set (data.playbin2, "uri", " "http://docs.gstreamer.com/media/sintel_trailer-480p.webm", NULL);
標準的GStreamer的初始化和playbin2管道的建立,以及GTK +的初始化。沒有太多新意。
/* Connect to interesting signals in playbin2 */ g_signal_connect (G_OBJECT (data.playbin2), "video-tags-changed", (GCallback) tags_cb, &data); g_signal_connect (G_OBJECT (data.playbin2), "audio-tags-changed", (GCallback) tags_cb, &data); g_signal_connect (G_OBJECT (data.playbin2), "text-tags-changed", (GCallback) tags_cb, &data);
當新的標籤(元數據)出如今流中,咱們感興趣的事件被通知。爲簡單起見,咱們將用同一個回調 tags_cb 處理各類標記(視頻,音頻和文本)。
/* Create the GUI */ create_ui (&data);
全部的GTK +控件的建立和信號登記發生在這個函數。它僅包含GTK相關的函數調用,所以咱們將跳過它的定義。其註冊的信號傳達用戶命令,以下方所示。
/* Instruct the bus to emit signals for each received message, and connect to the interesting signals */ bus = gst_element_get_bus (data.playbin2); gst_bus_add_signal_watch (bus); g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data); g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback)eos_cb, &data); g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, &data); g_signal_connect (G_OBJECT (bus), "message::application", (GCallback)application_cb, &data); gst_object_unref (bus);
在Playback tutorial 1: Playbin2 usage , gst_bus_add_watch() 用於註冊從GStreamer的總線接收每一個消息的函數。咱們能夠達到更精細的粒度經過使用信號來代替,這使咱們可以只註冊咱們感興趣的消息。
gst_bus_add_signal_watch()
咱們指示總線每收到一條消息時發出一個信號。這個信號的名稱爲 message::detail
,其中的
是觸發信號發射的消息。例如,當總線接收到的EOS消息時,它發出一個以message::eos命名的信號。detail
本教程使用的是Signals
的細節,只註冊咱們關心的消息。若是咱們已經註冊 message
的信號,咱們將通知全部單個消息,就像
會作的同樣。gst_bus_add_watch()
記住的是,爲了使總線的觀察機制工做(不管是gst_bus_add_watch()
或gst_bus_add_signal_watch()
),必須有GLib的主循環(
運行。在這種狀況下,它被隱藏在GTK + 主循環的內部。Main Loop
)
/* Register a function that GLib will call every second */ g_timeout_add_seconds (1, (GSourceFunc)refresh_ui, &data);
爲了動態控制GTK+,咱們使用
g_timeout_add_seconds ()
來註冊另外一個回調,每次超時,它將唄調用一次。咱們將從 refresh_ui 函數中調用它來刷新GUI。
在此以後,咱們已經完成了安裝並能啓動GTK +主循環。咱們會從咱們的回調從新得到控制時,有趣的事情發生。讓咱們回顧一下回調。每次回調都有一個不一樣的簽名,這取決於誰將會調用它。你能夠看看簽名(參數的意義和返回值),在信號的文檔中。
/* This function is called when the GUI toolkit creates the physical window that will hold the video. * At this point we can retrieve its handler (which has a different meaning depending on the windowing system) * and pass it to GStreamer through the XOverlay interface. */ static void realize_cb (GtkWidget *widget, CustomData *data) { GdkWindow *window = gtk_widget_get_window (widget); guintptr window_handle; if (!gdk_window_ensure_native (window)) g_error ("Couldn't create native window needed for GstXOverlay!"); /* Retrieve window handler from GDK */ #if defined (GDK_WINDOWING_WIN32) window_handle = (guintptr)GDK_WINDOW_HWND (window); #elif defined (GDK_WINDOWING_QUARTZ) window_handle = gdk_quartz_window_get_nsview (window); #elif defined (GDK_WINDOWING_X11) window_handle = GDK_WINDOW_XID (window); #endif /* Pass it to playbin2, which implements XOverlay and will forward it to the video sink */ gst_x_overlay_set_window_handle (GST_X_OVERLAY (data->playbin2), window_handle); }
代碼自己會完成會話。此時在應用程序的生命週期中,咱們知道即將表達視頻的窗口句柄(不管是一個X11的XID
,一個Window's HWND
或Quartz's NSView
)。咱們只是從窗口系統進行檢索,並經過 XOverlay 接口使用
。gst_x_overlay_set_window_handle() 把它傳遞給
playbin2
將查找視頻接收段並將窗口句柄傳遞給本身,因此它不會建立本身的窗口,並使用這一個。playbin2
這裏不用看太多; playbin2
和
XOverlay
真正大大地簡化這個過程了!
/* This function is called when the PLAY button is clicked */ static void play_cb (GtkButton *button, CustomData *data) { gst_element_set_state (data->playbin2, GST_STATE_PLAYING); } /* This function is called when the PAUSE button is clicked */ static void pause_cb (GtkButton *button, CustomData *data) { gst_element_set_state (data->playbin2, GST_STATE_PAUSED); } /* This function is called when the STOP button is clicked */ static void stop_cb (GtkButton *button, CustomData *data) { gst_element_set_state (data->playbin2, GST_STATE_READY); }
這三個小回調與GUI的播放,暫停和中止按鈕相關聯。他們簡單地將管道輸送到相應的狀態。請注意,在中止狀態下,咱們設置管道的狀態爲就緒(READY)。咱們也能夠把管道的全部向下的狀態置空,但這樣過渡會慢一些,由於有些資源(如音頻設備)將須要被釋放並從新獲取。
/* This function is called when the main window is closed */ static void delete_event_cb (GtkWidget *widget, GdkEvent *event, CustomData *data) { stop_cb (NULL, data); gtk_main_quit (); }
gtk_main_quit()將最終再調用到主函數中的 gtk_main_run()以終止程序。在這裏,咱們在當主窗口被關閉、管道被中止(只是爲了整潔)以後調用它。
/* This function is called everytime the video window needs to be redrawn (due to damage/exposure, * rescaling, etc). GStreamer takes care of this in the PAUSED and PLAYING states, otherwise, * we simply draw a black rectangle to avoid garbage showing up. */ static gboolean expose_cb (GtkWidget *widget, GdkEventExpose *event, CustomData *data) { if (data->state < GST_STATE_PAUSED) { GtkAllocation allocation; GdkWindow *window = gtk_widget_get_window (widget); cairo_t *cr; /* Cairo is a 2D graphics library which we use here to clean the video window. * It is used by GStreamer for other reasons, so it will always be available to us. */ gtk_widget_get_allocation (widget, &allocation); cr = gdk_cairo_create (window); cairo_set_source_rgb (cr, 0, 0, 0); cairo_rectangle (cr, 0, 0, allocation.width, allocation.height); cairo_fill (cr); cairo_destroy (cr); } return FALSE; }
當有數據流(在PAUSED
和PLAYING
狀態)的視頻接收器採用清爽的視頻窗口的內容負責。在其餘的狀況下,可是,它不會,因此咱們必須這樣作。在這個例子中,咱們只是填補了窗口,一個黑色矩形。
當有數據流(在PAUSED 和 PLAYING 狀態),視頻接收器刷新視頻窗口的內容。在其餘狀況下,它則不刷新。在這個例子中,咱們只是用一個黑色矩形填補了窗口。
/* This function is called when the slider changes its position. We perform a seek to the * new position here. */ static void slider_cb (GtkRange *range, CustomData *data) { gdouble value = gtk_range_get_value (GTK_RANGE (data->slider)); gst_element_seek_simple (data->playbin2, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT, (gint64)(value * GST_SECOND)); }
這是一個經過與GStreamer 和 GTK+合做很容易地完成具備一個滑動條的複雜的GUI的播放器的例子。若是滑塊一直拖動到新的位置,告訴GStreamer經過 gst_element_seek_simple()
尋求到該位置(如在 Basic tutorial 4: Time management看到的同樣)。滑塊已設置它如今的秒一級的值。
值得一提的是,一些性能(和響應)能夠經過作一些限制來得到,這就是不迴應每個用戶的請求。因爲尋道操做勢必會須要必定的時間,它每每是須要等待半秒鐘(例如),在容許後 一個請求前。不然在響應一個請求前,若是用戶拖動滑塊瘋狂,應用程序看起來會沒有反應。
/* This function is called periodically to refresh the GUI */ static gboolean refresh_ui (CustomData *data) { GstFormat fmt = GST_FORMAT_TIME; gint64 current = -1; /* We do not want to update anything unless we are in the PAUSED or PLAYING states */ if (data->state < GST_STATE_PAUSED) return TRUE;
此功能將移動滑塊到與媒體文件對應的位置。首先,若是咱們不是在PLAYING
狀態,咱們什麼都沒有作這裏(plus,位置和持續時間的查詢,一般會失敗)。
/* 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->playbin2, &fmt, &data->duration)) { g_printerr ("Could not query current duration.\n"); } else { /* Set the range of the slider to the clip duration, in SECONDS */ gtk_range_set_range (GTK_RANGE (data->slider), 0, (gdouble)data->duration / GST_SECOND); } }
若是咱們不知道媒體的持續時間,咱們能夠從新獲取它,這樣咱們能夠設定滑塊的範圍。
if (gst_element_query_position (data->playbin2, &fmt, ¤t)) { /* Block the "value-changed" signal, so the slider_cb function is not called * (which would trigger a seek the user has not requested) */ g_signal_handler_block (data->slider, data->slider_update_signal_id); /* Set the position of the slider to the current pipeline positoin, in SECONDS */ gtk_range_set_value (GTK_RANGE (data->slider), (gdouble)current / GST_SECOND); /* Re-enable the signal */ g_signal_handler_unblock (data->slider, data->slider_update_signal_id); } return TRUE;
咱們查詢當前管道的位置,並相應地設置滑塊的位置。這將觸發一個 value-changed
的信號,當用戶拖動滑塊。因爲咱們不但願發生seek,除非用戶要求,咱們禁用 value-changed 這一信號的發射使用
和g_signal_handler_block()
。g_signal_handler_unblock() 函數
從這個函數返回TRUE,事件會繼續傳遞。若是返回FALSE,定時器將被刪除。
/* This function is called when new metadata is discovered in the stream */ static void tags_cb (GstElement *playbin2, gint stream, CustomData *data) { /* We are possibly in a GStreamer working thread, so we notify the main * thread of this event through a message in the bus */ gst_element_post_message (playbin2, gst_message_new_application (GST_OBJECT (playbin2), gst_structure_new ("tags-changed", NULL))); }
這是本教程的重點之一。這個函數會被調用時,新的標籤被髮如今媒體上,從流的線程,這是另外一個線程而不是應用程序(或主)的線程。咱們要在這裏作的是更新一個GTK +控件以反映這個新的信息,但GTK +不容許從主線程之外的線程進行次操做。
解決的辦法是讓
playbin2
發佈消息總線上,並返回給調用線程。在適當的時候,主線程會拿起這個消息,並更新GTK。
gst_element_post_message() 使得 GStreamer 元件將給定的消息發送到總線。
gst_message_new_application()
建立一個新的
類型的消息。GStreamer的消息有不一樣的類型,而且該類型被保留到應用程序:它會經過總線而不受GStreamer的影響。類型列表能夠在中找到APPLICATION
GstMessageType
文檔。
信息能夠經過其內嵌的 GstStructure
提供更多信息,這是一個很是靈活的數據容器。在這裏,咱們建立了一個新的結構經過函數 gst_structure_new
,並將其命名爲
tags-changed
,以免在咱們想送其餘應用程序的消息的狀況下發生混淆。
然後,在主線程,總線將收到此消息,並放出與函數application_cb相關聯的
的信號:message::application
/* This function is called when an "application" message is posted on the bus. * Here we retrieve the message posted by the tags_cb callback */ static void application_cb (GstBus *bus, GstMessage *msg, CustomData *data) { if (g_strcmp0 (gst_structure_get_name (msg->structure), "tags-changed") == 0) { /* If the message is the "tags-changed" (only one we are currently issuing), update * the stream info GUI */ analyze_streams (data); } }
一旦我確信它是 tags-changed 的
消息,咱們稱之爲 analyze_streams 函數,也用於 Playback tutorial 1: Playbin2 usage ,更詳細的在那裏講述。它基本上完成了從流中恢復標籤並將它們寫在GUI中的一個文本組件上。
該error_cb
,eos_cb
和state_changed_cb
就不具體向你們解釋了,由於他們像在全部前面的教程中作的同樣。
這就是它!代碼本教程中的量彷佛使人生畏,但所須要瞭解的概念卻不多也容易理解。若是你已經閱讀了以往教程,並有必定的GTK知識的話,你會很天然而然地理解本教程,並能夠開始享受本身的媒體播放器了。
若是這個媒體播放器對你來講不夠好,嘗試改變,顯示有關的數據流信息到一個適當的列表視圖(或樹狀視圖)的文本組件。而後,當用戶選擇不一樣的數據流,使GStreamer切換流!要切換流,你將須要閱讀 Playback tutorial 1: Playbin2 usage。
本教程顯示:
如何使用 gst_x_overlay_set_window_handle()
輸出的視頻到一個特定的窗口句柄 。
如何按期刷新GUI經過使用 g_timeout_add_seconds ()
註冊一個超時回調。
如何經過應用程序消息的手段,經過總線使用 gst_element_post_message()
將信息傳遞給主線程。
如何使用 gst_bus_add_signal_watch() 在只在從總線發出的消息爲咱們感興趣的消息時被通知和使用信號細節判別全部消息類型。
這容許你創建一個有些完整的媒體播放器與一個適當的圖形用戶界面。
下面的基本教程繼續專一於其餘的GStreamer主題。
很高興在此與你一塊兒度過,並但願在之後的教程繼續見到你!