Make push_buffer() look similar to the code used in alsamidisrc
[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   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   GstClockTime time;
175   gpointer local_data;
176   GstBuffer *buffer;
177   int ret;
178
179   buffer = gst_buffer_new ();
180
181   time = app->tick * DEFAULT_TICK_PERIOD_MS * GST_MSECOND;
182
183   GST_BUFFER_DTS (buffer) = time;
184   GST_BUFFER_PTS (buffer) = time;
185   GST_BUFFER_OFFSET (buffer) = time;
186   GST_BUFFER_DURATION (buffer) = DEFAULT_TICK_PERIOD_MS * GST_MSECOND;
187
188   local_data = g_memdup (data, size);
189
190   gst_buffer_append_memory (buffer,
191       gst_memory_new_wrapped (0, local_data, size, 0, size, local_data,
192           g_free));
193
194   GST_MEMDUMP ("MIDI data:", local_data, size);
195
196   GST_DEBUG ("feed buffer %p, tick %" G_GUINT64_FORMAT " size: %u",
197       (gpointer) buffer, app->tick, size);
198   g_signal_emit_by_name (app->appsrc, "push-buffer", buffer, &ret);
199   gst_buffer_unref (buffer);
200
201   app->tick += 1;
202 }
203
204 static void
205 push_tick_buffer (App * app)
206 {
207   app->buffer[0] = 0xf9;
208   push_buffer (app, app->buffer, 1);
209 }
210
211 /* This method is called by the need-data signal callback, we feed data into the
212  * appsrc.
213  */
214 static void
215 feed_data (GstElement * appsrc, guint size, App * app)
216 {
217   long size_ev = 0;
218   int err;
219   int ret;
220
221   snd_seq_poll_descriptors (app->seq, app->pfds, app->npfds, POLLIN);
222   ret = poll (app->pfds, app->npfds, DEFAULT_POLL_TIMEOUT_MS);
223   if (ret < 0) {
224     GST_ERROR ("ERROR in poll: %s", strerror (errno));
225   } else if (ret == 0) {
226     push_tick_buffer (app);
227   } else {
228     do {
229       snd_seq_event_t *event;
230       err = snd_seq_event_input (app->seq, &event);
231       if (err < 0)
232         break;
233       if (event) {
234         size_ev =
235             snd_midi_event_decode (app->parser, app->buffer, DEFAULT_BUFSIZE,
236             event);
237         if (size_ev < 0) {
238           /* ENOENT indicates an event that is not a MIDI message, silently skip it */
239           if (-ENOENT == size_ev) {
240             GST_WARNING ("Warning: Received non-MIDI message");
241             push_tick_buffer (app);
242           } else {
243             GST_ERROR ("Error decoding event from ALSA to output: %s",
244                 strerror (-size_ev));
245             break;
246           }
247         } else {
248           push_buffer (app, app->buffer, size_ev);
249         }
250       }
251     } while (err > 0);
252   }
253
254   return;
255 }
256
257 /* this callback is called when pipeline has constructed a source object to read
258  * from. Since we provided the appsrc:// uri to pipeline, this will be the
259  * appsrc that we must handle. We set up a signals to push data into appsrc. */
260 static void
261 found_source (GObject * object, GObject * orig, GParamSpec * pspec, App * app)
262 {
263   /* get a handle to the appsrc */
264   g_object_get (orig, pspec->name, &app->appsrc, NULL);
265
266   GST_DEBUG ("got appsrc %p", (gpointer) app->appsrc);
267
268   /* configure the appsrc, we will push a buffer to appsrc when it needs more
269    * data */
270   g_signal_connect (app->appsrc, "need-data", G_CALLBACK (feed_data), app);
271 }
272
273 static gboolean
274 bus_message (GstBus * bus, GstMessage * message, App * app)
275 {
276   GST_DEBUG ("got message %s",
277       gst_message_type_get_name (GST_MESSAGE_TYPE (message)));
278
279   switch (GST_MESSAGE_TYPE (message)) {
280     case GST_MESSAGE_ERROR:
281     {
282       GError *error = NULL;
283       gchar *dbg_info = NULL;
284
285       gst_message_parse_error (message, &error, &dbg_info);
286       g_printerr ("ERROR from element %s: %s",
287           GST_OBJECT_NAME (message->src), error->message);
288       g_printerr ("Debugging info: %s", (dbg_info) ? dbg_info : "none");
289       g_error_free (error);
290       g_free (dbg_info);
291       g_main_loop_quit (app->loop);
292       break;
293     }
294     case GST_MESSAGE_EOS:
295       g_main_loop_quit (app->loop);
296       break;
297     default:
298       break;
299   }
300   return TRUE;
301 }
302
303 static int
304 app_init (App * app, char *ports)
305 {
306   int ret;
307
308   app->tick = 0;
309
310   ret = init_seq (app);
311   if (ret < 0)
312     goto err;
313
314   if (ports) {
315     ret = parse_ports (ports, app);
316     if (ret < 0)
317       goto err_seq_close;
318   }
319
320   ret = create_port (app);
321   if (ret < 0)
322     goto err_free_ports;
323
324   connect_ports (app);
325
326   ret = snd_seq_nonblock (app->seq, 1);
327   if (ret < 0) {
328     GST_ERROR ("Cannot set nonblock mode - %s", snd_strerror (ret));
329     goto err_free_ports;
330   }
331
332   snd_midi_event_new (DEFAULT_BUFSIZE, &app->parser);
333   snd_midi_event_init (app->parser);
334   snd_midi_event_reset_decode (app->parser);
335
336   snd_midi_event_no_status (app->parser, 1);
337
338   app->buffer = malloc (DEFAULT_BUFSIZE);
339   if (app->buffer == NULL) {
340     ret = -ENOMEM;
341     goto err_free_parser;
342   }
343
344   app->npfds = snd_seq_poll_descriptors_count (app->seq, POLLIN);
345   app->pfds = malloc (sizeof (*app->pfds) * app->npfds);
346   if (app->pfds == NULL) {
347     ret = -ENOMEM;
348     goto err_free_buffer;
349   }
350
351   return 0;
352
353 err_free_buffer:
354   free (app->buffer);
355 err_free_parser:
356   snd_midi_event_free (app->parser);
357 err_free_ports:
358   g_free (app->seq_ports);
359 err_seq_close:
360   snd_seq_close (app->seq);
361 err:
362   return ret;
363 }
364
365 static void
366 app_finalize (App * app)
367 {
368   /* free the resources */
369   free (app->pfds);
370   free (app->buffer);
371   snd_midi_event_free (app->parser);
372   g_free (app->seq_ports);
373   snd_seq_close (app->seq);
374 }
375
376 static gboolean
377 on_sigint (gpointer user_data)
378 {
379   GMainLoop *loop = (GMainLoop *) user_data;
380   g_message ("Caught SIGINT. Initiating shutdown.");
381   g_main_loop_quit (loop);
382   return FALSE;
383 }
384
385 int
386 main (int argc, char *argv[])
387 {
388   App *app = &s_app;
389   GstBus *bus;
390   GstCaps *caps;
391   int ret;
392
393   GOptionContext *ctx;
394   GError *err = NULL;
395   gchar *ports = NULL;
396   gboolean verbose = FALSE;
397   GOptionEntry options[] = {
398     {"ports", 'p', 0, G_OPTION_ARG_STRING, &ports,
399         "Comma separated list of sequencer ports", "client:port,..."},
400     {"verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose,
401          "Output status information and property notifications", NULL},
402     {NULL}
403   };
404
405   ctx = g_option_context_new (NULL);
406   g_option_context_add_main_entries (ctx, options, NULL);
407   g_option_context_add_group (ctx, gst_init_get_option_group ());
408   if (!g_option_context_parse (ctx, &argc, &argv, &err)) {
409     if (err)
410       g_printerr ("Error initializing: %s\n", GST_STR_NULL (err->message));
411     else
412       g_printerr ("Error initializing: Unknown error!\n");
413     exit (1);
414   }
415   g_option_context_free (ctx);
416
417   gst_init (&argc, &argv);
418
419   GST_DEBUG_CATEGORY_INIT (mysource_debug, "mysource", 0,
420       "ALSA MIDI sequencer appsrc pipeline");
421
422   ret = app_init (app, ports);
423   if (ret < 0)
424     return ret;
425   free (ports);
426
427   if (app->port_count > 0)
428     printf ("Waiting for data.\n");
429   else
430     printf ("Waiting for data at port %d:0.\n", snd_seq_client_id (app->seq));
431
432   /* create a mainloop to get messages */
433   app->loop = g_main_loop_new (NULL, FALSE);
434
435   app->pipeline =
436       gst_parse_launch
437       ("appsrc name=mysource ! fluiddec ! audioconvert ! autoaudiosink", NULL);
438   g_assert (app->pipeline);
439
440   if (verbose)
441     g_signal_connect (app->pipeline, "deep-notify", G_CALLBACK (gst_object_default_deep_notify), NULL);
442
443   bus = gst_pipeline_get_bus (GST_PIPELINE (app->pipeline));
444   g_assert (bus);
445
446   /* add watch for messages */
447   gst_bus_add_watch (bus, (GstBusFunc) bus_message, app);
448
449   /* get the appsrc */
450   app->appsrc = gst_bin_get_by_name (GST_BIN (app->pipeline), "mysource");
451   g_assert (app->appsrc);
452   g_assert (GST_IS_APP_SRC (app->appsrc));
453   g_signal_connect (app->appsrc, "need-data", G_CALLBACK (feed_data), app);
454
455   g_object_set (app->appsrc, "format", GST_FORMAT_TIME, NULL);
456   g_object_set (app->appsrc, "is-live", TRUE, NULL);
457
458   /* set the caps on the source */
459   caps = gst_caps_new_simple ("audio/x-midi-event", NULL, NULL);
460   gst_app_src_set_caps (GST_APP_SRC (app->appsrc), caps);
461   gst_caps_unref (caps);
462
463   /* get notification when the source is created so that we get a handle to it
464    * and can configure it */
465   g_signal_connect (app->pipeline, "deep-notify::source",
466       (GCallback) found_source, app);
467
468   /* go to playing and wait in a mainloop. */
469   gst_element_set_state (app->pipeline, GST_STATE_PLAYING);
470
471   /* this mainloop is stopped when we receive an error or EOS, or on SIGINT */
472   g_unix_signal_add (SIGINT, on_sigint, app->loop);
473   g_main_loop_run (app->loop);
474
475   g_main_loop_unref (app->loop);
476
477   GST_DEBUG ("stopping");
478
479   gst_element_set_state (app->pipeline, GST_STATE_NULL);
480
481   gst_object_unref (app->appsrc);
482
483   gst_object_unref (bus);
484
485   gst_object_unref (app->pipeline);
486
487   app_finalize (app);
488
489   return 0;
490 }