summaryrefslogtreecommitdiff
path: root/libs/midi++2/parser.cc
blob: 599f8764f15d8835012bc5b83f084db4d88b77c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
/*
    Copyright (C) 1998 Paul Barton-Davis

    This file was inspired by the MIDI parser for KeyKit by
    Tim Thompson.

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

    $Id$
*/

#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <cstring>
#include <iostream>
#include <iterator>

#include "midi++/types.h"
#include "midi++/parser.h"
#include "midi++/port.h"
#include "midi++/mmc.h"
#include "pbd/transmitter.h"

using namespace std;
using namespace MIDI;

const char *
Parser::midi_event_type_name (eventType t)

{
	switch (t) {
	case none:
		return "no midi messages";

	case raw:
		return "raw midi data";

	case MIDI::any:
		return "any midi message";

	case off:
		return "note off";

	case on:
		return "note on";

	case polypress:
		return "aftertouch";

	case MIDI::controller:
		return "controller";

	case program:
		return "program change";

	case chanpress:
		return "channel pressure";

	case MIDI::pitchbend:
		return "pitch bend";

	case MIDI::sysex:
		return "system exclusive";

	case MIDI::song:
		return "song position";

	case MIDI::tune:
		return "tune";

	case MIDI::eox:
		return "end of sysex";

	case MIDI::timing:
		return "timing";

	case MIDI::start:
		return "start";

	case MIDI::stop:
		return "continue";

	case MIDI::contineu:
		return "stop";

	case active:
		return "active sense";

	default:
		return "unknown MIDI event type";
	}
}

Parser::Parser ()
{
	trace_stream = 0;
	trace_prefix = "";
	memset (message_counter, 0, sizeof (message_counter[0]) * 256);
	msgindex = 0;
	msgtype = none;
	msglen = 256;
	msgbuf = (unsigned char *) malloc (msglen);
	msgbuf[msgindex++] = 0x90;
	_mmc_forward = false;
	reset_mtc_state ();
	_offline = false;

	/* this hack deals with the possibility of our first MIDI
	   bytes being running status messages.
	*/

	channel_msg (0x90);
	state = NEEDSTATUS;

	pre_variable_state = NEEDSTATUS;
	pre_variable_msgtype = none;
}

Parser::~Parser ()

{
	free (msgbuf);
}

void
Parser::trace_event (Parser &, MIDI::byte *msg, size_t len, samplecnt_t /*when*/)
{
	eventType type;
	ostream *o;

	if ((o = trace_stream) == NULL) { /* can be asynchronously removed */
		return;
	}

	type = (eventType) (msg[0]&0xF0);

	switch (type) {
	case off:
		*o << trace_prefix
		   << "Channel "
		   << (msg[0]&0xF)+1
		   << " NoteOff NoteNum "
		   << (int) msg[1]
		   << " Vel "
		   << (int) msg[2]
		   << endmsg;
		break;

	case on:
		*o << trace_prefix
		   << "Channel "
		   << (msg[0]&0xF)+1
		   << " NoteOn NoteNum "
		   << (int) msg[1]
		   << " Vel "
		   << (int) msg[2]
		   << endmsg;
		break;

	case polypress:
		*o << trace_prefix
		   << "Channel "
		   << (msg[0]&0xF)+1
		   << " PolyPressure "
		   << (int) msg[1]
		   << endmsg;
		break;

	case MIDI::controller:
		*o << trace_prefix
		   << "Channel "
		   << (msg[0]&0xF)+1
		   << " Controller "
		   << (int) msg[1]
		   << " Value "
		   << (int) msg[2]
		   << endmsg;
		break;

	case program:
		*o << trace_prefix
		   << "Channel "
		   << (msg[0]&0xF)+1
		   <<  " Program Change ProgNum "
		   << (int) msg[1]
		   << endmsg;
		break;

	case chanpress:
		*o << trace_prefix
		   << "Channel "
		   << (msg[0]&0xF)+1
		   << " Channel Pressure "
		   << (int) msg[1]
		   << endmsg;
		break;

	case MIDI::pitchbend:
		*o << trace_prefix
		   << "Channel "
		   << (msg[0]&0xF)+1
		   << " Pitch Bend "
		   << ((msg[2]<<7)|msg[1])
		   << endmsg;
		break;

	case MIDI::sysex:
		if (len == 1) {
			switch (msg[0]) {
			case 0xf8:
				*o << trace_prefix
				   << "Clock"
				   << endmsg;
				break;
			case 0xfa:
				*o << trace_prefix
				   << "Start"
				   << endmsg;
				break;
			case 0xfb:
				*o << trace_prefix
				   << "Continue"
				   << endmsg;
				break;
			case 0xfc:
				*o << trace_prefix
				   << "Stop"
				   << endmsg;
				break;
			case 0xfe:
				*o << trace_prefix
				   << "Active Sense"
				   << endmsg;
				break;
			case 0xff:
				*o << trace_prefix
				   << "System Reset"
				   << endmsg;
				break;
			default:
				*o << trace_prefix
				   << "System Exclusive (1 byte : " << hex << (int) *msg << dec << ')'
				   << endmsg;
				break;
			}
		} else {
			*o << trace_prefix
			   << "System Exclusive (" << len << ") = [ " << hex;
			for (unsigned int i = 0; i < len; ++i) {
				*o << (int) msgbuf[i] << ' ';
			}
			*o << dec << ']' << endmsg;

		}
		break;

	case MIDI::song:
		*o << trace_prefix << "Song" << endmsg;
		break;

	case MIDI::tune:
		*o << trace_prefix << "Tune" << endmsg;
		break;

	case MIDI::eox:
		*o << trace_prefix << "End-of-System Exclusive" << endmsg;
		break;

	case MIDI::timing:
		*o << trace_prefix << "Timing" << endmsg;
		break;

	case MIDI::start:
		*o << trace_prefix << "Start" << endmsg;
		break;

	case MIDI::stop:
		*o << trace_prefix << "Stop" << endmsg;
		break;

	case MIDI::contineu:
		*o << trace_prefix << "Continue" << endmsg;
		break;

	case active:
		*o << trace_prefix << "Active Sense" << endmsg;
		break;

	default:
		*o << trace_prefix << "Unrecognized MIDI message" << endmsg;
		break;
	}
}

