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