b6d38d0486456abaf19aee4841e737c1e67fbb77
[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 (mysrc_debug);
42 #define GST_CAT_DEFAULT mysrc_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 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   ret = snd_seq_set_client_name (app->seq, DEFAULT_CLIENT_NAME);
79   if (ret < 0) {
80     GST_ERROR ("Cannot set client name - %s", snd_strerror (ret));
81     goto error_seq_close;
82   }
83
84   return 0;
85
86 error_seq_close:
87   snd_seq_close (app->seq);
88 error:
89   return ret;
90 }
91
92 /* Parses one or more port addresses from the string */
93 static int
94 parse_ports (const char *arg, App * app)
95 {
96   gchar **ports_list;
97   guint i;
98   int ret = 0;
99
100   GST_DEBUG ("ports: %s", arg);
101
102   /*
103    * Assume that ports are separated by commas.
104    *
105    * Commas are used instead of spaces because those are valid in client
106    * names.
107    */
108   ports_list = g_strsplit (arg, ",", 0);
109
110   app->port_count = g_strv_length (ports_list);
111   app->seq_ports = g_try_new (snd_seq_addr_t, app->port_count);
112   if (!app->seq_ports) {
113     GST_ERROR ("Out of memory");
114     ret = -ENOMEM;
115     goto out_free_ports_list;
116   }
117
118   for (i = 0; i < (guint)app->port_count; i++) {
119     gchar *port_name = ports_list[i];
120
121     ret = snd_seq_parse_address (app->seq, &app->seq_ports[i],
122         port_name);
123     if (ret < 0) {
124       GST_ERROR ("Invalid port %s - %s", port_name,
125           snd_strerror (ret));
126       goto error_free_seq_ports;
127     }
128   }
129
130   goto out_free_ports_list;
131
132 error_free_seq_ports:
133   g_free (app->seq_ports);
134 out_free_ports_list:
135   g_strfreev (ports_list);
136   return ret;
137 }
138
139 static int
140 create_port (App * app)
141 {
142   int ret;
143
144   ret = snd_seq_create_simple_port (app->seq, DEFAULT_CLIENT_NAME,
145       SND_SEQ_PORT_CAP_WRITE |
146       SND_SEQ_PORT_CAP_SUBS_WRITE,
147       SND_SEQ_PORT_TYPE_MIDI_GENERIC | SND_SEQ_PORT_TYPE_APPLICATION);
148   if (ret < 0)
149     GST_ERROR ("Cannot create port - %s", snd_strerror (ret));
150
151   return ret;
152 }
153
154 static void
155 connect_ports (App * app)
156 {
157   int i;
158   int ret;
159
160   for (i = 0; i < app->port_count; ++i) {
161     ret =
162         snd_seq_connect_from (app->seq, 0, app->seq_ports[i].client,
163         app->seq_ports[i].port);
164     if (ret < 0)
165       /* warning */
166       GST_WARNING ("Cannot connect from port %d:%d - %s",
167           app->seq_ports[i].client, app->seq_ports[i].port, snd_strerror (ret));
168   }
169 }
170
171 static void
172 push_buffer (App * app, gpointer data, guint size)
173 {
174   GstBuffer *buffer;
175   GstClockTime time;
176   int ret;
177   gpointer local_data;
178
179   /* read the next chunk */
180   buffer = gst_buffer_new ();
181
182   time = app->tick * DEFAULT_TICK_PERIOD_MS * GST_MSECOND;
183
184   GST_BUFFER_DTS (buffer) = time;
185   GST_BUFFER_PTS (buffer) = time;
186   GST_BUFFER_OFFSET (buffer) = time;
187   GST_BUFFER_DURATION (buffer) = DEFAULT_TICK_PERIOD_MS * GST_MSECOND;
188
189   local_data = g_memdup (data, size);
190
191   gst_buffer_append_memory (buffer,
192       gst_memory_new_wrapped (0, local_data, size, 0, size, local_data,
193           g_free));
194
195   GST_DEBUG ("feed buffer %p, tick %" G_GUINT64_FORMAT " size: %u",
196       (gpointer) buffer, app->tick, size);
197   g_signal_emit_by_name (app->appsrc, "push-buffer", buffer, &ret);
198   gst_buffer_unref (buffer);
199
200   app->tick += 1;
201 }
202
203 static void
204 push_tick_buffer (App * app)
205 {
206   app->buffer[0] = 0xf9;
207   push_buffer (app, app->buffer, 1);
208 }
209
210 /* This method is called by the need-data signal callback, we feed data into the
211  * appsrc.
212  */
213 static void
214 feed_data (GstElement * appsrc, guint size, App * app)
215 {
216   long size_ev = 0;
217   int err;
218   int ret;
219
220   snd_seq_poll_descriptors (app->seq, app->pfds, app->npfds, POLLIN);
221   ret = poll (app->pfds, app->npfds, DEFAULT_POLL_TIMEOUT_MS);
222   if (ret < 0) {
223     GST_ERROR ("ERROR in poll: %s", strerror (errno));
224   } else if (ret == 0) {
225     push_tick_buffer (app);
226   } else {
227     do {
228       snd_seq_event_t *event;
229       err = snd_seq_event_input (app->seq, &event);
230       if (err < 0)
231         break;
232       if (event) {
233         size_ev =
234             snd_midi_event_decode (app->parser, app->buffer, DEFAULT_BUFSIZE,
235             event);
236         if (size_ev < 0) {
237           /* ENOENT indicates an event that is not a MIDI message, silently skip it */
238           if (-ENOENT == size_ev) {
239             GST_WARNING ("Warning: Received non-MIDI message");
240             push_tick_buffer (app);
241           } else {
242             GST_ERROR ("Error decoding event from ALSA to output: %s",
243                 strerror (-size_ev));
244             break;
245           }
246         } else {
247           push_buffer (app, app->buffer, size_ev);
248         }
249       }
250     } while (err > 0);
251   }
252
253   return;
254 }
255
256 /* this callback is called when pipeline has constructed a source object to read
257  * from. Since we provided the appsrc:// uri to pipeline, this will be the
258  * appsrc that we must handle. We set up a signals to push data into appsrc. */
259 static void
260 found_source (GObject * object, GObject * orig, GParamSpec * pspec, App * app)
261 {
262   /* get a handle to the appsrc */
263   g_object_get (orig, pspec->name, &app->appsrc, NULL);
264
265   GST_DEBUG ("got appsrc %p", (gpointer) app->appsrc);
266
267   /* configure the appsrc, we will push a buffer to appsrc when it needs more
268    * data */
269   g_signal_connect (app->appsrc, "need-data", G_CALLBACK (feed_data), app);
270 }
271
272 static gboolean
273 bus_message (GstBus * bus, GstMessage * message, App * app)
274 {
275   GST_DEBUG ("got message %s",
276       gst_message_type_get_name (GST_MESSAGE_TYPE (message)));
277
278   switch (GST_MESSAGE_TYPE (message)) {
279     case GST_MESSAGE_ERROR:
280     {
281       GError *error = NULL;
282       gchar *dbg_info = NULL;
283
284       gst_message_parse_error (message, &error, &dbg_info);
285       g_printerr ("ERROR from element %s: %s",
286           GST_OBJECT_NAME (message->src), error->message);
287       g_printerr ("Debugging info: %s", (dbg_info) ? dbg_info : "none");
288       g_error_free (error);
289       g_free (dbg_info);
290       g_main_loop_quit (app->loop);
291       break;
292     }
293     case GST_MESSAGE_EOS:
294       g_main_loop_quit (app->loop);
295       break;
296     default:
297       break;
298   }
299   return TRUE;
300 }
301
302 static int
303 app_init (App * app, char *ports)
304 {
305   int ret;
306
307   app->tick = 0;
308
309   ret = init_seq (app);
310   if (ret < 0)
311     goto err;
312
313   if (ports) {
314     ret = parse_ports (ports, app);
315     if (ret < 0)
316       goto err_seq_close;
317   }
318
319   ret = create_port (app);
320   if (ret < 0)
321     goto err_free_ports;
322
323   connect_ports (app);
324
325   ret = snd_seq_nonblock (app->seq, 1);
326   if (ret < 0) {
327     GST_ERROR ("Cannot set nonblock mode - %s", snd_strerror (ret));
328     goto err_free_ports;
329   }
330
331   snd_midi_event_new (DEFAULT_BUFSIZE, &app->parser);
332   snd_midi_event_init (app->parser);
333   snd_midi_event_reset_decode (app->parser);
334
335   snd_midi_event_no_status (app->parser, 1);
336
337   app->buffer = malloc (DEFAULT_BUFSIZE);
338   if (app->buffer == NULL) {
339     ret = -ENOMEM;
340     goto err_free_parser;
341   }
342
343   app->npfds = snd_seq_poll_descriptors_count (app->seq, POLLIN);
344   app->pfds = malloc (sizeof (*app->pfds) * app->npfds);
345   if (app->pfds == NULL) {
346     ret = -ENOMEM;
347     goto err_free_buffer;
348   }
349
350   return 0;
351
352 err_free_buffer:
353   free (app->buffer);
354 err_free_parser:
355   snd_midi_event_free (app->parser);
356 err_free_ports:
357   g_free (app->seq_ports);
358 err_seq_close:
359   snd_seq_close (app->seq);
360 err:
361   return ret;
362 }
363
364 static void
365 app_finalize (App * app)
366 {
367   /* free the resources */
368   free (app->pfds);
369   free (app->buffer);
370   snd_midi_event_free (app->parser);
371   g_free (app->seq_ports);
372   snd_seq_close (app->seq);
373 }
374
375 static gboolean
376 on_sigint (gpointer user_data)
377 {
378   GMainLoop *loop = (GMainLoop *) user_data;
379   g_message ("Caught SIGINT. Initiating shutdown.");
380   g_main_loop_quit (loop);
381   return FALSE;
382 }
383
384 int
385 main (int argc, char *argv[])
386 {
387   App *app = &s_app;
388   GstBus *bus;
389   GstCaps *caps;
390   int ret;
391
392   GOptionContext *ctx;
393   GError *err = NULL;
394   gchar *ports = NULL;
395   GOptionEntry options[] = {
396     {"ports", 'p', 0, G_OPTION_ARG_STRING, &ports,
397         "Comma separated list of sequencer ports", "client:port,..."},
398     {NULL}
399   };
400
401   ctx = g_option_context_new (NULL);
402   g_option_context_add_main_entries (ctx, options, NULL);
403   g_option_context_add_group (ctx, gst_init_get_option_group ());
404   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
405     if (err)
406       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
407     else
408       g_printerr ("Error initializing: Unknown error!\n");
409     exit (1);
410   }
411   g_option_context_free (ctx);
412
413   gst_init (&argc, &argv);
414
415   GST_DEBUG_CATEGORY_INIT (mysrc_debug, "mysrc", 0,
416       "ALSA MIDI sequencer appsrc pipeline");
417
418   ret = app_init (app, ports);
419   if (ret < 0)
420     return ret;
421   free (ports);
422
423   if (app->port_count > 0)
424     printf ("Waiting for data.\n");
425   else
426     printf ("Waiting for data at port %d:0.\n", snd_seq_client_id (app->seq));
427
428   /* create a mainloop to get messages */
429   app->loop = g_main_loop_new (NULL, FALSE);
430
431   app->pipeline =
432       gst_parse_launch
433       ("appsrc name=mysource ! fluiddec ! audioconvert ! autoaudiosink", NULL);
434   g_assert (app->pipeline);
435
436   bus = gst_pipeline_get_bus (GST_PIPELINE (app->pipeline));
437   g_assert (bus);
438
439   /* add watch for messages */
440   gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);
441
442   /* get the appsrc */
443   app->appsrc = gst_bin_get_by_name (GST_BIN (app->pipeline), "mysource");
444   g_assert (app->appsrc);
445   g_assert (GST_IS_APP_SRC (app->appsrc));
446   g_signal_connect (app->appsrc, "need-data", G_CALLBACK (feed_data), app);
447
448   g_object_set (app->appsrc, "format", GST_FORMAT_TIME, NULL);
449   g_object_set (app->appsrc, "is-live", TRUE, NULL);
450
451   /* set the caps on the source */
452   caps = gst_caps_new_simple ("audio/x-midi-event", NULL, NULL);
453   gst_app_src_set_caps (GST_APP_SRC (app->appsrc), caps);
454   gst_caps_unref (caps);
455
456   /* get notification when the source is created so that we get a handle to it
457    * and can configure it */
458   g_signal_connect (app->pipeline, "deep-notify::source",
459       (GCallback) found_source, app);
460
461   /* go to playing and wait in a mainloop. */
462   gst_element_set_state (app->pipeline, GST_STATE_PLAYING);
463
464   /* this mainloop is stopped when we receive an error or EOS, or on SIGINT */
465   g_unix_signal_add (SIGINT, on_sigint, app->loop);
466   g_main_loop_run (app->loop);
467
468   g_main_loop_unref (app->loop);
469
470   GST_DEBUG ("stopping");
471
472   gst_element_set_state (app->pipeline, GST_STATE_NULL);
473
474   gst_object_unref (app->appsrc);
475
476   gst_object_unref (bus);
477
478   gst_object_unref (app->pipeline);
479
480   app_finalize (app);
481
482   return 0;
483 }