void
Parser::trace (bool onoff, ostream *o, const string &prefix)
{
	trace_connection.disconnect ();

	if (onoff) {
		trace_stream = o;
		trace_prefix = prefix;
		any.connect_same_thread (trace_connection, boost::bind (&Parser::trace_event, this, _1, _2, _3, _4));
	} else {
		trace_prefix = "";
		trace_stream = 0;
	}
}

void
Parser::scanner (unsigned char inbyte)
{
	bool statusbit;
        boost::optional<int> edit_result;

	// cerr << "parse: " << hex << (int) inbyte << dec << " state = " << state << " msgindex = " << msgindex << " runnable = " << runnable << endl;

	/* Check active sensing early, so it doesn't interrupt sysex.

	   NOTE: active sense messages are not considered to fit under
	   "any" for the purposes of callbacks. If a caller wants
	   active sense messages handled, which is unlikely, then
	   they can just ask for it specifically. They are so unlike
	   every other MIDI message in terms of semantics that its
	   counter-productive to treat them similarly.
	*/

	if (inbyte == 0xfe) {
	        message_counter[inbyte]++;
		if (!_offline) {
			active_sense (*this);
		}
		return;
	}

	/* ditto for system reset, except do even less */

	if (inbyte == 0xff) {
		message_counter[inbyte]++;
		return;
	}

	/* If necessary, allocate larger message buffer. */

	if (msgindex >= msglen) {
		msglen *= 2;
		msgbuf = (unsigned char *) realloc (msgbuf, msglen);
	}

	/*
	  Real time messages can occur ANYPLACE,
	  but do not interrupt running status.
	*/

	bool rtmsg = false;

	switch (inbyte) {
	case 0xf8:
		rtmsg = true;
		break;
	case 0xfa:
		rtmsg = true;
		break;
	case 0xfb:
		rtmsg = true;
		break;
	case 0xfc:
		rtmsg = true;
		break;
	case 0xfd:
		rtmsg = true;
		break;
	case 0xfe:
		rtmsg = true;
		break;
	case 0xff:
		rtmsg = true;
		break;
	}

	if (rtmsg) {
		boost::optional<int> res = edit (&inbyte, 1);

		if (res.get_value_or (1) >= 0 && !_offline) {
			realtime_msg (inbyte);
		}

		return;
	}

	statusbit = (inbyte & 0x80);

	/*
	 * Variable length messages (ie. the 'system exclusive')
	 * can be terminated by the next status byte, not necessarily
	 * an EOX.  Actually, since EOX is a status byte, this
	 * code ALWAYS handles the end of a VARIABLELENGTH message.
	 */

	if (state == VARIABLELENGTH && statusbit)  {

		/* The message has ended, so process it */

		/* add EOX to any sysex message */

		if (inbyte == MIDI::eox) {
			msgbuf[msgindex++] = inbyte;
		}

#if 0
		cerr << "SYSEX: " << hex;
		for (unsigned int i = 0; i < msgindex; ++i) {
			cerr << (int) msgbuf[i] << ' ';
		}
		cerr << dec << endl;
#endif
		if (msgindex > 0) {

			boost::optional<int> res = edit (msgbuf, msgindex);

			if (res.get_value_or (1) >= 0) {
				if (!possible_mmc (msgbuf, msgindex) || _mmc_forward) {
					if (!possible_mtc (msgbuf, msgindex) || _mtc_forward) {
						if (!_offline) {
							sysex (*this, msgbuf, msgindex);
						}
					}
				}
				if (!_offline) {
					any (*this, msgbuf, msgindex, _timestamp);
				}
			}
		}
	}

	/*
	 * Status bytes always start a new message, except EOX
	 */

	if (statusbit) {

		msgindex = 0;

		if (inbyte == MIDI::eox) {
			/* return to the state we had pre-sysex */

			state = pre_variable_state;
			runnable = was_runnable;
			msgtype = pre_variable_msgtype;

			if (state != NEEDSTATUS && runnable) {
				msgbuf[msgindex++] = last_status_byte;
			}
		} else {
			msgbuf[msgindex++] = inbyte;
			if ((inbyte & 0xf0) == 0xf0) {
				system_msg (inbyte);
				runnable = false;
			} else {
				channel_msg (inbyte);
			}
		}

		return;
	}

	/*
	 * We've got a Data byte.
	 */

	msgbuf[msgindex++] = inbyte;

	switch (state) {
	case NEEDSTATUS:
		/*
		 * We shouldn't get here, since in NEEDSTATUS mode
		 * we're expecting a new status byte, NOT any
		 * data bytes. On the other hand, some equipment
		 * with leaky modwheels and the like might be
		 * sending data bytes as part of running controller
		 * messages, so just handle it silently.
		 */
		break;

	case NEEDTWOBYTES:
		/* wait for the second byte */
		if (msgindex < 3)
			return;
		/*FALLTHRU*/

	case NEEDONEBYTE:
		/* We've completed a 1 or 2 byte message. */

                edit_result = edit (msgbuf, msgindex);

		if (edit_result.get_value_or (1)) {

			/* message not cancelled by an editor */

		        message_counter[msgbuf[0] & 0xF0]++;

			if (!_offline) {
				signal (msgbuf, msgindex);
			}
		}

		if (runnable) {
			/* In Runnable mode, we reset the message
			   index, but keep the callbacks_pending and state the
			   same.  This provides the "running status
			   byte" feature.
			*/
			msgindex = 1;
		} else {
			/* If not Runnable, reset to NEEDSTATUS mode */
			state = NEEDSTATUS;
		}
		break;

	case VARIABLELENGTH:
		/* nothing to do */
		break;
	}
	return;
}

