摘要
在我們前面的文章中,我們的Pipline都是使用GStreamer自帶的插件去產生/消費數據。在實際的情況中,我們的數據源可能沒有相應的gstreamer插件,但我們又需要將數據發送到GStreamer Pipeline中。GStreamer為我們提供了Appsrc以及Appsink插件,用於處理這種情況,本文將介紹如何使用這些插件來實現數據與應用程序的交互。
Appsrc與Appsink
GStreamer提供了多種方法使得應用程序與GStreamer Pipeline之間可以進行數據交互,我們這里介紹的是最簡單的一種方式:appsrc與appsink。
- appsrc:
用於將應用程序的數據發送到Pipeline中。應用程序負責數據的生成,並將其作為GstBuffer傳輸到Pipeline中。
appsrc有2中模式,拉模式和推模式。在拉模式下,appsrc會在需要數據時,通過指定接口從應用程序中獲取相應數據。在推模式下,則需要由應用程序主動將數據推送到Pipeline中,應用程序可以指定在Pipeline的數據隊列滿時是否阻塞相應調用,或通過監聽enough-data和need-data信號來控制數據的發送。
- appsink:
用於從Pipeline中提取數據,並發送到應用程序中。
appsrc和appsink需要通過特殊的API才能與Pipeline進行數據交互,相應的接口可以查看官方文檔,在編譯的時候還需連接gstreamer-app庫。
GstBuffer
在GStreamer Pipeline中的plugin間傳輸的數據塊被稱為buffer,在GStreamer內部對應於GstBuffer。Buffer由Source Pad產生,並由Sink Pad消耗。一個Buffer只表示一塊數據,不同的buffer可能包含不同大小,不同時間長度的數據。同時,某些Element中可能對Buffer進行拆分或合並,所以GstBuffer中可能包含不止一個內存數據,實際的內存數據在GStreamer系統中通過GstMemory對象進行描述,因此,GstBuffer可以包含多個GstMemory對象。
每個GstBuffer都有相應的時間戳以及時間長度,用於描述這個buffer的解碼時間以及顯示時間。
示例代碼
本例在GStreamer基礎教程08 - 多線程示例上進行擴展,首先使用appsrc替代audiotestsrc用於產生audio數據,另外增加一個新的分支,將tee產生的數據發送到應用程序,由應用程序決定如何處理收到的數據。Pipeline的示意圖如下:
#include <gst/gst.h> #include <gst/audio/audio.h> #include <string.h> #define CHUNK_SIZE 1024 /* Amount of bytes we are sending in each buffer */ #define SAMPLE_RATE 44100 /* Samples per second we are sending */ /* Structure to contain all our information, so we can pass it to callbacks */ typedef struct _CustomData { GstElement *pipeline, *app_source, *tee, *audio_queue, *audio_convert1, *audio_resample, *audio_sink; GstElement *video_queue, *audio_convert2, *visual, *video_convert, *video_sink; GstElement *app_queue, *app_sink; guint64 num_samples; /* Number of samples generated so far (for timestamp generation) */ gfloat a, b, c, d; /* For waveform generation */ guint sourceid; /* To control the GSource */ GMainLoop *main_loop; /* GLib's Main Loop */ } CustomData; /* This method is called by the idle GSource in the mainloop, to feed CHUNK_SIZE bytes into appsrc. * The idle handler is added to the mainloop when appsrc requests us to start sending data (need-data signal) * and is removed when appsrc has enough data (enough-data signal). */ static gboolean push_data (CustomData *data) { GstBuffer *buffer; GstFlowReturn ret; int i; GstMapInfo map; gint16 *raw; gint num_samples = CHUNK_SIZE / 2; /* Because each sample is 16 bits */ gfloat freq; /* Create a new empty buffer */ buffer = gst_buffer_new_and_alloc (CHUNK_SIZE); /* Set its timestamp and duration */ GST_BUFFER_TIMESTAMP (buffer) = gst_util_uint64_scale (data->num_samples, GST_SECOND, SAMPLE_RATE); GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale (num_samples, GST_SECOND, SAMPLE_RATE); /* Generate some psychodelic waveforms */ gst_buffer_map (buffer, &map, GST_MAP_WRITE); raw = (gint16 *)map.data; data->c += data->d; data->d -= data->c / 1000; freq = 1100 + 1000 * data->d; for (i = 0; i < num_samples; i++) { data->a += data->b; data->b -= data->a / freq; raw[i] = (gint16)(500 * data->a); } gst_buffer_unmap (buffer, &map); data->num_samples += num_samples; /* Push the buffer into the appsrc */ g_signal_emit_by_name (data->app_source, "push-buffer", buffer, &ret); /* Free the buffer now that we are done with it */ gst_buffer_unref (buffer); if (ret != GST_FLOW_OK) { /* We got some error, stop sending data */ return FALSE; } return TRUE; } /* This signal callback triggers when appsrc needs data. Here, we add an idle handler * to the mainloop to start pushing data into the appsrc */ static void start_feed (GstElement *source, guint size, CustomData *data) { if (data->sourceid == 0) { g_print ("Start feeding\n"); data->sourceid = g_idle_add ((GSourceFunc) push_data, data); } } /* This callback triggers when appsrc has enough data and we can stop sending. * We remove the idle handler from the mainloop */ static void stop_feed (GstElement *source, CustomData *data) { if (data->sourceid != 0) { g_print ("Stop feeding\n"); g_source_remove (data->sourceid); data->sourceid = 0; } } /* The appsink has received a buffer */ static GstFlowReturn new_sample (GstElement *sink, CustomData *data) { GstSample *sample; /* Retrieve the buffer */ g_signal_emit_by_name (sink, "pull-sample", &sample); if (sample) { /* The only thing we do in this example is print a * to indicate a received buffer */ g_print ("*"); gst_sample_unref (sample); return GST_FLOW_OK; } return GST_FLOW_ERROR; } /* 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); g_main_loop_quit (data->main_loop); } int main(int argc, char *argv[]) { CustomData data; GstPad *tee_audio_pad, *tee_video_pad, *tee_app_pad; GstPad *queue_audio_pad, *queue_video_pad, *queue_app_pad; GstAudioInfo info; GstCaps *audio_caps; GstBus *bus; /* Initialize cumstom data structure */ memset (&data, 0, sizeof (data)); data.b = 1; /* For waveform generation */ data.d = 1; /* Initialize GStreamer */ gst_init (&argc, &argv); /* Create the elements */ data.app_source = gst_element_factory_make ("appsrc", "audio_source"); data.tee = gst_element_factory_make ("tee", "tee"); data.audio_queue = gst_element_factory_make ("queue", "audio_queue"); data.audio_convert1 = gst_element_factory_make ("audioconvert", "audio_convert1"); data.audio_resample = gst_element_factory_make ("audioresample", "audio_resample"); data.audio_sink = gst_element_factory_make ("autoaudiosink", "audio_sink"); data.video_queue = gst_element_factory_make ("queue", "video_queue"); data.audio_convert2 = gst_element_factory_make ("audioconvert", "audio_convert2"); data.visual = gst_element_factory_make ("wavescope", "visual"); data.video_convert = gst_element_factory_make ("videoconvert", "video_convert"); data.video_sink = gst_element_factory_make ("autovideosink", "video_sink"); data.app_queue = gst_element_factory_make ("queue", "app_queue"); data.app_sink = gst_element_factory_make ("appsink", "app_sink"); /* Create the empty pipeline */ data.pipeline = gst_pipeline_new ("test-pipeline"); if (!data.pipeline || !data.app_source || !data.tee || !data.audio_queue || !data.audio_convert1 || !data.audio_resample || !data.audio_sink || !data.video_queue || !data.audio_convert2 || !data.visual || !data.video_convert || !data.video_sink || !data.app_queue || !data.app_sink) { g_printerr ("Not all elements could be created.\n"); return -1; } /* Configure wavescope */ g_object_set (data.visual, "shader", 0, "style", 0, NULL); /* Configure appsrc */ gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16, SAMPLE_RATE, 1, NULL); audio_caps = gst_audio_info_to_caps (&info); g_object_set (data.app_source, "caps", audio_caps, "format", GST_FORMAT_TIME, NULL); g_signal_connect (data.app_source, "need-data", G_CALLBACK (start_feed), &data); g_signal_connect (data.app_source, "enough-data", G_CALLBACK (stop_feed), &data); /* Configure appsink */ g_object_set (data.app_sink, "emit-signals", TRUE, "caps", audio_caps, NULL); g_signal_connect (data.app_sink, "new-sample", G_CALLBACK (new_sample), &data); gst_caps_unref (audio_caps); /* Link all elements that can be automatically linked because they have "Always" pads */ gst_bin_add_many (GST_BIN (data.pipeline), data.app_source, data.tee, data.audio_queue, data.audio_convert1, data.audio_resample, data.audio_sink, data.video_queue, data.audio_convert2, data.visual, data.video_convert, data.video_sink, data.app_queue, data.app_sink, NULL); if (gst_element_link_many (data.app_source, data.tee, NULL) != TRUE || gst_element_link_many (data.audio_queue, data.audio_convert1, data.audio_resample, data.audio_sink, NULL) != TRUE || gst_element_link_many (data.video_queue, data.audio_convert2, data.visual, data.video_convert, data.video_sink, NULL) != TRUE || gst_element_link_many (data.app_queue, data.app_sink, NULL) != TRUE) { g_printerr ("Elements could not be linked.\n"); gst_object_unref (data.pipeline); return -1; } /* Manually link the Tee, which has "Request" pads */ tee_audio_pad = gst_element_get_request_pad (data.tee, "src_%u"); g_print ("Obtained request pad %s for audio branch.\n", gst_pad_get_name (tee_audio_pad)); queue_audio_pad = gst_element_get_static_pad (data.audio_queue, "sink"); tee_video_pad = gst_element_get_request_pad (data.tee, "src_%u"); g_print ("Obtained request pad %s for video branch.\n", gst_pad_get_name (tee_video_pad)); queue_video_pad = gst_element_get_static_pad (data.video_queue, "sink"); tee_app_pad = gst_element_get_request_pad (data.tee, "src_%u"); g_print ("Obtained request pad %s for app branch.\n", gst_pad_get_name (tee_app_pad)); queue_app_pad = gst_element_get_static_pad (data.app_queue, "sink"); if (gst_pad_link (tee_audio_pad, queue_audio_pad) != GST_PAD_LINK_OK || gst_pad_link (tee_video_pad, queue_video_pad) != GST_PAD_LINK_OK || gst_pad_link (tee_app_pad, queue_app_pad) != GST_PAD_LINK_OK) { g_printerr ("Tee could not be linked\n"); gst_object_unref (data.pipeline); return -1; } gst_object_unref (queue_audio_pad); gst_object_unref (queue_video_pad); gst_object_unref (queue_app_pad); /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */ bus = gst_element_get_bus (data.pipeline); gst_bus_add_signal_watch (bus); g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data); gst_object_unref (bus); /* Start playing the pipeline */ gst_element_set_state (data.pipeline, GST_STATE_PLAYING); /* Create a GLib Main Loop and set it to run */ data.main_loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (data.main_loop); /* Release the request pads from the Tee, and unref them */ gst_element_release_request_pad (data.tee, tee_audio_pad); gst_element_release_request_pad (data.tee, tee_video_pad); gst_element_release_request_pad (data.tee, tee_app_pad); gst_object_unref (tee_audio_pad); gst_object_unref (tee_video_pad); gst_object_unref (tee_app_pad); /* Free resources */ gst_element_set_state (data.pipeline, GST_STATE_NULL); gst_object_unref (data.pipeline); return 0; }
保存以上代碼,執行下列編譯命令即可得到可執行程序:
gcc basic-tutorial-9.c -o basic-tutorial-9 `pkg-config --cflags --libs gstreamer-1.0 gstreamer-audio-1.0 `
Note:本例在編譯時沒有連接gstreamer-app-1.0的庫是因為我們使用的是通過信號的方式,由appsrc自動處理buffer,所以無需在編譯時連接相應庫。在源碼分析部分會詳述。
源碼分析
與上一示例相同,首先對所需Element進行實例化,同時將Element的Always Pad連接起來,並與tee的Request Pad相連。此外我們還對appsrc及appsink進行了相應的配置:
/* Configure appsrc */ gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16, SAMPLE_RATE, 1, NULL); audio_caps = gst_audio_info_to_caps (&info); g_object_set (data.app_source, "caps", audio_caps, NULL); g_signal_connect (data.app_source, "need-data", G_CALLBACK (start_feed), &data); g_signal_connect (data.app_source, "enough-data", G_CALLBACK (stop_feed), &data);
首先需要對appsrc的caps進行設定,指定我們會產生何種類型的數據,這樣GStreamer會在連接階段檢查后續的Element是否支持此數據類型。這里的 caps必須為GstCaps對象,我們可以通過gst_caps_from_string()或gst_audio_info_to_caps ()得到相應的實例。
我們同時監聽了“need-data”與“enough-data”事件,這2個事件由appsrc在需要數據和緩沖區滿時觸發,使用這2個事件可以方便的控制何時產生數據與停止數據。
/* Configure appsink */ g_object_set (data.app_sink, "emit-signals", TRUE, "caps", audio_caps, NULL); g_signal_connect (data.app_sink, "new-sample", G_CALLBACK (new_sample), &data); gst_caps_unref (audio_caps);
對於appsink,我們監聽“new-sample”事件,用於appsink在收到數據時的處理。同時我們需要顯式的使能“new-sample”事件,因為這個事件默認是處於關閉狀態。
Pipeline的播放,停止及消息處理與其他示例相同,不再復述。我們接下來將查看我們監聽事件的回調函數。
/* This signal callback triggers when appsrc needs data. Here, we add an idle handler * to the mainloop to start pushing data into the appsrc */ static void start_feed (GstElement *source, guint size, CustomData *data) { if (data->sourceid == 0) { g_print ("Start feeding\n"); data->sourceid = g_idle_add ((GSourceFunc) push_data, data); } }
appsrc會在其內部的數據隊列即將缺乏數據時調用此回調函數,這里我們通過注冊一個GLib的idle函數來向appsrc填充數據,GLib的主循環在“idle”狀態時會循環調用 push_data,用於向appsrc填充數據。這只是一種向appsrc填充數據的方式,我們可以在任意線程中想appsrc填充數據。
我們保存了g_idle_add()的返回值,以便后續用於停止數據寫入。
/* This callback triggers when appsrc has enough data and we can stop sending. * We remove the idle handler from the mainloop */ static void stop_feed (GstElement *source, CustomData *data) { if (data->sourceid != 0) { g_print ("Stop feeding\n"); g_source_remove (data->sourceid); data->sourceid = 0; } }
stop_feed函數會在appsrc內部數據隊列滿時被調用。這里我們僅僅通過g_source_remove() 將先前注冊的idle處理函數從GLib的主循環中移除(idle處理函數是被實現為一個GSource)。
/* This method is called by the idle GSource in the mainloop, to feed CHUNK_SIZE bytes into appsrc. * The ide handler is added to the mainloop when appsrc requests us to start sending data (need-data signal) * and is removed when appsrc has enough data (enough-data signal). */ static gboolean push_data (CustomData *data) { GstBuffer *buffer; GstFlowReturn ret; int i; gint16 *raw; gint num_samples = CHUNK_SIZE / 2; /* Because each sample is 16 bits */ gfloat freq; /* Create a new empty buffer */ buffer = gst_buffer_new_and_alloc (CHUNK_SIZE); /* Set its timestamp and duration */ GST_BUFFER_TIMESTAMP (buffer) = gst_util_uint64_scale (data->num_samples, GST_SECOND, SAMPLE_RATE); GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale (num_samples, GST_SECOND, SAMPLE_RATE); /* Generate some psychodelic waveforms */ raw = (gint16 *)GST_BUFFER_DATA (buffer);
此函數會將真實的數據填充到appsrc的數據隊列中,首先通過gst_buffer_new_and_alloc()分配一個GstBuffer對象,然后通過產生的采樣數量計算這塊buffre所對應的時間戳及事件長度。
gst_util_uint64_scale(val, num, denom)函數用於計算 val * num / denom,此函數內部會對數據范圍進行檢測,避免溢出的問題。
GstBuffer的數據指針可以通過GST_BUFFER_DATA 宏獲取,在寫數據時需要避免超出內存分配大小。本文將跳過audio波形生成的函數,其內容不是本文介紹的重點。
/* Push the buffer into the appsrc */ g_signal_emit_by_name (data->app_source, "push-buffer", buffer, &ret); /* Free the buffer now that we are done with it */ gst_buffer_unref (buffer);
在我們准備好數據后,我們這里通過“push-buffer”事件通知appsrc數據就緒,並釋放我們申請的buffer。 另外一種方式為通過調用gst_app_src_push_buffer() 向appsrc填充數據,這種方式就需要在編譯時鏈接gstreamer-app-1.0庫,同時gst_app_src_push_buffer() 會接管GstBuffer的所有權,調用者無需釋放buffer。在所有數據都發送完成后,我們可以調用gst_app_src_end_of_stream()向Pipeline寫入EOS事件。
/* The appsink has received a buffer */ static GstFlowReturn new_sample (GstElement *sink, CustomData *data) { GstSample *sample; /* Retrieve the buffer */ g_signal_emit_by_name (sink, "pull-sample", &sample); if (sample) { /* The only thing we do in this example is print a * to indicate a received buffer */ g_print ("*"); gst_sample_unref (sample); return GST_FLOW_OK; } return GST_FLOW_ERROR; }
當appsink得到數據時會調用new_sample函數,我們使用“pull-sample”信號提取sample,這里僅輸出一個”*“表明此函數被調用。除此之外,我們同樣可以使用gst_app_sink_pull_sample ()獲取Sample。得到GstSample之后,我們可以通過gst_sample_get_buffer()得到Sample中所包含的GstBuffer,再使用GST_BUFFER_DATA, GST_BUFFER_SIZE 等接口訪問其中的數據。使用完后,得到的GstSample同樣需要通過gst_sample_unref()進行釋放。
需要注意的是,在某些Pipeline里得到的GstBuffer可能會和source中填充的GstBuffer有所差異,因為Pipeline中的Element可能對Buffer進行各種處理(此例中不存在此種情況,因為在appsrc與appsink之間只存在一個tee)。
總結
在本文中,我們介紹了:
- 如何通過appsrc向Pipeline中寫入數據
- 如何通過appsink取得Pipeline中的數據
- 如何獲取/填充GstBuffer中對應的數據
后續我們將繼續學習有關GStreamer的其他知識。
引用