- merge with master
[oweals/gnunet.git] / src / conversation / gnunet-helper-audio-playback-gst.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013 GNUnet e.V.
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20 /**
21  * @file conversation/gnunet-helper-audio-playback-gst.c
22  * @brief program to playback audio data to the speaker (GStreamer version)
23  * @author LRN
24  */
25 #include "platform.h"
26 #include "gnunet_util_lib.h"
27 #include "gnunet_protocols.h"
28 #include "conversation.h"
29 #include "gnunet_constants.h"
30 #include "gnunet_core_service.h"
31
32 #include <gst/gst.h>
33 #include <gst/audio/gstaudiobasesrc.h>
34 #include <gst/app/gstappsrc.h>
35 #include <glib.h>
36
37 #define DEBUG_READ_PURE_OGG 1
38
39 /**
40  * How much data to read in one go
41  */
42 #define MAXLINE 4096
43
44 /**
45  * Max number of microseconds to buffer in audiosink.
46  * Default is 1000
47  */
48 #define BUFFER_TIME 1000
49
50 /**
51  * Min number of microseconds to buffer in audiosink.
52  * Default is 1000
53  */
54 #define LATENCY_TIME 1000
55
56 /**
57  * Tokenizer for the data we get from stdin
58  */
59 struct GNUNET_MessageStreamTokenizer *stdin_mst;
60
61 /**
62  * Main pipeline.
63  */
64 static GstElement *pipeline;
65
66 /**
67  * Appsrc instance into which we write data for the pipeline.
68  */
69 static GstElement *source;
70
71 static GstElement *demuxer;
72 static GstElement *decoder;
73 static GstElement *conv;
74 static GstElement *resampler;
75 static GstElement *sink;
76
77 /**
78  * Set to 1 to break the reading loop
79  */
80 static int abort_read;
81
82
83 static void
84 sink_child_added (GstChildProxy *child_proxy,
85                   GObject *object,
86                   gchar *name,
87                   gpointer user_data)
88 {
89   if (GST_IS_AUDIO_BASE_SRC (object))
90     g_object_set (object,
91                   "buffer-time", (gint64) BUFFER_TIME,
92                   "latency-time", (gint64) LATENCY_TIME,
93                   NULL);
94 }
95
96
97 static void
98 ogg_pad_added (GstElement *element,
99                GstPad *pad,
100                gpointer data)
101 {
102   GstPad *sinkpad;
103   GstElement *decoder = (GstElement *) data;
104
105   /* We can now link this pad with the opus-decoder sink pad */
106   sinkpad = gst_element_get_static_pad (decoder, "sink");
107
108   gst_pad_link (pad, sinkpad);
109
110   gst_element_link_many (decoder, conv, resampler, sink, NULL);
111
112   gst_object_unref (sinkpad);
113 }
114
115
116 static void
117 quit ()
118 {
119   if (NULL != source)
120     gst_app_src_end_of_stream (GST_APP_SRC (source));
121   if (NULL != pipeline)
122     gst_element_set_state (pipeline, GST_STATE_NULL);
123   abort_read = 1;
124 }
125
126
127 static gboolean
128 bus_call (GstBus *bus, GstMessage *msg, gpointer data)
129 {
130   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
131               "Bus message\n");
132   switch (GST_MESSAGE_TYPE (msg))
133   {
134   case GST_MESSAGE_EOS:
135     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
136                 "End of stream\n");
137     quit ();
138     break;
139
140   case GST_MESSAGE_ERROR:
141     {
142       gchar  *debug;
143       GError *error;
144
145       gst_message_parse_error (msg, &error, &debug);
146       g_free (debug);
147
148       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
149                   "Error: %s\n",
150                   error->message);
151       g_error_free (error);
152
153       quit ();
154       break;
155     }
156   default:
157     break;
158   }
159
160   return TRUE;
161 }
162
163
164 static void
165 signalhandler (int s)
166 {
167   quit ();
168 }
169
170
171 static int
172 feed_buffer_to_gst (const char *audio, size_t b_len)
173 {
174   GstBuffer *b;
175   gchar *bufspace;
176   GstFlowReturn flow;
177
178   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
179               "Feeding %u bytes to GStreamer\n",
180               (unsigned int) b_len);
181
182   bufspace = g_memdup (audio, b_len);
183   b = gst_buffer_new_wrapped (bufspace, b_len);
184   if (NULL == b)
185   {
186     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
187                 "Failed to wrap a buffer\n");
188     g_free (bufspace);
189     return GNUNET_SYSERR;
190   }
191   flow = gst_app_src_push_buffer (GST_APP_SRC (source), b);
192   /* They all return GNUNET_OK, because currently player stops when
193    * data stops coming. This might need to be changed for the player
194    * to also stop when pipeline breaks.
195    */
196   switch (flow)
197   {
198   case GST_FLOW_OK:
199     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
200                 "Fed %u bytes to the pipeline\n",
201                 (unsigned int) b_len);
202     break;
203   case GST_FLOW_FLUSHING:
204     /* buffer was dropped, because pipeline state is not PAUSED or PLAYING */
205     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
206                 "Dropped a buffer\n");
207     break;
208   case GST_FLOW_EOS:
209     /* end of stream */
210     GNUNET_log (GNUNET_ERROR_TYPE_INFO,
211                 "EOS\n");
212     break;
213   default:
214     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
215                 "Unexpected push result\n");
216     break;
217   }
218   return GNUNET_OK;
219 }
220
221
222 /**
223  * Message callback
224  */
225 static int
226 stdin_receiver (void *cls,
227                 const struct GNUNET_MessageHeader *msg)
228 {
229   struct AudioMessage *audio;
230   size_t b_len;
231
232   switch (ntohs (msg->type))
233   {
234   case GNUNET_MESSAGE_TYPE_CONVERSATION_AUDIO:
235     audio = (struct AudioMessage *) msg;
236
237     b_len = ntohs (audio->header.size) - sizeof (struct AudioMessage);
238     feed_buffer_to_gst ((const char *) &audio[1], b_len);
239     break;
240   default:
241     break;
242   }
243   return GNUNET_OK;
244 }
245
246
247 int
248 main (int argc, char **argv)
249 {
250   GstBus *bus;
251   guint bus_watch_id;
252   uint64_t toff;
253
254   typedef void (*SignalHandlerPointer) (int);
255
256   SignalHandlerPointer inthandler, termhandler;
257 #ifdef DEBUG_READ_PURE_OGG
258   int read_pure_ogg = getenv ("GNUNET_READ_PURE_OGG") ? 1 : 0;
259 #endif
260
261   inthandler = signal (SIGINT,
262                        &signalhandler);
263   termhandler = signal (SIGTERM,
264                         &signalhandler);
265
266 #ifdef WINDOWS
267   setmode (0, _O_BINARY);
268 #endif
269
270   /* Initialisation */
271   gst_init (&argc, &argv);
272
273   GNUNET_assert (GNUNET_OK ==
274                  GNUNET_log_setup ("gnunet-helper-audio-playback-gst",
275                                    "WARNING",
276                                    NULL));
277
278   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
279               "Audio sink starts\n");
280
281   stdin_mst = GNUNET_MST_create (&stdin_receiver,
282                                  NULL);
283
284   /* Create gstreamer elements */
285   pipeline = gst_pipeline_new ("audio-player");
286   source   = gst_element_factory_make ("appsrc",        "audio-input");
287   demuxer  = gst_element_factory_make ("oggdemux",      "ogg-demuxer");
288   decoder  = gst_element_factory_make ("opusdec",       "opus-decoder");
289   conv     = gst_element_factory_make ("audioconvert",  "converter");
290   resampler= gst_element_factory_make ("audioresample", "resampler");
291   sink     = gst_element_factory_make ("autoaudiosink", "audiosink");
292
293   if (!pipeline || !source || !conv || !resampler || !decoder || !demuxer || !sink)
294   {
295     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
296                 "One element could not be created. Exiting.\n");
297     return -1;
298   }
299
300   g_signal_connect (sink,
301                     "child-added",
302                     G_CALLBACK (sink_child_added),
303                     NULL);
304   g_signal_connect (demuxer,
305                     "pad-added",
306                     G_CALLBACK (ogg_pad_added),
307                     decoder);
308
309   /* Keep a reference to it, we operate on it */
310   gst_object_ref (GST_OBJECT (source));
311
312   /* Set up the pipeline */
313
314   /* we feed appsrc as fast as possible, it just blocks when it's full */
315   g_object_set (G_OBJECT (source),
316 /*      "format", GST_FORMAT_TIME,*/
317       "block", TRUE,
318       "is-live", TRUE,
319       NULL);
320
321   g_object_set (G_OBJECT (decoder),
322 /*      "plc", FALSE,*/
323 /*      "apply-gain", TRUE,*/
324       "use-inband-fec", TRUE,
325       NULL);
326
327   /* we add a message handler */
328   bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
329   bus_watch_id = gst_bus_add_watch (bus, bus_call, pipeline);
330   gst_object_unref (bus);
331
332   /* we add all elements into the pipeline */
333   /* audio-input | ogg-demuxer | opus-decoder | converter | resampler | audiosink */
334   gst_bin_add_many (GST_BIN (pipeline), source, demuxer, decoder, conv,
335       resampler, sink, NULL);
336
337   /* we link the elements together */
338   gst_element_link_many (source, demuxer, NULL);
339
340   /* Set the pipeline to "playing" state*/
341   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Now playing\n");
342   gst_element_set_state (pipeline, GST_STATE_PLAYING);
343
344   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Running...\n");
345   /* Iterate */
346   toff = 0;
347   while (!abort_read)
348   {
349     char readbuf[MAXLINE];
350     int ret;
351
352     ret = read (0, readbuf, sizeof (readbuf));
353     if (0 > ret)
354     {
355       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
356                   _("Read error from STDIN: %d %s\n"),
357                   ret, strerror (errno));
358       break;
359     }
360     toff += ret;
361     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
362                 "Received %d bytes of audio data (total: %llu)\n",
363                 (int) ret,
364                 (unsigned long long) toff);
365     if (0 == ret)
366       break;
367 #ifdef DEBUG_READ_PURE_OGG
368     if (read_pure_ogg)
369     {
370       feed_buffer_to_gst (readbuf, ret);
371     }
372     else
373 #endif
374     GNUNET_MST_from_buffer (stdin_mst,
375                             readbuf,
376                             ret,
377                             GNUNET_NO,
378                             GNUNET_NO);
379   }
380   GNUNET_MST_destroy (stdin_mst);
381
382   signal (SIGINT, inthandler);
383   signal (SIGINT, termhandler);
384
385   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
386               "Returned, stopping playback\n");
387   quit ();
388
389   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
390               "Deleting pipeline\n");
391   gst_object_unref (GST_OBJECT (source));
392   source = NULL;
393   gst_object_unref (GST_OBJECT (pipeline));
394   pipeline = NULL;
395   g_source_remove (bus_watch_id);
396
397   return 0;
398 }