/** Call the real-time function for the specified byte, immediately.
 * These can occur anywhere, so they don't change the state.
 */
void
Parser::realtime_msg(unsigned char inbyte)

{
	message_counter[inbyte]++;

	if (_offline) {
		return;
	}

	switch (inbyte) {
	case 0xf8:
		timing (*this, _timestamp);
		break;
	case 0xfa:
		start (*this, _timestamp);
		break;
	case 0xfb:
		contineu (*this, _timestamp);
		break;
	case 0xfc:
		stop (*this, _timestamp);
		break;
	case 0xfe:
		/* !!! active sense message in realtime_msg: should not reach here
		 */
		break;
	case 0xff:
		reset (*this);
		break;
	}

	any (*this, &inbyte, 1, _timestamp);
}


/** Interpret a Channel (voice or mode) Message status byte.
 */
void
Parser::channel_msg(unsigned char inbyte)
{
	last_status_byte = inbyte;
	runnable = true;		/* Channel messages can use running status */

	/* The high 4 bits, which determine the type of channel message. */

	switch (inbyte&0xF0) {
	case 0x80:
		msgtype = off;
		state = NEEDTWOBYTES;
		break;
	case 0x90:
		msgtype = on;
		state = NEEDTWOBYTES;
		break;
	case 0xa0:
		msgtype = polypress;
		state = NEEDTWOBYTES;
		break;
	case 0xb0:
		msgtype = MIDI::controller;
		state = NEEDTWOBYTES;
		break;
	case 0xc0:
		msgtype = program;
		state = NEEDONEBYTE;
		break;
	case 0xd0:
		msgtype = chanpress;
		state = NEEDONEBYTE;
		break;
	case 0xe0:
		msgtype = MIDI::pitchbend;
		state = NEEDTWOBYTES;
		break;
	}
}

/** Initialize (and possibly emit) the signals for the
 * specified byte.  Set the state that the state-machine
 * should go into.  If the signal is not emitted
 * immediately, it will be when the state machine gets to
 * the end of the MIDI message.
 */
