fix gcc4.4 compile warnings
[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 {
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 &, 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[2]<<7)|msg[1])
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                 any.connect_same_thread (trace_connection, boost::bind (&Parser::trace_event, this, _1, _2, _3));
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         boost::optional<int> edit_result;
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                 boost::optional<int> res = edit (&inbyte, 1);
391                 
392                 if (res.get_value_or (1) >= 0 && !_offline) {
393                         realtime_msg (inbyte);
394                 } 
395                 
396                 return;
397         } 
398
399         statusbit = (inbyte & 0x80);
400
401         /*
402          * Variable length messages (ie. the 'system exclusive')
403          * can be terminated by the next status byte, not necessarily
404          * an EOX.  Actually, since EOX is a status byte, this
405          * code ALWAYS handles the end of a VARIABLELENGTH message.
406          */
407
408         if (state == VARIABLELENGTH && statusbit)  {
409
410                 /* The message has ended, so process it */
411
412                 /* add EOX to any sysex message */
413
414                 if (inbyte == MIDI::eox) {
415                         msgbuf[msgindex++] = inbyte;
416                 }
417
418 #if 0
419                 cerr << "SYSEX: " << hex;
420                 for (unsigned int i = 0; i < msgindex; ++i) {
421                         cerr << (int) msgbuf[i] << ' ';
422                 }
423                 cerr << dec << endl;
424 #endif
425                 if (msgindex > 0) {
426
427                         boost::optional<int> res = edit (msgbuf, msgindex);
428
429                         if (res.get_value_or (1) >= 0) {
430                                 if (!possible_mmc (msgbuf, msgindex) || _mmc_forward) {
431                                         if (!possible_mtc (msgbuf, msgindex) || _mtc_forward) {
432                                                 if (!_offline) {
433                                                         sysex (*this, msgbuf, msgindex);
434                                                 }
435                                         }
436                                 }
437                                 if (!_offline) {
438                                         any (*this, msgbuf, msgindex);
439                                 } 
440                         }
441                 }
442         }
443         
444         /*
445          * Status bytes always start a new message, except EOX
446          */
447         
448         if (statusbit) {
449
450                 msgindex = 0;
451
452                 if (inbyte == MIDI::eox) {
453                         /* return to the state we had pre-sysex */
454
455                         state = pre_variable_state;
456                         runnable = was_runnable;
457                         msgtype = pre_variable_msgtype;
458
459                         if (state != NEEDSTATUS && runnable) {
460                                 msgbuf[msgindex++] = last_status_byte;
461                         }
462                 } else {
463                         msgbuf[msgindex++] = inbyte;
464                         if ((inbyte & 0xf0) == 0xf0) {
465                                 system_msg (inbyte);
466                                 runnable = false;
467                         } else {
468                                 channel_msg (inbyte);
469                         }
470                 }
471
472                 return;
473         }
474         
475         /*
476          * We've got a Data byte.
477          */
478         
479         msgbuf[msgindex++] = inbyte;
480
481         switch (state) {
482         case NEEDSTATUS:
483                 /*
484                  * We shouldn't get here, since in NEEDSTATUS mode
485                  * we're expecting a new status byte, NOT any
486                  * data bytes. On the other hand, some equipment
487                  * with leaky modwheels and the like might be
488                  * sending data bytes as part of running controller
489                  * messages, so just handle it silently.
490                  */
491                 break;
492                 
493         case NEEDTWOBYTES:
494                 /* wait for the second byte */
495                 if (msgindex < 3)
496                         return;
497                 /*FALLTHRU*/
498                 
499         case NEEDONEBYTE:
500                 /* We've completed a 1 or 2 byte message. */
501
502                 edit_result = edit (msgbuf, msgindex);
503                 
504                 if (edit_result.get_value_or (1)) {
505                         
506                         /* message not cancelled by an editor */
507                         
508                         message_counter[msgbuf[0] & 0xF0]++;
509
510                         if (!_offline) {
511                                 signal (msgbuf, msgindex);
512                         }
513                 }
514                 
515                 if (runnable) {
516                         /* In Runnable mode, we reset the message 
517                            index, but keep the callbacks_pending and state the 
518                            same.  This provides the "running status 
519                            byte" feature.
520                         */
521                         msgindex = 1;
522                 } else {
523                         /* If not Runnable, reset to NEEDSTATUS mode */
524                         state = NEEDSTATUS;
525                 }
526                 break;
527                 
528         case VARIABLELENGTH:
529                 /* nothing to do */
530                 break;
531         }
532         return;
533 }
534
535 /** Call the real-time function for the specified byte, immediately.
536  * These can occur anywhere, so they don't change the state.
537  */
538 void
539 Parser::realtime_msg(unsigned char inbyte)
540
541 {
542         message_counter[inbyte]++;
543
544         if (_offline) {
545                 return;
546         }
547
548         switch (inbyte) {
549         case 0xf8:
550                 timing (*this, _timestamp);
551                 break;
552         case 0xfa:
553                 start (*this, _timestamp);
554                 break;
555         case 0xfb:
556                 contineu (*this, _timestamp);
557                 break;
558         case 0xfc:
559                 stop (*this, _timestamp);
560                 break;
561         case 0xfe:
562                 /* !!! active sense message in realtime_msg: should not reach here
563                  */  
564                 break;
565         case 0xff:
566                 reset (*this);
567                 break;
568         }
569
570         any (*this, &inbyte, 1);
571 }
572
573
574 /** Interpret a Channel (voice or mode) Message status byte.
575  */
576 void
577 Parser::channel_msg(unsigned char inbyte)
578 {
579         last_status_byte = inbyte;
580         runnable = true;                /* Channel messages can use running status */
581     
582         /* The high 4 bits, which determine the type of channel message. */
583     
584         switch (inbyte&0xF0) {
585         case 0x80:
586                 msgtype = off;
587                 state = NEEDTWOBYTES;
588                 break;
589         case 0x90:
590                 msgtype = on;
591                 state = NEEDTWOBYTES;
592                 break;
593         case 0xa0:
594                 msgtype = polypress;
595                 state = NEEDTWOBYTES;
596                 break;
597         case 0xb0:
598                 msgtype = MIDI::controller;
599                 state = NEEDTWOBYTES;
600                 break;
601         case 0xc0:
602                 msgtype = program;
603                 state = NEEDONEBYTE;
604                 break;
605         case 0xd0:
606                 msgtype = chanpress;
607                 state = NEEDONEBYTE;
608                 break;
609         case 0xe0:
610                 msgtype = MIDI::pitchbend;
611                 state = NEEDTWOBYTES;
612                 break;
613         }
614 }
615
616 /** Initialize (and possibly emit) the signals for the
617  * specified byte.  Set the state that the state-machine
618  * should go into.  If the signal is not emitted
619  * immediately, it will be when the state machine gets to
620  * the end of the MIDI message.
621  */
622 void
623 Parser::system_msg (unsigned char inbyte)
624 {
625         message_counter[inbyte]++;
626
627         switch (inbyte) {
628         case 0xf0:
629                 pre_variable_msgtype = msgtype;
630                 pre_variable_state = state;
631                 was_runnable = runnable;
632                 msgtype = MIDI::sysex;
633                 state = VARIABLELENGTH;
634                 break;
635         case 0xf1:
636                 msgtype = MIDI::mtc_quarter;
637                 state = NEEDONEBYTE;
638                 break;
639         case 0xf2:
640                 msgtype = MIDI::position;
641                 state = NEEDTWOBYTES;
642                 break;
643         case 0xf3:
644                 msgtype = MIDI::song;
645                 state = NEEDONEBYTE;
646                 break;
647         case 0xf6:
648                 if (!_offline) {
649                         tune (*this);
650                 }
651                 state = NEEDSTATUS;
652                 break;
653         case 0xf7:
654                 break;
655         }
656
657         // all these messages will be sent via any() 
658         // when they are complete.
659         // any (*this, &inbyte, 1);
660 }
661
662 void 
663 Parser::signal (byte *msg, size_t len)
664 {
665         channel_t chan = msg[0]&0xF;
666         int chan_i = chan;
667
668         switch (msgtype) {
669         case none:
670                 break;
671                 
672         case off:
673                 channel_active_preparse[chan_i] (*this);
674                 note_off (*this, (EventTwoBytes *) &msg[1]);
675                 channel_note_off[chan_i] 
676                         (*this, (EventTwoBytes *) &msg[1]);
677                 channel_active_postparse[chan_i] (*this);
678                 break;
679                 
680         case on:
681                 channel_active_preparse[chan_i] (*this);
682
683                 /* Hack to deal with MIDI sources that use velocity=0
684                    instead of noteOff.
685                 */
686
687                 if (msg[2] == 0) {
688                         note_off (*this, (EventTwoBytes *) &msg[1]);
689                         channel_note_off[chan_i] 
690                                 (*this, (EventTwoBytes *) &msg[1]);
691                 } else {
692                         note_on (*this, (EventTwoBytes *) &msg[1]);
693                         channel_note_on[chan_i] 
694                                 (*this, (EventTwoBytes *) &msg[1]);
695                 }
696
697                 channel_active_postparse[chan_i] (*this);
698                 break;
699                 
700         case MIDI::controller:
701                 channel_active_preparse[chan_i] (*this);
702                 controller (*this, (EventTwoBytes *) &msg[1]);
703                 channel_controller[chan_i] 
704                         (*this, (EventTwoBytes *) &msg[1]);
705                 channel_active_postparse[chan_i] (*this);
706                 break;
707                 
708         case program:
709                 channel_active_preparse[chan_i] (*this);
710                 program_change (*this, msg[1]);
711                 channel_program_change[chan_i] (*this, msg[1]);
712                 channel_active_postparse[chan_i] (*this);
713                 break;
714                 
715         case chanpress:
716                 channel_active_preparse[chan_i] (*this);
717                 pressure (*this, msg[1]);
718                 channel_pressure[chan_i] (*this, msg[1]);
719                 channel_active_postparse[chan_i] (*this);
720                 break;
721                 
722         case polypress:
723                 channel_active_preparse[chan_i] (*this);
724                 poly_pressure (*this, (EventTwoBytes *) &msg[1]);
725                 channel_poly_pressure[chan_i] 
726                         (*this, (EventTwoBytes *) &msg[1]);
727                 channel_active_postparse[chan_i] (*this);
728                 break;
729                 
730         case MIDI::pitchbend:
731                 channel_active_preparse[chan_i] (*this);
732                 pitchbend (*this, (msg[2]<<7)|msg[1]);
733                 channel_pitchbend[chan_i] (*this, (msg[2]<<7)|msg[1]);
734                 channel_active_postparse[chan_i] (*this);
735                 break;
736                 
737         case MIDI::sysex:
738                 sysex (*this, msg, len);
739                 break;
740
741         case MIDI::mtc_quarter:
742                 process_mtc_quarter_frame (msg);
743                 mtc_quarter_frame (*this, *msg);
744                 break;
745                 
746         case MIDI::position:
747                 position (*this, msg, len);
748                 break;
749                 
750         case MIDI::song:
751                 song (*this, msg, len);
752                 break;
753         
754         case MIDI::tune:
755                 tune (*this);
756         
757         default:
758                 /* XXX some kind of warning ? */
759                 break;
760         }
761         
762         any (*this, msg, len);
763 }
764
765 bool
766 Parser::possible_mmc (byte *msg, size_t msglen)
767 {
768         if (!MachineControl::is_mmc (msg, msglen)) {
769                 return false;
770         }
771
772         /* hand over the just the interior MMC part of
773            the sysex msg without the leading 0xF0
774         */
775
776         if (!_offline) {
777                 mmc (*this, &msg[1], msglen - 1);
778         }
779
780         return true;
781 }
782
783 void
784 Parser::set_offline (bool yn)
785 {
786         if (_offline != yn) {
787                 _offline = yn;
788                 OfflineStatusChanged ();
789
790                 /* this hack deals with the possibility of our first MIDI
791                    bytes being running status messages.
792                 */
793                 
794                 channel_msg (0x90);
795                 state = NEEDSTATUS;
796         }
797 }
798