ALSA backend: add raw midi parser
[ardour.git] / libs / backends / alsa / alsa_rawmidi.cc
1 /*
2  * Copyright (C) 2014 Robin Gareus <robin@gareus.org>
3  * Copyright (C) 2010 Devin Anderson
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19
20 #include <unistd.h>
21
22 #include <glibmm.h>
23
24 #include "alsa_rawmidi.h"
25 #include "rt_thread.h"
26
27 #include "pbd/error.h"
28 #include "i18n.h"
29
30 using namespace ARDOUR;
31
32 /* max bytes per individual midi-event
33  * events larger than this are ignored */
34 #define MaxAlsaRawEventSize (64)
35
36 #ifndef NDEBUG
37 #define _DEBUGPRINT(STR) fprintf(stderr, STR);
38 #else
39 #define _DEBUGPRINT(STR) ;
40 #endif
41
42 AlsaRawMidiIO::AlsaRawMidiIO (const char *device, const bool input)
43         : _state (-1)
44         , _running (false)
45         , _device (0)
46         , _pfds (0)
47         , _sample_length_us (1e6 / 48000.0)
48         , _period_length_us (1.024e6 / 48000.0)
49         , _samples_per_period (1024)
50         , _rb (0)
51 {
52         pthread_mutex_init (&_notify_mutex, 0);
53         pthread_cond_init (&_notify_ready, 0);
54         init (device, input);
55 }
56
57 AlsaRawMidiIO::~AlsaRawMidiIO ()
58 {
59         if (_device) {
60                 snd_rawmidi_close (_device);
61                 _device = 0;
62         }
63         delete _rb;
64         pthread_mutex_destroy (&_notify_mutex);
65         pthread_cond_destroy (&_notify_ready);
66         free (_pfds);
67 }
68
69 void
70 AlsaRawMidiIO::init (const char *device_name, const bool input)
71 {
72         if (snd_rawmidi_open (
73                                 input ? &_device : NULL,
74                                 input ? NULL : &_device,
75                                 device_name, SND_RAWMIDI_NONBLOCK) < 0) {
76                 return;
77         }
78
79         _npfds = snd_rawmidi_poll_descriptors_count (_device);
80         if (_npfds < 1) {
81                 _DEBUGPRINT("AlsaRawMidiIO: no poll descriptor(s).\n");
82                 snd_rawmidi_close (_device);
83                 _device = 0;
84                 return;
85         }
86         _pfds = (struct pollfd*) malloc (_npfds * sizeof(struct pollfd));
87         snd_rawmidi_poll_descriptors (_device, _pfds, _npfds);
88
89         // MIDI (hw port) 31.25 kbaud
90         // worst case here is  8192 SPP and 8KSPS for which we'd need
91         // 4000 bytes sans MidiEventHeader.
92         // since we're not always in sync, let's use 4096.
93         _rb = new RingBuffer<uint8_t>(4096 + 4096 * sizeof(MidiEventHeader));
94
95 #if 0
96         _state = 0;
97 #else
98         snd_rawmidi_params_t *params;
99         if (snd_rawmidi_params_malloc (&params)) {
100                 goto initerr;
101         }
102         if (snd_rawmidi_params_current (_device, params)) {
103                 goto initerr;
104         }
105         if (snd_rawmidi_params_set_avail_min (_device, params, 1)) {
106                 goto initerr;
107         }
108         if ( snd_rawmidi_params_set_buffer_size (_device, params, 64)) {
109                 goto initerr;
110         }
111         if (snd_rawmidi_params_set_no_active_sensing (_device, params, 1)) {
112                 goto initerr;
113         }
114
115         _state = 0;
116         return;
117
118 initerr:
119         _DEBUGPRINT("AlsaRawMidiIO: parameter setup error\n");
120         snd_rawmidi_close (_device);
121         _device = 0;
122 #endif
123         return;
124 }
125
126 static void * pthread_process (void *arg)
127 {
128         AlsaRawMidiIO *d = static_cast<AlsaRawMidiIO *>(arg);
129         d->main_process_thread ();
130         pthread_exit (0);
131         return 0;
132 }
133
134 int
135 AlsaRawMidiIO::start ()
136 {
137         if (_realtime_pthread_create (SCHED_FIFO, -19,
138                                 &_main_thread, pthread_process, this))
139         {
140                 if (pthread_create (&_main_thread, NULL, pthread_process, this)) {
141                         PBD::error << _("AlsaRawMidiIO: Failed to create process thread.") << endmsg;
142                         return -1;
143                 } else {
144                         PBD::warning << _("AlsaRawMidiIO: Cannot acquire realtime permissions.") << endmsg;
145                 }
146         }
147         int timeout = 5000;
148         while (!_running && --timeout > 0) { Glib::usleep (1000); }
149         if (timeout == 0 || !_running) {
150                 return -1;
151         }
152         return 0;
153 }
154
155 int
156 AlsaRawMidiIO::stop ()
157 {
158         void *status;
159         if (!_running) {
160                 return 0;
161         }
162
163         _running = false;
164
165         pthread_mutex_lock (&_notify_mutex);
166         pthread_cond_signal (&_notify_ready);
167         pthread_mutex_unlock (&_notify_mutex);
168
169         if (pthread_join (_main_thread, &status)) {
170                 PBD::error << _("AlsaRawMidiIO: Failed to terminate.") << endmsg;
171                 return -1;
172         }
173         return 0;
174 }
175
176 void
177 AlsaRawMidiIO::setup_timing (const size_t samples_per_period, const float samplerate)
178 {
179         _period_length_us = (double) samples_per_period * 1e6 / samplerate;
180         _sample_length_us = 1e6 / samplerate;
181         _samples_per_period = samples_per_period;
182 }
183
184 void
185 AlsaRawMidiIO::sync_time (const uint64_t tme)
186 {
187         // TODO consider a PLL, if this turns out to be the bottleneck for jitter
188         // also think about using
189         // snd_pcm_status_get_tstamp() and snd_rawmidi_status_get_tstamp()
190         // instead of monotonic clock.
191 #ifdef DEBUG_TIMING
192         double tdiff = (_clock_monotonic + _period_length_us - tme) / 1000.0;
193         if (abs(tdiff) >= .05) {
194                 printf("AlsaRawMidiIO MJ: %.1f ms\n", tdiff);
195         }
196 #endif
197         _clock_monotonic = tme;
198 }
199
200 ///////////////////////////////////////////////////////////////////////////////
201
202 // select sleeps _at most_ (compared to usleep() which sleeps at least)
203 static void select_sleep (uint32_t usec) {
204         if (usec <= 10) return;
205         fd_set fd;
206         int max_fd=0;
207         struct timeval tv;
208         tv.tv_sec = usec / 1000000;
209         tv.tv_usec = usec % 1000000;
210         FD_ZERO (&fd);
211         select (max_fd, &fd, NULL, NULL, &tv);
212 }
213
214 ///////////////////////////////////////////////////////////////////////////////
215
216 AlsaRawMidiOut::AlsaRawMidiOut (const char *device)
217                 : AlsaRawMidiIO (device, false)
218 {
219 }
220
221
222 int
223 AlsaRawMidiOut::send_event (const pframes_t time, const uint8_t *data, const size_t size)
224 {
225         const uint32_t  buf_size = sizeof (MidiEventHeader) + size;
226         if (_rb->write_space() < buf_size) {
227                 _DEBUGPRINT("AlsaRawMidiOut: ring buffer overflow\n");
228                 return -1;
229         }
230         struct MidiEventHeader h (_clock_monotonic + time * _sample_length_us, size);
231         _rb->write ((uint8_t*) &h, sizeof(MidiEventHeader));
232         _rb->write (data, size);
233
234         if (pthread_mutex_trylock (&_notify_mutex) == 0) {
235                 pthread_cond_signal (&_notify_ready);
236                 pthread_mutex_unlock (&_notify_mutex);
237         }
238         return 0;
239 }
240
241 void *
242 AlsaRawMidiOut::main_process_thread ()
243 {
244         _running = true;
245         pthread_mutex_lock (&_notify_mutex);
246         while (_running) {
247                 bool have_data = false;
248                 struct MidiEventHeader h(0,0);
249                 uint8_t data[MaxAlsaRawEventSize];
250
251                 const uint32_t read_space = _rb->read_space();
252
253                 if (read_space > sizeof(MidiEventHeader)) {
254                         if (_rb->read ((uint8_t*)&h, sizeof(MidiEventHeader)) != sizeof(MidiEventHeader)) {
255                                 _DEBUGPRINT("AlsaRawMidiOut: Garbled MIDI EVENT HEADER!!\n");
256                                 break;
257                         }
258                         assert (read_space >= h.size);
259                         if (h.size > MaxAlsaRawEventSize) {
260                                 _rb->increment_read_idx (h.size);
261                                 _DEBUGPRINT("AlsaRawMidiOut: MIDI event too large!\n");
262                                 continue;
263                         }
264                         if (_rb->read (&data[0], h.size) != h.size) {
265                                 _DEBUGPRINT("AlsaRawMidiOut: Garbled MIDI EVENT DATA!!\n");
266                                 break;
267                         }
268                         have_data = true;
269                 }
270
271                 if (!have_data) {
272                         pthread_cond_wait (&_notify_ready, &_notify_mutex);
273                         continue;
274                 }
275
276                 uint64_t now = g_get_monotonic_time();
277                 while (h.time > now + 500) {
278                         select_sleep(h.time - now);
279                         now = g_get_monotonic_time();
280                 }
281
282 retry:
283                 int perr = poll (_pfds, _npfds, 10 /* ms */);
284                 if (perr < 0) {
285                         PBD::error << _("AlsaRawMidiOut: Error polling device. Terminating Midi Thread.") << endmsg;
286                         break;
287                 }
288                 if (perr == 0) {
289                         _DEBUGPRINT("AlsaRawMidiOut: poll() timed out.\n");
290                         goto retry;
291                 }
292
293                 unsigned short revents = 0;
294                 if (snd_rawmidi_poll_descriptors_revents (_device, _pfds, _npfds, &revents)) {
295                         PBD::error << _("AlsaRawMidiOut: Failed to poll device. Terminating Midi Thread.") << endmsg;
296                         break;
297                 }
298
299                 if (revents & (POLLERR | POLLHUP | POLLNVAL)) {
300                         PBD::error << _("AlsaRawMidiOut: poll error. Terminating Midi Thread.") << endmsg;
301                         break;
302                 }
303
304                 if (!(revents & POLLOUT)) {
305                         _DEBUGPRINT("AlsaRawMidiOut: POLLOUT not ready.\n");
306                         select_sleep (1000);
307                         goto retry;
308                 }
309
310                 ssize_t err = snd_rawmidi_write (_device, data, h.size);
311
312                 if ((err == -EAGAIN) || (err == -EWOULDBLOCK)) {
313                         select_sleep (1000);
314                         goto retry;
315                 }
316                 if (err < 0) {
317                         PBD::error << _("AlsaRawMidiOut: write failed. Terminating Midi Thread.") << endmsg;
318                         break;
319                 }
320                 if ((size_t) err < h.size) {
321                         _DEBUGPRINT("AlsaRawMidiOut: short write\n");
322                         memmove(&data[0], &data[err], err);
323                         h.size -= err;
324                         goto retry;
325                 }
326                 snd_rawmidi_drain (_device);
327         }
328
329         pthread_mutex_unlock (&_notify_mutex);
330         _DEBUGPRINT("AlsaRawMidiOut: MIDI OUT THREAD STOPPED\n");
331         return 0;
332 }
333
334
335 ///////////////////////////////////////////////////////////////////////////////
336
337 AlsaRawMidiIn::AlsaRawMidiIn (const char *device)
338                 : AlsaRawMidiIO (device, true)
339                 , _event(0,0)
340                 , _unbuffered_bytes(0)
341                 , _total_bytes(0)
342                 , _expected_bytes(0)
343                 , _status_byte(0)
344 {
345 }
346
347 size_t
348 AlsaRawMidiIn::recv_event (pframes_t &time, uint8_t *data, size_t &size)
349 {
350         const uint32_t read_space = _rb->read_space();
351         struct MidiEventHeader h(0,0);
352
353         if (read_space <= sizeof(MidiEventHeader)) {
354                 return 0;
355         }
356
357 #if 1
358         // check if event is in current cycle
359         RingBuffer<uint8_t>::rw_vector vector;
360         _rb->get_read_vector(&vector);
361         if (vector.len[0] >= sizeof(MidiEventHeader)) {
362                 memcpy((uint8_t*)&h, vector.buf[0], sizeof(MidiEventHeader));
363         } else {
364                 if (vector.len[0] > 0) {
365                         memcpy ((uint8_t*)&h, vector.buf[0], vector.len[0]);
366                 }
367                 memcpy (((uint8_t*)&h) + vector.len[0], vector.buf[1], sizeof(MidiEventHeader) - vector.len[0]);
368         }
369
370         if (h.time >= _clock_monotonic + _period_length_us ) {
371 #ifdef DEBUG_TIMING
372                 printf("AlsaRawMidiIn DEBUG: POSTPONE EVENT TO NEXT CYCLE: %.1f spl\n", ((h.time - _clock_monotonic) / _sample_length_us));
373 #endif
374                 return 0;
375         }
376         _rb->increment_read_idx (sizeof(MidiEventHeader));
377 #else
378         if (_rb->read ((uint8_t*)&h, sizeof(MidiEventHeader)) != sizeof(MidiEventHeader)) {
379                 _DEBUGPRINT("AlsaRawMidiIn::recv_event Garbled MIDI EVENT HEADER!!\n");
380                 return 0;
381         }
382 #endif
383         assert (h.size > 0);
384         if (h.size > size) {
385                 _DEBUGPRINT("AlsaRawMidiIn::recv_event MIDI event too large!\n");
386                 _rb->increment_read_idx (h.size);
387                 return 0;
388         }
389         if (_rb->read (&data[0], h.size) != h.size) {
390                 _DEBUGPRINT("AlsaRawMidiIn::recv_event Garbled MIDI EVENT DATA!!\n");
391                 return 0;
392         }
393         if (h.time < _clock_monotonic) {
394 #ifdef DEBUG_TIMING
395                 printf("AlsaRawMidiIn DEBUG: MIDI TIME < 0 %.1f spl\n", ((_clock_monotonic - h.time) / -_sample_length_us));
396 #endif
397                 time = 0;
398         } else if (h.time >= _clock_monotonic + _period_length_us ) {
399 #ifdef DEBUG_TIMING
400                 printf("AlsaRawMidiIn DEBUG: MIDI TIME > PERIOD %.1f spl\n", ((h.time - _clock_monotonic) / _sample_length_us));
401 #endif
402                 time = _samples_per_period - 1;
403         } else {
404                 time = floor ((h.time - _clock_monotonic) / _sample_length_us);
405         }
406         assert(time < _samples_per_period);
407         size = h.size;
408         return h.size;
409 }
410
411 void *
412 AlsaRawMidiIn::main_process_thread ()
413 {
414         _running = true;
415         while (_running) {
416                 unsigned short revents = 0;
417
418                 int perr = poll (_pfds, _npfds, 100 /* ms */);
419                 if (perr < 0) {
420                         PBD::error << _("AlsaRawMidiIn: Error polling device. Terminating Midi Thread.") << endmsg;
421                         break;
422                 }
423                 if (perr == 0) {
424                         continue;
425                 }
426
427                 if (snd_rawmidi_poll_descriptors_revents (_device, _pfds, _npfds, &revents)) {
428                         PBD::error << _("AlsaRawMidiIn: Failed to poll device. Terminating Midi Thread.") << endmsg;
429                         break;
430                 }
431
432                 if (revents & (POLLERR | POLLHUP | POLLNVAL)) {
433                         PBD::error << _("AlsaRawMidiIn: poll error. Terminating Midi Thread.") << endmsg;
434                         break;
435                 }
436
437                 if (!(revents & POLLIN)) {
438                         _DEBUGPRINT("AlsaRawMidiOut: POLLIN not ready.\n");
439                         select_sleep (1000);
440                         continue;
441                 }
442
443                 uint8_t data[MaxAlsaRawEventSize];
444                 uint64_t time = g_get_monotonic_time();
445                 ssize_t err = snd_rawmidi_read (_device, data, sizeof(data));
446
447                 if ((err == -EAGAIN) || (err == -EWOULDBLOCK)) {
448                         continue;
449                 }
450                 if (err < 0) {
451                         PBD::error << _("AlsaRawMidiIn: read error. Terminating Midi") << endmsg;
452                         break;
453                 }
454                 if (err == 0) {
455                         _DEBUGPRINT("AlsaRawMidiIn: zero read\n");
456                         continue;
457                 }
458
459 #if 0
460                 queue_event (time, data, err);
461 #else
462                 parse_events (time, data, err);
463 #endif
464         }
465
466         _DEBUGPRINT("AlsaRawMidiIn: MIDI IN THREAD STOPPED\n");
467         return 0;
468 }
469
470 int
471 AlsaRawMidiIn::queue_event (const uint64_t time, const uint8_t *data, const size_t size) {
472         const uint32_t  buf_size = sizeof(MidiEventHeader) + size;
473         _event._pending = false;
474         if (_rb->write_space() < buf_size) {
475                 _DEBUGPRINT("AlsaRawMidiIn: ring buffer overflow\n");
476                 return -1;
477         }
478         struct MidiEventHeader h (time, size);
479         _rb->write ((uint8_t*) &h, sizeof(MidiEventHeader));
480         _rb->write (data, size);
481         return 0;
482 }
483
484 void
485 AlsaRawMidiIn::parse_events (const uint64_t time, const uint8_t *data, const size_t size) {
486         if (_event._pending) {
487                 if (queue_event (_event._time, _parser_buffer, _event._size)) {
488                         return;
489                 }
490         }
491         for (size_t i = 0; i < size; ++i) {
492                 if (process_byte(time, data[i])) {
493                         if (queue_event (_event._time, _parser_buffer, _event._size)) {
494                                 return;
495                         }
496                 }
497         }
498 }
499
500 // based on JackMidiRawInputWriteQueue by Devin Anderson //
501 bool
502 AlsaRawMidiIn::process_byte(const uint64_t time, const uint8_t byte)
503 {
504         if (byte >= 0xf8) {
505                 // Realtime
506                 if (byte == 0xfd) {
507                         return false;
508                 }
509                 _parser_buffer[0] = byte;
510                 prepare_byte_event(time, byte);
511                 return true;
512         }
513         if (byte == 0xf7) {
514                 // Sysex end
515                 if (_status_byte == 0xf0) {
516                         record_byte(byte);
517                         return prepare_buffered_event(time);
518                 }
519     _total_bytes = 0;
520     _unbuffered_bytes = 0;
521                 _expected_bytes = 0;
522                 _status_byte = 0;
523                 return false;
524         }
525         if (byte >= 0x80) {
526                 // Non-realtime status byte
527                 if (_total_bytes) {
528                         _total_bytes = 0;
529                         _unbuffered_bytes = 0;
530                 }
531                 _status_byte = byte;
532                 switch (byte & 0xf0) {
533                         case 0x80:
534                         case 0x90:
535                         case 0xa0:
536                         case 0xb0:
537                         case 0xe0:
538                                 // Note On, Note Off, Aftertouch, Control Change, Pitch Wheel
539                                 _expected_bytes = 3;
540                                 break;
541                         case 0xc0:
542                         case 0xd0:
543                                 // Program Change, Channel Pressure
544                                 _expected_bytes = 2;
545                                 break;
546                         case 0xf0:
547                                 switch (byte) {
548                                         case 0xf0:
549                                                 // Sysex
550                                                 _expected_bytes = 0;
551                                                 break;
552                                         case 0xf1:
553                                         case 0xf3:
554                                                 // MTC Quarter Frame, Song Select
555                                                 _expected_bytes = 2;
556                                                 break;
557                                         case 0xf2:
558                                                 // Song Position
559                                                 _expected_bytes = 3;
560                                                 break;
561                                         case 0xf4:
562                                         case 0xf5:
563                                                 // Undefined
564                                                 _expected_bytes = 0;
565                                                 _status_byte = 0;
566                                                 return false;
567                                         case 0xf6:
568                                                 // Tune Request
569                                                 prepare_byte_event(time, byte);
570                                                 _expected_bytes = 0;
571                                                 _status_byte = 0;
572                                                 return true;
573                                 }
574                 }
575                 record_byte(byte);
576                 return false;
577         }
578         // Data byte
579         if (! _status_byte) {
580                 // Data bytes without a status will be discarded.
581                 _total_bytes++;
582                 _unbuffered_bytes++;
583                 return false;
584         }
585         if (! _total_bytes) {
586                 // Apply running status.
587                 record_byte(_status_byte);
588         }
589         record_byte(byte);
590         return (_total_bytes == _expected_bytes) ? prepare_buffered_event(time) : false;
591 }