forked from thestk/rtmidi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RtMidi.cpp
3774 lines (3213 loc) · 121 KB
/
RtMidi.cpp
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
/**********************************************************************/
/*! \class RtMidi
\brief An abstract base class for realtime MIDI input/output.
This class implements some common functionality for the realtime
MIDI input/output subclasses RtMidiIn and RtMidiOut.
RtMidi GitHub site: https://github.com/thestk/rtmidi
RtMidi WWW site: http://www.music.mcgill.ca/~gary/rtmidi/
RtMidi: realtime MIDI i/o C++ classes
Copyright (c) 2003-2019 Gary P. Scavone
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.
Any person wishing to distribute modifications to the Software is
asked to send the modifications to the original developer so that
they can be incorporated into the canonical version. This is,
however, not a binding provision of this license.
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.
*/
/**********************************************************************/
#include "RtMidi.h"
#include <sstream>
#if defined(__MACOSX_CORE__)
#if TARGET_OS_IPHONE
#define AudioGetCurrentHostTime CAHostTimeBase::GetCurrentTime
#define AudioConvertHostTimeToNanos CAHostTimeBase::ConvertToNanos
#endif
#endif
// Default for Windows is to add an identifier to the port names; this
// flag can be defined (e.g. in your project file) to disable this behaviour.
//#define RTMIDI_DO_NOT_ENSURE_UNIQUE_PORTNAMES
// **************************************************************** //
//
// MidiInApi and MidiOutApi subclass prototypes.
//
// **************************************************************** //
#if !defined(__LINUX_ALSA__) && !defined(__UNIX_JACK__) && !defined(__MACOSX_CORE__) && !defined(__WINDOWS_MM__)
#define __RTMIDI_DUMMY__
#endif
#if defined(__MACOSX_CORE__)
class MidiInCore: public MidiInApi
{
public:
MidiInCore( const std::string &clientName, unsigned int queueSizeLimit );
~MidiInCore( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::MACOSX_CORE; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName );
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
protected:
void initialize( const std::string& clientName );
};
class MidiOutCore: public MidiOutApi
{
public:
MidiOutCore( const std::string &clientName );
~MidiOutCore( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::MACOSX_CORE; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName );
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
void sendMessage( const unsigned char *message, size_t size );
protected:
void initialize( const std::string& clientName );
};
#endif
#if defined(__UNIX_JACK__)
class MidiInJack: public MidiInApi
{
public:
MidiInJack( const std::string &clientName, unsigned int queueSizeLimit );
~MidiInJack( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::UNIX_JACK; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName);
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
protected:
std::string clientName;
void connect( void );
void initialize( const std::string& clientName );
};
class MidiOutJack: public MidiOutApi
{
public:
MidiOutJack( const std::string &clientName );
~MidiOutJack( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::UNIX_JACK; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName);
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
void sendMessage( const unsigned char *message, size_t size );
protected:
std::string clientName;
void connect( void );
void initialize( const std::string& clientName );
};
#endif
#if defined(__LINUX_ALSA__)
class MidiInAlsa: public MidiInApi
{
public:
MidiInAlsa( const std::string &clientName, unsigned int queueSizeLimit );
~MidiInAlsa( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::LINUX_ALSA; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName);
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
protected:
void initialize( const std::string& clientName );
};
class MidiOutAlsa: public MidiOutApi
{
public:
MidiOutAlsa( const std::string &clientName );
~MidiOutAlsa( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::LINUX_ALSA; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName );
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
void sendMessage( const unsigned char *message, size_t size );
protected:
void initialize( const std::string& clientName );
};
#endif
#if defined(__WINDOWS_MM__)
class MidiInWinMM: public MidiInApi
{
public:
MidiInWinMM( const std::string &clientName, unsigned int queueSizeLimit );
~MidiInWinMM( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::WINDOWS_MM; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName );
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
protected:
void initialize( const std::string& clientName );
};
class MidiOutWinMM: public MidiOutApi
{
public:
MidiOutWinMM( const std::string &clientName );
~MidiOutWinMM( void );
RtMidi::Api getCurrentApi( void ) { return RtMidi::WINDOWS_MM; };
void openPort( unsigned int portNumber, const std::string &portName );
void openVirtualPort( const std::string &portName );
void closePort( void );
void setClientName( const std::string &clientName );
void setPortName( const std::string &portName );
unsigned int getPortCount( void );
std::string getPortName( unsigned int portNumber );
void sendMessage( const unsigned char *message, size_t size );
protected:
void initialize( const std::string& clientName );
};
#endif
#if defined(__RTMIDI_DUMMY__)
class MidiInDummy: public MidiInApi
{
public:
MidiInDummy( const std::string &/*clientName*/, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit ) { errorString_ = "MidiInDummy: This class provides no functionality."; error( RtMidiError::WARNING, errorString_ ); }
RtMidi::Api getCurrentApi( void ) { return RtMidi::RTMIDI_DUMMY; }
void openPort( unsigned int /*portNumber*/, const std::string &/*portName*/ ) {}
void openVirtualPort( const std::string &/*portName*/ ) {}
void closePort( void ) {}
void setClientName( const std::string &/*clientName*/ ) {};
void setPortName( const std::string &/*portName*/ ) {};
unsigned int getPortCount( void ) { return 0; }
std::string getPortName( unsigned int /*portNumber*/ ) { return ""; }
protected:
void initialize( const std::string& /*clientName*/ ) {}
};
class MidiOutDummy: public MidiOutApi
{
public:
MidiOutDummy( const std::string &/*clientName*/ ) { errorString_ = "MidiOutDummy: This class provides no functionality."; error( RtMidiError::WARNING, errorString_ ); }
RtMidi::Api getCurrentApi( void ) { return RtMidi::RTMIDI_DUMMY; }
void openPort( unsigned int /*portNumber*/, const std::string &/*portName*/ ) {}
void openVirtualPort( const std::string &/*portName*/ ) {}
void closePort( void ) {}
void setClientName( const std::string &/*clientName*/ ) {};
void setPortName( const std::string &/*portName*/ ) {};
unsigned int getPortCount( void ) { return 0; }
std::string getPortName( unsigned int /*portNumber*/ ) { return ""; }
void sendMessage( const unsigned char * /*message*/, size_t /*size*/ ) {}
protected:
void initialize( const std::string& /*clientName*/ ) {}
};
#endif
//*********************************************************************//
// RtMidi Definitions
//*********************************************************************//
RtMidi :: RtMidi()
: rtapi_(0)
{
}
RtMidi :: ~RtMidi()
{
delete rtapi_;
rtapi_ = 0;
}
std::string RtMidi :: getVersion( void ) throw()
{
return std::string( RTMIDI_VERSION );
}
// Define API names and display names.
// Must be in same order as API enum.
extern "C" {
const char* rtmidi_api_names[][2] = {
{ "unspecified" , "Unknown" },
{ "core" , "CoreMidi" },
{ "alsa" , "ALSA" },
{ "jack" , "Jack" },
{ "winmm" , "Windows MultiMedia" },
{ "dummy" , "Dummy" },
};
const unsigned int rtmidi_num_api_names =
sizeof(rtmidi_api_names)/sizeof(rtmidi_api_names[0]);
// The order here will control the order of RtMidi's API search in
// the constructor.
extern "C" const RtMidi::Api rtmidi_compiled_apis[] = {
#if defined(__MACOSX_CORE__)
RtMidi::MACOSX_CORE,
#endif
#if defined(__LINUX_ALSA__)
RtMidi::LINUX_ALSA,
#endif
#if defined(__UNIX_JACK__)
RtMidi::UNIX_JACK,
#endif
#if defined(__WINDOWS_MM__)
RtMidi::WINDOWS_MM,
#endif
#if defined(__RTMIDI_DUMMY__)
RtMidi::RTMIDI_DUMMY,
#endif
RtMidi::UNSPECIFIED,
};
extern "C" const unsigned int rtmidi_num_compiled_apis =
sizeof(rtmidi_compiled_apis)/sizeof(rtmidi_compiled_apis[0])-1;
}
// This is a compile-time check that rtmidi_num_api_names == RtMidi::NUM_APIS.
// If the build breaks here, check that they match.
template<bool b> class StaticAssert { private: StaticAssert() {} };
template<> class StaticAssert<true>{ public: StaticAssert() {} };
class StaticAssertions { StaticAssertions() {
StaticAssert<rtmidi_num_api_names == RtMidi::NUM_APIS>();
}};
void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw()
{
apis = std::vector<RtMidi::Api>(rtmidi_compiled_apis,
rtmidi_compiled_apis + rtmidi_num_compiled_apis);
}
std::string RtMidi :: getApiName( RtMidi::Api api )
{
if (api < 0 || api >= RtMidi::NUM_APIS)
return "";
return rtmidi_api_names[api][0];
}
std::string RtMidi :: getApiDisplayName( RtMidi::Api api )
{
if (api < 0 || api >= RtMidi::NUM_APIS)
return "Unknown";
return rtmidi_api_names[api][1];
}
RtMidi::Api RtMidi :: getCompiledApiByName( const std::string &name )
{
unsigned int i=0;
for (i = 0; i < rtmidi_num_compiled_apis; ++i)
if (name == rtmidi_api_names[rtmidi_compiled_apis[i]][0])
return rtmidi_compiled_apis[i];
return RtMidi::UNSPECIFIED;
}
void RtMidi :: setClientName( const std::string &clientName )
{
rtapi_->setClientName( clientName );
}
void RtMidi :: setPortName( const std::string &portName )
{
rtapi_->setPortName( portName );
}
//*********************************************************************//
// RtMidiIn Definitions
//*********************************************************************//
void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit )
{
delete rtapi_;
rtapi_ = 0;
#if defined(__UNIX_JACK__)
if ( api == UNIX_JACK )
rtapi_ = new MidiInJack( clientName, queueSizeLimit );
#endif
#if defined(__LINUX_ALSA__)
if ( api == LINUX_ALSA )
rtapi_ = new MidiInAlsa( clientName, queueSizeLimit );
#endif
#if defined(__WINDOWS_MM__)
if ( api == WINDOWS_MM )
rtapi_ = new MidiInWinMM( clientName, queueSizeLimit );
#endif
#if defined(__MACOSX_CORE__)
if ( api == MACOSX_CORE )
rtapi_ = new MidiInCore( clientName, queueSizeLimit );
#endif
#if defined(__RTMIDI_DUMMY__)
if ( api == RTMIDI_DUMMY )
rtapi_ = new MidiInDummy( clientName, queueSizeLimit );
#endif
}
RTMIDI_DLL_PUBLIC RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit )
: RtMidi()
{
if ( api != UNSPECIFIED ) {
// Attempt to open the specified API.
openMidiApi( api, clientName, queueSizeLimit );
if ( rtapi_ ) return;
// No compiled support for specified API value. Issue a warning
// and continue as if no API was specified.
std::cerr << "\nRtMidiIn: no compiled support for specified API argument!\n\n" << std::endl;
}
// Iterate through the compiled APIs and return as soon as we find
// one with at least one port or we reach the end of the list.
std::vector< RtMidi::Api > apis;
getCompiledApi( apis );
for ( unsigned int i=0; i<apis.size(); i++ ) {
openMidiApi( apis[i], clientName, queueSizeLimit );
if ( rtapi_ && rtapi_->getPortCount() ) break;
}
if ( rtapi_ ) return;
// It should not be possible to get here because the preprocessor
// definition __RTMIDI_DUMMY__ is automatically defined if no
// API-specific definitions are passed to the compiler. But just in
// case something weird happens, we'll throw an error.
std::string errorText = "RtMidiIn: no compiled API support found ... critical error!!";
throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
}
RtMidiIn :: ~RtMidiIn() throw()
{
}
//*********************************************************************//
// RtMidiOut Definitions
//*********************************************************************//
void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string &clientName )
{
delete rtapi_;
rtapi_ = 0;
#if defined(__UNIX_JACK__)
if ( api == UNIX_JACK )
rtapi_ = new MidiOutJack( clientName );
#endif
#if defined(__LINUX_ALSA__)
if ( api == LINUX_ALSA )
rtapi_ = new MidiOutAlsa( clientName );
#endif
#if defined(__WINDOWS_MM__)
if ( api == WINDOWS_MM )
rtapi_ = new MidiOutWinMM( clientName );
#endif
#if defined(__MACOSX_CORE__)
if ( api == MACOSX_CORE )
rtapi_ = new MidiOutCore( clientName );
#endif
#if defined(__RTMIDI_DUMMY__)
if ( api == RTMIDI_DUMMY )
rtapi_ = new MidiOutDummy( clientName );
#endif
}
RTMIDI_DLL_PUBLIC RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string &clientName)
{
if ( api != UNSPECIFIED ) {
// Attempt to open the specified API.
openMidiApi( api, clientName );
if ( rtapi_ ) return;
// No compiled support for specified API value. Issue a warning
// and continue as if no API was specified.
std::cerr << "\nRtMidiOut: no compiled support for specified API argument!\n\n" << std::endl;
}
// Iterate through the compiled APIs and return as soon as we find
// one with at least one port or we reach the end of the list.
std::vector< RtMidi::Api > apis;
getCompiledApi( apis );
for ( unsigned int i=0; i<apis.size(); i++ ) {
openMidiApi( apis[i], clientName );
if ( rtapi_ && rtapi_->getPortCount() ) break;
}
if ( rtapi_ ) return;
// It should not be possible to get here because the preprocessor
// definition __RTMIDI_DUMMY__ is automatically defined if no
// API-specific definitions are passed to the compiler. But just in
// case something weird happens, we'll thrown an error.
std::string errorText = "RtMidiOut: no compiled API support found ... critical error!!";
throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) );
}
RtMidiOut :: ~RtMidiOut() throw()
{
}
//*********************************************************************//
// Common MidiApi Definitions
//*********************************************************************//
MidiApi :: MidiApi( void )
: apiData_( 0 ), connected_( false ), errorCallback_(0), firstErrorOccurred_(false), errorCallbackUserData_(0)
{
}
MidiApi :: ~MidiApi( void )
{
}
void MidiApi :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData = 0 )
{
errorCallback_ = errorCallback;
errorCallbackUserData_ = userData;
}
void MidiApi :: error( RtMidiError::Type type, std::string errorString )
{
if ( errorCallback_ ) {
if ( firstErrorOccurred_ )
return;
firstErrorOccurred_ = true;
const std::string errorMessage = errorString;
errorCallback_( type, errorMessage, errorCallbackUserData_ );
firstErrorOccurred_ = false;
return;
}
if ( type == RtMidiError::WARNING ) {
std::cerr << '\n' << errorString << "\n\n";
}
else if ( type == RtMidiError::DEBUG_WARNING ) {
#if defined(__RTMIDI_DEBUG__)
std::cerr << '\n' << errorString << "\n\n";
#endif
}
else {
std::cerr << '\n' << errorString << "\n\n";
throw RtMidiError( errorString, type );
}
}
//*********************************************************************//
// Common MidiInApi Definitions
//*********************************************************************//
MidiInApi :: MidiInApi( unsigned int queueSizeLimit )
: MidiApi()
{
// Allocate the MIDI queue.
inputData_.queue.ringSize = queueSizeLimit;
if ( inputData_.queue.ringSize > 0 )
inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ];
}
MidiInApi :: ~MidiInApi( void )
{
// Delete the MIDI queue.
if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring;
}
void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData )
{
if ( inputData_.usingCallback ) {
errorString_ = "MidiInApi::setCallback: a callback function is already set!";
error( RtMidiError::WARNING, errorString_ );
return;
}
if ( !callback ) {
errorString_ = "RtMidiIn::setCallback: callback function value is invalid!";
error( RtMidiError::WARNING, errorString_ );
return;
}
inputData_.userCallback = callback;
inputData_.userData = userData;
inputData_.usingCallback = true;
}
void MidiInApi :: cancelCallback()
{
if ( !inputData_.usingCallback ) {
errorString_ = "RtMidiIn::cancelCallback: no callback function was set!";
error( RtMidiError::WARNING, errorString_ );
return;
}
inputData_.userCallback = 0;
inputData_.userData = 0;
inputData_.usingCallback = false;
}
void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense )
{
inputData_.ignoreFlags = 0;
if ( midiSysex ) inputData_.ignoreFlags = 0x01;
if ( midiTime ) inputData_.ignoreFlags |= 0x02;
if ( midiSense ) inputData_.ignoreFlags |= 0x04;
}
double MidiInApi :: getMessage( std::vector<unsigned char> *message )
{
message->clear();
if ( inputData_.usingCallback ) {
errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port.";
error( RtMidiError::WARNING, errorString_ );
return 0.0;
}
double timeStamp;
if ( !inputData_.queue.pop( message, &timeStamp ) )
return 0.0;
return timeStamp;
}
unsigned int MidiInApi::MidiQueue::size( unsigned int *__back,
unsigned int *__front )
{
// Access back/front members exactly once and make stack copies for
// size calculation
unsigned int _back = back, _front = front, _size;
if ( _back >= _front )
_size = _back - _front;
else
_size = ringSize - _front + _back;
// Return copies of back/front so no new and unsynchronized accesses
// to member variables are needed.
if ( __back ) *__back = _back;
if ( __front ) *__front = _front;
return _size;
}
// As long as we haven't reached our queue size limit, push the message.
bool MidiInApi::MidiQueue::push( const MidiInApi::MidiMessage& msg )
{
// Local stack copies of front/back
unsigned int _back, _front, _size;
// Get back/front indexes exactly once and calculate current size
_size = size( &_back, &_front );
if ( _size < ringSize-1 )
{
ring[_back] = msg;
back = (back+1)%ringSize;
return true;
}
return false;
}
bool MidiInApi::MidiQueue::pop( std::vector<unsigned char> *msg, double* timeStamp )
{
// Local stack copies of front/back
unsigned int _back, _front, _size;
// Get back/front indexes exactly once and calculate current size
_size = size( &_back, &_front );
if ( _size == 0 )
return false;
// Copy queued message to the vector pointer argument and then "pop" it.
msg->assign( ring[_front].bytes.begin(), ring[_front].bytes.end() );
*timeStamp = ring[_front].timeStamp;
// Update front
front = (front+1)%ringSize;
return true;
}
//*********************************************************************//
// Common MidiOutApi Definitions
//*********************************************************************//
MidiOutApi :: MidiOutApi( void )
: MidiApi()
{
}
MidiOutApi :: ~MidiOutApi( void )
{
}
// *************************************************** //
//
// OS/API-specific methods.
//
// *************************************************** //
#if defined(__MACOSX_CORE__)
// The CoreMIDI API is based on the use of a callback function for
// MIDI input. We convert the system specific time stamps to delta
// time values.
// OS-X CoreMIDI header files.
#include <CoreMIDI/CoreMIDI.h>
#include <CoreAudio/HostTime.h>
#include <CoreServices/CoreServices.h>
// A structure to hold variables related to the CoreMIDI API
// implementation.
struct CoreMidiData {
MIDIClientRef client;
MIDIPortRef port;
MIDIEndpointRef endpoint;
MIDIEndpointRef destinationId;
unsigned long long lastTime;
MIDISysexSendRequest sysexreq;
};
//*********************************************************************//
// API: OS-X
// Class Definitions: MidiInCore
//*********************************************************************//
static void midiInputCallback( const MIDIPacketList *list, void *procRef, void */*srcRef*/ )
{
MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef);
CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData);
unsigned char status;
unsigned short nBytes, iByte, size;
unsigned long long time;
bool& continueSysex = data->continueSysex;
MidiInApi::MidiMessage& message = data->message;
const MIDIPacket *packet = &list->packet[0];
for ( unsigned int i=0; i<list->numPackets; ++i ) {
// My interpretation of the CoreMIDI documentation: all message
// types, except sysex, are complete within a packet and there may
// be several of them in a single packet. Sysex messages can be
// broken across multiple packets and PacketLists but are bundled
// alone within each packet (these packets do not contain other
// message types). If sysex messages are split across multiple
// MIDIPacketLists, they must be handled by multiple calls to this
// function.
nBytes = packet->length;
if ( nBytes == 0 ) {
packet = MIDIPacketNext( packet );
continue;
}
// Calculate time stamp.
if ( data->firstMessage ) {
message.timeStamp = 0.0;
data->firstMessage = false;
}
else {
time = packet->timeStamp;
if ( time == 0 ) { // this happens when receiving asynchronous sysex messages
time = AudioGetCurrentHostTime();
}
time -= apiData->lastTime;
time = AudioConvertHostTimeToNanos( time );
if ( !continueSysex )
message.timeStamp = time * 0.000000001;
}
// Track whether any non-filtered messages were found in this
// packet for timestamp calculation
bool foundNonFiltered = false;
iByte = 0;
if ( continueSysex ) {
// We have a continuing, segmented sysex message.
if ( !( data->ignoreFlags & 0x01 ) ) {
// If we're not ignoring sysex messages, copy the entire packet.
for ( unsigned int j=0; j<nBytes; ++j )
message.bytes.push_back( packet->data[j] );
}
continueSysex = packet->data[nBytes-1] != 0xF7;
if ( !( data->ignoreFlags & 0x01 ) && !continueSysex ) {
// If not a continuing sysex message, invoke the user callback function or queue the message.
if ( data->usingCallback ) {
RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
callback( message.timeStamp, &message.bytes, data->userData );
}
else {
// As long as we haven't reached our queue size limit, push the message.
if ( !data->queue.push( message ) )
std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
}
message.bytes.clear();
}
}
else {
while ( iByte < nBytes ) {
size = 0;
// We are expecting that the next byte in the packet is a status byte.
status = packet->data[iByte];
if ( !(status & 0x80) ) break;
// Determine the number of bytes in the MIDI message.
if ( status < 0xC0 ) size = 3;
else if ( status < 0xE0 ) size = 2;
else if ( status < 0xF0 ) size = 3;
else if ( status == 0xF0 ) {
// A MIDI sysex
if ( data->ignoreFlags & 0x01 ) {
size = 0;
iByte = nBytes;
}
else size = nBytes - iByte;
continueSysex = packet->data[nBytes-1] != 0xF7;
}
else if ( status == 0xF1 ) {
// A MIDI time code message
if ( data->ignoreFlags & 0x02 ) {
size = 0;
iByte += 2;
}
else size = 2;
}
else if ( status == 0xF2 ) size = 3;
else if ( status == 0xF3 ) size = 2;
else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) {
// A MIDI timing tick message and we're ignoring it.
size = 0;
iByte += 1;
}
else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) {
// A MIDI active sensing message and we're ignoring it.
size = 0;
iByte += 1;
}
else size = 1;
// Copy the MIDI data to our vector.
if ( size ) {
foundNonFiltered = true;
message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] );
if ( !continueSysex ) {
// If not a continuing sysex message, invoke the user callback function or queue the message.
if ( data->usingCallback ) {
RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback;
callback( message.timeStamp, &message.bytes, data->userData );
}
else {
// As long as we haven't reached our queue size limit, push the message.
if ( !data->queue.push( message ) )
std::cerr << "\nMidiInCore: message queue limit reached!!\n\n";
}
message.bytes.clear();
}
iByte += size;
}
}
}
// Save the time of the last non-filtered message
if ( foundNonFiltered ) {
apiData->lastTime = packet->timeStamp;
if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages
apiData->lastTime = AudioGetCurrentHostTime();
}
}
packet = MIDIPacketNext(packet);
}
}
MidiInCore :: MidiInCore( const std::string &clientName, unsigned int queueSizeLimit )
: MidiInApi( queueSizeLimit )
{
MidiInCore::initialize( clientName );
}
MidiInCore :: ~MidiInCore( void )
{
// Close a connection if it exists.
MidiInCore::closePort();
// Cleanup.
CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
MIDIClientDispose( data->client );
if ( data->endpoint ) MIDIEndpointDispose( data->endpoint );
delete data;
}
void MidiInCore :: initialize( const std::string& clientName )
{
// Set up our client.
MIDIClientRef client;
CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII );
OSStatus result = MIDIClientCreate(name, NULL, NULL, &client );
if ( result != noErr ) {
std::ostringstream ost;
ost << "MidiInCore::initialize: error creating OS-X MIDI client object (" << result << ").";
errorString_ = ost.str();
error( RtMidiError::DRIVER_ERROR, errorString_ );
return;
}
// Save our api-specific connection information.
CoreMidiData *data = (CoreMidiData *) new CoreMidiData;
data->client = client;
data->endpoint = 0;
apiData_ = (void *) data;
inputData_.apiData = (void *) data;
CFRelease( name );
}
void MidiInCore :: openPort( unsigned int portNumber, const std::string &portName )
{
if ( connected_ ) {
errorString_ = "MidiInCore::openPort: a valid connection already exists!";
error( RtMidiError::WARNING, errorString_ );
return;
}
CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false );
unsigned int nSrc = MIDIGetNumberOfSources();
if ( nSrc < 1 ) {
errorString_ = "MidiInCore::openPort: no MIDI input sources found!";
error( RtMidiError::NO_DEVICES_FOUND, errorString_ );
return;
}
if ( portNumber >= nSrc ) {
std::ostringstream ost;
ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid.";
errorString_ = ost.str();
error( RtMidiError::INVALID_PARAMETER, errorString_ );
return;
}
MIDIPortRef port;
CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII );
OSStatus result = MIDIInputPortCreate( data->client,
portNameRef,
midiInputCallback, (void *)&inputData_, &port );
CFRelease( portNameRef );
if ( result != noErr ) {
MIDIClientDispose( data->client );
errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port.";
error( RtMidiError::DRIVER_ERROR, errorString_ );
return;
}
// Get the desired input source identifier.
MIDIEndpointRef endpoint = MIDIGetSource( portNumber );
if ( endpoint == 0 ) {
MIDIPortDispose( port );
MIDIClientDispose( data->client );
errorString_ = "MidiInCore::openPort: error getting MIDI input source reference.";
error( RtMidiError::DRIVER_ERROR, errorString_ );
return;
}
// Make the connection.
result = MIDIPortConnectSource( port, endpoint, NULL );
if ( result != noErr ) {
MIDIPortDispose( port );
MIDIClientDispose( data->client );
errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port.";
error( RtMidiError::DRIVER_ERROR, errorString_ );
return;
}
// Save our api-specific port information.
data->port = port;
connected_ = true;
}
void MidiInCore :: openVirtualPort( const std::string &portName )
{
CoreMidiData *data = static_cast<CoreMidiData *> (apiData_);
// Create a virtual MIDI input destination.
MIDIEndpointRef endpoint;