Prevent Valgrind from reporting cached configuration as memory leaks
[gst-aseq-appsrc.git] / gst-aseq-appsrc.c
1 /* GStreamer
2  *
3  * gst-aseq-appsrc: a GStreamer appsrc for the ALSA MIDI sequencer API
4  *
5  * Copyright (C) 2014  Antonio Ospite <ao2@ao2.it>
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Library General Public
9  * License as published by the Free Software Foundation; either
10  * version 2 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Library General Public License for more details.
16  *
17  * You should have received a copy of the GNU Library General Public
18  * License along with this library; if not, write to the
19  * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 /* Code _heavily_ inspired to aseqdump and amidicat:
24  * http://git.alsa-project.org/?p=alsa-utils.git;a=tree;f=seq/aseqdump
25  * http://krellan.com/amidicat/
26  */
27
28 #include <gst/gst.h>
29 #include <gst/app/gstappsrc.h>
30
31 #include <string.h>
32 #include <sys/poll.h>
33 #include <alsa/asoundlib.h>
34 #include <glib-unix.h>
35
36 #define DEFAULT_BUFSIZE 65536
37 #define DEFAULT_CLIENT_NAME "gst-aseq-appsrc"
38 #define DEFAULT_TICK_PERIOD_MS 10
39 #define DEFAULT_POLL_TIMEOUT_MS (DEFAULT_TICK_PERIOD_MS / 2)
40
41 GST_DEBUG_CATEGORY (mysource_debug);
42 #define GST_CAT_DEFAULT mysource_debug
43
44 typedef struct _App App;
45
46 struct _App
47 {
48   GstElement *pipeline;
49   GstElement *appsrc;
50
51   GMainLoop *loop;
52
53   snd_seq_t *seq;
54   int port_count;
55   snd_seq_addr_t *seq_ports;
56   snd_midi_event_t *parser;
57   unsigned char *buffer;
58
59   struct pollfd *pfds;
60   int npfds;
61
62   guint64 tick;
63 };
64
65 static App s_app;
66
67 static int
68 init_seq (App * app)
69 {
70   int ret;
71
72   ret = snd_seq_open (&app->seq, "default", SND_SEQ_OPEN_DUPLEX, 0);
73   if (ret < 0) {
74     GST_ERROR ("Cannot open sequencer - %s", snd_strerror (ret));
75     goto error;
76   }
77
78   /*
79    * Prevent Valgrind from reporting cached configuration as memory leaks, see:
80    * http://git.alsa-project.org/?p=alsa-lib.git;a=blob;f=MEMORY-LEAK;hb=HEAD
81    */
82   snd_config_update_free_global();
83
84   ret = snd_seq_set_client_name (app->seq, DEFAULT_CLIENT_NAME);
85   if (ret < 0) {
86     GST_ERROR ("Cannot set client name - %s", snd_strerror (ret));
87     goto error_seq_close;
88   }
89
90   return 0;
91
92 error_seq_close:
93   snd_seq_close (app->seq);
94 error:
95   return ret;
96 }
97
98 /* Parses one or more port addresses from the string */
99 static int
100 parse_ports (const char *arg, App * app)
101 {
102   gchar **ports_list;
103   guint i;
104   int ret = 0;
105
106   GST_DEBUG ("ports: %s", arg);
107
108   /*
109    * Assume that ports are separated by commas.
110    *
111    * Commas are used instead of spaces because those are valid in client
112    * names.
113    */
114   ports_list = g_strsplit (arg, ",", 0);
115
116   app->port_count = g_strv_length (ports_list);
117   app->seq_ports = g_try_new (snd_seq_addr_t, app->port_count);
118   if (!app->seq_ports) {
119     GST_ERROR ("Out of memory");
120     ret = -ENOMEM;
121     goto out_free_ports_list;
122   }
123
124   for (i = 0; i < (guint)app->port_count; i++) {
125     gchar *port_name = ports_list[i];
126
127     ret = snd_seq_parse_address (app->seq, &app->seq_ports[i],
128         port_name);
129     if (ret < 0) {
130       GST_ERROR ("Invalid port %s - %s", port_name,
131           snd_strerror (ret));
132       goto error_free_seq_ports;
133     }
134   }
135
136   goto out_free_ports_list;
137
138 error_free_seq_ports:
139   g_free (app->seq_ports);
140 out_free_ports_list:
141   g_strfreev (ports_list);
142   return ret;
143 }
144
145 static int
146 create_port (App * app)
147 {
148   int ret;
149
150   ret = snd_seq_create_simple_port (app->seq, DEFAULT_CLIENT_NAME,
151       SND_SEQ_PORT_CAP_WRITE |
152       SND_SEQ_PORT_CAP_SUBS_WRITE,
153       SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
154   if (ret < 0)
155     GST_ERROR ("Cannot create port - %s", snd_strerror (ret));
156
157   return ret;
158 }
159
160 static void
161 connect_ports (App * app)
162 {
163   int i;
164   int ret;
165
166   for (i = 0; i < app->port_count; ++i) {
167     ret =
168         snd_seq_connect_from (app->seq, 0, app->seq_ports[i].client,
169         app->seq_ports[i].port);
170     if (ret < 0)
171       /* warning */
172       GST_WARNING ("Cannot connect from port %d:%d - %s",
173           app->seq_ports[i].client, app->seq_ports[i].port, snd_strerror (ret));
174   }
175 }
176
177 static void
178 push_buffer (App * app, gpointer data, guint size)
179 {
180   GstClockTime time;
181   gpointer local_data;
182   GstBuffer *buffer;
183   int ret;
184
185   buffer = gst_buffer_new ();
186
187   time = app->tick * DEFAULT_TICK_PERIOD_MS * GST_MSECOND;
188
189   GST_BUFFER_DTS (buffer) = time;
190   GST_BUFFER_PTS (buffer) = time;
191   GST_BUFFER_OFFSET (buffer) = time;
192   GST_BUFFER_DURATION (buffer) = DEFAULT_TICK_PERIOD_MS * GST_MSECOND;
193
194   local_data = g_memdup (data, size);
195
196   gst_buffer_append_memory (buffer,
197       gst_memory_new_wrapped (0, local_data, size, 0, size, local_data,
198           g_free));
199
200   GST_MEMDUMP ("MIDI data:", local_data, size);
201
202   GST_DEBUG ("feed buffer %p, tick %" G_GUINT64_FORMAT " size: %u",
203       (gpointer) buffer, app->tick, size);
204   g_signal_emit_by_name (app->appsrc, "push-buffer", buffer, &ret);
205   gst_buffer_unref (buffer);
206
207   app->tick += 1;
208 }
209
210 static void
211 push_tick_buffer (App * app)
212 {
213   app->buffer[0] = 0xf9;
214   push_buffer (app, app->buffer, 1);
215 }
216
217 /* This method is called by the need-data signal callback, we feed data into the
218  * appsrc.
219  */
220 static void
221 feed_data (GstElement * appsrc, guint size, App * app)
222 {
223   long size_ev = 0;
224   int err;
225   int ret;
226
227   snd_seq_poll_descriptors (app->seq, app->pfds, app->npfds, POLLIN);
228   ret = poll (app->pfds, app->npfds, DEFAULT_POLL_TIMEOUT_MS);
229   if (ret < 0) {
230     GST_ERROR ("ERROR in poll: %s", strerror (errno));
231     gst_app_src_end_of_stream (GST_APP_SRC (appsrc));
232   } else if (ret == 0) {
233     push_tick_buffer (app);
234   } else {
235     do {
236       snd_seq_event_t *event;
237       err = snd_seq_event_input (app->seq, &event);
238       if (err < 0 && err != -EAGAIN) {
239         GST_ERROR ("Error in snd_seq_event_input: %s", snd_strerror (err));
240         gst_app_src_end_of_stream (GST_APP_SRC (appsrc));
241         break;
242       }
243       if (event) {
244         size_ev =
245             snd_midi_event_decode (app->parser, app->buffer, DEFAULT_BUFSIZE,
246             event);
247         if (size_ev < 0) {
248           /* ENOENT indicates an event that is not a MIDI message, silently skip it */
249           if (-ENOENT == size_ev) {
250             GST_WARNING ("Warning: Received non-MIDI message");
251             push_tick_buffer (app);
252           } else {
253             GST_ERROR ("Error decoding event from ALSA to output: %s",
254                 strerror (-size_ev));
255             gst_app_src_end_of_stream (GST_APP_SRC (appsrc));
256             break;
257           }
258         } else {
259           push_buffer (app, app->buffer, size_ev);
260         }
261       }
262     } while (err > 0);
263   }
264
265   return;
266 }
267
268 /* this callback is called when pipeline has constructed a source object to read
269  * from. Since we provided the appsrc:// uri to pipeline, this will be the
270  * appsrc that we must handle. We set up a signals to push data into appsrc. */
271 static void
272 found_source (GObject * object, GObject * orig, GParamSpec * pspec, App * app)
273 {
274   /* get a handle to the appsrc */
275   g_object_get (orig, pspec->name, &app->appsrc, NULL);
276
277   GST_DEBUG ("got appsrc %p", (gpointer) app->appsrc);
278
279   /* configure the appsrc, we will push a buffer to appsrc when it needs more
280    * data */
281   g_signal_connect (app->appsrc, "need-data", G_CALLBACK (feed_data), app);
282 }
283
284 static gboolean
285 bus_message (GstBus * bus, GstMessage * message, App * app)
286 {
287   GST_DEBUG ("got message %s",
288       gst_message_type_get_name (GST_MESSAGE_TYPE (message)));
289
290   switch (GST_MESSAGE_TYPE (message)) {
291     case GST_MESSAGE_ERROR:
292     {
293       GError *error = NULL;
294       gchar *dbg_info = NULL;
295
296       gst_message_parse_error (message, &error, &dbg_info);
297       g_printerr ("ERROR from element %s: %s",
298           GST_OBJECT_NAME (message->src), error->message);
299       g_printerr ("Debugging info: %s", (dbg_info) ? dbg_info : "none");
300       g_error_free (error);
301       g_free (dbg_info);
302       g_main_loop_quit (app->loop);
303       break;
304     }
305     case GST_MESSAGE_EOS:
306       g_main_loop_quit (app->loop);
307       break;
308     default:
309       break;
310   }
311   return TRUE;
312 }
313
314 static int
315 app_init (App * app, char *ports)
316 {
317   int ret;
318
319   app->tick = 0;
320
321   ret = init_seq (app);
322   if (ret < 0)
323     goto err;
324
325   if (ports) {
326     ret = parse_ports (ports, app);
327     if (ret < 0)
328       goto err_seq_close;
329   }
330
331   ret = create_port (app);
332   if (ret < 0)
333     goto err_free_ports;
334
335   connect_ports (app);
336
337   ret = snd_seq_nonblock (app->seq, 1);
338   if (ret < 0) {
339     GST_ERROR ("Cannot set nonblock mode - %s", snd_strerror (ret));
340     goto err_free_ports;
341   }
342
343   snd_midi_event_new (DEFAULT_BUFSIZE, &app->parser);
344   snd_midi_event_init (app->parser);
345   snd_midi_event_reset_decode (app->parser);
346
347   snd_midi_event_no_status (app->parser, 1);
348
349   app->buffer = malloc (DEFAULT_BUFSIZE);
350   if (app->buffer == NULL) {
351     ret = -ENOMEM;
352     goto err_free_parser;
353   }
354
355   app->npfds = snd_seq_poll_descriptors_count (app->seq, POLLIN);
356   app->pfds = malloc (sizeof (*app->pfds) * app->npfds);
357   if (app->pfds == NULL) {
358     ret = -ENOMEM;
359     goto err_free_buffer;
360   }
361
362   return 0;
363
364 err_free_buffer:
365   free (app->buffer);
366 err_free_parser:
367   snd_midi_event_free (app->parser);
368 err_free_ports:
369   g_free (app->seq_ports);
370 err_seq_close:
371   snd_seq_close (app->seq);
372 err:
373   return ret;
374 }
375
376 static void
377 app_finalize (App * app)
378 {
379   /* free the resources */
380   free (app->pfds);
381   free (app->buffer);
382   snd_midi_event_free (app->parser);
383   g_free (app->seq_ports);
384   snd_seq_close (app->seq);
385 }
386
387 static gboolean
388 on_sigint (gpointer user_data)
389 {
390   GMainLoop *loop = (GMainLoop *) user_data;
391   g_message ("Caught SIGINT. Initiating shutdown.");
392   g_main_loop_quit (loop);
393   return FALSE;
394 }
395
396 int
397 main (int argc, char *argv[])
398 {
399   App *app = &s_app;
400   GstBus *bus;
401   GstCaps *caps;
402   int ret;
403
404   GOptionContext *ctx;
405   GError *err = NULL;
406   gchar *ports = NULL;
407   gboolean verbose = FALSE;
408   GOptionEntry options[] = {
409     {"ports", 'p', 0, G_OPTION_ARG_STRING, &ports,
410         "Comma separated list of sequencer ports", "client:port,..."},
411     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
412          "Output status information and property notifications", NULL},
413     {NULL}
414   };
415
416   ctx = g_option_context_new (NULL);
417   g_option_context_add_main_entries (ctx, options, NULL);
418   g_option_context_add_group (ctx, gst_init_get_option_group ());
419   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
420     if (err)
421       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
422     else
423       g_printerr ("Error initializing: Unknown error!\n");
424     exit (1);
425   }
426   g_option_context_free (ctx);
427
428   gst_init (&argc, &argv);
429
430   GST_DEBUG_CATEGORY_INIT (mysource_debug, "mysource", 0,
431       "ALSA MIDI sequencer appsrc pipeline");
432
433   ret = app_init (app, ports);
434   if (ret < 0)
435     return ret;
436   free (ports);
437
438   if (app->port_count > 0)
439     printf ("Waiting for data.\n");
440   else
441     printf ("Waiting for data at port %d:0.\n", snd_seq_client_id (app->seq));
442
443   /* create a mainloop to get messages */
444   app->loop = g_main_loop_new (NULL, FALSE);
445
446   app->pipeline =
447       gst_parse_launch
448       ("appsrc name=mysource ! fluiddec ! audioconvert ! autoaudiosink", NULL);
449   g_assert (app->pipeline);
450
451   if (verbose)
452     g_signal_connect (app->pipeline, "deep-notify", G_CALLBACK (gst_object_default_deep_notify), NULL);
453
454   bus = gst_pipeline_get_bus (GST_PIPELINE (app->pipeline));
455   g_assert (bus);
456
457   /* add watch for messages */
458   gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);
459
460   /* get the appsrc */
461   app->appsrc = gst_bin_get_by_name (GST_BIN (app->pipeline), "mysource");
462   g_assert (app->appsrc);
463   g_assert (GST_IS_APP_SRC (app->appsrc));
464   g_signal_connect (app->appsrc, "need-data", G_CALLBACK (feed_data), app);
465
466   g_object_set (app->appsrc, "format", GST_FORMAT_TIME, NULL);
467   g_object_set (app->appsrc, "is-live", TRUE, NULL);
468
469   /* set the caps on the source */
470   caps = gst_caps_new_simple ("audio/x-midi-event", NULL, NULL);
471   gst_app_src_set_caps (GST_APP_SRC (app->appsrc), caps);
472   gst_caps_unref (caps);
473
474   /* get notification when the source is created so that we get a handle to it
475    * and can configure it */
476   g_signal_connect (app->pipeline, "deep-notify::source",
477       (GCallback) found_source, app);
478
479   /* go to playing and wait in a mainloop. */
480   gst_element_set_state (app->pipeline, GST_STATE_PLAYING);
481
482   /* this mainloop is stopped when we receive an error or EOS, or on SIGINT */
483   g_unix_signal_add (SIGINT, on_sigint, app->loop);
484   g_main_loop_run (app->loop);
485
486   g_main_loop_unref (app->loop);
487
488   GST_DEBUG ("stopping");
489
490   gst_element_set_state (app->pipeline, GST_STATE_NULL);
491
492   gst_object_unref (app->appsrc);
493
494   gst_object_unref (bus);
495
496   gst_object_unref (app->pipeline);
497
498   app_finalize (app);
499
500   return 0;
501 }