在咱們前面的文章中,咱們的Pipline都是使用GStreamer自帶的插件去產生/消費數據。在實際的狀況中,咱們的數據源可能沒有相應的gstreamer插件,但咱們又須要將數據發送到GStreamer Pipeline中。GStreamer爲咱們提供了Appsrc以及Appsink插件,用於處理這種狀況,本文將介紹如何使用這些插件來實現數據與應用程序的交互。html
GStreamer提供了多種方法使得應用程序與GStreamer Pipeline之間能夠進行數據交互,咱們這裏介紹的是最簡單的一種方式:appsrc與appsink。ios
用於將應用程序的數據發送到Pipeline中。應用程序負責數據的生成,並將其做爲GstBuffer傳輸到Pipeline中。
appsrc有2中模式,拉模式和推模式。在拉模式下,appsrc會在須要數據時,經過指定接口從應用程序中獲取相應數據。在推模式下,則須要由應用程序主動將數據推送到Pipeline中,應用程序能夠指定在Pipeline的數據隊列滿時是否阻塞相應調用,或經過監聽enough-data和need-data信號來控制數據的發送。多線程
用於從Pipeline中提取數據,併發送到應用程序中。併發
appsrc和appsink須要經過特殊的API才能與Pipeline進行數據交互,相應的接口能夠查看官方文檔,在編譯的時候還需鏈接gstreamer-app庫。app
在GStreamer Pipeline中的plugin間傳輸的數據塊被稱爲buffer,在GStreamer內部對應於GstBuffer。Buffer由Source Pad產生,並由Sink Pad消耗。一個Buffer只表示一塊數據,不一樣的buffer可能包含不一樣大小,不一樣時間長度的數據。同時,某些Element中可能對Buffer進行拆分或合併,因此GstBuffer中可能包含不止一個內存數據,實際的內存數據在GStreamer系統中經過GstMemory對象進行描述,所以,GstBuffer能夠包含多個GstMemory對象。
每一個GstBuffer都有相應的時間戳以及時間長度,用於描述這個buffer的解碼時間以及顯示時間。ide
本例在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; }
保存以上代碼,執行下列編譯命令便可獲得可執行程序:oop
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進行了相應的配置:post
/* 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)。
在本文中,咱們介紹了:
後續咱們將繼續學習有關GStreamer的其餘知識。