new transport slave/master implementation, libs/ edition
[ardour.git] / libs / midi++2 / parser.cc
1 /*
2     Copyright (C) 1998 Paul Barton-Davis
3
4     This file was inspired by the MIDI parser for KeyKit by
5     Tim Thompson.
6
7     This program is free software; you can redistribute it and/or modify
8     it under the terms of the GNU General Public License as published by
9     the Free Software Foundation; either version 2 of the License, or
10     (at your option) any later version.
11
12     This program 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
15     GNU General Public License for more details.
16
17     You should have received a copy of the GNU General Public License
18     along with this program; if not, write to the Free Software
19     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20
21     $Id$
22 */
23
24 #include <cstring>
25 #include <cstdlib>
26 #include <unistd.h>
27 #include <cstring>
28 #include <iostream>
29 #include <iterator>
30
31 #include "midi++/types.h"
32 #include "midi++/parser.h"
33 #include "midi++/port.h"
34 #include "midi++/mmc.h"
35 #include "pbd/transmitter.h"
36
37 using namespace std;
38 using namespace MIDI;
39
40 const char *
41 Parser::midi_event_type_name (eventType t)
42
43 {
44         switch (t) {
45         case none:
46                 return "no midi messages";
47
48         case raw:
49                 return "raw midi data";
50
51         case MIDI::any:
52                 return "any midi message";
53
54         case off:
55                 return "note off";
56
57         case on:
58                 return "note on";
59
60         case polypress:
61                 return "aftertouch";
62
63         case MIDI::controller:
64                 return "controller";
65
66         case program:
67                 return "program change";
68
69         case chanpress:
70                 return "channel pressure";
71
72         case MIDI::pitchbend:
73                 return "pitch bend";
74
75         case MIDI::sysex:
76                 return "system exclusive";
77
78         case MIDI::song:
79                 return "song position";
80
81         case MIDI::tune:
82                 return "tune";
83
84         case MIDI::eox:
85                 return "end of sysex";
86
87         case MIDI::timing:
88                 return "timing";
89
90         case MIDI::start:
91                 return "start";
92
93         case MIDI::stop:
94                 return "continue";
95
96         case MIDI::contineu:
97                 return "stop";
98
99         case active:
100                 return "active sense";
101
102         default:
103                 return "unknown MIDI event type";
104         }
105 }
106
107 Parser::Parser ()
108 {
109         trace_stream = 0;
110         trace_prefix = "";
111         memset (message_counter, 0, sizeof (message_counter[0]) * 256);
112         msgindex = 0;
113         msgtype = none;
114         msglen = 256;
115         msgbuf = (unsigned char *) malloc (msglen);
116         msgbuf[msgindex++] = 0x90;
117         _mmc_forward = false;
118         reset_mtc_state ();
119         _offline = false;
120
121         /* this hack deals with the possibility of our first MIDI
122            bytes being running status messages.
123         */
124
125         channel_msg (0x90);
126         state = NEEDSTATUS;
127
128         pre_variable_state = NEEDSTATUS;
129         pre_variable_msgtype = none;
130 }
131
132 Parser::~Parser ()
133
134 {
135         free (msgbuf);
136 }
137
138 void
139 Parser::trace_event (Parser &, MIDI::byte *msg, size_t len, samplecnt_t /*when*/)
140 {
141         eventType type;
142         ostream *o;
143
144         if ((o = trace_stream) == NULL) { /* can be asynchronously removed */
145                 return;
146         }
147
148         type = (eventType) (msg[0]&0xF0);
149
150         switch (type) {
151         case off:
152                 *o << trace_prefix
153                    << "Channel "
154                    << (msg[0]&0xF)+1
155                    << " NoteOff NoteNum "
156                    << (int) msg[1]
157                    << " Vel "
158                    << (int) msg[2]
159                    << endmsg;
160                 break;
161
162         case on:
163                 *o << trace_prefix
164                    << "Channel "
165                    << (msg[0]&0xF)+1
166                    << " NoteOn NoteNum "
167                    << (int) msg[1]
168                    << " Vel "
169                    << (int) msg[2]
170                    << endmsg;
171                 break;
172
173         case polypress:
174                 *o << trace_prefix
175                    << "Channel "
176                    << (msg[0]&0xF)+1
177                    << " PolyPressure "
178                    << (int) msg[1]
179                    << endmsg;
180                 break;
181
182         case MIDI::controller:
183                 *o << trace_prefix
184                    << "Channel "
185                    << (msg[0]&0xF)+1
186                    << " Controller "
187                    << (int) msg[1]
188                    << " Value "
189                    << (int) msg[2]
190                    << endmsg;
191                 break;
192
193         case program:
194                 *o << trace_prefix
195                    << "Channel "
196                    << (msg[0]&0xF)+1
197                    <<  " Program Change ProgNum "
198                    << (int) msg[1]
199                    << endmsg;
200                 break;
201
202         case chanpress:
203                 *o << trace_prefix
204                    << "Channel "
205                    << (msg[0]&0xF)+1
206                    << " Channel Pressure "
207                    << (int) msg[1]
208                    << endmsg;
209                 break;
210
211         case MIDI::pitchbend:
212                 *o << trace_prefix
213                    << "Channel "
214                    << (msg[0]&0xF)+1
215                    << " Pitch Bend "
216                    << ((msg[2]<<7)|msg[1])
217                    << endmsg;
218                 break;
219
220         case MIDI::sysex:
221                 if (len == 1) {
222                         switch (msg[0]) {
223                         case 0xf8:
224                                 *o << trace_prefix
225                                    << "Clock"
226                                    << endmsg;
227                                 break;
228                         case 0xfa:
229                                 *o << trace_prefix
230                                    << "Start"
231                                    << endmsg;
232                                 break;
233                         case 0xfb:
234                                 *o << trace_prefix
235                                    << "Continue"
236                                    << endmsg;
237                                 break;
238                         case 0xfc:
239                                 *o << trace_prefix
240                                    << "Stop"
241                                    << endmsg;
242                                 break;
243                         case 0xfe:
244                                 *o << trace_prefix
245                                    << "Active Sense"
246                                    << endmsg;
247                                 break;
248                         case 0xff:
249                                 *o << trace_prefix
250                                    << "System Reset"
251                                    << endmsg;
252                                 break;
253                         default:
254                                 *o << trace_prefix
255                                    << "System Exclusive (1 byte : " << hex << (int) *msg << dec << ')'
256                                    << endmsg;
257                                 break;
258                         }
259                 } else {
260                         *o << trace_prefix
261                            << "System Exclusive (" << len << ") = [ " << hex;
262                         for (unsigned int i = 0; i < len; ++i) {
263                                 *o << (int) msgbuf[i] << ' ';
264                         }
265                         *o << dec << ']' << endmsg;
266
267                 }
268                 break;
269
270         case MIDI::song:
271                 *o << trace_prefix << "Song" << endmsg;
272                 break;
273
274         case MIDI::tune:
275                 *o << trace_prefix << "Tune" << endmsg;
276                 break;
277
278         case MIDI::eox:
279                 *o << trace_prefix << "End-of-System Exclusive" << endmsg;
280                 break;
281
282         case MIDI::timing:
283                 *o << trace_prefix << "Timing" << endmsg;
284                 break;
285
286         case MIDI::start:
287                 *o << trace_prefix << "Start" << endmsg;
288                 break;
289
290         case MIDI::stop:
291                 *o << trace_prefix << "Stop" << endmsg;
292                 break;
293
294         case MIDI::contineu:
295                 *o << trace_prefix << "Continue" << endmsg;
296                 break;
297
298         case active:
299                 *o << trace_prefix << "Active Sense" << endmsg;
300                 break;
301
302         default:
303                 *o << trace_prefix << "Unrecognized MIDI message" << endmsg;
304                 break;
305         }
306 }
307
308 void
309 Parser::trace (bool onoff, ostream *o, const string &prefix)
310 {
311         trace_connection.disconnect ();
312
313         if (onoff) {
314                 trace_stream = o;
315                 trace_prefix = prefix;
316                 any.connect_same_thread (trace_connection, boost::bind (&Parser::trace_event, this, _1, _2, _3, _4));
317         } else {
318                 trace_prefix = "";
319                 trace_stream = 0;
320         }
321 }
322
323 void
324 Parser::scanner (unsigned char inbyte)
325 {
326         bool statusbit;
327         boost::optional<int> edit_result;
328
329         // cerr << "parse: " << hex << (int) inbyte << dec << " state = " << state << " msgindex = " << msgindex << " runnable = " << runnable << endl;
330
331         /* Check active sensing early, so it doesn't interrupt sysex.
332
333            NOTE: active sense messages are not considered to fit under
334            "any" for the purposes of callbacks. If a caller wants
335            active sense messages handled, which is unlikely, then
336            they can just ask for it specifically. They are so unlike
337            every other MIDI message in terms of semantics that its
338            counter-productive to treat them similarly.
339         */
340
341         if (inbyte == 0xfe) {
342                 message_counter[inbyte]++;
343                 if (!_offline) {
344                         active_sense (*this);
345                 }
346                 return;
347         }
348
349         /* ditto for system reset, except do even less */
350
351         if (inbyte == 0xff) {
352                 message_counter[inbyte]++;
353                 return;
354         }
355
356         /* If necessary, allocate larger message buffer. */
357
358         if (msgindex >= msglen) {
359                 msglen *= 2;
360                 msgbuf = (unsigned char *) realloc (msgbuf, msglen);
361         }
362
363         /*
364           Real time messages can occur ANYPLACE,
365           but do not interrupt running status.
366         */
367
368         bool rtmsg = false;
369
370         switch (inbyte) {
371         case 0xf8:
372                 rtmsg = true;
373                 break;
374         case 0xfa:
375                 rtmsg = true;
376                 break;
377         case 0xfb:
378                 rtmsg = true;
379                 break;
380         case 0xfc:
381                 rtmsg = true;
382                 break;
383         case 0xfd:
384                 rtmsg = true;
385                 break;
386         case 0xfe:
387                 rtmsg = true;
388                 break;
389         case 0xff:
390                 rtmsg = true;
391                 break;
392         }
393
394         if (rtmsg) {
395                 boost::optional<int> res = edit (&inbyte, 1);
396
397                 if (res.get_value_or (1) >= 0 && !_offline) {
398                         realtime_msg (inbyte);
399                 }
400
401                 return;
402         }
403
404         statusbit = (inbyte & 0x80);
405
406         /*
407          * Variable length messages (ie. the 'system exclusive')
408          * can be terminated by the next status byte, not necessarily
409          * an EOX.  Actually, since EOX is a status byte, this
410          * code ALWAYS handles the end of a VARIABLELENGTH message.
411          */
412
413         if (state == VARIABLELENGTH && statusbit)  {
414
415                 /* The message has ended, so process it */
416
417                 /* add EOX to any sysex message */
418
419                 if (inbyte == MIDI::eox) {
420                         msgbuf[msgindex++] = inbyte;
421                 }
422
423 #if 0
424                 cerr << "SYSEX: " << hex;
425                 for (unsigned int i = 0; i < msgindex; ++i) {
426                         cerr << (int) msgbuf[i] << ' ';
427                 }
428                 cerr << dec << endl;
429 #endif
430                 if (msgindex > 0) {
431
432                         boost::optional<int> res = edit (msgbuf, msgindex);
433
434                         if (res.get_value_or (1) >= 0) {
435                                 if (!possible_mmc (msgbuf, msgindex) || _mmc_forward) {
436                                         if (!possible_mtc (msgbuf, msgindex) || _mtc_forward) {
437                                                 if (!_offline) {
438                                                         sysex (*this, msgbuf, msgindex);
439                                                 }
440                                         }
441                                 }
442                                 if (!_offline) {
443                                         any (*this, msgbuf, msgindex, _timestamp);
444                                 }
445                         }
446                 }
447         }
448
449         /*
450          * Status bytes always start a new message, except EOX
451          */
452
453         if (statusbit) {
454
455                 msgindex = 0;
456
457                 if (inbyte == MIDI::eox) {
458                         /* return to the state we had pre-sysex */
459
460                         state = pre_variable_state;
461                         runnable = was_runnable;
462                         msgtype = pre_variable_msgtype;
463
464                         if (state != NEEDSTATUS && runnable) {
465                                 msgbuf[msgindex++] = last_status_byte;
466                         }
467                 } else {
468                         msgbuf[msgindex++] = inbyte;
469                         if ((inbyte & 0xf0) == 0xf0) {
470                                 system_msg (inbyte);
471                                 runnable = false;
472                         } else {
473                                 channel_msg (inbyte);
474                         }
475                 }
476
477                 return;
478         }
479
480         /*
481          * We've got a Data byte.
482          */
483
484         msgbuf[msgindex++] = inbyte;
485
486         switch (state) {
487         case NEEDSTATUS:
488                 /*
489                  * We shouldn't get here, since in NEEDSTATUS mode
490                  * we're expecting a new status byte, NOT any
491                  * data bytes. On the other hand, some equipment
492                  * with leaky modwheels and the like might be
493                  * sending data bytes as part of running controller
494                  * messages, so just handle it silently.
495                  */
496                 break;
497
498         case NEEDTWOBYTES:
499                 /* wait for the second byte */
500                 if (msgindex < 3)
501                         return;
502                 /*FALLTHRU*/
503
504         case NEEDONEBYTE:
505                 /* We've completed a 1 or 2 byte message. */
506
507                 edit_result = edit (msgbuf, msgindex);
508
509                 if (edit_result.get_value_or (1)) {
510
511                         /* message not cancelled by an editor */
512
513                         message_counter[msgbuf[0] & 0xF0]++;
514
515                         if (!_offline) {
516                                 signal (msgbuf, msgindex);
517                         }
518                 }
519
520                 if (runnable) {
521                         /* In Runnable mode, we reset the message
522                            index, but keep the callbacks_pending and state the
523                            same.  This provides the "running status
524                            byte" feature.
525                         */
526                         msgindex = 1;
527                 } else {
528                         /* If not Runnable, reset to NEEDSTATUS mode */
529                         state = NEEDSTATUS;
530                 }
531                 break;
532
533         case VARIABLELENGTH:
534                 /* nothing to do */
535                 break;
536         }
537         return;
538 }
539
540 /** Call the real-time function for the specified byte, immediately.
541  * These can occur anywhere, so they don't change the state.
542  */
543 void
544 Parser::realtime_msg(unsigned char inbyte)
545
546 {
547         message_counter[inbyte]++;
548
549         if (_offline) {
550                 return;
551         }
552
553         switch (inbyte) {
554         case 0xf8:
555                 timing (*this, _timestamp);
556                 break;
557         case 0xfa:
558                 start (*this, _timestamp);
559                 break;
560         case 0xfb:
561                 contineu (*this, _timestamp);
562                 break;
563         case 0xfc:
564                 stop (*this, _timestamp);
565                 break;
566         case 0xfe:
567                 /* !!! active sense message in realtime_msg: should not reach here
568                  */
569                 break;
570         case 0xff:
571                 reset (*this);
572                 break;
573         }
574
575         any (*this, &inbyte, 1, _timestamp);
576 }
577
578
579 /** Interpret a Channel (voice or mode) Message status byte.
580  */
581 void
582 Parser::channel_msg(unsigned char inbyte)
583 {
584         last_status_byte = inbyte;
585         runnable = true;                /* Channel messages can use running status */
586
587         /* The high 4 bits, which determine the type of channel message. */
588
589         switch (inbyte&0xF0) {
590         case 0x80:
591                 msgtype = off;
592                 state = NEEDTWOBYTES;
593                 break;
594         case 0x90:
595                 msgtype = on;
596                 state = NEEDTWOBYTES;
597                 break;
598         case 0xa0:
599                 msgtype = polypress;
600                 state = NEEDTWOBYTES;
601                 break;
602         case 0xb0:
603                 msgtype = MIDI::controller;
604                 state = NEEDTWOBYTES;
605                 break;
606         case 0xc0:
607                 msgtype = program;
608                 state = NEEDONEBYTE;
609                 break;
610         case 0xd0:
611                 msgtype = chanpress;
612                 state = NEEDONEBYTE;
613                 break;
614         case 0xe0:
615                 msgtype = MIDI::pitchbend;
616                 state = NEEDTWOBYTES;
617                 break;
618         }
619 }
620
621 /** Initialize (and possibly emit) the signals for the
622  * specified byte.  Set the state that the state-machine
623  * should go into.  If the signal is not emitted
624  * immediately, it will be when the state machine gets to
625  * the end of the MIDI message.
626  */
627 void
628 Parser::system_msg (unsigned char inbyte)
629 {
630         message_counter[inbyte]++;
631
632         switch (inbyte) {
633         case 0xf0:
634                 pre_variable_msgtype = msgtype;
635                 pre_variable_state = state;
636                 was_runnable = runnable;
637                 msgtype = MIDI::sysex;
638                 state = VARIABLELENGTH;
639                 break;
640         case 0xf1:
641                 msgtype = MIDI::mtc_quarter;
642                 state = NEEDONEBYTE;
643                 break;
644         case 0xf2:
645                 msgtype = MIDI::position;
646                 state = NEEDTWOBYTES;
647                 break;
648         case 0xf3:
649                 msgtype = MIDI::song;
650                 state = NEEDONEBYTE;
651                 break;
652         case 0xf6:
653                 if (!_offline) {
654                         tune (*this);
655                 }
656                 state = NEEDSTATUS;
657                 break;
658         case 0xf7:
659                 break;
660         }
661
662         // all these messages will be sent via any()
663         // when they are complete.
664         // any (*this, &inbyte, 1, _timestamp);
665 }
666
667 void
668 Parser::signal (MIDI::byte *msg, size_t len)
669 {
670         channel_t chan = msg[0]&0xF;
671         int chan_i = chan;
672
673         switch (msgtype) {
674         case none:
675                 break;
676
677         case off:
678                 channel_active_preparse[chan_i] (*this);
679                 note_off (*this, (EventTwoBytes *) &msg[1]);
680                 channel_note_off[chan_i]
681                         (*this, (EventTwoBytes *) &msg[1]);
682                 channel_active_postparse[chan_i] (*this);
683                 break;
684
685         case on:
686                 channel_active_preparse[chan_i] (*this);
687
688                 /* Hack to deal with MIDI sources that use velocity=0
689                    instead of noteOff.
690                 */
691
692                 if (msg[2] == 0) {
693                         note_off (*this, (EventTwoBytes *) &msg[1]);
694                         channel_note_off[chan_i]
695                                 (*this, (EventTwoBytes *) &msg[1]);
696                 } else {
697                         note_on (*this, (EventTwoBytes *) &msg[1]);
698                         channel_note_on[chan_i]
699                                 (*this, (EventTwoBytes *) &msg[1]);
700                 }
701
702                 channel_active_postparse[chan_i] (*this);
703                 break;
704
705         case MIDI::controller:
706                 channel_active_preparse[chan_i] (*this);
707                 controller (*this, (EventTwoBytes *) &msg[1]);
708                 channel_controller[chan_i]
709                         (*this, (EventTwoBytes *) &msg[1]);
710                 channel_active_postparse[chan_i] (*this);
711                 break;
712
713         case program:
714                 channel_active_preparse[chan_i] (*this);
715                 program_change (*this, msg[1]);
716                 channel_program_change[chan_i] (*this, msg[1]);
717                 channel_active_postparse[chan_i] (*this);
718                 break;
719
720         case chanpress:
721                 channel_active_preparse[chan_i] (*this);
722                 pressure (*this, msg[1]);
723                 channel_pressure[chan_i] (*this, msg[1]);
724                 channel_active_postparse[chan_i] (*this);
725                 break;
726
727         case polypress:
728                 channel_active_preparse[chan_i] (*this);
729                 poly_pressure (*this, (EventTwoBytes *) &msg[1]);
730                 channel_poly_pressure[chan_i]
731                         (*this, (EventTwoBytes *) &msg[1]);
732                 channel_active_postparse[chan_i] (*this);
733                 break;
734
735         case MIDI::pitchbend:
736                 channel_active_preparse[chan_i] (*this);
737                 pitchbend (*this, (msg[2]<<7)|msg[1]);
738                 channel_pitchbend[chan_i] (*this, (msg[2]<<7)|msg[1]);
739                 channel_active_postparse[chan_i] (*this);
740                 break;
741
742         case MIDI::sysex:
743                 sysex (*this, msg, len);
744                 break;
745
746         case MIDI::mtc_quarter:
747                 process_mtc_quarter_frame (msg);
748                 mtc_quarter_frame (*this, *msg);
749                 break;
750
751         case MIDI::position:
752                 position (*this, msg, len);
753                 break;
754
755         case MIDI::song:
756                 song (*this, msg, len);
757                 break;
758
759         case MIDI::tune:
760                 tune (*this);
761
762         default:
763                 /* XXX some kind of warning ? */
764                 break;
765         }
766
767         any (*this, msg, len, _timestamp);
768 }
769
770 bool
771 Parser::possible_mmc (MIDI::byte *msg, size_t msglen)
772 {
773         if (!MachineControl::is_mmc (msg, msglen)) {
774                 return false;
775         }
776
777         /* hand over the just the interior MMC part of
778            the sysex msg without the leading 0xF0
779         */
780
781         if (!_offline) {
782                 mmc (*this, &msg[1], msglen - 1);
783         }
784
785         return true;
786 }
787
788 void
789 Parser::set_offline (bool yn)
790 {
791         if (_offline != yn) {
792                 _offline = yn;
793                 OfflineStatusChanged ();
794
795                 /* this hack deals with the possibility of our first MIDI
796                    bytes being running status messages.
797                 */
798
799                 channel_msg (0x90);
800                 state = NEEDSTATUS;
801         }
802 }