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