forked from FortySevenEffects/arduino_midi_library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMIDI.hpp
1502 lines (1295 loc) · 55.9 KB
/
MIDI.hpp
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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* @file MIDI.hpp
* Project Arduino MIDI Library
* @brief MIDI Library for the Arduino - Inline implementations
* @author Francois Best, lathoub
* @date 24/02/11
* @license MIT - Copyright (c) 2015 Francois Best
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#pragma once
BEGIN_MIDI_NAMESPACE
/// \brief Constructor for MidiInterface.
template<class Transport, class Settings, class Platform>
inline MidiInterface<Transport, Settings, Platform>::MidiInterface(Transport& inTransport)
: mTransport(inTransport)
, mInputChannel(0)
, mRunningStatus_RX(InvalidType)
, mRunningStatus_TX(InvalidType)
, mPendingMessageExpectedLength(0)
, mPendingMessageIndex(0)
, mCurrentRpnNumber(0xffff)
, mCurrentNrpnNumber(0xffff)
, mThruActivated(true)
, mThruFilterMode(Thru::Full)
, mLastMessageSentTime(0)
, mLastMessageReceivedTime(0)
, mSenderActiveSensingPeriodicity(0)
, mReceiverActiveSensingActivated(false)
, mLastError(0)
{
mSenderActiveSensingPeriodicity = Settings::SenderActiveSensingPeriodicity;
}
/*! \brief Destructor for MidiInterface.
This is not really useful for the Arduino, as it is never called...
*/
template<class Transport, class Settings, class Platform>
inline MidiInterface<Transport, Settings, Platform>::~MidiInterface()
{
}
// -----------------------------------------------------------------------------
/*! \brief Call the begin method in the setup() function of the Arduino.
All parameters are set to their default values:
- Input channel set to 1 if no value is specified
- Full thru mirroring
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::begin(Channel inChannel)
{
// Initialise the Transport layer
mTransport.begin();
mInputChannel = inChannel;
mRunningStatus_TX = InvalidType;
mRunningStatus_RX = InvalidType;
mPendingMessageIndex = 0;
mPendingMessageExpectedLength = 0;
mCurrentRpnNumber = 0xffff;
mCurrentNrpnNumber = 0xffff;
mLastMessageSentTime = Platform::now();
mMessage.valid = false;
mMessage.type = InvalidType;
mMessage.channel = 0;
mMessage.data1 = 0;
mMessage.data2 = 0;
mMessage.length = 0;
mThruFilterMode = Thru::Full;
mThruActivated = mTransport.thruActivated;
}
// -----------------------------------------------------------------------------
// Output
// -----------------------------------------------------------------------------
/*! \addtogroup output
@{
*/
/*! \brief Send a MIDI message.
\param inMessage The message
This method is used when you want to send a Message that has not been constructed
by the library, but by an external source.
This method does *not* check against any of the constraints.
Typically this function is use by MIDI Bridges taking MIDI messages and passing
them thru.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::send(const MidiMessage& inMessage)
{
if (!inMessage.valid)
return;
if (mTransport.beginTransmission(inMessage.type))
{
const StatusByte status = getStatus(inMessage.type, inMessage.channel);
mTransport.write(status);
if (inMessage.type != MidiType::SystemExclusive)
{
if (inMessage.length > 1) mTransport.write(inMessage.data1);
if (inMessage.length > 2) mTransport.write(inMessage.data2);
} else
{
// sysexArray does not contain the start and end tags
mTransport.write(MidiType::SystemExclusiveStart);
for (size_t i = 0; i < inMessage.getSysExSize(); i++)
mTransport.write(inMessage.sysexArray[i]);
mTransport.write(MidiType::SystemExclusiveEnd);
}
}
mTransport.endTransmission();
UpdateLastSentTime();
}
/*! \brief Generate and send a MIDI message from the values given.
\param inType The message type (see type defines for reference)
\param inData1 The first data byte.
\param inData2 The second data byte (if the message contains only 1 data byte,
set this one to 0).
\param inChannel The output channel on which the message will be sent
(values from 1 to 16). Note: you cannot send to OMNI.
This is an internal method, use it only if you need to send raw data
from your code, at your own risks.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::send(MidiType inType,
DataByte inData1,
DataByte inData2,
Channel inChannel)
{
if (inType <= PitchBend) // Channel messages
{
// Then test if channel is valid
if (inChannel >= MIDI_CHANNEL_OFF ||
inChannel == MIDI_CHANNEL_OMNI ||
inType < 0x80)
{
return; // Don't send anything
}
// Protection: remove MSBs on data
inData1 &= 0x7f;
inData2 &= 0x7f;
const StatusByte status = getStatus(inType, inChannel);
if (mTransport.beginTransmission(inType))
{
if (Settings::UseRunningStatus)
{
if (mRunningStatus_TX != status)
{
// New message, memorise and send header
mRunningStatus_TX = status;
mTransport.write(mRunningStatus_TX);
}
}
else
{
// Don't care about running status, send the status byte.
mTransport.write(status);
}
// Then send data
mTransport.write(inData1);
if (inType != ProgramChange && inType != AfterTouchChannel)
{
mTransport.write(inData2);
}
mTransport.endTransmission();
UpdateLastSentTime();
}
}
else if (inType >= Clock && inType <= SystemReset)
{
sendRealTime(inType); // System Real-time and 1 byte.
}
}
// -----------------------------------------------------------------------------
/*! \brief Send a Note On message
\param inNoteNumber Pitch value in the MIDI format (0 to 127).
\param inVelocity Note attack velocity (0 to 127). A NoteOn with 0 velocity
is considered as a NoteOff.
\param inChannel The channel on which the message will be sent (1 to 16).
Take a look at the values, names and frequencies of notes here:
http://www.phys.unsw.edu.au/jw/notes.html
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendNoteOn(DataByte inNoteNumber,
DataByte inVelocity,
Channel inChannel)
{
send(NoteOn, inNoteNumber, inVelocity, inChannel);
}
/*! \brief Send a Note Off message
\param inNoteNumber Pitch value in the MIDI format (0 to 127).
\param inVelocity Release velocity (0 to 127).
\param inChannel The channel on which the message will be sent (1 to 16).
Note: you can send NoteOn with zero velocity to make a NoteOff, this is based
on the Running Status principle, to avoid sending status messages and thus
sending only NoteOn data. sendNoteOff will always send a real NoteOff message.
Take a look at the values, names and frequencies of notes here:
http://www.phys.unsw.edu.au/jw/notes.html
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendNoteOff(DataByte inNoteNumber,
DataByte inVelocity,
Channel inChannel)
{
send(NoteOff, inNoteNumber, inVelocity, inChannel);
}
/*! \brief Send a Program Change message
\param inProgramNumber The Program to select (0 to 127).
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendProgramChange(DataByte inProgramNumber,
Channel inChannel)
{
send(ProgramChange, inProgramNumber, 0, inChannel);
}
/*! \brief Send a Control Change message
\param inControlNumber The controller number (0 to 127).
\param inControlValue The value for the specified controller (0 to 127).
\param inChannel The channel on which the message will be sent (1 to 16).
@see MidiControlChangeNumber
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendControlChange(DataByte inControlNumber,
DataByte inControlValue,
Channel inChannel)
{
send(ControlChange, inControlNumber, inControlValue, inChannel);
}
/*! \brief Send a Polyphonic AfterTouch message (applies to a specified note)
\param inNoteNumber The note to apply AfterTouch to (0 to 127).
\param inPressure The amount of AfterTouch to apply (0 to 127).
\param inChannel The channel on which the message will be sent (1 to 16).
Note: this method is deprecated and will be removed in a future revision of the
library, @see sendAfterTouch to send polyphonic and monophonic AfterTouch messages.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendPolyPressure(DataByte inNoteNumber,
DataByte inPressure,
Channel inChannel)
{
send(AfterTouchPoly, inNoteNumber, inPressure, inChannel);
}
/*! \brief Send a MonoPhonic AfterTouch message (applies to all notes)
\param inPressure The amount of AfterTouch to apply to all notes.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendAfterTouch(DataByte inPressure,
Channel inChannel)
{
send(AfterTouchChannel, inPressure, 0, inChannel);
}
/*! \brief Send a Polyphonic AfterTouch message (applies to a specified note)
\param inNoteNumber The note to apply AfterTouch to (0 to 127).
\param inPressure The amount of AfterTouch to apply (0 to 127).
\param inChannel The channel on which the message will be sent (1 to 16).
@see Replaces sendPolyPressure (which is now deprecated).
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendAfterTouch(DataByte inNoteNumber,
DataByte inPressure,
Channel inChannel)
{
send(AfterTouchPoly, inNoteNumber, inPressure, inChannel);
}
/*! \brief Send a Pitch Bend message using a signed integer value.
\param inPitchValue The amount of bend to send (in a signed integer format),
between MIDI_PITCHBEND_MIN and MIDI_PITCHBEND_MAX,
center value is 0.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendPitchBend(int inPitchValue,
Channel inChannel)
{
const unsigned bend = unsigned(inPitchValue - int(MIDI_PITCHBEND_MIN));
send(PitchBend, (bend & 0x7f), (bend >> 7) & 0x7f, inChannel);
}
/*! \brief Send a Pitch Bend message using a floating point value.
\param inPitchValue The amount of bend to send (in a floating point format),
between -1.0f (maximum downwards bend)
and +1.0f (max upwards bend), center value is 0.0f.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendPitchBend(double inPitchValue,
Channel inChannel)
{
const int scale = inPitchValue > 0.0 ? MIDI_PITCHBEND_MAX : - MIDI_PITCHBEND_MIN;
const int value = int(inPitchValue * double(scale));
sendPitchBend(value, inChannel);
}
/*! \brief Generate and send a System Exclusive frame.
\param inLength The size of the array to send
\param inArray The byte array containing the data to send
\param inArrayContainsBoundaries When set to 'true', 0xf0 & 0xf7 bytes
(start & stop SysEx) will NOT be sent
(and therefore must be included in the array).
default value for ArrayContainsBoundaries is set to 'false' for compatibility
with previous versions of the library.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendSysEx(unsigned inLength,
const byte* inArray,
bool inArrayContainsBoundaries)
{
const bool writeBeginEndBytes = !inArrayContainsBoundaries;
if (mTransport.beginTransmission(MidiType::SystemExclusiveStart))
{
if (writeBeginEndBytes)
mTransport.write(MidiType::SystemExclusiveStart);
for (unsigned i = 0; i < inLength; ++i)
mTransport.write(inArray[i]);
if (writeBeginEndBytes)
mTransport.write(MidiType::SystemExclusiveEnd);
mTransport.endTransmission();
UpdateLastSentTime();
}
if (Settings::UseRunningStatus)
mRunningStatus_TX = InvalidType;
}
/*! \brief Send a Tune Request message.
When a MIDI unit receives this message,
it should tune its oscillators (if equipped with any).
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendTuneRequest()
{
sendCommon(TuneRequest);
}
/*! \brief Send a MIDI Time Code Quarter Frame.
\param inTypeNibble MTC type
\param inValuesNibble MTC data
See MIDI Specification for more information.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendTimeCodeQuarterFrame(DataByte inTypeNibble,
DataByte inValuesNibble)
{
const byte data = byte((((inTypeNibble & 0x07) << 4) | (inValuesNibble & 0x0f)));
sendTimeCodeQuarterFrame(data);
}
/*! \brief Send a MIDI Time Code Quarter Frame.
See MIDI Specification for more information.
\param inData if you want to encode directly the nibbles in your program,
you can send the byte here.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendTimeCodeQuarterFrame(DataByte inData)
{
sendCommon(TimeCodeQuarterFrame, inData);
}
/*! \brief Send a Song Position Pointer message.
\param inBeats The number of beats since the start of the song.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendSongPosition(unsigned inBeats)
{
sendCommon(SongPosition, inBeats);
}
/*! \brief Send a Song Select message */
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendSongSelect(DataByte inSongNumber)
{
sendCommon(SongSelect, inSongNumber);
}
/*! \brief Send a Common message. Common messages reset the running status.
\param inType The available Common types are:
TimeCodeQuarterFrame, SongPosition, SongSelect and TuneRequest.
@see MidiType
\param inData1 The byte that goes with the common message.
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendCommon(MidiType inType, unsigned inData1)
{
switch (inType)
{
case TimeCodeQuarterFrame:
case SongPosition:
case SongSelect:
case TuneRequest:
break;
default:
// Invalid Common marker
return;
}
if (mTransport.beginTransmission(inType))
{
mTransport.write((byte)inType);
switch (inType)
{
case TimeCodeQuarterFrame:
mTransport.write(inData1);
break;
case SongPosition:
mTransport.write(inData1 & 0x7f);
mTransport.write((inData1 >> 7) & 0x7f);
break;
case SongSelect:
mTransport.write(inData1 & 0x7f);
break;
case TuneRequest:
break;
default:
break; // LCOV_EXCL_LINE - Coverage blind spot
}
mTransport.endTransmission();
UpdateLastSentTime();
}
if (Settings::UseRunningStatus)
mRunningStatus_TX = InvalidType;
}
/*! \brief Send a Real Time (one byte) message.
\param inType The available Real Time types are:
Start, Stop, Continue, Clock, ActiveSensing and SystemReset.
@see MidiType
*/
template<class Transport, class Settings, class Platform>
void MidiInterface<Transport, Settings, Platform>::sendRealTime(MidiType inType)
{
// Do not invalidate Running Status for real-time messages
// as they can be interleaved within any message.
switch (inType)
{
case Clock:
case Start:
case Stop:
case Continue:
case ActiveSensing:
case SystemReset:
if (mTransport.beginTransmission(inType))
{
mTransport.write((byte)inType);
mTransport.endTransmission();
UpdateLastSentTime();
}
break;
default:
// Invalid Real Time marker
break;
}
}
/*! \brief Start a Registered Parameter Number frame.
\param inNumber The 14-bit number of the RPN you want to select.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::beginRpn(unsigned inNumber,
Channel inChannel)
{
if (mCurrentRpnNumber != inNumber)
{
const byte numMsb = 0x7f & (inNumber >> 7);
const byte numLsb = 0x7f & inNumber;
sendControlChange(RPNLSB, numLsb, inChannel);
sendControlChange(RPNMSB, numMsb, inChannel);
mCurrentRpnNumber = inNumber;
}
}
/*! \brief Send a 14-bit value for the currently selected RPN number.
\param inValue The 14-bit value of the selected RPN.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendRpnValue(unsigned inValue,
Channel inChannel)
{;
const byte valMsb = 0x7f & (inValue >> 7);
const byte valLsb = 0x7f & inValue;
sendControlChange(DataEntryMSB, valMsb, inChannel);
sendControlChange(DataEntryLSB, valLsb, inChannel);
}
/*! \brief Send separate MSB/LSB values for the currently selected RPN number.
\param inMsb The MSB part of the value to send. Meaning depends on RPN number.
\param inLsb The LSB part of the value to send. Meaning depends on RPN number.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendRpnValue(byte inMsb,
byte inLsb,
Channel inChannel)
{
sendControlChange(DataEntryMSB, inMsb, inChannel);
sendControlChange(DataEntryLSB, inLsb, inChannel);
}
/* \brief Increment the value of the currently selected RPN number by the specified amount.
\param inAmount The amount to add to the currently selected RPN value.
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendRpnIncrement(byte inAmount,
Channel inChannel)
{
sendControlChange(DataIncrement, inAmount, inChannel);
}
/* \brief Decrement the value of the currently selected RPN number by the specified amount.
\param inAmount The amount to subtract to the currently selected RPN value.
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendRpnDecrement(byte inAmount,
Channel inChannel)
{
sendControlChange(DataDecrement, inAmount, inChannel);
}
/*! \brief Terminate an RPN frame.
This will send a Null Function to deselect the currently selected RPN.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::endRpn(Channel inChannel)
{
sendControlChange(RPNLSB, 0x7f, inChannel);
sendControlChange(RPNMSB, 0x7f, inChannel);
mCurrentRpnNumber = 0xffff;
}
/*! \brief Start a Non-Registered Parameter Number frame.
\param inNumber The 14-bit number of the NRPN you want to select.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::beginNrpn(unsigned inNumber,
Channel inChannel)
{
if (mCurrentNrpnNumber != inNumber)
{
const byte numMsb = 0x7f & (inNumber >> 7);
const byte numLsb = 0x7f & inNumber;
sendControlChange(NRPNLSB, numLsb, inChannel);
sendControlChange(NRPNMSB, numMsb, inChannel);
mCurrentNrpnNumber = inNumber;
}
}
/*! \brief Send a 14-bit value for the currently selected NRPN number.
\param inValue The 14-bit value of the selected NRPN.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendNrpnValue(unsigned inValue,
Channel inChannel)
{;
const byte valMsb = 0x7f & (inValue >> 7);
const byte valLsb = 0x7f & inValue;
sendControlChange(DataEntryMSB, valMsb, inChannel);
sendControlChange(DataEntryLSB, valLsb, inChannel);
}
/*! \brief Send separate MSB/LSB values for the currently selected NRPN number.
\param inMsb The MSB part of the value to send. Meaning depends on NRPN number.
\param inLsb The LSB part of the value to send. Meaning depends on NRPN number.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendNrpnValue(byte inMsb,
byte inLsb,
Channel inChannel)
{
sendControlChange(DataEntryMSB, inMsb, inChannel);
sendControlChange(DataEntryLSB, inLsb, inChannel);
}
/* \brief Increment the value of the currently selected NRPN number by the specified amount.
\param inAmount The amount to add to the currently selected NRPN value.
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendNrpnIncrement(byte inAmount,
Channel inChannel)
{
sendControlChange(DataIncrement, inAmount, inChannel);
}
/* \brief Decrement the value of the currently selected NRPN number by the specified amount.
\param inAmount The amount to subtract to the currently selected NRPN value.
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::sendNrpnDecrement(byte inAmount,
Channel inChannel)
{
sendControlChange(DataDecrement, inAmount, inChannel);
}
/*! \brief Terminate an NRPN frame.
This will send a Null Function to deselect the currently selected NRPN.
\param inChannel The channel on which the message will be sent (1 to 16).
*/
template<class Transport, class Settings, class Platform>
inline void MidiInterface<Transport, Settings, Platform>::endNrpn(Channel inChannel)
{
sendControlChange(NRPNLSB, 0x7f, inChannel);
sendControlChange(NRPNMSB, 0x7f, inChannel);
mCurrentNrpnNumber = 0xffff;
}
/*! @} */ // End of doc group MIDI Output
// -----------------------------------------------------------------------------
template<class Transport, class Settings, class Platform>
StatusByte MidiInterface<Transport, Settings, Platform>::getStatus(MidiType inType,
Channel inChannel) const
{
return StatusByte(((byte)inType | ((inChannel - 1) & 0x0f)));
}
// -----------------------------------------------------------------------------
// Input
// -----------------------------------------------------------------------------
/*! \addtogroup input
@{
*/
/*! \brief Read messages from the serial port using the main input channel.
\return True if a valid message has been stored in the structure, false if not.
A valid message is a message that matches the input channel. \n\n
If the Thru is enabled and the message matches the filter,
it is sent back on the MIDI output.
@see see setInputChannel()
*/
template<class Transport, class Settings, class Platform>
inline bool MidiInterface<Transport, Settings, Platform>::read()
{
return read(mInputChannel);
}
/*! \brief Read messages on a specified channel.
*/
template<class Transport, class Settings, class Platform>
inline bool MidiInterface<Transport, Settings, Platform>::read(Channel inChannel)
{
#ifndef RegionActiveSending
// Active Sensing. This message is intended to be sent
// repeatedly to tell the receiver that a connection is alive. Use
// of this message is optional. When initially received, the
// receiver will expect to receive another Active Sensing
// message each 300ms (max), and if it does not then it will
// assume that the connection has been terminated. At
// termination, the receiver will turn off all voices and return to
// normal (non- active sensing) operation.
if (Settings::UseSenderActiveSensing && (mSenderActiveSensingPeriodicity > 0) && (Platform::now() - mLastMessageSentTime) > mSenderActiveSensingPeriodicity)
{
sendActiveSensing();
mLastMessageSentTime = Platform::now();
}
if (Settings::UseReceiverActiveSensing && mReceiverActiveSensingActivated && (mLastMessageReceivedTime + ActiveSensingTimeout < Platform::now()))
{
mReceiverActiveSensingActivated = false;
mLastError |= 1UL << ErrorActiveSensingTimeout; // set the ErrorActiveSensingTimeout bit
if (mErrorCallback)
mErrorCallback(mLastError);
}
#endif
if (inChannel >= MIDI_CHANNEL_OFF)
return false; // MIDI Input disabled.
if (!parse())
return false;
#ifndef RegionActiveSending
if (Settings::UseReceiverActiveSensing && mMessage.type == ActiveSensing)
{
// When an ActiveSensing message is received, the time keeping is activated.
// When a timeout occurs, an error message is send and time keeping ends.
mReceiverActiveSensingActivated = true;
// is ErrorActiveSensingTimeout bit in mLastError on
if (mLastError & (1 << (ErrorActiveSensingTimeout - 1)))
{
mLastError &= ~(1UL << ErrorActiveSensingTimeout); // clear the ErrorActiveSensingTimeout bit
if (mErrorCallback)
mErrorCallback(mLastError);
}
}
// Keep the time of the last received message, so we can check for the timeout
if (Settings::UseReceiverActiveSensing && mReceiverActiveSensingActivated)
mLastMessageReceivedTime = Platform::now();
#endif
handleNullVelocityNoteOnAsNoteOff();
const bool channelMatch = inputFilter(inChannel);
if (channelMatch)
launchCallback();
thruFilter(inChannel);
return channelMatch;
}
// -----------------------------------------------------------------------------
// Private method: MIDI parser
template<class Transport, class Settings, class Platform>
bool MidiInterface<Transport, Settings, Platform>::parse()
{
if (mTransport.available() == 0)
return false; // No data available.
// clear the ErrorParse bit
mLastError &= ~(1UL << ErrorParse);
// Parsing algorithm:
// Get a byte from the serial buffer.
// If there is no pending message to be recomposed, start a new one.
// - Find type and channel (if pertinent)
// - Look for other bytes in buffer, call parser recursively,
// until the message is assembled or the buffer is empty.
// Else, add the extracted byte to the pending message, and check validity.
// When the message is done, store it.
const byte extracted = mTransport.read();
// Ignore Undefined
if (extracted == Undefined_FD)
return (Settings::Use1ByteParsing) ? false : parse();
if (mPendingMessageIndex == 0)
{
// Start a new pending message
mPendingMessage[0] = extracted;
// Check for running status first
if (isChannelMessage(getTypeFromStatusByte(mRunningStatus_RX)))
{
// Only these types allow Running Status
// If the status byte is not received, prepend it
// to the pending message
if (extracted < 0x80)
{
mPendingMessage[0] = mRunningStatus_RX;
mPendingMessage[1] = extracted;
mPendingMessageIndex = 1;
}
// Else: well, we received another status byte,
// so the running status does not apply here.
// It will be updated upon completion of this message.
}
const MidiType pendingType = getTypeFromStatusByte(mPendingMessage[0]);
switch (pendingType)
{
// 1 byte messages
case Start:
case Continue:
case Stop:
case Clock:
case Tick:
case ActiveSensing:
case SystemReset:
case TuneRequest:
// Handle the message type directly here.
mMessage.type = pendingType;
mMessage.channel = 0;
mMessage.data1 = 0;
mMessage.data2 = 0;
mMessage.valid = true;
// Do not reset all input attributes, Running Status must remain unchanged.
// We still need to reset these
mPendingMessageIndex = 0;
mPendingMessageExpectedLength = 0;
return true;
break;
// 2 bytes messages
case ProgramChange:
case AfterTouchChannel:
case TimeCodeQuarterFrame:
case SongSelect:
mPendingMessageExpectedLength = 2;
break;
// 3 bytes messages
case NoteOn:
case NoteOff:
case ControlChange:
case PitchBend:
case AfterTouchPoly:
case SongPosition:
mPendingMessageExpectedLength = 3;
break;
case SystemExclusiveStart:
case SystemExclusiveEnd:
// The message can be any length
// between 3 and MidiMessage::sSysExMaxSize bytes
mPendingMessageExpectedLength = MidiMessage::sSysExMaxSize;
mRunningStatus_RX = InvalidType;
mMessage.sysexArray[0] = pendingType;
break;
case InvalidType:
default:
// This is obviously wrong. Let's get the hell out'a here.
mLastError |= 1UL << ErrorParse; // set the ErrorParse bit
if (mErrorCallback)
mErrorCallback(mLastError); // LCOV_EXCL_LINE
resetInput();
return false;
break;
}
if (mPendingMessageIndex >= (mPendingMessageExpectedLength - 1))
{
// Reception complete
mMessage.type = pendingType;
mMessage.channel = getChannelFromStatusByte(mPendingMessage[0]);
mMessage.data1 = mPendingMessage[1];
mMessage.data2 = 0; // Completed new message has 1 data byte
mMessage.length = 1;
mPendingMessageIndex = 0;
mPendingMessageExpectedLength = 0;
mMessage.valid = true;
return true;
}
else
{
// Waiting for more data
mPendingMessageIndex++;
}
return (Settings::Use1ByteParsing) ? false : parse();
}
else
{
// First, test if this is a status byte
if (extracted >= 0x80)
{
// Reception of status bytes in the middle of an uncompleted message
// are allowed only for interleaved Real Time message or EOX
switch (extracted)
{
case Clock:
case Start:
case Tick:
case Continue:
case Stop:
case ActiveSensing:
case SystemReset:
// Here we will have to extract the one-byte message,
// pass it to the structure for being read outside
// the MIDI class, and recompose the message it was
// interleaved into. Oh, and without killing the running status..
// This is done by leaving the pending message as is,
// it will be completed on next calls.
mMessage.type = (MidiType)extracted;
mMessage.data1 = 0;
mMessage.data2 = 0;
mMessage.channel = 0;
mMessage.length = 1;
mMessage.valid = true;
return true;
// Exclusive
case SystemExclusiveStart:
case SystemExclusiveEnd:
if ((mMessage.sysexArray[0] == SystemExclusiveStart)
|| (mMessage.sysexArray[0] == SystemExclusiveEnd))
{
// Store the last byte (EOX)
mMessage.sysexArray[mPendingMessageIndex++] = extracted;
mMessage.type = SystemExclusive;
// Get length
mMessage.data1 = mPendingMessageIndex & 0xff; // LSB
mMessage.data2 = byte(mPendingMessageIndex >> 8); // MSB
mMessage.channel = 0;
mMessage.length = mPendingMessageIndex;
mMessage.valid = true;
resetInput();
return true;
}
else
{
// Well well well.. error.
mLastError |= 1UL << ErrorParse; // set the error bits
if (mErrorCallback)
mErrorCallback(mLastError); // LCOV_EXCL_LINE
resetInput();
return false;
}
default:
break; // LCOV_EXCL_LINE - Coverage blind spot
}
}
// Add extracted data byte to pending message
if ((mPendingMessage[0] == SystemExclusiveStart)
|| (mPendingMessage[0] == SystemExclusiveEnd))
mMessage.sysexArray[mPendingMessageIndex] = extracted;
else
mPendingMessage[mPendingMessageIndex] = extracted;
// Now we are going to check if we have reached the end of the message
if (mPendingMessageIndex >= (mPendingMessageExpectedLength - 1))
{
// SysEx larger than the allocated buffer size,
// Split SysEx like so: