added configure rules to check presence of swig, python,
[aubio.git] / ext / midi / midi_alsa_seq.c
1 /* 
2  * Copyright 2004 Paul Brossier
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Library General Public License
6  * as published by the Free Software Foundation; either version 2 of
7  * the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Library General Public License for more details.
13  *  
14  * You should have received a copy of the GNU Library General Public
15  * License along with this library; if not, write to the Free
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17  * 02111-1307, USA
18  */
19
20 /* this file originally taken from Fluidsynth, Peter Hanappe and others. */
21
22 /** \file
23  * Midi driver for the Advanced Linux Sound Architecture (sequencer mode)
24  */
25
26
27 #include "aubio_priv.h"
28 #include "midi.h"
29 #include "midi_event.h"
30 #include "midi_parser.h"
31 #include "midi_driver.h"
32 #include "config.h"
33
34 #if ALSA_SUPPORT
35
36 #define ALSA_PCM_NEW_HW_PARAMS_API
37 #include <alsa/asoundlib.h>
38 #include <pthread.h>
39 #include <fcntl.h>
40 #include <unistd.h>
41 #include <sys/poll.h>
42 /* #include <errno.h> //perror is in stdio.h */
43
44 #define AUBIO_ALSA_DEFAULT_SEQ_DEVICE   "default"
45
46 #define AUBIO_ALSA_BUFFER_LENGTH 512
47
48 /* SCHED_FIFO priorities for ALSA threads (see pthread_attr_setschedparam) */
49 #define ALSA_RAWMIDI_SCHED_PRIORITY 90
50 #define ALSA_SEQ_SCHED_PRIORITY 90
51
52
53 /** aubio_alsa_seq_driver_t */
54 typedef struct {
55     aubio_midi_driver_t driver;
56     snd_seq_t *seq_handle;
57     int seq_port;
58     struct pollfd *pfd;
59     int npfd;
60     pthread_t thread;
61     int status;
62 } aubio_alsa_seq_driver_t;
63
64 aubio_midi_driver_t* new_aubio_alsa_seq_driver(//aubio_settings_t* settings, 
65         handle_midi_event_func_t handler, 
66         void* data);
67 int del_aubio_alsa_seq_driver(aubio_midi_driver_t* p);
68 static void* aubio_alsa_seq_run(void* d);
69
70 //void aubio_alsa_seq_driver_settings(aubio_settings_t* settings)
71 //{
72 //  aubio_settings_register_str(settings, "midi.alsa_seq.device", "default", 0, NULL, NULL);
73 //  aubio_settings_register_str(settings, "midi.alsa_seq.id", "pid", 0, NULL, NULL);
74 //}
75
76 /** new_aubio_alsa_seq_driver */
77 aubio_midi_driver_t*  new_aubio_alsa_seq_driver(//aubio_settings_t* settings, 
78         handle_midi_event_func_t handler, void* data)
79 {
80     int i, err;                     
81     aubio_alsa_seq_driver_t* dev;   /**< object to return */
82     pthread_attr_t attr;            /**< sequencer thread */
83     int sched = SCHED_FIFO;         /**< default scheduling policy */
84     struct sched_param priority;    /**< scheduling priority settings */
85     int count;                      /**< number of MIDI file descriptors */
86     struct pollfd *pfd = NULL;      /**< poll file descriptor array (copied in dev->pfd) */
87     char* device = NULL;            /**< the device name */
88     char* id = NULL;
89     char full_id[64];
90     char full_name[64];
91
92     /* not much use doing anything */
93     if (handler == NULL) {
94         AUBIO_ERR( "Invalid argument");
95         return NULL;
96     }
97
98     /* allocate the device */
99     dev = AUBIO_NEW(aubio_alsa_seq_driver_t);
100     if (dev == NULL) {
101         AUBIO_ERR( "Out of memory");
102         return NULL;
103     }
104     AUBIO_MEMSET(dev, 0, sizeof(aubio_alsa_seq_driver_t));
105     dev->seq_port = -1;
106     dev->driver.data = data;
107     dev->driver.handler = handler;
108
109     /* get the device name. if none is specified, use the default device. */
110     //aubio_settings_getstr(settings, "midi.alsa_seq.device", &device);
111     if (device == NULL) {
112         device = "default";
113     }
114
115     /* open the sequencer INPUT only, non-blocking */
116     //if ((err = snd_seq_open(&dev->seq_handle, device, SND_SEQ_OPEN_INPUT,
117     if ((err = snd_seq_open(&dev->seq_handle, device, SND_SEQ_OPEN_DUPLEX,
118                     SND_SEQ_NONBLOCK)) < 0) {
119         AUBIO_ERR( "Error opening ALSA sequencer");
120         goto error_recovery;
121     }
122
123     /* tell the ladcca server our client id */
124 #ifdef LADCCA_SUPPORT
125     {
126         int enable_ladcca = 1;
127         //aubio_settings_getint (settings, "ladcca.enable", &enable_ladcca);
128         if (enable_ladcca)
129             cca_alsa_client_id (aubio_cca_client, snd_seq_client_id (dev->seq_handle));
130     }
131 #endif /* LADCCA_SUPPORT */
132
133     /* get # of MIDI file descriptors */
134     count = snd_seq_poll_descriptors_count(dev->seq_handle, POLLIN);
135     if (count > 0) {        /* make sure there are some */
136         pfd = AUBIO_MALLOC(sizeof (struct pollfd) * count);
137         dev->pfd = AUBIO_MALLOC(sizeof (struct pollfd) * count);
138         /* grab file descriptor POLL info structures */
139         count = snd_seq_poll_descriptors(dev->seq_handle, pfd, count, POLLIN);
140     }
141
142     for (i = 0; i < count; i++) {        /* loop over file descriptors */
143         /* copy the input FDs */
144         if (pfd[i].events & POLLIN) { /* use only the input FDs */
145             dev->pfd[dev->npfd].fd = pfd[i].fd;
146             dev->pfd[dev->npfd].events = POLLIN; 
147             dev->pfd[dev->npfd].revents = 0; 
148             dev->npfd++;
149         }
150     }
151     AUBIO_FREE(pfd);
152
153     //aubio_settings_getstr(settings, "midi.alsa_seq.id", &id);
154
155     if (id != NULL) {
156         if (AUBIO_STRCMP(id, "pid") == 0) {
157             snprintf(full_id, 64, "aubio (%d)", getpid());
158             snprintf(full_name, 64, "aubio_port (%d)", getpid());
159         } else {
160             snprintf(full_id, 64, "aubio (%s)", id);
161             snprintf(full_name, 64, "aubio_port (%s)", id);
162         }
163     } else {
164         snprintf(full_id, 64, "aubio");
165         snprintf(full_name, 64, "aubio_port");
166     }
167
168     /* set the client name */
169     snd_seq_set_client_name (dev->seq_handle, full_id);
170
171     if ((dev->seq_port = snd_seq_create_simple_port (dev->seq_handle,
172                     full_name,
173                     SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE |
174                     SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ | 
175                     SND_SEQ_PORT_CAP_DUPLEX,
176                     SND_SEQ_PORT_TYPE_APPLICATION)) < 0)
177     {
178         AUBIO_ERR( "Error creating ALSA sequencer port");
179         goto error_recovery;
180     }
181
182     dev->status = AUBIO_MIDI_READY;
183
184     /* create the midi thread */
185     if (pthread_attr_init(&attr)) {
186         AUBIO_ERR( "Couldn't initialize midi thread attributes");
187         goto error_recovery;
188     }
189
190     /* use fifo scheduling. if it fails, use default scheduling. */
191     while (1) {
192         err = pthread_attr_setschedpolicy(&attr, sched);
193         if (err) {
194             AUBIO_MSG( "Couldn't set high priority scheduling for the MIDI input");
195             if (sched == SCHED_FIFO) {
196                 sched = SCHED_OTHER;
197                 continue;
198             } else {
199                 AUBIO_ERR( "Couldn't set scheduling policy.");
200                 goto error_recovery;
201             }
202         }
203
204         /* SCHED_FIFO will not be active without setting the priority */
205         priority.sched_priority = (sched == SCHED_FIFO) ? ALSA_SEQ_SCHED_PRIORITY : 0;
206         pthread_attr_setschedparam (&attr, &priority);
207
208         err = pthread_create(&dev->thread, &attr, aubio_alsa_seq_run, (void*) dev);
209         if (err) {
210             AUBIO_ERR( "Couldn't set high priority scheduling for the MIDI input");
211             if (sched == SCHED_FIFO) {
212                 sched = SCHED_OTHER;
213                 continue;
214             } else {
215                 //AUBIO_LOG(AUBIO_PANIC, "Couldn't create the midi thread.");
216                 AUBIO_ERR( "Couldn't create the midi thread.");
217                 goto error_recovery;
218             }
219         }
220         break;
221     }
222     return (aubio_midi_driver_t*) dev;
223
224
225 error_recovery:
226     del_aubio_alsa_seq_driver((aubio_midi_driver_t*) dev);
227     return NULL;
228 }
229
230 /** del_aubio_alsa_seq_driver */
231 int del_aubio_alsa_seq_driver(aubio_midi_driver_t* p)
232 {
233     aubio_alsa_seq_driver_t* dev;
234
235     dev = (aubio_alsa_seq_driver_t*) p;
236     if (dev == NULL) {
237         return AUBIO_OK;
238     }
239
240     dev->status = AUBIO_MIDI_DONE;
241
242     /* cancel the thread and wait for it before cleaning up */
243     if (dev->thread) {
244         if (pthread_cancel(dev->thread)) {
245             AUBIO_ERR( "Failed to cancel the midi thread");
246             return AUBIO_FAIL;
247         }
248         if (pthread_join(dev->thread, NULL)) {
249             AUBIO_ERR( "Failed to join the midi thread");
250             return AUBIO_FAIL;
251         }
252     }
253     if (dev->seq_port >= 0) {
254         snd_seq_delete_simple_port (dev->seq_handle, dev->seq_port);
255     }
256     if (dev->seq_handle) {
257         snd_seq_drain_output(dev->seq_handle);
258         snd_seq_close(dev->seq_handle);
259     }
260     AUBIO_FREE(dev);
261     return AUBIO_OK;
262 }
263
264 /** aubio_alsa_seq_run */
265 void* aubio_alsa_seq_run(void* d)
266 {
267     int n;//, i;
268     snd_seq_event_t *seq_ev;
269     aubio_midi_event_t evt;
270     aubio_alsa_seq_driver_t* dev = (aubio_alsa_seq_driver_t*) d;
271
272     /* make sure the other threads can cancel this thread any time */
273     if (pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL)) {
274         AUBIO_ERR( "Failed to set the cancel state of the midi thread");
275         pthread_exit(NULL);
276     }
277     if (pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL)) {
278         AUBIO_ERR( "Failed to set the cancel state of the midi thread");
279         pthread_exit(NULL);
280     }
281
282     /* go into a loop until someone tells us to stop */
283     dev->status = AUBIO_MIDI_LISTENING;
284     while (dev->status == AUBIO_MIDI_LISTENING) {
285
286         /* is there something to read? */
287         n = poll(dev->pfd, dev->npfd, 1); /* use a 1 milliseconds timeout */
288         if (n < 0) {
289             perror("poll");
290         } else if (n > 0) {
291
292             /* read new events from the midi input port */
293             while ((n = snd_seq_event_input(dev->seq_handle, &seq_ev)) >= 0)
294             {
295                 switch (seq_ev->type)
296                 {
297                     case SND_SEQ_EVENT_NOTEON:
298                         evt.type = NOTE_ON;
299                         evt.channel = seq_ev->data.note.channel;
300                         evt.param1 = seq_ev->data.note.note;
301                         evt.param2 = seq_ev->data.note.velocity;
302                         break;
303                     case SND_SEQ_EVENT_NOTEOFF:
304                         evt.type = NOTE_OFF;
305                         evt.channel = seq_ev->data.note.channel;
306                         evt.param1 = seq_ev->data.note.note;
307                         evt.param2 = seq_ev->data.note.velocity;
308                         break;
309                     case SND_SEQ_EVENT_KEYPRESS:
310                         evt.type = KEY_PRESSURE;
311                         evt.channel = seq_ev->data.note.channel;
312                         evt.param1 = seq_ev->data.note.note;
313                         evt.param2 = seq_ev->data.note.velocity;
314                         break;
315                     case SND_SEQ_EVENT_CONTROLLER:
316                         evt.type = CONTROL_CHANGE;
317                         evt.channel = seq_ev->data.control.channel;
318                         evt.param1 = seq_ev->data.control.param;
319                         evt.param2 = seq_ev->data.control.value;
320                         break;
321                     case SND_SEQ_EVENT_PITCHBEND:
322                         evt.type = PITCH_BEND;
323                         evt.channel = seq_ev->data.control.channel;
324                         /* ALSA pitch bend is -8192 - 8191, we adjust it here */
325                         evt.param1 = seq_ev->data.control.value + 8192;
326                         break;
327                     case SND_SEQ_EVENT_PGMCHANGE:
328                         evt.type = PROGRAM_CHANGE;
329                         evt.channel = seq_ev->data.control.channel;
330                         evt.param1 = seq_ev->data.control.value;
331                         break;
332                     case SND_SEQ_EVENT_CHANPRESS:
333                         evt.type = CHANNEL_PRESSURE;
334                         evt.channel = seq_ev->data.control.channel;
335                         evt.param1 = seq_ev->data.control.value;
336                         break;
337                     default:
338                         continue;        /* unhandled event, next loop iteration */
339                 }
340
341                 /* send the events to the next link in the chain */
342                 (*dev->driver.handler)(dev->driver.data, &evt);
343                 
344                 /* dump input on output */
345                 //snd_seq_ev_set_source(new_ev, dev->seq_port);
346                 //snd_seq_ev_set_dest(seq_ev,dev->seq_handle,dev->seq_client);
347                 //snd_seq_ev_set_subs(new_ev);
348                 //snd_seq_ev_set_direct(new_ev);
349                 //snd_seq_event_output(dev->seq_handle, new_ev);
350                 //snd_seq_drain_output(dev->seq_handle);
351
352             }
353         }
354
355         if ((n < 0) && (n != -EAGAIN)) {
356             AUBIO_ERR( "Error occured while reading ALSA sequencer events");
357             dev->status = AUBIO_MIDI_DONE;
358         }
359
360 //        /* added by piem to handle new data to output */
361 //        while (/* get new data, but from where ??? (n = snd_seq_event_output(dev->seq_handle, seq_ev)) >= 0*/ )
362 //        {
363 //            /* dump input on output */
364 //            snd_seq_ev_set_source(new_ev, dev->seq_port);
365 //            //snd_seq_ev_set_dest(seq_ev,dev->seq_handle,dev->seq_client);
366 //            snd_seq_ev_set_subs(new_ev);
367 //            snd_seq_ev_set_direct(new_ev);
368 //            snd_seq_event_output(dev->seq_handle, new_ev);
369 //            snd_seq_drain_output(dev->seq_handle);
370 //        }
371
372     }
373     pthread_exit(NULL);
374 }
375
376
377 snd_seq_event_t ev;
378
379 void aubio_midi_direct_output(aubio_midi_driver_t * d, aubio_midi_event_t * event) 
380 {
381     aubio_alsa_seq_driver_t* dev = (aubio_alsa_seq_driver_t*) d;
382     if (dev->thread){ if(pthread_join(dev->thread, NULL)) {
383         AUBIO_ERR( "Failed to join the midi thread");
384     }}
385     switch(event->type) 
386     {
387         case NOTE_ON:
388             ev.type = SND_SEQ_EVENT_NOTEON;
389             ev.data.note.channel  = event->channel;
390             ev.data.note.note     = event->param1;
391             ev.data.note.velocity = event->param2;
392             //AUBIO_ERR( "NOTE_ON %d\n", event->param1);
393             break;
394         case NOTE_OFF:
395             ev.type = SND_SEQ_EVENT_NOTEOFF;
396             ev.data.note.channel  = event->channel;
397             ev.data.note.note     = event->param1;
398             ev.data.note.velocity = event->param2;
399             //AUBIO_ERR( "NOTE_OFF %d\n", event->param1);
400             break;
401         default:
402             break;
403     }
404     if (ev.type == SND_SEQ_EVENT_NOTEOFF || ev.type == SND_SEQ_EVENT_NOTEON ) { 
405         snd_seq_ev_set_subs(&ev);
406         snd_seq_ev_set_direct(&ev);
407         snd_seq_ev_set_source(&ev, dev->seq_port);
408         snd_seq_event_output_direct(dev->seq_handle, &ev);
409     }
410     if (dev->thread) { if(pthread_detach(dev->thread)) {
411         AUBIO_ERR( "Failed to leave the midi thread");
412     }}
413 }
414
415 #endif /* #if ALSA_SUPPORT */