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