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