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