经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C 语言 » 查看文章
GStreamer基础教程09 - Appsrc及Appsink
来源:cnblogs  作者:John.Leng  时间:2019/10/8 9:10:55  对本文有异议

摘要

在我们前面的文章中,我们的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的示意图如下:

  1. #include <gst/gst.h>
  2. #include <gst/audio/audio.h>
  3. #include <string.h>
  4.  
  5. #define CHUNK_SIZE 1024 /* Amount of bytes we are sending in each buffer */
  6. #define SAMPLE_RATE 44100 /* Samples per second we are sending */
  7.  
  8. /* Structure to contain all our information, so we can pass it to callbacks */
  9. typedef struct _CustomData {
  10. GstElement *pipeline, *app_source, *tee, *audio_queue, *audio_convert1, *audio_resample, *audio_sink;
  11. GstElement *video_queue, *audio_convert2, *visual, *video_convert, *video_sink;
  12. GstElement *app_queue, *app_sink;
  13. guint64 num_samples; /* Number of samples generated so far (for timestamp generation) */
  14. gfloat a, b, c, d; /* For waveform generation */
  15. guint sourceid; /* To control the GSource */
  16. GMainLoop *main_loop; /* GLib's Main Loop */
  17. } CustomData;
  18. /* This method is called by the idle GSource in the mainloop, to feed CHUNK_SIZE bytes into appsrc.
  19. * The idle handler is added to the mainloop when appsrc requests us to start sending data (need-data signal)
  20. * and is removed when appsrc has enough data (enough-data signal).
  21. */
  22. static gboolean push_data (CustomData *data) {
  23. GstBuffer *buffer;
  24. GstFlowReturn ret;
  25. int i;
  26. GstMapInfo map;
  27. gint16 *raw;
  28. gint num_samples = CHUNK_SIZE / 2; /* Because each sample is 16 bits */
  29. gfloat freq;
  30. /* Create a new empty buffer */
  31. buffer = gst_buffer_new_and_alloc (CHUNK_SIZE);
  32. /* Set its timestamp and duration */
  33. GST_BUFFER_TIMESTAMP (buffer) = gst_util_uint64_scale (data->num_samples, GST_SECOND, SAMPLE_RATE);
  34. GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale (num_samples, GST_SECOND, SAMPLE_RATE);
  35. /* Generate some psychodelic waveforms */
  36. gst_buffer_map (buffer, &map, GST_MAP_WRITE);
  37. raw = (gint16 *)map.data;
  38. data->c += data->d;
  39. data->d -= data->c / 1000;
  40. freq = 1100 + 1000 * data->d;
  41. for (i = 0; i < num_samples; i++) {
  42. data->a += data->b;
  43. data->b -= data->a / freq;
  44. raw[i] = (gint16)(500 * data->a);
  45. }
  46. gst_buffer_unmap (buffer, &map);
  47. data->num_samples += num_samples;
  48. /* Push the buffer into the appsrc */
  49. g_signal_emit_by_name (data->app_source, "push-buffer", buffer, &ret);
  50. /* Free the buffer now that we are done with it */
  51. gst_buffer_unref (buffer);
  52. if (ret != GST_FLOW_OK) {
  53. /* We got some error, stop sending data */
  54. return FALSE;
  55. }
  56. return TRUE;
  57. }
  58. /* This signal callback triggers when appsrc needs data. Here, we add an idle handler
  59. * to the mainloop to start pushing data into the appsrc */
  60. static void start_feed (GstElement *source, guint size, CustomData *data) {
  61. if (data->sourceid == 0) {
  62. g_print ("Start feeding\n");
  63. data->sourceid = g_idle_add ((GSourceFunc) push_data, data);
  64. }
  65. }
  66. /* This callback triggers when appsrc has enough data and we can stop sending.
  67. * We remove the idle handler from the mainloop */
  68. static void stop_feed (GstElement *source, CustomData *data) {
  69. if (data->sourceid != 0) {
  70. g_print ("Stop feeding\n");
  71. g_source_remove (data->sourceid);
  72. data->sourceid = 0;
  73. }
  74. }
  75. /* The appsink has received a buffer */
  76. static GstFlowReturn new_sample (GstElement *sink, CustomData *data) {
  77. GstSample *sample;
  78. /* Retrieve the buffer */
  79. g_signal_emit_by_name (sink, "pull-sample", &sample);
  80. if (sample) {
  81. /* The only thing we do in this example is print a * to indicate a received buffer */
  82. g_print ("*");
  83. gst_sample_unref (sample);
  84. return GST_FLOW_OK;
  85. }
  86. return GST_FLOW_ERROR;
  87. }
  88. /* This function is called when an error message is posted on the bus */
  89. static void error_cb (GstBus *bus, GstMessage *msg, CustomData *data) {
  90. GError *err;
  91. gchar *debug_info;
  92. /* Print error details on the screen */
  93. gst_message_parse_error (msg, &err, &debug_info);
  94. g_printerr ("Error received from element %s: %s\n", GST_OBJECT_NAME (msg->src), err->message);
  95. g_printerr ("Debugging information: %s\n", debug_info ? debug_info : "none");
  96. g_clear_error (&err);
  97. g_free (debug_info);
  98. g_main_loop_quit (data->main_loop);
  99. }
  100. int main(int argc, char *argv[]) {
  101. CustomData data;
  102. GstPad *tee_audio_pad, *tee_video_pad, *tee_app_pad;
  103. GstPad *queue_audio_pad, *queue_video_pad, *queue_app_pad;
  104. GstAudioInfo info;
  105. GstCaps *audio_caps;
  106. GstBus *bus;
  107. /* Initialize cumstom data structure */
  108. memset (&data, 0, sizeof (data));
  109. data.b = 1; /* For waveform generation */
  110. data.d = 1;
  111. /* Initialize GStreamer */
  112. gst_init (&argc, &argv);
  113. /* Create the elements */
  114. data.app_source = gst_element_factory_make ("appsrc", "audio_source");
  115. data.tee = gst_element_factory_make ("tee", "tee");
  116. data.audio_queue = gst_element_factory_make ("queue", "audio_queue");
  117. data.audio_convert1 = gst_element_factory_make ("audioconvert", "audio_convert1");
  118. data.audio_resample = gst_element_factory_make ("audioresample", "audio_resample");
  119. data.audio_sink = gst_element_factory_make ("autoaudiosink", "audio_sink");
  120. data.video_queue = gst_element_factory_make ("queue", "video_queue");
  121. data.audio_convert2 = gst_element_factory_make ("audioconvert", "audio_convert2");
  122. data.visual = gst_element_factory_make ("wavescope", "visual");
  123. data.video_convert = gst_element_factory_make ("videoconvert", "video_convert");
  124. data.video_sink = gst_element_factory_make ("autovideosink", "video_sink");
  125. data.app_queue = gst_element_factory_make ("queue", "app_queue");
  126. data.app_sink = gst_element_factory_make ("appsink", "app_sink");
  127. /* Create the empty pipeline */
  128. data.pipeline = gst_pipeline_new ("test-pipeline");
  129. if (!data.pipeline || !data.app_source || !data.tee || !data.audio_queue || !data.audio_convert1 ||
  130. !data.audio_resample || !data.audio_sink || !data.video_queue || !data.audio_convert2 || !data.visual ||
  131. !data.video_convert || !data.video_sink || !data.app_queue || !data.app_sink) {
  132. g_printerr ("Not all elements could be created.\n");
  133. return -1;
  134. }
  135. /* Configure wavescope */
  136. g_object_set (data.visual, "shader", 0, "style", 0, NULL);
  137. /* Configure appsrc */
  138. gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16, SAMPLE_RATE, 1, NULL);
  139. audio_caps = gst_audio_info_to_caps (&info);
  140. g_object_set (data.app_source, "caps", audio_caps, "format", GST_FORMAT_TIME, NULL);
  141. g_signal_connect (data.app_source, "need-data", G_CALLBACK (start_feed), &data);
  142. g_signal_connect (data.app_source, "enough-data", G_CALLBACK (stop_feed), &data);
  143. /* Configure appsink */
  144. g_object_set (data.app_sink, "emit-signals", TRUE, "caps", audio_caps, NULL);
  145. g_signal_connect (data.app_sink, "new-sample", G_CALLBACK (new_sample), &data);
  146. gst_caps_unref (audio_caps);
  147. /* Link all elements that can be automatically linked because they have "Always" pads */
  148. gst_bin_add_many (GST_BIN (data.pipeline), data.app_source, data.tee, data.audio_queue, data.audio_convert1, data.audio_resample,
  149. data.audio_sink, data.video_queue, data.audio_convert2, data.visual, data.video_convert, data.video_sink, data.app_queue,
  150. data.app_sink, NULL);
  151. if (gst_element_link_many (data.app_source, data.tee, NULL) != TRUE ||
  152. gst_element_link_many (data.audio_queue, data.audio_convert1, data.audio_resample, data.audio_sink, NULL) != TRUE ||
  153. gst_element_link_many (data.video_queue, data.audio_convert2, data.visual, data.video_convert, data.video_sink, NULL) != TRUE ||
  154. gst_element_link_many (data.app_queue, data.app_sink, NULL) != TRUE) {
  155. g_printerr ("Elements could not be linked.\n");
  156. gst_object_unref (data.pipeline);
  157. return -1;
  158. }
  159. /* Manually link the Tee, which has "Request" pads */
  160. tee_audio_pad = gst_element_get_request_pad (data.tee, "src_%u");
  161. g_print ("Obtained request pad %s for audio branch.\n", gst_pad_get_name (tee_audio_pad));
  162. queue_audio_pad = gst_element_get_static_pad (data.audio_queue, "sink");
  163. tee_video_pad = gst_element_get_request_pad (data.tee, "src_%u");
  164. g_print ("Obtained request pad %s for video branch.\n", gst_pad_get_name (tee_video_pad));
  165. queue_video_pad = gst_element_get_static_pad (data.video_queue, "sink");
  166. tee_app_pad = gst_element_get_request_pad (data.tee, "src_%u");
  167. g_print ("Obtained request pad %s for app branch.\n", gst_pad_get_name (tee_app_pad));
  168. queue_app_pad = gst_element_get_static_pad (data.app_queue, "sink");
  169. if (gst_pad_link (tee_audio_pad, queue_audio_pad) != GST_PAD_LINK_OK ||
  170. gst_pad_link (tee_video_pad, queue_video_pad) != GST_PAD_LINK_OK ||
  171. gst_pad_link (tee_app_pad, queue_app_pad) != GST_PAD_LINK_OK) {
  172. g_printerr ("Tee could not be linked\n");
  173. gst_object_unref (data.pipeline);
  174. return -1;
  175. }
  176. gst_object_unref (queue_audio_pad);
  177. gst_object_unref (queue_video_pad);
  178. gst_object_unref (queue_app_pad);
  179. /* Instruct the bus to emit signals for each received message, and connect to the interesting signals */
  180. bus = gst_element_get_bus (data.pipeline);
  181. gst_bus_add_signal_watch (bus);
  182. g_signal_connect (G_OBJECT (bus), "message::error", (GCallback)error_cb, &data);
  183. gst_object_unref (bus);
  184. /* Start playing the pipeline */
  185. gst_element_set_state (data.pipeline, GST_STATE_PLAYING);
  186. /* Create a GLib Main Loop and set it to run */
  187. data.main_loop = g_main_loop_new (NULL, FALSE);
  188. g_main_loop_run (data.main_loop);
  189. /* Release the request pads from the Tee, and unref them */
  190. gst_element_release_request_pad (data.tee, tee_audio_pad);
  191. gst_element_release_request_pad (data.tee, tee_video_pad);
  192. gst_element_release_request_pad (data.tee, tee_app_pad);
  193. gst_object_unref (tee_audio_pad);
  194. gst_object_unref (tee_video_pad);
  195. gst_object_unref (tee_app_pad);
  196. /* Free resources */
  197. gst_element_set_state (data.pipeline, GST_STATE_NULL);
  198. gst_object_unref (data.pipeline);
  199. return 0;
  200. }