void
Parser::system_msg (unsigned char inbyte)
{
	message_counter[inbyte]++;

	switch (inbyte) {
	case 0xf0:
		pre_variable_msgtype = msgtype;
		pre_variable_state = state;
		was_runnable = runnable;
		msgtype = MIDI::sysex;
		state = VARIABLELENGTH;
		break;
	case 0xf1:
		msgtype = MIDI::mtc_quarter;
		state = NEEDONEBYTE;
		break;
	case 0xf2:
		msgtype = MIDI::position;
		state = NEEDTWOBYTES;
		break;
	case 0xf3:
		msgtype = MIDI::song;
		state = NEEDONEBYTE;
		break;
	case 0xf6:
		if (!_offline) {
			tune (*this);
		}
		state = NEEDSTATUS;
		break;
	case 0xf7:
		break;
	}

	// all these messages will be sent via any()
	// when they are complete.
	// any (*this, &inbyte, 1, _timestamp);
}

void
Parser::signal (MIDI::byte *msg, size_t len)
{
	channel_t chan = msg[0]&0xF;
	int chan_i = chan;

	switch (msgtype) {
	case none:
		break;

	case off:
		channel_active_preparse[chan_i] (*this);
		note_off (*this, (EventTwoBytes *) &msg[1]);
		channel_note_off[chan_i]
			(*this, (EventTwoBytes *) &msg[1]);
		channel_active_postparse[chan_i] (*this);
		break;

	case on:
		channel_active_preparse[chan_i] (*this);

		/* Hack to deal with MIDI sources that use velocity=0
		   instead of noteOff.
		*/

		if (msg[2] == 0) {
			note_off (*this, (EventTwoBytes *) &msg[1]);
			channel_note_off[chan_i]
				(*this, (EventTwoBytes *) &msg[1]);
		} else {
			note_on (*this, (EventTwoBytes *) &msg[1]);
			channel_note_on[chan_i]
				(*this, (EventTwoBytes *) &msg[1]);
		}

		channel_active_postparse[chan_i] (*this);
		break;

	case MIDI::controller:
		channel_active_preparse[chan_i] (*this);
		controller (*this, (EventTwoBytes *) &msg[1]);
		channel_controller[chan_i]
			(*this, (EventTwoBytes *) &msg[1]);
		channel_active_postparse[chan_i] (*this);
		break;

	case program:
		channel_active_preparse[chan_i] (*this);
		program_change (*this, msg[1]);
		channel_program_change[chan_i] (*this, msg[1]);
		channel_active_postparse[chan_i] (*this);
		break;

	case chanpress:
		channel_active_preparse[chan_i] (*this);
		pressure (*this, msg[1]);
		channel_pressure[chan_i] (*this, msg[1]);
		channel_active_postparse[chan_i] (*this);
		break;

	case polypress:
		channel_active_preparse[chan_i] (*this);
		poly_pressure (*this, (EventTwoBytes *) &msg[1]);
		channel_poly_pressure[chan_i]
			(*this, (EventTwoBytes *) &msg[1]);
		channel_active_postparse[chan_i] (*this);
		break;

	case MIDI::pitchbend:
		channel_active_preparse[chan_i] (*this);
		pitchbend (*this, (msg[2]<<7)|msg[1]);
		channel_pitchbend[chan_i] (*this, (msg[2]<<7)|msg[1]);
		channel_active_postparse[chan_i] (*this);
		break;

	case MIDI::sysex:
		sysex (*this, msg, len);
		break;

	case MIDI::mtc_quarter:
		process_mtc_quarter_frame (msg);
		mtc_quarter_frame (*this, *msg);
		break;

	case MIDI::position:
		position (*this, msg, len);
		break;

	case MIDI::song:
		song (*this, msg, len);
		break;

	case MIDI::tune:
		tune (*this);

	default:
		/* XXX some kind of warning ? */
		break;
	}

	any (*this, msg, len, _timestamp);
}

bool
Parser::possible_mmc (MIDI::byte *msg, size_t msglen)
{
	if (!MachineControl::is_mmc (msg, msglen)) {
		return false;
	}

	/* hand over the just the interior MMC part of
	   the sysex msg without the leading 0xF0
	*/

	if (!_offline) {
		mmc (*this, &msg[1], msglen - 1);
	}

	return true;
}

void
Parser::set_offline (bool yn)
{
	if (_offline != yn) {
		_offline = yn;
		OfflineStatusChanged ();

		/* this hack deals with the possibility of our first MIDI
		   bytes being running status messages.
		*/

		channel_msg (0x90);
		state = NEEDSTATUS;
	}
}