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