ALSA backend: tweak midi parser (fix start mid sequence)
[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                 , _first_time(true)
341                 , _unbuffered_bytes(0)
342                 , _total_bytes(0)
343                 , _expected_bytes(0)
344                 , _status_byte(0)
345 {
346 }
347
348 size_t
349 AlsaRawMidiIn::recv_event (pframes_t &time, uint8_t *data, size_t &size)
350 {
351         const uint32_t read_space = _rb->read_space();
352         struct MidiEventHeader h(0,0);
353
354         if (read_space <= sizeof(MidiEventHeader)) {
355                 return 0;
356         }
357
358 #if 1
359         // check if event is in current cycle
360         RingBuffer<uint8_t>::rw_vector vector;
361         _rb->get_read_vector(&vector);
362         if (vector.len[0] >= sizeof(MidiEventHeader)) {
363                 memcpy((uint8_t*)&h, vector.buf[0], sizeof(MidiEventHeader));
364         } else {
365                 if (vector.len[0] > 0) {
366                         memcpy ((uint8_t*)&h, vector.buf[0], vector.len[0]);
367                 }
368                 memcpy (((uint8_t*)&h) + vector.len[0], vector.buf[1], sizeof(MidiEventHeader) - vector.len[0]);
369         }
370
371         if (h.time >= _clock_monotonic + _period_length_us ) {
372 #ifdef DEBUG_TIMING
373                 printf("AlsaRawMidiIn DEBUG: POSTPONE EVENT TO NEXT CYCLE: %.1f spl\n", ((h.time - _clock_monotonic) / _sample_length_us));
374 #endif
375                 return 0;
376         }
377         _rb->increment_read_idx (sizeof(MidiEventHeader));
378 #else
379         if (_rb->read ((uint8_t*)&h, sizeof(MidiEventHeader)) != sizeof(MidiEventHeader)) {
380                 _DEBUGPRINT("AlsaRawMidiIn::recv_event Garbled MIDI EVENT HEADER!!\n");
381                 return 0;
382         }
383 #endif
384         assert (h.size > 0);
385         if (h.size > size) {
386                 _DEBUGPRINT("AlsaRawMidiIn::recv_event MIDI event too large!\n");
387                 _rb->increment_read_idx (h.size);
388                 return 0;
389         }
390         if (_rb->read (&data[0], h.size) != h.size) {
391                 _DEBUGPRINT("AlsaRawMidiIn::recv_event Garbled MIDI EVENT DATA!!\n");
392                 return 0;
393         }
394         if (h.time < _clock_monotonic) {
395 #ifdef DEBUG_TIMING
396                 printf("AlsaRawMidiIn DEBUG: MIDI TIME < 0 %.1f spl\n", ((_clock_monotonic - h.time) / -_sample_length_us));
397 #endif
398                 time = 0;
399         } else if (h.time >= _clock_monotonic + _period_length_us ) {
400 #ifdef DEBUG_TIMING
401                 printf("AlsaRawMidiIn DEBUG: MIDI TIME > PERIOD %.1f spl\n", ((h.time - _clock_monotonic) / _sample_length_us));
402 #endif
403                 time = _samples_per_period - 1;
404         } else {
405                 time = floor ((h.time - _clock_monotonic) / _sample_length_us);
406         }
407         assert(time < _samples_per_period);
408         size = h.size;
409         return h.size;
410 }
411
412 void *
413 AlsaRawMidiIn::main_process_thread ()
414 {
415         _running = true;
416         while (_running) {
417                 unsigned short revents = 0;
418
419                 int perr = poll (_pfds, _npfds, 100 /* ms */);
420                 if (perr < 0) {
421                         PBD::error << _("AlsaRawMidiIn: Error polling device. Terminating Midi Thread.") << endmsg;
422                         break;
423                 }
424                 if (perr == 0) {
425                         continue;
426                 }
427
428                 if (snd_rawmidi_poll_descriptors_revents (_device, _pfds, _npfds, &revents)) {
429                         PBD::error << _("AlsaRawMidiIn: Failed to poll device. Terminating Midi Thread.") << endmsg;
430                         break;
431                 }
432
433                 if (revents & (POLLERR | POLLHUP | POLLNVAL)) {
434                         PBD::error << _("AlsaRawMidiIn: poll error. Terminating Midi Thread.") << endmsg;
435                         break;
436                 }
437
438                 if (!(revents & POLLIN)) {
439                         _DEBUGPRINT("AlsaRawMidiOut: POLLIN not ready.\n");
440                         select_sleep (1000);
441                         continue;
442                 }
443
444                 uint8_t data[MaxAlsaRawEventSize];
445                 uint64_t time = g_get_monotonic_time();
446                 ssize_t err = snd_rawmidi_read (_device, data, sizeof(data));
447
448                 if ((err == -EAGAIN) || (err == -EWOULDBLOCK)) {
449                         continue;
450                 }
451                 if (err < 0) {
452                         PBD::error << _("AlsaRawMidiIn: read error. Terminating Midi") << endmsg;
453                         break;
454                 }
455                 if (err == 0) {
456                         _DEBUGPRINT("AlsaRawMidiIn: zero read\n");
457                         continue;
458                 }
459
460 #if 0
461                 queue_event (time, data, err);
462 #else
463                 parse_events (time, data, err);
464 #endif
465         }
466
467         _DEBUGPRINT("AlsaRawMidiIn: MIDI IN THREAD STOPPED\n");
468         return 0;
469 }
470
471 int
472 AlsaRawMidiIn::queue_event (const uint64_t time, const uint8_t *data, const size_t size) {
473         const uint32_t  buf_size = sizeof(MidiEventHeader) + size;
474         _event._pending = false;
475         if (size == 0) {
476                 return -1;
477         }
478         if (_rb->write_space() < buf_size) {
479                 _DEBUGPRINT("AlsaRawMidiIn: ring buffer overflow\n");
480                 return -1;
481         }
482         struct MidiEventHeader h (time, size);
483         _rb->write ((uint8_t*) &h, sizeof(MidiEventHeader));
484         _rb->write (data, size);
485         return 0;
486 }
487
488 void
489 AlsaRawMidiIn::parse_events (const uint64_t time, const uint8_t *data, const size_t size) {
490         if (_event._pending) {
491                 if (queue_event (_event._time, _parser_buffer, _event._size)) {
492                         return;
493                 }
494         }
495         for (size_t i = 0; i < size; ++i) {
496                 if (_first_time && !(data[i] & 0x80)) {
497                         continue;
498                 }
499                 _first_time = false; /// TODO optimize e.g. use fn pointer to different parse_events()
500                 if (process_byte(time, data[i])) {
501                         if (queue_event (_event._time, _parser_buffer, _event._size)) {
502                                 return;
503                         }
504                 }
505         }
506 }
507
508 // based on JackMidiRawInputWriteQueue by Devin Anderson //
509 bool
510 AlsaRawMidiIn::process_byte(const uint64_t time, const uint8_t byte)
511 {
512         if (byte >= 0xf8) {
513                 // Realtime
514                 if (byte == 0xfd) {
515                         return false;
516                 }
517                 _parser_buffer[0] = byte;
518                 prepare_byte_event(time, byte);
519                 return true;
520         }
521         if (byte == 0xf7) {
522                 // Sysex end
523                 if (_status_byte == 0xf0) {
524                         record_byte(byte);
525                         return prepare_buffered_event(time);
526                 }
527     _total_bytes = 0;
528     _unbuffered_bytes = 0;
529                 _expected_bytes = 0;
530                 _status_byte = 0;
531                 return false;
532         }
533         if (byte >= 0x80) {
534                 // Non-realtime status byte
535                 if (_total_bytes) {
536                         _total_bytes = 0;
537                         _unbuffered_bytes = 0;
538                 }
539                 _status_byte = byte;
540                 switch (byte & 0xf0) {
541                         case 0x80:
542                         case 0x90:
543                         case 0xa0:
544                         case 0xb0:
545                         case 0xe0:
546                                 // Note On, Note Off, Aftertouch, Control Change, Pitch Wheel
547                                 _expected_bytes = 3;
548                                 break;
549                         case 0xc0:
550                         case 0xd0:
551                                 // Program Change, Channel Pressure
552                                 _expected_bytes = 2;
553                                 break;
554                         case 0xf0:
555                                 switch (byte) {
556                                         case 0xf0:
557                                                 // Sysex
558                                                 _expected_bytes = 0;
559                                                 break;
560                                         case 0xf1:
561                                         case 0xf3:
562                                                 // MTC Quarter Frame, Song Select
563                                                 _expected_bytes = 2;
564                                                 break;
565                                         case 0xf2:
566                                                 // Song Position
567                                                 _expected_bytes = 3;
568                                                 break;
569                                         case 0xf4:
570                                         case 0xf5:
571                                                 // Undefined
572                                                 _expected_bytes = 0;
573                                                 _status_byte = 0;
574                                                 return false;
575                                         case 0xf6:
576                                                 // Tune Request
577                                                 prepare_byte_event(time, byte);
578                                                 _expected_bytes = 0;
579                                                 _status_byte = 0;
580                                                 return true;
581                                 }
582                 }
583                 record_byte(byte);
584                 return false;
585         }
586         // Data byte
587         if (! _status_byte) {
588                 // Data bytes without a status will be discarded.
589                 _total_bytes++;
590                 _unbuffered_bytes++;
591                 return false;
592         }
593         if (! _total_bytes) {
594                 // Apply running status.
595                 record_byte(_status_byte);
596         }
597         record_byte(byte);
598         return (_total_bytes == _expected_bytes) ? prepare_buffered_event(time) : false;
599 }