保存以上代码,执行下列编译命令即可得到可执行程序:

  1. 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进行了相应的配置:

  1. /* Configure appsrc */
  2. gst_audio_info_set_format (&info, GST_AUDIO_FORMAT_S16, SAMPLE_RATE, 1, NULL);
  3. audio_caps = gst_audio_info_to_caps (&info);
  4. g_object_set (data.app_source, "caps", audio_caps, NULL);
  5. g_signal_connect (data.app_source, "need-data", G_CALLBACK (start_feed), &data);
  6. 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个事件可以方便的控制何时产生数据与停止数据。

 

  1. /* Configure appsink */
  2. g_object_set (data.app_sink, "emit-signals", TRUE, "caps", audio_caps, NULL);
  3. g_signal_connect (data.app_sink, "new-sample", G_CALLBACK (new_sample), &data);
  4. gst_caps_unref (audio_caps);

  对于appsink,我们监听“new-sample”事件,用于appsink在收到数据时的处理。同时我们需要显式的使能“new-sample”事件,因为这个事件默认是处于关闭状态。

  Pipeline的播放,停止及消息处理与其他示例相同,不再复述。我们接下来将查看我们监听事件的回调函数。

 

  1. /* This signal callback triggers when appsrc needs data. Here, we add an idle handler
  2. * to the mainloop to start pushing data into the appsrc */
  3. static void start_feed (GstElement *source, guint size, CustomData *data) {
  4. if (data->sourceid == 0) {
  5. g_print ("Start feeding\n");
  6. data->sourceid = g_idle_add ((GSourceFunc) push_data, data);
  7. }
  8. }

  appsrc会在其内部的数据队列即将缺乏数据时调用此回调函数,这里我们通过注册一个GLib的idle函数来向appsrc填充数据,GLib的主循环在“idle”状态时会循环调用 push_data,用于向appsrc填充数据。这只是一种向appsrc填充数据的方式,我们可以在任意线程中想appsrc填充数据。
  我们保存了g_idle_add()的返回值,以便后续用于停止数据写入。

  1. /* This callback triggers when appsrc has enough data and we can stop sending.
  2. * We remove the idle handler from the mainloop */
  3. static void stop_feed (GstElement *source, CustomData *data) {
  4. if (data->sourceid != 0) {
  5. g_print ("Stop feeding\n");
  6. g_source_remove (data->sourceid);
  7. data->sourceid = 0;
  8. }
  9. }

  stop_feed函数会在appsrc内部数据队列满时被调用。这里我们仅仅通过g_source_remove() 将先前注册的idle处理函数从GLib的主循环中移除(idle处理函数是被实现为一个GSource)。

 

  1. /* This method is called by the idle GSource in the mainloop, to feed CHUNK_SIZE bytes into appsrc.
  2. * The ide handler is added to the mainloop when appsrc requests us to start sending data (need-data signal)
  3. * and is removed when appsrc has enough data (enough-data signal).
  4. */
  5. static gboolean push_data (CustomData *data) {
  6. GstBuffer *buffer;
  7. GstFlowReturn ret;
  8. int i;
  9. gint16 *raw;
  10. gint num_samples = CHUNK_SIZE / 2; /* Because each sample is 16 bits */
  11. gfloat freq;
  12. /* Create a new empty buffer */
  13. buffer = gst_buffer_new_and_alloc (CHUNK_SIZE);
  14. /* Set its timestamp and duration */
  15. GST_BUFFER_TIMESTAMP (buffer) = gst_util_uint64_scale (data->num_samples, GST_SECOND, SAMPLE_RATE);
  16. GST_BUFFER_DURATION (buffer) = gst_util_uint64_scale (num_samples, GST_SECOND, SAMPLE_RATE);
  17. /* Generate some psychodelic waveforms */
  18. 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波形生成的函数,其内容不是本文介绍的重点。

 

  1. /* Push the buffer into the appsrc */
  2. g_signal_emit_by_name (data->app_source, "push-buffer", buffer, &ret);
  3. /* Free the buffer now that we are done with it */
  4. 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事件。

  1. /* The appsink has received a buffer */
  2. static GstFlowReturn new_sample (GstElement *sink, CustomData *data) {
  3. GstSample *sample;
  4. /* Retrieve the buffer */
  5. g_signal_emit_by_name (sink, "pull-sample", &sample);
  6. if (sample) {
  7. /* The only thing we do in this example is print a * to indicate a received buffer */
  8. g_print ("*");
  9. gst_sample_unref (sample);
  10. return GST_FLOW_OK;
  11. }
  12. return GST_FLOW_ERROR;
  13. }

  当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的其他知识。

 

引用

https://gstreamer.freedesktop.org/documentation/tutorials/basic/short-cutting-the-pipeline.html?gi-language=c

  

作者:John.Leng
本文版权归作者所有,欢迎转载。商业转载请联系作者获得授权,非商业转载请在文章页面明显位置给出原文连接.

原文链接:http://www.cnblogs.com/xleng/p/11611450.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号