zoukankan      html  css  js  c++  java
  • 【GStreamer开发】GStreamer基础教程05——集成GUI工具

    目标

          本教程展示了如何在GStreamer集成一个GUI(比如:GTK+)。最基本的原则是GStreamer处理多媒体的播放而GUI处理和用户的交互。

          在这个教程里面,我们可以学到:

          如何告诉GStreamer输出视频到一个window

          如何持续的刷新GUI

          在GStreamer多线程时如何保持UI的更新

          一个仅发送给你订阅的消息而不是所有消息的机制


    介绍

          我们下面就用GTK+这样一个GUI工具来些一个播放器,但基本概念是可以推广到其它工具的(比如QT)。如果你对GTK+有一定的了解有助于理解本教程。

          最重要的是告诉GStreamer把视频输出到哪个window,而这个是依赖于操作系统的,好在GStreamer提供了一个平台无关的抽象层。这个抽象层称为XOverlay,它让应用可以告诉一个视频输出到哪个window进行渲染。 

          另一个问题是GUI工具通常只能用主线程来进行绘制,但GStreamer通常使用多线程来处理不同的任务。在回调函数中调用GTK+的函数通常会失败,因为回调函数是在调用线程运行的,往往不是主线程。这个问题的解决方法是给GStreamer发送一个消息——消息的接收是在主线程。

          在现在为止,我们仅仅注册了一个handle_message函数,每次总线上有消息出现是这个函数会呗调用。这个函数中我们会解析每个消息,看是否是我们关注的。本教程我们采用另一种方法:给每一个消息注册一个回调函数,这样解析代码会少一点。


    GTK+实现的播放器

          我们使用playbin2实现一个很简单的播放器,但这次,我们有GUI!

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. #include <string.h>  
    2.     
    3. #include <gtk/gtk.h>  
    4. #include <gst/gst.h>  
    5. #include <gst/interfaces/xoverlay.h>  
    6.     
    7. #include <gdk/gdk.h>  
    8. #if defined (GDK_WINDOWING_X11)  
    9. #include <gdk/gdkx.h>  
    10. #elif defined (GDK_WINDOWING_WIN32)  
    11. #include <gdk/gdkwin32.h>  
    12. #elif defined (GDK_WINDOWING_QUARTZ)  
    13. #include <gdk/gdkquartz.h>  
    14. #endif  
    15.     
    16. /* Structure to contain all our information, so we can pass it around */  
    17. typedef struct _CustomData {  
    18.   GstElement *playbin2;           /* Our one and only pipeline */  
    19.     
    20.   GtkWidget *slider;              /* Slider widget to keep track of current position */  
    21.   GtkWidget *streams_list;        /* Text widget to display info about the streams */  
    22.   gulong slider_update_signal_id; /* Signal ID for the slider update signal */  
    23.     
    24.   GstState state;                 /* Current state of the pipeline */  
    25.   gint64 duration;                /* Duration of the clip, in nanoseconds */  
    26. } CustomData;  
    27.     
    28. /* This function is called when the GUI toolkit creates the physical window that will hold the video. 
    29.  * At this point we can retrieve its handler (which has a different meaning depending on the windowing system) 
    30.  * and pass it to GStreamer through the XOverlay interface. */  
    31. static void realize_cb (GtkWidget *widget, CustomData *data) {  
    32.   GdkWindow *window = gtk_widget_get_window (widget);  
    33.   guintptr window_handle;  
    34.     
    35.   if (!gdk_window_ensure_native (window))  
    36.     g_error ("Couldn't create native window needed for GstXOverlay!");  
    37.     
    38.   /* Retrieve window handler from GDK */  
    39. #if defined (GDK_WINDOWING_WIN32)  
    40.   window_handle = (guintptr)GDK_WINDOW_HWND (window);  
    41. #elif defined (GDK_WINDOWING_QUARTZ)  
    42.   window_handle = gdk_quartz_window_get_nsview (window);  
    43. #elif defined (GDK_WINDOWING_X11)  
    44.   window_handle = GDK_WINDOW_XID (window);  
    45. #endif  
    46.   /* Pass it to playbin2, which implements XOverlay and will forward it to the video sink */  
    47.   gst_x_overlay_set_window_handle (GST_X_OVERLAY (data->playbin2), window_handle);  
    48. }  
    49.     
    50. /* This function is called when the PLAY button is clicked */  
    51. static void play_cb (GtkButton *button, CustomData *data) {  
    52.   gst_element_set_state (data->playbin2, GST_STATE_PLAYING);  
    53. }  
    54.     
    55. /* This function is called when the PAUSE button is clicked */  
    56. static void pause_cb (GtkButton *button, CustomData *data) {  
    57.   gst_element_set_state (data->playbin2, GST_STATE_PAUSED);  
    58. }  
    59.     
    60. /* This function is called when the STOP button is clicked */  
    61. static void stop_cb (GtkButton *button, CustomData *data) {  
    62.   gst_element_set_state (data->playbin2, GST_STATE_READY);  
    63. }  
    64.     
    65. /* This function is called when the main window is closed */  
    66. static void delete_event_cb (GtkWidget *widget, GdkEvent *event, CustomData *data) {  
    67.   stop_cb (NULL, data);  
    68.   gtk_main_quit ();  
    69. }  
    70.     
    71. /* This function is called everytime the video window needs to be redrawn (due to damage/exposure, 
    72.  * rescaling, etc). GStreamer takes care of this in the PAUSED and PLAYING states, otherwise, 
    73.  * we simply draw a black rectangle to avoid garbage showing up. */  
    74. static gboolean expose_cb (GtkWidget *widget, GdkEventExpose *event, CustomData *data) {  
    75.   if (data->state < GST_STATE_PAUSED) {  
    76.     GtkAllocation allocation;  
    77.     GdkWindow *window = gtk_widget_get_window (widget);  
    78.     cairo_t *cr;  
    79.       
    80.     /* Cairo is a 2D graphics library which we use here to clean the video window. 
    81.      * It is used by GStreamer for other reasons, so it will always be available to us. */  
    82.     gtk_widget_get_allocation (widget, &allocation);  
    83.     cr = gdk_cairo_create (window);  
    84.     cairo_set_source_rgb (cr, 000);  
    85.     cairo_rectangle (cr, 00, allocation.width, allocation.height);  
    86.     cairo_fill (cr);  
    87.     cairo_destroy (cr);  
    88.   }  
    89.     
    90.   return FALSE;  
    91. }  
    92.     
    93. /* This function is called when the slider changes its position. We perform a seek to the 
    94.  * new position here. */  
    95. static void slider_cb (GtkRange *range, CustomData *data) {  
    96.   gdouble value = gtk_range_get_value (GTK_RANGE (data->slider));  
    97.   gst_element_seek_simple (data->playbin2, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT,  
    98.       (gint64)(value * GST_SECOND));  
    99. }  
    100.     
    101. /* This creates all the GTK+ widgets that compose our application, and registers the callbacks */  
    102. static void create_ui (CustomData *data) {  
    103.   GtkWidget *main_window;  /* The uppermost window, containing all other windows */  
    104.   GtkWidget *video_window; /* The drawing area where the video will be shown */  
    105.   GtkWidget *main_box;     /* VBox to hold main_hbox and the controls */  
    106.   GtkWidget *main_hbox;    /* HBox to hold the video_window and the stream info text widget */  
    107.   GtkWidget *controls;     /* HBox to hold the buttons and the slider */  
    108.   GtkWidget *play_button, *pause_button, *stop_button; /* Buttons */  
    109.     
    110.   main_window = gtk_window_new (GTK_WINDOW_TOPLEVEL);  
    111.   g_signal_connect (G_OBJECT (main_window), "delete-event", G_CALLBACK (delete_event_cb), data);  
    112.     
    113.   video_window = gtk_drawing_area_new ();  
    114.   gtk_widget_set_double_buffered (video_window, FALSE);  
    115.   g_signal_connect (video_window, "realize", G_CALLBACK (realize_cb), data);  
    116.   g_signal_connect (video_window, "expose_event", G_CALLBACK (expose_cb), data);  
    117.     
    118.   play_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_PLAY);  
    119.   g_signal_connect (G_OBJECT (play_button), "clicked", G_CALLBACK (play_cb), data);  
    120.     
    121.   pause_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_PAUSE);  
    122.   g_signal_connect (G_OBJECT (pause_button), "clicked", G_CALLBACK (pause_cb), data);  
    123.     
    124.   stop_button = gtk_button_new_from_stock (GTK_STOCK_MEDIA_STOP);  
    125.   g_signal_connect (G_OBJECT (stop_button), "clicked", G_CALLBACK (stop_cb), data);  
    126.     
    127.   data->slider = gtk_hscale_new_with_range (01001);  
    128.   gtk_scale_set_draw_value (GTK_SCALE (data->slider), 0);  
    129.   data->slider_update_signal_id = g_signal_connect (G_OBJECT (data->slider), "value-changed", G_CALLBACK (slider_cb), data);  
    130.     
    131.   data->streams_list = gtk_text_view_new ();  
    132.   gtk_text_view_set_editable (GTK_TEXT_VIEW (data->streams_list), FALSE);  
    133.     
    134.   controls = gtk_hbox_new (FALSE, 0);  
    135.   gtk_box_pack_start (GTK_BOX (controls), play_button, FALSE, FALSE, 2);  
    136.   gtk_box_pack_start (GTK_BOX (controls), pause_button, FALSE, FALSE, 2);  
    137.   gtk_box_pack_start (GTK_BOX (controls), stop_button, FALSE, FALSE, 2);  
    138.   gtk_box_pack_start (GTK_BOX (controls), data->slider, TRUE, TRUE, 2);  
    139.     
    140.   main_hbox = gtk_hbox_new (FALSE, 0);  
    141.   gtk_box_pack_start (GTK_BOX (main_hbox), video_window, TRUE, TRUE, 0);  
    142.   gtk_box_pack_start (GTK_BOX (main_hbox), data->streams_list, FALSE, FALSE, 2);  
    143.     
    144.   main_box = gtk_vbox_new (FALSE, 0);  
    145.   gtk_box_pack_start (GTK_BOX (main_box), main_hbox, TRUE, TRUE, 0);  
    146.   gtk_box_pack_start (GTK_BOX (main_box), controls, FALSE, FALSE, 0);  
    147.   gtk_container_add (GTK_CONTAINER (main_window), main_box);  
    148.   gtk_window_set_default_size (GTK_WINDOW (main_window), 640480);  
    149.     
    150.   gtk_widget_show_all (main_window);  
    151. }  
    152.     
    153. /* This function is called periodically to refresh the GUI */  
    154. static gboolean refresh_ui (CustomData *data) {  
    155.   GstFormat fmt = GST_FORMAT_TIME;  
    156.   gint64 current = -1;  
    157.     
    158.   /* We do not want to update anything unless we are in the PAUSED or PLAYING states */  
    159.   if (data->state < GST_STATE_PAUSED)  
    160.     return TRUE;  
    161.     
    162.   /* If we didn't know it yet, query the stream duration */  
    163.   if (!GST_CLOCK_TIME_IS_VALID (data->duration)) {  
    164.     if (!gst_element_query_duration (data->playbin2, &fmt, &data->duration)) {  
    165.       g_printerr ("Could not query current duration. ");  
    166.     } else {  
    167.       /* Set the range of the slider to the clip duration, in SECONDS */  
    168.       gtk_range_set_range (GTK_RANGE (data->slider), 0, (gdouble)data->duration / GST_SECOND);  
    169.     }  
    170.   }  
    171.     
    172.   if (gst_element_query_position (data->playbin2, &fmt, ¤t)) {  
    173.     /* Block the "value-changed" signal, so the slider_cb function is not called 
    174.      * (which would trigger a seek the user has not requested) */  
    175.     g_signal_handler_block (data->slider, data->slider_update_signal_id);  
    176.     /* Set the position of the slider to the current pipeline positoin, in SECONDS */  
    177.     gtk_range_set_value (GTK_RANGE (data->slider), (gdouble)current / GST_SECOND);  
    178.     /* Re-enable the signal */  
    179.     g_signal_handler_unblock (data->slider, data->slider_update_signal_id);  
    180.   }  
    181.   return TRUE;  
    182. }  
    183.     
    184. /* This function is called when new metadata is discovered in the stream */  
    185. static void tags_cb (GstElement *playbin2, gint stream, CustomData *data) {  
    186.   /* We are possibly in a GStreamer working thread, so we notify the main 
    187.    * thread of this event through a message in the bus */  
    188.   gst_element_post_message (playbin2,  
    189.     gst_message_new_application (GST_OBJECT (playbin2),  
    190.       gst_structure_new ("tags-changed"NULL)));  
    191. }  
    192.     
    193. /* This function is called when an error message is posted on the bus */  
    194. static void error_cb (GstBus *bus, GstMessage *msg, CustomData *data) {  
    195.   GError *err;  
    196.   gchar *debug_info;  
    197.     
    198.   /* Print error details on the screen */  
    199.   gst_message_parse_error (msg, &err, &debug_info);  
    200.   g_printerr ("Error received from element %s: %s ", GST_OBJECT_NAME (msg->src), err->message);  
    201.   g_printerr ("Debugging information: %s ", debug_info ? debug_info : "none");  
    202.   g_clear_error (&err);  
    203.   g_free (debug_info);  
    204.     
    205.   /* Set the pipeline to READY (which stops playback) */  
    206.   gst_element_set_state (data->playbin2, GST_STATE_READY);  
    207. }  
    208.     
    209. /* This function is called when an End-Of-Stream message is posted on the bus. 
    210.  * We just set the pipeline to READY (which stops playback) */  
    211. static void eos_cb (GstBus *bus, GstMessage *msg, CustomData *data) {  
    212.   g_print ("End-Of-Stream reached. ");  
    213.   gst_element_set_state (data->playbin2, GST_STATE_READY);  
    214. }  
    215.     
    216. /* This function is called when the pipeline changes states. We use it to 
    217.  * keep track of the current state. */  
    218. static void state_changed_cb (GstBus *bus, GstMessage *msg, CustomData *data) {  
    219.   GstState old_state, new_state, pending_state;  
    220.   gst_message_parse_state_changed (msg, &old_state, &new_state, &pending_state);  
    221.   if (GST_MESSAGE_SRC (msg) == GST_OBJECT (data->playbin2)) {  
    222.     data->state = new_state;  
    223.     g_print ("State set to %s ", gst_element_state_get_name (new_state));  
    224.     if (old_state == GST_STATE_READY && new_state == GST_STATE_PAUSED) {  
    225.       /* For extra responsiveness, we refresh the GUI as soon as we reach the PAUSED state */  
    226.       refresh_ui (data);  
    227.     }  
    228.   }  
    229. }  
    230.     
    231. /* Extract metadata from all the streams and write it to the text widget in the GUI */  
    232. static void analyze_streams (CustomData *data) {  
    233.   gint i;  
    234.   GstTagList *tags;  
    235.   gchar *str, *total_str;  
    236.   guint rate;  
    237.   gint n_video, n_audio, n_text;  
    238.   GtkTextBuffer *text;  
    239.     
    240.   /* Clean current contents of the widget */  
    241.   text = gtk_text_view_get_buffer (GTK_TEXT_VIEW (data->streams_list));  
    242.   gtk_text_buffer_set_text (text, "", -1);  
    243.     
    244.   /* Read some properties */  
    245.   g_object_get (data->playbin2"n-video", &n_video, NULL);  
    246.   g_object_get (data->playbin2"n-audio", &n_audio, NULL);  
    247.   g_object_get (data->playbin2"n-text", &n_text, NULL);  
    248.     
    249.   for (i = 0; i < n_video; i++) {  
    250.     tags = NULL;  
    251.     /* Retrieve the stream's video tags */  
    252.     g_signal_emit_by_name (data->playbin2"get-video-tags", i, &tags);  
    253.     if (tags) {  
    254.       total_str = g_strdup_printf ("video stream %d: ", i);  
    255.       gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    256.       g_free (total_str);  
    257.       gst_tag_list_get_string (tags, GST_TAG_VIDEO_CODEC, &str);  
    258.       total_str = g_strdup_printf ("  codec: %s ", str ? str : "unknown");  
    259.       gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    260.       g_free (total_str);  
    261.       g_free (str);  
    262.       gst_tag_list_free (tags);  
    263.     }  
    264.   }  
    265.     
    266.   for (i = 0; i < n_audio; i++) {  
    267.     tags = NULL;  
    268.     /* Retrieve the stream's audio tags */  
    269.     g_signal_emit_by_name (data->playbin2"get-audio-tags", i, &tags);  
    270.     if (tags) {  
    271.       total_str = g_strdup_printf (" audio stream %d: ", i);  
    272.       gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    273.       g_free (total_str);  
    274.       if (gst_tag_list_get_string (tags, GST_TAG_AUDIO_CODEC, &str)) {  
    275.         total_str = g_strdup_printf ("  codec: %s ", str);  
    276.         gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    277.         g_free (total_str);  
    278.         g_free (str);  
    279.       }  
    280.       if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &str)) {  
    281.         total_str = g_strdup_printf ("  language: %s ", str);  
    282.         gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    283.         g_free (total_str);  
    284.         g_free (str);  
    285.       }  
    286.       if (gst_tag_list_get_uint (tags, GST_TAG_BITRATE, &rate)) {  
    287.         total_str = g_strdup_printf ("  bitrate: %d ", rate);  
    288.         gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    289.         g_free (total_str);  
    290.       }  
    291.       gst_tag_list_free (tags);  
    292.     }  
    293.   }  
    294.     
    295.   for (i = 0; i < n_text; i++) {  
    296.     tags = NULL;  
    297.     /* Retrieve the stream's subtitle tags */  
    298.     g_signal_emit_by_name (data->playbin2"get-text-tags", i, &tags);  
    299.     if (tags) {  
    300.       total_str = g_strdup_printf (" subtitle stream %d: ", i);  
    301.       gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    302.       g_free (total_str);  
    303.       if (gst_tag_list_get_string (tags, GST_TAG_LANGUAGE_CODE, &str)) {  
    304.         total_str = g_strdup_printf ("  language: %s ", str);  
    305.         gtk_text_buffer_insert_at_cursor (text, total_str, -1);  
    306.         g_free (total_str);  
    307.         g_free (str);  
    308.       }  
    309.       gst_tag_list_free (tags);  
    310.     }  
    311.   }  
    312. }  
    313.     
    314. /* This function is called when an "application" message is posted on the bus. 
    315.  * Here we retrieve the message posted by the tags_cb callback */  
    316. static void application_cb (GstBus *bus, GstMessage *msg, CustomData *data) {  
    317.   if (g_strcmp0 (gst_structure_get_name (msg->structure), "tags-changed") == 0) {  
    318.     /* If the message is the "tags-changed" (only one we are currently issuing), update 
    319.      * the stream info GUI */  
    320.     analyze_streams (data);  
    321.   }  
    322. }  
    323.     
    324. int main(int argc, charchar *argv[]) {  
    325.   CustomData data;  
    326.   GstStateChangeReturn ret;  
    327.   GstBus *bus;  
    328.     
    329.   /* Initialize GTK */  
    330.   gtk_init (&argc, &argv);  
    331.     
    332.   /* Initialize GStreamer */  
    333.   gst_init (&argc, &argv);  
    334.     
    335.   /* Initialize our data structure */  
    336.   memset (&data, 0sizeof (data));  
    337.   data.duration = GST_CLOCK_TIME_NONE;  
    338.     
    339.   /* Create the elements */  
    340.   data.playbin2 = gst_element_factory_make ("playbin2""playbin2");  
    341.      
    342.   if (!data.playbin2) {  
    343.     g_printerr ("Not all elements could be created. ");  
    344.     return -1;  
    345.   }  
    346.     
    347.   /* Set the URI to play */  
    348.   g_object_set (data.playbin2"uri""http://docs.gstreamer.com/media/sintel_trailer-480p.webm"NULL);  
    349.     
    350.   /* Connect to interesting signals in playbin2 */  
    351.   g_signal_connect (G_OBJECT (data.playbin2), "video-tags-changed", (GCallback) tags_cb, &data);  
    352.   g_signal_connect (G_OBJECT (data.playbin2), "audio-tags-changed", (GCallback) tags_cb, &data);  
    353.   g_signal_connect (G_OBJECT (data.playbin2), "text-tags-changed", (GCallback) tags_cb, &data);  
    354.     
    355.   /* Create the GUI */  
    356.   create_ui (&data);  
    357.     
    358.   /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */  
    359.   bus = gst_element_get_bus (data.playbin2);  
    360.   gst_bus_add_signal_watch (bus);  
    361.   g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data);  
    362.   g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback)eos_cb, &data);  
    363.   g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, &data);  
    364.   g_signal_connect (G_OBJECT (bus), "message::application", (GCallback)application_cb, &data);  
    365.   gst_object_unref (bus);  
    366.     
    367.   /* Start playing */  
    368.   ret = gst_element_set_state (data.playbin2, GST_STATE_PLAYING);  
    369.   if (ret == GST_STATE_CHANGE_FAILURE) {  
    370.     g_printerr ("Unable to set the pipeline to the playing state. ");  
    371.     gst_object_unref (data.playbin2);  
    372.     return -1;  
    373.   }  
    374.     
    375.   /* Register a function that GLib will call every second */  
    376.   g_timeout_add_seconds (1, (GSourceFunc)refresh_ui, &data);  
    377.     
    378.   /* Start the GTK main loop. We will not regain control until gtk_main_quit is called. */  
    379.   gtk_main ();  
    380.     
    381.   /* Free resources */  
    382.   gst_element_set_state (data.playbin2, GST_STATE_NULL);  
    383.   gst_object_unref (data.playbin2);  
    384.   return 0;  
    385. }  

    工作流程

          不管本教程的数据结构是怎么样的,我们都不再打算继续使用前向引用的方式。但是,作为显示声明时,代码的顺序并不是一成不变的。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. #include <gdk/gdk.h>  
    2. #if defined (GDK_WINDOWING_X11)  
    3. #include <gdk/gdkx.h>  
    4. #elif defined (GDK_WINDOWING_WIN32)  
    5. #include <gdk/gdkwin32.h>  
    6. #elif defined (GDK_WINDOWING_QUARTZ)  
    7. #include <gdk/gdkquartz.h>  
    8. #endif  
          第一件值得注意的是我们需要根据平台来确定包含的头文件,也就是说,这个代码并非是平台无关的了。幸运的时,并没有很多的window系统,我们仅仅需要考虑Linux下的X11,Windows下的Win32或者MacOSX下的Quartz。

          本教程绝大部分都是在实现由GStreamer或者GTK+调用的回调函数,这些回调函数都在main函数中被注册进去的。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. int main(int argc, charchar *argv[]) {  
    2.   CustomData data;  
    3.   GstStateChangeReturn ret;  
    4.   GstBus *bus;  
    5.     
    6.   /* Initialize GTK */  
    7.   gtk_init (&argc, &argv);  
    8.     
    9.   /* Initialize GStreamer */  
    10.   gst_init (&argc, &argv);  
    11.     
    12.   /* Initialize our data structure */  
    13.   memset (&data, 0sizeof (data));  
    14.   data.duration = GST_CLOCK_TIME_NONE;  
    15.     
    16.   /* Create the elements */  
    17.   data.playbin2 = gst_element_factory_make ("playbin2""playbin2");  
    18.      
    19.   if (!data.playbin2) {  
    20.     g_printerr ("Not all elements could be created. ");  
    21.     return -1;  
    22.   }  
    23.     
    24.   /* Set the URI to play */  
    25.   g_object_set (data.playbin2"uri""http://docs.gstreamer.com/media/sintel_trailer-480p.webm"NULL);  
          标准的GStreamer初始化和playbin2 pipeline的建立以及GTK+的初始化,没有更多的新内容。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* Connect to interesting signals in playbin2 */  
    2. g_signal_connect (G_OBJECT (data.playbin2), "video-tags-changed", (GCallback) tags_cb, &data);  
    3. g_signal_connect (G_OBJECT (data.playbin2), "audio-tags-changed", (GCallback) tags_cb, &data);  
    4. g_signal_connect (G_OBJECT (data.playbin2), "text-tags-changed", (GCallback) tags_cb, &data);  
          我们希望在流里面出现新的tags的时候有通知给到我们,简单来说,我们希望通过tags_cb回调函数处理所有的tag(音频,视频或者字幕)。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* Create the GUI */  
    2. create_ui (&data);  
          在这个函数里会创建所有的GTK+的widget以及注册所有的信号。这里当然只能调用和GTK相关的函数,所以我们简单略过去。这里的信号是给到用户命令,在下面讲回调函数的时候再逐一展开。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */  
    2. bus = gst_element_get_bus (data.playbin2);  
    3. gst_bus_add_signal_watch (bus);  
    4. g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data);  
    5. g_signal_connect (G_OBJECT (bus), "message::eos", (GCallback)eos_cb, &data);  
    6. g_signal_connect (G_OBJECT (bus), "message::state-changed", (GCallback)state_changed_cb, &data);  
    7. g_signal_connect (G_OBJECT (bus), "message::application", (GCallback)application_cb, &data);  
    8. gst_object_unref (bus);  
          在Playback教程01(后面的一个教程),我们用gst_bus_add_watch()方法来注册一个监视所有发送到GStreamer总线上的消息。我们也可以用信号来实现,同样达到一个很好的粒度,而且我们可以只注册我们关注的消息。通过gst_bus_add_signal_watch()方法我们让总线在收到消息时发出一个信号,这个信号的名字是形如:message::detail的样式,这里的detail取决于收到的消息。比如:当收到EOS消息时,会发出message::eos的信号。

          本教程使用注册信号的方法来保证只有我们关注的消息才会调用回调,如果我们注册message信号,那么每个消息都会调用回调,就和使用gst_bus_add_watch()方法一样。

          请记住,要监视总线的工作(使用gst_bus_add_watch()方法或者gst_bus_add_signal_watch()方法),必须保证GLib的主循环在运行。在本教程中,GTK+的主循环隐含了这个部分。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* Register a function that GLib will call every second */  
    2. g_timeout_add_seconds (1, (GSourceFunc)refresh_ui, &data);  
          在控制权转到GTK+之前,我们用g_timeout_add_seconds()方法来注册另一个回调函数,这次是定时回调,每1s调一次,我们用来刷新GUI(调用refresh_ui函数)。

          在这些之后,我们完成了设置,然后就可以开始GTK+的主循环了。当我们关注的事件发生时,我们会再次拿到控制权。让我们看一下这些回调吧,每个回调有不同的签名(这里签名是输入参数和返回值),你可以在文档中查到。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called when the GUI toolkit creates the physical window that will hold the video. 
    2.  * At this point we can retrieve its handler (which has a different meaning depending on the windowing system) 
    3.  * and pass it to GStreamer through the XOverlay interface. */  
    4. static void realize_cb (GtkWidget *widget, CustomData *data) {  
    5.   GdkWindow *window = gtk_widget_get_window (widget);  
    6.   guintptr window_handle;  
    7.     
    8.   if (!gdk_window_ensure_native (window))  
    9.     g_error ("Couldn't create native window needed for GstXOverlay!");  
    10.     
    11.   /* Retrieve window handler from GDK */  
    12. #if defined (GDK_WINDOWING_WIN32)  
    13.   window_handle = (guintptr)GDK_WINDOW_HWND (window);  
    14. #elif defined (GDK_WINDOWING_QUARTZ)  
    15.   window_handle = gdk_quartz_window_get_nsview (window);  
    16. #elif defined (GDK_WINDOWING_X11)  
    17.   window_handle = GDK_WINDOW_XID (window);  
    18. #endif  
    19.   /* Pass it to playbin2, which implements XOverlay and will forward it to the video sink */  
    20.   gst_x_overlay_set_window_handle (GST_X_OVERLAY (data->playbin2), window_handle);  
    21. }  
          代码的注释已经说得很清楚了。在应用的生命周期里,这是我们知道了GStreamer应该做视频渲染的window的handle。我们从window系统获得这个handle之后通过XOverlay接口gst_x_overlay_set_window_handle()传给了playbin2。playbin2会把这个handle传给视频输出,这样输出时就不再自行创建一个window而是使用这个。

          playbin2和XOverlay让这个过程变得很简单,没有太多需要解释的地方。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called when the PLAY button is clicked */  
    2. static void play_cb (GtkButton *button, CustomData *data) {  
    3.   gst_element_set_state (data->playbin2, GST_STATE_PLAYING);  
    4. }  
    5.     
    6. /* This function is called when the PAUSE button is clicked */  
    7. static void pause_cb (GtkButton *button, CustomData *data) {  
    8.   gst_element_set_state (data->playbin2, GST_STATE_PAUSED);  
    9. }  
    10.     
    11. /* This function is called when the STOP button is clicked */  
    12. static void stop_cb (GtkButton *button, CustomData *data) {  
    13.   gst_element_set_state (data->playbin2, GST_STATE_READY);  
    14. }  
          这三个是播放器上PLAY,PAUSE以及STOP按钮的回调函数。他们也仅仅是简单地把pipeline转到相应的状态。请注意在STOP时我们是把pipeline切换到READY状态。虽然我们可以做到每次都把pipeline置到NULL状态,但是这样一来转换速度就会变慢,尤其是有些资源(比如声音)还会经历释放和重新获得等过程。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called when the main window is closed */  
    2. static void delete_event_cb (GtkWidget *widget, GdkEvent *event, CustomData *data) {  
    3.   stop_cb (NULL, data);  
    4.   gtk_main_quit ();  
    5. }  
          gtk_main_quit()让main函数里的gtk_main()结束,这样也就是让这个应用终止了。所以我们在pipeline停了,主窗口关闭的时候调用它。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called everytime the video window needs to be redrawn (due to damage/exposure, 
    2.  * rescaling, etc). GStreamer takes care of this in the PAUSED and PLAYING states, otherwise, 
    3.  * we simply draw a black rectangle to avoid garbage showing up. */  
    4. static gboolean expose_cb (GtkWidget *widget, GdkEventExpose *event, CustomData *data) {  
    5.   if (data->state < GST_STATE_PAUSED) {  
    6.     GtkAllocation allocation;  
    7.     GdkWindow *window = gtk_widget_get_window (widget);  
    8.     cairo_t *cr;  
    9.       
    10.     /* Cairo is a 2D graphics library which we use here to clean the video window. 
    11.      * It is used by GStreamer for other reasons, so it will always be available to us. */  
    12.     gtk_widget_get_allocation (widget, &allocation);  
    13.     cr = gdk_cairo_create (window);  
    14.     cairo_set_source_rgb (cr, 000);  
    15.     cairo_rectangle (cr, 00, allocation.width, allocation.height);  
    16.     cairo_fill (cr);  
    17.     cairo_destroy (cr);  
    18.   }  
    19.     
    20.   return FALSE;  
    21. }  
          当有数据流过时(PAUSED或PLAYING状态),视频输出部分负责刷新window的视频内容。但是,反过来说,不在这样的情况下,视频内容就没有刷新了,这时我们要去刷新。在这个例子中,我们用黑色矩形填充window。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called when the slider changes its position. We perform a seek to the 
    2.  * new position here. */  
    3. static void slider_cb (GtkRange *range, CustomData *data) {  
    4.   gdouble value = gtk_range_get_value (GTK_RANGE (data->slider));  
    5.   gst_element_seek_simple (data->playbin2, GST_FORMAT_TIME, GST_SEEK_FLAG_FLUSH | GST_SEEK_FLAG_KEY_UNIT,  
    6.       (gint64)(value * GST_SECOND));  
    7. }  
          这是一个用GStreamer配合GTK+,用非常简单的方法实现搜索条之类比较复杂的UI元件的例子。如果搜索条被拉到了一个新的位置,用gst_element_seek_simple()方法告诉GStreamer跳转到那个位置(参考《GStreamer基础教程04——时间管理》)。

          因为搜索需要花费一点时间,所以常常在搜索结束后隔半秒才可以开始下一次搜索。否则,应用在用户疯狂地拖动的时候会表现的几乎没有响应。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called periodically to refresh the GUI */  
    2. static gboolean refresh_ui (CustomData *data) {  
    3.   GstFormat fmt = GST_FORMAT_TIME;  
    4.   gint64 current = -1;  
    5.     
    6.   /* We do not want to update anything unless we are in the PAUSED or PLAYING states */  
    7.   if (data->state < GST_STATE_PAUSED)  
    8.     return TRUE;  
          这个函数会把滑块移到当前的位置,而且如果我们不在PLAYING状态,那么我们什么都不用做。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* If we didn't know it yet, query the stream duration */  
    2. if (!GST_CLOCK_TIME_IS_VALID (data->duration)) {  
    3.   if (!gst_element_query_duration (data->playbin2, &fmt, &data->duration)) {  
    4.     g_printerr ("Could not query current duration. ");  
    5.   } else {  
    6.     /* Set the range of the slider to the clip duration, in SECONDS */  
    7.     gtk_range_set_range (GTK_RANGE (data->slider), 0, (gdouble)data->duration / GST_SECOND);  
    8.   }  
    9. }  

          如果我们不知道播放总时间,我们就再查询一次,这样我们才能设置滑块的距离。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. if (gst_element_query_position (data->playbin2, &fmt, ¤t)) {  
    2.   /* Block the "value-changed" signal, so the slider_cb function is not called 
    3.    * (which would trigger a seek the user has not requested) */  
    4.   g_signal_handler_block (data->slider, data->slider_update_signal_id);  
    5.   /* Set the position of the slider to the current pipeline positoin, in SECONDS */  
    6.   gtk_range_set_value (GTK_RANGE (data->slider), (gdouble)current / GST_SECOND);  
    7.   /* Re-enable the signal */  
    8.   g_signal_handler_unblock (data->slider, data->slider_update_signal_id);  
    9. }  
    10. return TRUE;  
          我们查询pipeline当前的位置,并把滑块设置到相应的位置。这会触发value-changed信号,而我们用这个信号来判断用户拖动了滑块。所以我们在操作时用g_signal_handler_block()和g_signal_handler_unblock()来临时关闭value-changed信号。

          如果返回TRUE,那么定时器继续工作,下次还会调这个回调函数;如果返回FALSE,那么关闭定时器。

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called when new metadata is discovered in the stream */  
    2. static void tags_cb (GstElement *playbin2, gint stream, CustomData *data) {  
    3.   /* We are possibly in a GStreamer working thread, so we notify the main 
    4.    * thread of this event through a message in the bus */  
    5.   gst_element_post_message (playbin2,  
    6.     gst_message_new_application (GST_OBJECT (playbin2),  
    7.       gst_structure_new ("tags-changed"NULL)));  
    8. }  
          这是本教程的一个重点。在播放时发现新的tag时会调用这个函数,所以这个函数并不是在应用的主线程中被调用。这个时候我们需要刷新GTK+的widget来响应,但GTK+不允许非主线程的其他线程操作UI。

          解决方法是让playbin2发出一个消息然后回到调用线程,这样,主线程会收到消息然后刷新GTK。

          gst_element_post_message()方法让一个GStreamer element发送一个特定消息到总线上。gst_message_new_application()创建一个新的APPLICATION类型的消息。GStreamer有不同类型的消息,而这个特定的消息是预留给应用的,它会不受影响的通过总线。在GstMessageType文档里面有所有类型的列表。  

          消息可以通过他们自己的GstStructure来携带一些信息。在这里,我们用gst_structure_new来创建了一个新的数据结构并起名tags-changed,避免和其他的消息混淆。

          一旦切换到主线程,总线会接受到消息,并发出message:application信号,这个信号会调用application_cb回调函数:

    [objc] view plain copy
     在CODE上查看代码片派生到我的代码片
    1. /* This function is called when an "application" message is posted on the bus. 
    2.  * Here we retrieve the message posted by the tags_cb callback */  
    3. static void application_cb (GstBus *bus, GstMessage *msg, CustomData *data) {  
    4.   if (g_strcmp0 (gst_structure_get_name (msg->structure), "tags-changed") == 0) {  
    5.     /* If the message is the "tags-changed" (only one we are currently issuing), update 
    6.      * the stream info GUI */  
    7.     analyze_streams (data);  
    8.   }  
    9. }  
          一旦我们确定是tags-changed消息,我们会调用analyze_stream函数,这个函数在后面的教程中还会用到,在那里我们会给出更详细的解释。基本上做的工作是把流里面的tags拿出来,写到GUI得文本widget里面。

          至于error_cb、eos_cb和state_changed_cb因为和前面的教程一样,所以不拿出来详细解释了。

          本教程的代码看上去有点令人生畏,但是概念比较少而且容易理解。如果你看过前面的教程并对GTK有一定的了解,你就会比较容易的理解本教程还可以写一个自己的播放器!


          下面给张播放器的截图:



  • 相关阅读:
    仿当当网鼠标经过图片翻转
    静态随鼠标移动的Tip
    Weblogic免项目名
    weblogic中文乱码问题
    IE6下的{clear:both}出现怪异的空白
    动态随鼠标移动的Tip
    base标签在ie6下的恶心问题
    javascript中for和for in 区别
    jQuery性能优化<<转>>
    Ant项目打包脚本
  • 原文地址:https://www.cnblogs.com/huty/p/8517322.html
Copyright © 2011-2022 走看看