forked from thestk/rtaudio
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RtAudio.cpp
11534 lines (9982 loc) · 402 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-2023 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 6.0.1
#include "RtAudio.h"
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cmath>
#include <algorithm>
#include <codecvt>
#include <locale>
#if defined(_WIN32)
#include <windows.h>
#endif
// 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
};
template<typename T> inline
std::string convertCharPointerToStdString(const T *text);
template<> inline
std::string convertCharPointerToStdString(const char *text)
{
return text;
}
template<> inline
std::string convertCharPointerToStdString(const wchar_t *text)
{
return std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>>{}.to_bytes(text);
}
#if defined(_MSC_VER)
#define MUTEX_INITIALIZE(A) InitializeCriticalSection(A)
#define MUTEX_DESTROY(A) DeleteCriticalSection(A)
#define MUTEX_LOCK(A) EnterCriticalSection(A)
#define MUTEX_UNLOCK(A) LeaveCriticalSection(A)
#else
#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)
#endif
// *************************************************** //
//
// RtApi subclass prototypes.
//
// *************************************************** //
#if defined(__MACOSX_CORE__)
#include <CoreAudio/AudioHardware.h>
class RtApiCore: public RtApi
{
public:
RtApiCore();
~RtApiCore();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::MACOSX_CORE; }
unsigned int getDefaultOutputDevice( void ) override;
unsigned int getDefaultInputDevice( void ) override;
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by an internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
bool callbackEvent( AudioDeviceID deviceId,
const AudioBufferList *inBufferList,
const AudioBufferList *outBufferList );
private:
void probeDevices( void ) override;
bool probeDeviceInfo( AudioDeviceID id, RtAudio::DeviceInfo &info );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
static const char* getErrorCode( OSStatus code );
std::vector< AudioDeviceID > deviceIds_;
};
#endif
#if defined(__UNIX_JACK__)
#include <jack/jack.h>
class RtApiJack: public RtApi
{
public:
RtApiJack();
~RtApiJack();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::UNIX_JACK; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
bool callbackEvent( unsigned long nframes );
private:
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, jack_client_t *client );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
bool shouldAutoconnect_;
};
#endif
#if defined(__WINDOWS_ASIO__)
class RtApiAsio: public RtApi
{
public:
RtApiAsio();
~RtApiAsio();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::WINDOWS_ASIO; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
bool callbackEvent( long bufferIndex );
private:
bool coInitialized_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info );
bool probeDeviceOpen( unsigned int device, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__WINDOWS_DS__)
class RtApiDs: public RtApi
{
public:
RtApiDs();
~RtApiDs();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::WINDOWS_DS; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
private:
bool coInitialized_;
bool buffersRolling;
long duplexPrerollBytes;
std::vector<struct DsDevice> dsDevices_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, DsDevice &dsDevice );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__WINDOWS_WASAPI__)
struct IMMDeviceEnumerator;
class RtApiWasapi : public RtApi
{
public:
RtApiWasapi();
virtual ~RtApiWasapi();
RtAudio::Api getCurrentApi( void ) override { return RtAudio::WINDOWS_WASAPI; }
unsigned int getDefaultOutputDevice( void ) override;
unsigned int getDefaultInputDevice( void ) override;
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
private:
bool coInitialized_;
IMMDeviceEnumerator* deviceEnumerator_;
std::vector< std::pair< std::string, bool> > deviceIds_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, LPWSTR deviceId, bool isCaptureDevice );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int* bufferSize,
RtAudio::StreamOptions* options ) override;
static DWORD WINAPI runWasapiThread( void* wasapiPtr );
static DWORD WINAPI stopWasapiThread( void* wasapiPtr );
static DWORD WINAPI abortWasapiThread( void* wasapiPtr );
void wasapiThread();
};
#endif
#if defined(__LINUX_ALSA__)
class RtApiAlsa: public RtApi
{
public:
RtApiAlsa();
~RtApiAlsa();
RtAudio::Api getCurrentApi() override { return RtAudio::LINUX_ALSA; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
private:
std::vector<std::pair<std::string, unsigned int>> deviceIdPairs_;
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, std::string name );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__LINUX_PULSE__)
#include <pulse/pulseaudio.h>
class RtApiPulse: public RtApi
{
public:
~RtApiPulse();
RtAudio::Api getCurrentApi() override { return RtAudio::LINUX_PULSE; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
struct PaDeviceInfo {
std::string sinkName;
std::string sourceName;
};
private:
std::vector< PaDeviceInfo > paDeviceList_;
void probeDevices( void ) override;
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__LINUX_OSS__)
#include <sys/soundcard.h>
class RtApiOss: public RtApi
{
public:
RtApiOss();
~RtApiOss();
RtAudio::Api getCurrentApi() override { return RtAudio::LINUX_OSS; }
void closeStream( void ) override;
RtAudioErrorType startStream( void ) override;
RtAudioErrorType stopStream( void ) override;
RtAudioErrorType abortStream( void ) override;
// This function is intended for internal use only. It must be
// public because it is called by the internal callback handler,
// which is not a member of RtAudio. External use of this function
// will most likely produce highly undesirable results!
void callbackEvent( void );
private:
void probeDevices( void ) override;
bool probeDeviceInfo( RtAudio::DeviceInfo &info, oss_audioinfo &ainfo );
bool probeDeviceOpen( unsigned int deviceId, StreamMode mode, unsigned int channels,
unsigned int firstChannel, unsigned int sampleRate,
RtAudioFormat format, unsigned int *bufferSize,
RtAudio::StreamOptions *options ) override;
};
#endif
#if defined(__RTAUDIO_DUMMY__)
class RtApiDummy: public RtApi
{
public:
RtApiDummy() { errorText_ = "RtApiDummy: This class provides no functionality."; error( RTAUDIO_WARNING ); }
RtAudio::Api getCurrentApi( void ) override { return RtAudio::RTAUDIO_DUMMY; }
void closeStream( void ) override {}
RtAudioErrorType startStream( void ) override { return RTAUDIO_NO_ERROR; }
RtAudioErrorType stopStream( void ) override { return RTAUDIO_NO_ERROR; }
RtAudioErrorType abortStream( void ) override { return RTAUDIO_NO_ERROR; }
private:
bool probeDeviceOpen( unsigned int /*deviceId*/, StreamMode /*mode*/, unsigned int /*channels*/,
unsigned int /*firstChannel*/, unsigned int /*sampleRate*/,
RtAudioFormat /*format*/, unsigned int * /*bufferSize*/,
RtAudio::StreamOptions * /*options*/ ) override { return false; }
};
#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" },
{ "core" , "CoreAudio" },
{ "alsa" , "ALSA" },
{ "jack" , "Jack" },
{ "pulse" , "Pulse" },
{ "oss" , "OpenSoundSystem" },
{ "asio" , "ASIO" },
{ "wasapi" , "WASAPI" },
{ "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(__MACOSX_CORE__)
RtAudio::MACOSX_CORE,
#endif
#if defined(__LINUX_ALSA__)
RtAudio::LINUX_ALSA,
#endif
#if defined(__UNIX_JACK__)
RtAudio::UNIX_JACK,
#endif
#if defined(__LINUX_PULSE__)
RtAudio::LINUX_PULSE,
#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(__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;
}
RtAudio::Api RtAudio :: getCompiledApiByDisplayName( 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]][1])
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, RtAudioErrorCallback&& errorCallback )
{
rtapi_ = 0;
std::string errorMessage;
if ( api != UNSPECIFIED ) {
// Attempt to open the specified API.
openRtApi( api );
if ( rtapi_ ) {
if ( errorCallback ) rtapi_->setErrorCallback( errorCallback );
return;
}
// No compiled support for specified API value. Issue a warning
// and continue as if no API was specified.
errorMessage = "RtAudio: no compiled support for specified API argument!";
if ( errorCallback )
errorCallback( RTAUDIO_INVALID_USE, errorMessage );
else
std::cerr << '\n' << errorMessage << '\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_->getDeviceNames()).size() > 0 )
break;
}
if ( rtapi_ ) {
if ( errorCallback ) rtapi_->setErrorCallback( errorCallback );
return;
}
// It should not be possible to get here because the preprocessor
// definition __RTAUDIO_DUMMY__ is automatically defined in RtAudio.h
// if no API-specific definitions are passed to the compiler. But just
// in case something weird happens, issue an error message and abort.
errorMessage = "RtAudio: no compiled API support found ... critical error!";
if ( errorCallback )
errorCallback( RTAUDIO_INVALID_USE, errorMessage );
else
std::cerr << '\n' << errorMessage << '\n' << std::endl;
abort();
}
RtAudio :: ~RtAudio()
{
if ( rtapi_ )
delete rtapi_;
}
RtAudioErrorType RtAudio :: openStream( RtAudio::StreamParameters *outputParameters,
RtAudio::StreamParameters *inputParameters,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options )
{
return rtapi_->openStream( outputParameters, inputParameters, format,
sampleRate, bufferFrames, callback,
userData, options );
}
// *************************************************** //
//
// Public RtApi definitions (see end of file for
// private or protected utility functions).
//
// *************************************************** //
RtApi :: RtApi()
{
clearStreamInfo();
MUTEX_INITIALIZE( &stream_.mutex );
errorCallback_ = 0;
showWarnings_ = true;
currentDeviceId_ = 129;
}
RtApi :: ~RtApi()
{
MUTEX_DESTROY( &stream_.mutex );
}
RtAudioErrorType RtApi :: openStream( RtAudio::StreamParameters *oParams,
RtAudio::StreamParameters *iParams,
RtAudioFormat format, unsigned int sampleRate,
unsigned int *bufferFrames,
RtAudioCallback callback, void *userData,
RtAudio::StreamOptions *options )
{
if ( stream_.state != STREAM_CLOSED ) {
errorText_ = "RtApi::openStream: a stream is already open!";
return error( RTAUDIO_INVALID_USE );
}
// 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.";
return error( RTAUDIO_INVALID_PARAMETER );
}
if ( iParams && iParams->nChannels < 1 ) {
errorText_ = "RtApi::openStream: a non-NULL input StreamParameters structure cannot have an nChannels value less than one.";
return error( RTAUDIO_INVALID_PARAMETER );
}
if ( oParams == NULL && iParams == NULL ) {
errorText_ = "RtApi::openStream: input and output StreamParameters structures are both NULL!";
return error( RTAUDIO_INVALID_PARAMETER );
}
if ( formatBytes(format) == 0 ) {
errorText_ = "RtApi::openStream: 'format' parameter value is undefined.";
return error( RTAUDIO_INVALID_PARAMETER );
}
// Scan devices if none currently listed.
if ( deviceList_.size() == 0 ) probeDevices();
unsigned int m, oChannels = 0;
if ( oParams ) {
oChannels = oParams->nChannels;
// Verify that the oParams->deviceId is found in our list
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == oParams->deviceId ) break;
}
if ( m == deviceList_.size() ) {
errorText_ = "RtApi::openStream: output device ID is invalid.";
return error( RTAUDIO_INVALID_PARAMETER );
}
}
unsigned int iChannels = 0;
if ( iParams ) {
iChannels = iParams->nChannels;
for ( m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == iParams->deviceId ) break;
}
if ( m == deviceList_.size() ) {
errorText_ = "RtApi::openStream: input device ID is invalid.";
return error( RTAUDIO_INVALID_PARAMETER );
}
}
bool result;
if ( oChannels > 0 ) {
result = probeDeviceOpen( oParams->deviceId, OUTPUT, oChannels, oParams->firstChannel,
sampleRate, format, bufferFrames, options );
if ( result == false )
return error( RTAUDIO_SYSTEM_ERROR );
}
if ( iChannels > 0 ) {
result = probeDeviceOpen( iParams->deviceId, INPUT, iChannels, iParams->firstChannel,
sampleRate, format, bufferFrames, options );
if ( result == false )
return error( RTAUDIO_SYSTEM_ERROR );
}
stream_.callbackInfo.callback = (void *) callback;
stream_.callbackInfo.userData = userData;
if ( options ) options->numberOfBuffers = stream_.nBuffers;
stream_.state = STREAM_STOPPED;
return RTAUDIO_NO_ERROR;
}
void RtApi :: probeDevices( void )
{
// This function MUST be implemented in all subclasses! Within each
// API, this function will be used to:
// - enumerate the devices and fill or update our
// std::vector< RtAudio::DeviceInfo> deviceList_ class variable
// - store corresponding (usually API-specific) identifiers that
// are needed to open each device
// - make sure that the default devices are properly identified
// within the deviceList_ (unless API-specific functions are
// available for this purpose).
//
// The function should not reprobe devices that have already been
// found. The function must properly handle devices that are removed
// or added.
//
// Ideally, we would also configure callback functions to be invoked
// when devices are added or removed (which could be used to inform
// clients about changes). However, none of the APIs currently
// support notification of _new_ devices and I don't see the
// usefulness of having this work only for device removal.
return;
}
unsigned int RtApi :: getDeviceCount( void )
{
probeDevices();
return (unsigned int)deviceList_.size();
}
std::vector<unsigned int> RtApi :: getDeviceIds( void )
{
probeDevices();
// Copy device IDs into output vector.
std::vector<unsigned int> deviceIds;
for ( unsigned int m=0; m<deviceList_.size(); m++ )
deviceIds.push_back( deviceList_[m].ID );
return deviceIds;
}
std::vector<std::string> RtApi :: getDeviceNames( void )
{
probeDevices();
// Copy device names into output vector.
std::vector<std::string> deviceNames;
for ( unsigned int m=0; m<deviceList_.size(); m++ )
deviceNames.push_back( deviceList_[m].name );
return deviceNames;
}
unsigned int RtApi :: getDefaultInputDevice( void )
{
// Should be reimplemented in subclasses if necessary.
if ( deviceList_.size() == 0 ) probeDevices();
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].isDefaultInput )
return deviceList_[i].ID;
}
// If not found, find the first device with input channels, set it
// as the default, and return the ID.
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].inputChannels > 0 ) {
deviceList_[i].isDefaultInput = true;
return deviceList_[i].ID;
}
}
return 0;
}
unsigned int RtApi :: getDefaultOutputDevice( void )
{
// Should be reimplemented in subclasses if necessary.
if ( deviceList_.size() == 0 ) probeDevices();
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].isDefaultOutput )
return deviceList_[i].ID;
}
// If not found, find the first device with output channels, set it
// as the default, and return the ID.
for ( unsigned int i = 0; i < deviceList_.size(); i++ ) {
if ( deviceList_[i].outputChannels > 0 ) {
deviceList_[i].isDefaultOutput = true;
return deviceList_[i].ID;
}
}
return 0;
}
RtAudio::DeviceInfo RtApi :: getDeviceInfo( unsigned int deviceId )
{
if ( deviceList_.size() == 0 ) probeDevices();
for ( unsigned int m=0; m<deviceList_.size(); m++ ) {
if ( deviceList_[m].ID == deviceId )
return deviceList_[m];
}
errorText_ = "RtApi::getDeviceInfo: deviceId argument not found.";
error( RTAUDIO_INVALID_PARAMETER );
return RtAudio::DeviceInfo();
}
void RtApi :: closeStream( void )
{
// MUST be implemented in subclasses!
return;
}
bool RtApi :: probeDeviceOpen( unsigned int /*deviceId*/, 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 )
{
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 )
{
#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 )
{
if ( time >= 0.0 )
stream_.streamTime = time;
/*
#if defined( HAVE_GETTIMEOFDAY )
gettimeofday( &stream_.lastTickTimestamp, NULL );
#endif
*/
}
unsigned int RtApi :: getStreamSampleRate( void )
{
if ( isStreamOpen() ) return stream_.sampleRate;
else return 0;
}
// *************************************************** //
//
// OS/API-specific methods.
//
// *************************************************** //
#if defined(__MACOSX_CORE__)
#include <unistd.h>
// 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.
bool xrunListenerAdded[2];
bool disconnectListenerAdded[2];
CoreHandle()
:deviceBuffer(0), drainCounter(0), internalDrain(false) { nStreams[0] = 1; nStreams[1] = 1; id[0] = 0; id[1] = 0; procId[0] = 0; procId[1] = 0; xrun[0] = false; xrun[1] = false; xrunListenerAdded[0] = false; xrunListenerAdded[1] = false; disconnectListenerAdded[0] = false; disconnectListenerAdded[1] = false; }
};
#if defined( MAC_OS_VERSION_12_0 ) && ( MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_VERSION_12_0 )
#define KAUDIOOBJECTPROPERTYELEMENT kAudioObjectPropertyElementMain
#else
#define KAUDIOOBJECTPROPERTYELEMENT kAudioObjectPropertyElementMaster // deprecated with macOS 12
#endif
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,
KAUDIOOBJECTPROPERTYELEMENT };
OSStatus result = AudioObjectSetPropertyData( kAudioObjectSystemObject, &property, 0, NULL, sizeof(CFRunLoopRef), &theRunLoop);
if ( result != noErr ) {
errorText_ = "RtApiCore::RtApiCore: error setting run loop property!";
error( RTAUDIO_SYSTEM_ERROR );
}
#endif