-
Notifications
You must be signed in to change notification settings - Fork 13
/
RtAudio.cpp
10891 lines (9403 loc) · 373 KB
/
RtAudio.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 RtAudio
\brief Realtime audio i/o C++ classes.
RtAudio provides a common API (Application Programming Interface)
for realtime audio input/output across Linux (native ALSA, Jack,
and OSS), Macintosh OS X (CoreAudio and Jack), and Windows
(DirectSound, ASIO and WASAPI) operating systems.
RtAudio GitHub site: https://github.com/thestk/rtaudio
RtAudio WWW site: http://www.music.mcgill.ca/~gary/rtaudio/
RtAudio: realtime audio i/o C++ classes
Copyright (c) 2001-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.
*/
/************************************************************************/
// RtAudio: Version 5.1.0
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cmath>
#include <algorithm>
// Static variable definitions.
const unsigned int RtApi::MAX_SAMPLE_RATES = 14;
const unsigned int RtApi::SAMPLE_RATES[] = {
4000, 5512, 8000, 9600, 11025, 16000, 22050,
32000, 44100, 48000, 88200, 96000, 176400, 192000
};
#if defined(__WINDOWS_DS__) || defined(__WINDOWS_ASIO__) || defined(__WINDOWS_WASAPI__)
#define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
#define MUTEX_DESTROY(A) DeleteCriticalSection(A)
#define MUTEX_LOCK(A) EnterCriticalSection(A)
#define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
#include "tchar.h"
template<typename T> inline
std::string convertCharPointerToStdString(const T *text);
template<> inline
std::string convertCharPointerToStdString(const char *text)
{
return std::string(text);
}
template<> inline
std::string convertCharPointerToStdString(const wchar_t *text)
{
int length = WideCharToMultiByte(CP_UTF8, 0, text, -1, NULL, 0, NULL, NULL);
std::string s( length-1, '\0' );
WideCharToMultiByte(CP_UTF8, 0, text, -1, &s[0], length, NULL, NULL);
return s;
}
#elif defined(__LINUX_ALSA__) || defined(__LINUX_PULSE__) || defined(__UNIX_JACK__) || defined(__LINUX_OSS__) || defined(__MACOSX_CORE__)
// pthread API
#define MUTEX_INITIALIZE(A) pthread_mutex_init(A, NULL)
#define MUTEX_DESTROY(A) pthread_mutex_destroy(A)
#define MUTEX_LOCK(A) pthread_mutex_lock(A)
#define MUTEX_UNLOCK(A) pthread_mutex_unlock(A)
#else
#define MUTEX_INITIALIZE(A) abs(*A) // dummy definitions
#define MUTEX_DESTROY(A) abs(*A) // dummy definitions
#endif
// *************************************************** //
//
// RtAudio definitions.
//
// *************************************************** //
std::string RtAudio :: getVersion( void )
{
return RTAUDIO_VERSION;
}
// Define API names and display names.
// Must be in same order as API enum.
extern "C" {
const char* rtaudio_api_names[][2] = {
{ "unspecified" , "Unknown" },
{ "alsa" , "ALSA" },
{ "pulse" , "Pulse" },
{ "oss" , "OpenSoundSystem" },
{ "jack" , "Jack" },
{ "core" , "CoreAudio" },
{ "wasapi" , "WASAPI" },
{ "asio" , "ASIO" },
{ "ds" , "DirectSound" },
{ "dummy" , "Dummy" },
};
const unsigned int rtaudio_num_api_names =
sizeof(rtaudio_api_names)/sizeof(rtaudio_api_names[0]);
// The order here will control the order of RtAudio's API search in
// the constructor.
extern "C" const RtAudio::Api rtaudio_compiled_apis[] = {
#if defined(__UNIX_JACK__)
RtAudio::UNIX_JACK,
#endif
#if defined(__LINUX_PULSE__)
RtAudio::LINUX_PULSE,
#endif
#if defined(__LINUX_ALSA__)
RtAudio::LINUX_ALSA,
#endif
#if defined(__LINUX_OSS__)
RtAudio::LINUX_OSS,
#endif
#if defined(__WINDOWS_ASIO__)
RtAudio::WINDOWS_ASIO,
#endif
#if defined(__WINDOWS_WASAPI__)
RtAudio::WINDOWS_WASAPI,
#endif
#if defined(__WINDOWS_DS__)
RtAudio::WINDOWS_DS,
#endif
#if defined(__MACOSX_CORE__)
RtAudio::MACOSX_CORE,
#endif
#if defined(__RTAUDIO_DUMMY__)
RtAudio::RTAUDIO_DUMMY,
#endif
RtAudio::UNSPECIFIED,
};
extern "C" const unsigned int rtaudio_num_compiled_apis =
sizeof(rtaudio_compiled_apis)/sizeof(rtaudio_compiled_apis[0])-1;
}
// This is a compile-time check that rtaudio_num_api_names == RtAudio::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<rtaudio_num_api_names == RtAudio::NUM_APIS>();
}};
void RtAudio :: getCompiledApi( std::vector<RtAudio::Api> &apis )
{
apis = std::vector<RtAudio::Api>(rtaudio_compiled_apis,
rtaudio_compiled_apis + rtaudio_num_compiled_apis);
}
std::string RtAudio :: getApiName( RtAudio::Api api )
{
if (api < 0 || api >= RtAudio::NUM_APIS)
return "";
return rtaudio_api_names[api][0];
}
std::string RtAudio :: getApiDisplayName( RtAudio::Api api )
{
if (api < 0 || api >= RtAudio::NUM_APIS)
return "Unknown";
return rtaudio_api_names[api][1];
}
RtAudio::Api RtAudio :: getCompiledApiByName( const std::string &name )
{
unsigned int i=0;
for (i = 0; i < rtaudio_num_compiled_apis; ++i)
if (name == rtaudio_api_names[rtaudio_compiled_apis[i]][0])
return rtaudio_compiled_apis[i];
return RtAudio::UNSPECIFIED;
}
void RtAudio :: openRtApi( RtAudio::Api api )
{
if ( rtapi_ )
delete rtapi_;
rtapi_ = 0;
#if defined(__UNIX_JACK__)
if ( api == UNIX_JACK )
rtapi_ = new RtApiJack();
#endif
#if defined(__LINUX_ALSA__)
if ( api == LINUX_ALSA )
rtapi_ = new RtApiAlsa();
#endif
#if defined(__LINUX_PULSE__)
if ( api == LINUX_PULSE )
rtapi_ = new RtApiPulse();
#endif
#if defined(__LINUX_OSS__)
if ( api == LINUX_OSS )
rtapi_ = new RtApiOss();
#endif
#if defined(__WINDOWS_ASIO__)
if ( api == WINDOWS_ASIO )
rtapi_ = new RtApiAsio();
#endif
#if defined(__WINDOWS_WASAPI__)
if ( api == WINDOWS_WASAPI )
rtapi_ = new RtApiWasapi();
#endif
#if defined(__WINDOWS_DS__)
if ( api == WINDOWS_DS )
rtapi_ = new RtApiDs();
#endif
#if defined(__MACOSX_CORE__)
if ( api == MACOSX_CORE )
rtapi_ = new RtApiCore();
#endif
#if defined(__RTAUDIO_DUMMY__)
if ( api == RTAUDIO_DUMMY )
rtapi_ = new RtApiDummy();
#endif
}
RtAudio :: RtAudio( RtAudio::Api api )
{
rtapi_ = 0;
if ( api != UNSPECIFIED ) {
// Attempt to open the specified API.
openRtApi( api );
if ( rtapi_ ) return;
// No compiled support for specified API value. Issue a debug
// warning and continue as if no API was specified.
std::cerr << "\nRtAudio: no compiled support for specified API argument!\n" << std::endl;
}
// Iterate through the compiled APIs and return as soon as we find
// one with at least one device or we reach the end of the list.
std::vector< RtAudio::Api > apis;
getCompiledApi( apis );
for ( unsigned int i=0; i<apis.size(); i++ ) {
openRtApi( apis[i] );
if ( rtapi_ && rtapi_->getDeviceCount() ) break;
}
if ( rtapi_ ) return;
// It should not be possible to get here because the preprocessor
// definition __RTAUDIO_DUMMY__ is automatically defined if no
// API-specific definitions are passed to the compiler. But just in
// case something weird happens, we'll thow an error.
std::string errorText = "\nRtAudio: no compiled API support found ... critical error!!\n\n";
throw( RtAudioError( errorText, RtAudioError::UNSPECIFIED ) );
}
RtAudio :: ~RtAudio()
{
if ( rtapi_ )
delete rtapi_;
}
void RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
RtAudio::StreamParameters *inputParameters,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options,
RtAudioErrorCallback errorCallback )
{
return rtapi_->openStream( outputParameters, inputParameters, format,
sampleRate, bufferFrames, callback,
userData, options, errorCallback );
}
// *************************************************** //
//
// Public RtApi definitions (see end of file for
// private or protected utility functions).
//
// *************************************************** //
RtApi :: RtApi()
{
stream_.state = STREAM_CLOSED;
stream_.mode = UNINITIALIZED;
stream_.apiHandle = 0;
stream_.userBuffer[0] = 0;
stream_.userBuffer[1] = 0;
MUTEX_INITIALIZE( &stream_.mutex );
showWarnings_ = true;
firstErrorOccurred_ = false;
}
RtApi :: ~RtApi()
{
MUTEX_DESTROY( &stream_.mutex );
}
void RtApi :: openStream( RtAudio::StreamParameters *oParams,
RtAudio::StreamParameters *iParams,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options,
RtAudioErrorCallback errorCallback )
{
if ( stream_.state != STREAM_CLOSED ) {
errorText_ = "RtApi::openStream: a stream is already open!";
error( RtAudioError::INVALID_USE );
return;
}
// Clear stream information potentially left from a previously open stream.
clearStreamInfo();
if ( oParams && oParams->nChannels < 1 ) {
errorText_ = "RtApi::openStream: a non-NULL output StreamParameters structure cannot have an nChannels value less than one.";
error( RtAudioError::INVALID_USE );
return;
}
if ( iParams && iParams->nChannels < 1 ) {
errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
error( RtAudioError::INVALID_USE );
return;
}
if ( oParams == NULL && iParams == NULL ) {
errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
error( RtAudioError::INVALID_USE );
return;
}
if ( formatBytes(format) == 0 ) {
errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
error( RtAudioError::INVALID_USE );
return;
}
unsigned int nDevices = getDeviceCount();
unsigned int oChannels = 0;
if ( oParams ) {
oChannels = oParams->nChannels;
if ( oParams->deviceId >= nDevices ) {
errorText_ = "RtApi::openStream: output device parameter value is invalid.";
error( RtAudioError::INVALID_USE );
return;
}
}
unsigned int iChannels = 0;
if ( iParams ) {
iChannels = iParams->nChannels;
if ( iParams->deviceId >= nDevices ) {
errorText_ = "RtApi::openStream: input device parameter value is invalid.";
error( RtAudioError::INVALID_USE );
return;
}
}
bool result;
if ( oChannels > 0 ) {
result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
sampleRate, format, bufferFrames, options );
if ( result == false ) {
error( RtAudioError::SYSTEM_ERROR );
return;
}
}
if ( iChannels > 0 ) {
result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
sampleRate, format, bufferFrames, options );
if ( result == false ) {
if ( oChannels > 0 ) closeStream();
error( RtAudioError::SYSTEM_ERROR );
return;
}
}
stream_.callbackInfo.callback = (void *) callback;
stream_.callbackInfo.userData = userData;
stream_.callbackInfo.errorCallback = (void *) errorCallback;
if ( options ) options->numberOfBuffers = stream_.nBuffers;
stream_.state = STREAM_STOPPED;
}
unsigned int RtApi :: getDefaultInputDevice( void )
{
// Should be implemented in subclasses if possible.
return 0;
}
unsigned int RtApi :: getDefaultOutputDevice( void )
{
// Should be implemented in subclasses if possible.
return 0;
}
void RtApi :: closeStream( void )
{
// MUST be implemented in subclasses!
return;
}
bool RtApi :: probeDeviceOpen( unsigned int /*device*/, StreamMode /*mode*/, unsigned int /*channels*/,
unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
RtAudio::StreamOptions * /*options*/ )
{
// MUST be implemented in subclasses!
return FAILURE;
}
void RtApi :: tickStreamTime( void )
{
// Subclasses that do not provide their own implementation of
// getStreamTime should call this function once per buffer I/O to
// provide basic stream time support.
stream_.streamTime += ( stream_.bufferSize * 1.0 / stream_.sampleRate );
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
}
long RtApi :: getStreamLatency( void )
{
verifyStream();
long totalLatency = 0;
if ( stream_.mode == OUTPUT || stream_.mode == DUPLEX )
totalLatency = stream_.latency[0];
if ( stream_.mode == INPUT || stream_.mode == DUPLEX )
totalLatency += stream_.latency[1];
return totalLatency;
}
double RtApi :: getStreamTime( void )
{
verifyStream();
#if defined( HAVE_GETTIMEOFDAY )
// Return a very accurate estimate of the stream time by
// adding in the elapsed time since the last tick.
struct timeval then;
struct timeval now;
if ( stream_.state != STREAM_RUNNING || stream_.streamTime == 0.0 )
return stream_.streamTime;
gettimeofday( &now, NULL );
then = stream_.lastTickTimestamp;
return stream_.streamTime +
((now.tv_sec + 0.000001 * now.tv_usec) -
(then.tv_sec + 0.000001 * then.tv_usec));
#else
return stream_.streamTime;
#endif
}
void RtApi :: setStreamTime( double time )
{
verifyStream();
if ( time >= 0.0 )
stream_.streamTime = time;
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
}
unsigned int RtApi :: getStreamSampleRate( void )
{
verifyStream();
return stream_.sampleRate;
}
// *************************************************** //
//
// OS/API-specific methods.
//
// *************************************************** //
#if defined(__MACOSX_CORE__)
// The OS X CoreAudio API is designed to use a separate callback
// procedure for each of its audio devices. A single RtAudio duplex
// stream using two different devices is supported here, though it
// cannot be guaranteed to always behave correctly because we cannot
// synchronize these two callbacks.
//
// A property listener is installed for over/underrun information.
// However, no functionality is currently provided to allow property
// listeners to trigger user handlers because it is unclear what could
// be done if a critical stream parameter (buffer size, sample rate,
// device disconnect) notification arrived. The listeners entail
// quite a bit of extra code and most likely, a user program wouldn't
// be prepared for the result anyway. However, we do provide a flag
// to the client callback function to inform of an over/underrun.
// A structure to hold various information related to the CoreAudio API
// implementation.
struct CoreHandle {
AudioDeviceID id[2]; // device ids
#if defined( MAC_OS_X_VERSION_10_5 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5 )
AudioDeviceIOProcID procId[2];
#endif
UInt32 iStream[2]; // device stream index (or first if using multiple)
UInt32 nStreams[2]; // number of streams to use
bool xrun[2];
char *deviceBuffer;
pthread_cond_t condition;
int drainCounter; // Tracks callback counts when draining
bool internalDrain; // Indicates if stop is initiated from callback or not.
CoreHandle()
:deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; xrun[0] = false; xrun[1] = false; }
};
RtApiCore:: RtApiCore()
{
#if defined( AVAILABLE_MAC_OS_X_VERSION_10_6_AND_LATER )
// This is a largely undocumented but absolutely necessary
// requirement starting with OS-X 10.6. If not called, queries and
// updates to various audio device properties are not handled
// correctly.
CFRunLoopRef theRunLoop = NULL;
AudioObjectPropertyAddress property = { kAudioHardwarePropertyRunLoop,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster };
OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
if ( result != noErr ) {
errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
error( RtAudioError::WARNING );
}
#endif
}
RtApiCore :: ~RtApiCore()
{
// The subclass destructor gets called before the base class
// destructor, so close an existing stream before deallocating
// apiDeviceId memory.
if ( stream_.state != STREAM_CLOSED ) closeStream();
}
unsigned int RtApiCore :: getDeviceCount( void )
{
// Find out how many audio devices there are, if any.
UInt32 dataSize;
AudioObjectPropertyAddress propertyAddress = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
OSStatus result = AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &propertyAddress, 0, NULL, &dataSize );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDeviceCount: OS-X error getting device info!";
error( RtAudioError::WARNING );
return 0;
}
return dataSize / sizeof( AudioDeviceID );
}
unsigned int RtApiCore :: getDefaultInputDevice( void )
{
unsigned int nDevices = getDeviceCount();
if ( nDevices <= 1 ) return 0;
AudioDeviceID id;
UInt32 dataSize = sizeof( AudioDeviceID );
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device.";
error( RtAudioError::WARNING );
return 0;
}
dataSize *= nDevices;
AudioDeviceID deviceList[ nDevices ];
property.mSelector = kAudioHardwarePropertyDevices;
result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDefaultInputDevice: OS-X system error getting device IDs.";
error( RtAudioError::WARNING );
return 0;
}
for ( unsigned int i=0; i<nDevices; i++ )
if ( id == deviceList[i] ) return i;
errorText_ = "RtApiCore::getDefaultInputDevice: No default device found!";
error( RtAudioError::WARNING );
return 0;
}
unsigned int RtApiCore :: getDefaultOutputDevice( void )
{
unsigned int nDevices = getDeviceCount();
if ( nDevices <= 1 ) return 0;
AudioDeviceID id;
UInt32 dataSize = sizeof( AudioDeviceID );
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, &id );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device.";
error( RtAudioError::WARNING );
return 0;
}
dataSize = sizeof( AudioDeviceID ) * nDevices;
AudioDeviceID deviceList[ nDevices ];
property.mSelector = kAudioHardwarePropertyDevices;
result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, &dataSize, (void *) &deviceList );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDefaultOutputDevice: OS-X system error getting device IDs.";
error( RtAudioError::WARNING );
return 0;
}
for ( unsigned int i=0; i<nDevices; i++ )
if ( id == deviceList[i] ) return i;
errorText_ = "RtApiCore::getDefaultOutputDevice: No default device found!";
error( RtAudioError::WARNING );
return 0;
}
RtAudio::DeviceInfo RtApiCore :: getDeviceInfo( unsigned int device )
{
RtAudio::DeviceInfo info;
info.probed = false;
// Get device ID
unsigned int nDevices = getDeviceCount();
if ( nDevices == 0 ) {
errorText_ = "RtApiCore::getDeviceInfo: no devices found!";
error( RtAudioError::INVALID_USE );
return info;
}
if ( device >= nDevices ) {
errorText_ = "RtApiCore::getDeviceInfo: device ID is invalid!";
error( RtAudioError::INVALID_USE );
return info;
}
AudioDeviceID deviceList[ nDevices ];
UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster };
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
0, NULL, &dataSize, (void *) &deviceList );
if ( result != noErr ) {
errorText_ = "RtApiCore::getDeviceInfo: OS-X system error getting device IDs.";
error( RtAudioError::WARNING );
return info;
}
AudioDeviceID id = deviceList[ device ];
// Get the device name.
info.name.erase();
CFStringRef cfname;
dataSize = sizeof( CFStringRef );
property.mSelector = kAudioObjectPropertyManufacturer;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device manufacturer.";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
//const char *mname = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
int length = CFStringGetLength(cfname);
char *mname = (char *)malloc(length * 3 + 1);
#if defined( UNICODE ) || defined( _UNICODE )
CFStringGetCString(cfname, mname, length * 3 + 1, kCFStringEncodingUTF8);
#else
CFStringGetCString(cfname, mname, length * 3 + 1, CFStringGetSystemEncoding());
#endif
info.name.append( (const char *)mname, strlen(mname) );
info.name.append( ": " );
CFRelease( cfname );
free(mname);
property.mSelector = kAudioObjectPropertyName;
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &cfname );
if ( result != noErr ) {
errorStream_ << "RtApiCore::probeDeviceInfo: system error (" << getErrorCode( result ) << ") getting device name.";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
//const char *name = CFStringGetCStringPtr( cfname, CFStringGetSystemEncoding() );
length = CFStringGetLength(cfname);
char *name = (char *)malloc(length * 3 + 1);
#if defined( UNICODE ) || defined( _UNICODE )
CFStringGetCString(cfname, name, length * 3 + 1, kCFStringEncodingUTF8);
#else
CFStringGetCString(cfname, name, length * 3 + 1, CFStringGetSystemEncoding());
#endif
info.name.append( (const char *)name, strlen(name) );
CFRelease( cfname );
free(name);
// Get the output stream "configuration".
AudioBufferList *bufferList = nil;
property.mSelector = kAudioDevicePropertyStreamConfiguration;
property.mScope = kAudioDevicePropertyScopeOutput;
// property.mElement = kAudioObjectPropertyElementWildcard;
dataSize = 0;
result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != noErr || dataSize == 0 ) {
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration info for device (" << device << ").";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *) malloc( dataSize );
if ( bufferList == NULL ) {
errorText_ = "RtApiCore::getDeviceInfo: memory error allocating output AudioBufferList.";
error( RtAudioError::WARNING );
return info;
}
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
if ( result != noErr || dataSize == 0 ) {
free( bufferList );
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting output stream configuration for device (" << device << ").";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
// Get output channel information.
unsigned int i, nStreams = bufferList->mNumberBuffers;
for ( i=0; i<nStreams; i++ )
info.outputChannels += bufferList->mBuffers[i].mNumberChannels;
free( bufferList );
// Get the input stream "configuration".
property.mScope = kAudioDevicePropertyScopeInput;
result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != noErr || dataSize == 0 ) {
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration info for device (" << device << ").";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *) malloc( dataSize );
if ( bufferList == NULL ) {
errorText_ = "RtApiCore::getDeviceInfo: memory error allocating input AudioBufferList.";
error( RtAudioError::WARNING );
return info;
}
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, bufferList );
if (result != noErr || dataSize == 0) {
free( bufferList );
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting input stream configuration for device (" << device << ").";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
// Get input channel information.
nStreams = bufferList->mNumberBuffers;
for ( i=0; i<nStreams; i++ )
info.inputChannels += bufferList->mBuffers[i].mNumberChannels;
free( bufferList );
// If device opens for both playback and capture, we determine the channels.
if ( info.outputChannels > 0 && info.inputChannels > 0 )
info.duplexChannels = (info.outputChannels > info.inputChannels) ? info.inputChannels : info.outputChannels;
// Probe the device sample rates.
bool isInput = false;
if ( info.outputChannels == 0 ) isInput = true;
// Determine the supported sample rates.
property.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
if ( isInput == false ) property.mScope = kAudioDevicePropertyScopeOutput;
result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != kAudioHardwareNoError || dataSize == 0 ) {
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rate info.";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
UInt32 nRanges = dataSize / sizeof( AudioValueRange );
AudioValueRange rangeList[ nRanges ];
result = AudioObjectGetPropertyData( id, &property, 0, NULL, &dataSize, &rangeList );
if ( result != kAudioHardwareNoError ) {
errorStream_ << "RtApiCore::getDeviceInfo: system error (" << getErrorCode( result ) << ") getting sample rates.";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
// The sample rate reporting mechanism is a bit of a mystery. It
// seems that it can either return individual rates or a range of
// rates. I assume that if the min / max range values are the same,
// then that represents a single supported rate and if the min / max
// range values are different, the device supports an arbitrary
// range of values (though there might be multiple ranges, so we'll
// use the most conservative range).
Float64 minimumRate = 1.0, maximumRate = 10000000000.0;
bool haveValueRange = false;
info.sampleRates.clear();
for ( UInt32 i=0; i<nRanges; i++ ) {
if ( rangeList[i].mMinimum == rangeList[i].mMaximum ) {
unsigned int tmpSr = (unsigned int) rangeList[i].mMinimum;
info.sampleRates.push_back( tmpSr );
if ( !info.preferredSampleRate || ( tmpSr <= 48000 && tmpSr > info.preferredSampleRate ) )
info.preferredSampleRate = tmpSr;
} else {
haveValueRange = true;
if ( rangeList[i].mMinimum > minimumRate ) minimumRate = rangeList[i].mMinimum;
if ( rangeList[i].mMaximum < maximumRate ) maximumRate = rangeList[i].mMaximum;
}
}
if ( haveValueRange ) {
for ( unsigned int k=0; k<MAX_SAMPLE_RATES; k++ ) {
if ( SAMPLE_RATES[k] >= (unsigned int) minimumRate && SAMPLE_RATES[k] <= (unsigned int) maximumRate ) {
info.sampleRates.push_back( SAMPLE_RATES[k] );
if ( !info.preferredSampleRate || ( SAMPLE_RATES[k] <= 48000 && SAMPLE_RATES[k] > info.preferredSampleRate ) )
info.preferredSampleRate = SAMPLE_RATES[k];
}
}
}
// Sort and remove any redundant values
std::sort( info.sampleRates.begin(), info.sampleRates.end() );
info.sampleRates.erase( unique( info.sampleRates.begin(), info.sampleRates.end() ), info.sampleRates.end() );
if ( info.sampleRates.size() == 0 ) {
errorStream_ << "RtApiCore::probeDeviceInfo: No supported sample rates found for device (" << device << ").";
errorText_ = errorStream_.str();
error( RtAudioError::WARNING );
return info;
}
// CoreAudio always uses 32-bit floating point data for PCM streams.
// Thus, any other "physical" formats supported by the device are of
// no interest to the client.
info.nativeFormats = RTAUDIO_FLOAT32;
if ( info.outputChannels > 0 )
if ( getDefaultOutputDevice() == device ) info.isDefaultOutput = true;
if ( info.inputChannels > 0 )
if ( getDefaultInputDevice() == device ) info.isDefaultInput = true;
info.probed = true;
return info;
}
static OSStatus callbackHandler( AudioDeviceID inDevice,
const AudioTimeStamp* /*inNow*/,
const AudioBufferList* inInputData,
const AudioTimeStamp* /*inInputTime*/,
AudioBufferList* outOutputData,
const AudioTimeStamp* /*inOutputTime*/,
void* infoPointer )
{
CallbackInfo *info = (CallbackInfo *) infoPointer;
RtApiCore *object = (RtApiCore *) info->object;
if ( object->callbackEvent( inDevice, inInputData, outOutputData ) == false )
return kAudioHardwareUnspecifiedError;
else
return kAudioHardwareNoError;
}
static OSStatus xrunListener( AudioObjectID /*inDevice*/,
UInt32 nAddresses,
const AudioObjectPropertyAddress properties[],
void* handlePointer )
{
CoreHandle *handle = (CoreHandle *) handlePointer;
for ( UInt32 i=0; i<nAddresses; i++ ) {
if ( properties[i].mSelector == kAudioDeviceProcessorOverload ) {
if ( properties[i].mScope == kAudioDevicePropertyScopeInput )
handle->xrun[1] = true;
else
handle->xrun[0] = true;
}
}
return kAudioHardwareNoError;
}
static OSStatus rateListener( AudioObjectID inDevice,
UInt32 /*nAddresses*/,
const AudioObjectPropertyAddress /*properties*/[],
void* ratePointer )
{
Float64 *rate = (Float64 *) ratePointer;
UInt32 dataSize = sizeof( Float64 );
AudioObjectPropertyAddress property = { kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster };
AudioObjectGetPropertyData( inDevice, &property, 0, NULL, &dataSize, rate );
return kAudioHardwareNoError;
}
bool RtApiCore :: probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options )
{
// Get device ID
unsigned int nDevices = getDeviceCount();
if ( nDevices == 0 ) {
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiCore::probeDeviceOpen: no devices found!";
return FAILURE;
}
if ( device >= nDevices ) {
// This should not happen because a check is made before this function is called.
errorText_ = "RtApiCore::probeDeviceOpen: device ID is invalid!";
return FAILURE;
}
AudioDeviceID deviceList[ nDevices ];
UInt32 dataSize = sizeof( AudioDeviceID ) * nDevices;
AudioObjectPropertyAddress property = { kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster };
OSStatus result = AudioObjectGetPropertyData( kAudioObjectSystemObject, &property,
0, NULL, &dataSize, (void *) &deviceList );
if ( result != noErr ) {
errorText_ = "RtApiCore::probeDeviceOpen: OS-X system error getting device IDs.";
return FAILURE;
}
AudioDeviceID id = deviceList[ device ];
// Setup for stream mode.
bool isInput = false;
if ( mode == INPUT ) {
isInput = true;
property.mScope = kAudioDevicePropertyScopeInput;
}
else
property.mScope = kAudioDevicePropertyScopeOutput;
// Get the stream "configuration".
AudioBufferList *bufferList = nil;
dataSize = 0;
property.mSelector = kAudioDevicePropertyStreamConfiguration;
result = AudioObjectGetPropertyDataSize( id, &property, 0, NULL, &dataSize );
if ( result != noErr || dataSize == 0 ) {
errorStream_ << "RtApiCore::probeDeviceOpen: system error (" << getErrorCode( result ) << ") getting stream configuration info for device (" << device << ").";
errorText_ = errorStream_.str();
return FAILURE;
}
// Allocate the AudioBufferList.
bufferList = (AudioBufferList *) malloc( dataSize );