-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
juce_CoreAudio_mac.cpp
2329 lines (1850 loc) · 88 KB
/
juce_CoreAudio_mac.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
/*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2022 - Raw Material Software Limited
JUCE is an open source library subject to commercial or open-source
licensing.
The code included in this file is provided under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license. Permission
To use, copy, modify, and/or distribute this software for any purpose with or
without fee is hereby granted provided that the above copyright notice and
this permission notice appear in all copies.
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include <juce_audio_basics/native/juce_CoreAudioTimeConversions_mac.h>
#include <juce_audio_basics/native/juce_AudioWorkgroup_mac.h>
namespace juce
{
#if JUCE_COREAUDIO_LOGGING_ENABLED
#define JUCE_COREAUDIOLOG(a) { String camsg ("CoreAudio: "); camsg << a; Logger::writeToLog (camsg); }
#else
#define JUCE_COREAUDIOLOG(a)
#endif
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wnonnull")
constexpr auto juceAudioObjectPropertyElementMain =
#if defined (MAC_OS_VERSION_12_0)
kAudioObjectPropertyElementMain;
#else
kAudioObjectPropertyElementMaster;
#endif
//==============================================================================
class ManagedAudioBufferList : public AudioBufferList
{
public:
struct Deleter
{
void operator() (ManagedAudioBufferList* p) const
{
if (p != nullptr)
p->~ManagedAudioBufferList();
delete[] reinterpret_cast<std::byte*> (p);
}
};
using Ref = std::unique_ptr<ManagedAudioBufferList, Deleter>;
//==============================================================================
static Ref create (std::size_t numBuffers)
{
static_assert (alignof (ManagedAudioBufferList) <= alignof (std::max_align_t));
if (std::unique_ptr<std::byte[]> storage { new std::byte[storageSizeForNumBuffers (numBuffers)] })
return Ref { new (storage.release()) ManagedAudioBufferList (numBuffers) };
return nullptr;
}
//==============================================================================
static std::size_t storageSizeForNumBuffers (std::size_t numBuffers) noexcept
{
return audioBufferListHeaderSize + (numBuffers * sizeof (::AudioBuffer));
}
static std::size_t numBuffersForStorageSize (std::size_t bytes) noexcept
{
bytes -= audioBufferListHeaderSize;
// storage size ends between to buffers in AudioBufferList
jassert ((bytes % sizeof (::AudioBuffer)) == 0);
return bytes / sizeof (::AudioBuffer);
}
private:
// Do not call the base constructor here as this will zero-initialize the first buffer,
// for which no storage may be available though (when numBuffers == 0).
explicit ManagedAudioBufferList (std::size_t numBuffers)
{
mNumberBuffers = static_cast<UInt32> (numBuffers);
}
static constexpr auto audioBufferListHeaderSize = sizeof (AudioBufferList) - sizeof (::AudioBuffer);
JUCE_DECLARE_NON_COPYABLE (ManagedAudioBufferList)
JUCE_DECLARE_NON_MOVEABLE (ManagedAudioBufferList)
};
//==============================================================================
struct IgnoreUnused
{
template <typename... Ts>
void operator() (Ts&&...) const {}
};
template <typename T>
static auto getDataPtrAndSize (T& t)
{
static_assert (std::is_pod_v<T>);
return std::make_tuple (&t, (UInt32) sizeof (T));
}
static auto getDataPtrAndSize (ManagedAudioBufferList::Ref& t)
{
const auto size = t.get() != nullptr
? ManagedAudioBufferList::storageSizeForNumBuffers (t->mNumberBuffers)
: 0;
return std::make_tuple (t.get(), (UInt32) size);
}
//==============================================================================
[[nodiscard]] static bool audioObjectHasProperty (AudioObjectID objectID, const AudioObjectPropertyAddress address)
{
return objectID != kAudioObjectUnknown && AudioObjectHasProperty (objectID, &address);
}
template <typename T, typename OnError = IgnoreUnused>
[[nodiscard]] static auto audioObjectGetProperty (AudioObjectID objectID,
const AudioObjectPropertyAddress address,
OnError&& onError = {})
{
using Result = std::conditional_t<std::is_same_v<T, AudioBufferList>, ManagedAudioBufferList::Ref, std::optional<T>>;
if (! audioObjectHasProperty (objectID, address))
return Result{};
auto result = [&]
{
if constexpr (std::is_same_v<T, AudioBufferList>)
{
UInt32 size{};
if (auto status = AudioObjectGetPropertyDataSize (objectID, &address, 0, nullptr, &size); status != noErr)
{
onError (status);
return Result{};
}
return ManagedAudioBufferList::create (ManagedAudioBufferList::numBuffersForStorageSize (size));
}
else
{
return T{};
}
}();
auto [ptr, size] = getDataPtrAndSize (result);
if (size == 0)
return Result{};
if (auto status = AudioObjectGetPropertyData (objectID, &address, 0, nullptr, &size, ptr); status != noErr)
{
onError (status);
return Result{};
}
return Result { std::move (result) };
}
template <typename T, typename OnError = IgnoreUnused>
static bool audioObjectSetProperty (AudioObjectID objectID,
const AudioObjectPropertyAddress address,
const T value,
OnError&& onError = {})
{
if (! audioObjectHasProperty (objectID, address))
return false;
Boolean isSettable = NO;
if (auto status = AudioObjectIsPropertySettable (objectID, &address, &isSettable); status != noErr)
{
onError (status);
return false;
}
if (! isSettable)
return false;
if (auto status = AudioObjectSetPropertyData (objectID, &address, 0, nullptr, static_cast<UInt32> (sizeof (T)), &value); status != noErr)
{
onError (status);
return false;
}
return true;
}
template <typename T, typename OnError = IgnoreUnused>
[[nodiscard]] static std::vector<T> audioObjectGetProperties (AudioObjectID objectID,
const AudioObjectPropertyAddress address,
OnError&& onError = {})
{
if (! audioObjectHasProperty (objectID, address))
return {};
UInt32 size{};
if (auto status = AudioObjectGetPropertyDataSize (objectID, &address, 0, nullptr, &size); status != noErr)
{
onError (status);
return {};
}
// If this is hit, the number of results is not integral, and the following
// AudioObjectGetPropertyData will probably write past the end of the result buffer.
jassert ((size % sizeof (T)) == 0);
std::vector<T> result (size / sizeof (T));
if (auto status = AudioObjectGetPropertyData (objectID, &address, 0, nullptr, &size, result.data()); status != noErr)
{
onError (status);
return {};
}
return result;
}
//==============================================================================
struct AsyncRestarter
{
virtual ~AsyncRestarter() = default;
virtual void restartAsync() = 0;
};
struct SystemVol
{
explicit SystemVol (AudioObjectPropertySelector selector) noexcept
: outputDeviceID (audioObjectGetProperty<AudioDeviceID> (kAudioObjectSystemObject, { kAudioHardwarePropertyDefaultOutputDevice,
kAudioObjectPropertyScopeGlobal,
juceAudioObjectPropertyElementMain }).value_or (kAudioObjectUnknown)),
addr { selector, kAudioDevicePropertyScopeOutput, juceAudioObjectPropertyElementMain }
{}
float getGain() const noexcept
{
return audioObjectGetProperty<Float32> (outputDeviceID, addr).value_or (0.0f);
}
bool setGain (float gain) const noexcept
{
return audioObjectSetProperty (outputDeviceID, addr, static_cast<Float32> (gain));
}
bool isMuted() const noexcept
{
return audioObjectGetProperty<UInt32> (outputDeviceID, addr).value_or (0) != 0;
}
bool setMuted (bool mute) const noexcept
{
return audioObjectSetProperty (outputDeviceID, addr, static_cast<UInt32> (mute ? 1 : 0));
}
private:
AudioDeviceID outputDeviceID;
AudioObjectPropertyAddress addr;
};
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
constexpr auto juceAudioHardwareServiceDeviceProperty_VirtualMainVolume =
#if defined (MAC_OS_VERSION_12_0)
kAudioHardwareServiceDeviceProperty_VirtualMainVolume;
#else
kAudioHardwareServiceDeviceProperty_VirtualMasterVolume;
#endif
#define JUCE_SYSTEMAUDIOVOL_IMPLEMENTED 1
float JUCE_CALLTYPE SystemAudioVolume::getGain() { return SystemVol (juceAudioHardwareServiceDeviceProperty_VirtualMainVolume).getGain(); }
bool JUCE_CALLTYPE SystemAudioVolume::setGain (float gain) { return SystemVol (juceAudioHardwareServiceDeviceProperty_VirtualMainVolume).setGain (gain); }
bool JUCE_CALLTYPE SystemAudioVolume::isMuted() { return SystemVol (kAudioDevicePropertyMute).isMuted(); }
bool JUCE_CALLTYPE SystemAudioVolume::setMuted (bool mute) { return SystemVol (kAudioDevicePropertyMute).setMuted (mute); }
//==============================================================================
struct CoreAudioClasses
{
class CoreAudioIODeviceType;
class CoreAudioIODevice;
//==============================================================================
class CoreAudioInternal : private Timer,
private AsyncUpdater
{
private:
// members with deduced return types need to be defined before they
// are used, so define it here. decltype doesn't help as you can't
// capture anything in lambdas inside a decltype context.
auto err2log() const { return [this] (OSStatus err) { OK (err); }; }
public:
CoreAudioInternal (CoreAudioIODevice& d, AudioDeviceID id, bool hasInput, bool hasOutput)
: owner (d),
deviceID (id),
inStream (hasInput ? new Stream (true, *this, {}) : nullptr),
outStream (hasOutput ? new Stream (false, *this, {}) : nullptr)
{
jassert (deviceID != 0);
updateDetailsFromDevice();
JUCE_COREAUDIOLOG ("Creating CoreAudioInternal\n"
<< (inStream != nullptr ? (" inputDeviceId " + String (deviceID) + "\n") : "")
<< (outStream != nullptr ? (" outputDeviceId " + String (deviceID) + "\n") : "")
<< getDeviceDetails().joinIntoString ("\n "));
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioObjectPropertySelectorWildcard;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
}
~CoreAudioInternal() override
{
stopTimer();
cancelPendingUpdate();
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioObjectPropertySelectorWildcard;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = kAudioObjectPropertyElementWildcard;
AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
stop (false);
}
auto getStreams() const { return std::array<Stream*, 2> { { inStream.get(), outStream.get() } }; }
void allocateTempBuffers()
{
auto tempBufSize = bufferSize + 4;
auto streams = getStreams();
const auto total = std::accumulate (streams.begin(), streams.end(), 0,
[] (int n, const auto& s) { return n + (s != nullptr ? s->channels : 0); });
audioBuffer.calloc (total * tempBufSize);
auto channels = 0;
for (auto* stream : streams)
channels += stream != nullptr ? stream->allocateTempBuffers (tempBufSize, channels, audioBuffer) : 0;
}
struct CallbackDetailsForChannel
{
int streamNum;
int dataOffsetSamples;
int dataStrideSamples;
};
Array<double> getSampleRatesFromDevice() const
{
Array<double> newSampleRates;
if (auto ranges = audioObjectGetProperties<AudioValueRange> (deviceID,
{ kAudioDevicePropertyAvailableNominalSampleRates,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain },
err2log()); ! ranges.empty())
{
for (const auto rate : SampleRateHelpers::getAllSampleRates())
{
for (auto range = ranges.rbegin(); range != ranges.rend(); ++range)
{
if (range->mMinimum - 2 <= rate && rate <= range->mMaximum + 2)
{
newSampleRates.add (rate);
break;
}
}
}
}
if (newSampleRates.isEmpty() && sampleRate > 0)
newSampleRates.add (sampleRate);
auto nominalRate = getNominalSampleRate();
if ((nominalRate > 0) && ! newSampleRates.contains (nominalRate))
newSampleRates.addUsingDefaultSort (nominalRate);
return newSampleRates;
}
Array<int> getBufferSizesFromDevice() const
{
Array<int> newBufferSizes;
if (auto ranges = audioObjectGetProperties<AudioValueRange> (deviceID, { kAudioDevicePropertyBufferFrameSizeRange,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain },
err2log()); ! ranges.empty())
{
newBufferSizes.add ((int) (ranges[0].mMinimum + 15) & ~15);
for (int i = 32; i <= 2048; i += 32)
{
for (auto range = ranges.rbegin(); range != ranges.rend(); ++range)
{
if (i >= range->mMinimum && i <= range->mMaximum)
{
newBufferSizes.addIfNotAlreadyThere (i);
break;
}
}
}
if (bufferSize > 0)
newBufferSizes.addIfNotAlreadyThere (bufferSize);
}
if (newBufferSizes.isEmpty() && bufferSize > 0)
newBufferSizes.add (bufferSize);
return newBufferSizes;
}
int getFrameSizeFromDevice() const
{
return static_cast<int> (audioObjectGetProperty<UInt32> (deviceID, { kAudioDevicePropertyBufferFrameSize,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain }).value_or (0));
}
bool isDeviceAlive() const
{
return deviceID != 0
&& audioObjectGetProperty<UInt32> (deviceID, { kAudioDevicePropertyDeviceIsAlive,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain }, err2log()).value_or (0) != 0;
}
bool updateDetailsFromDevice (const BigInteger& activeIns, const BigInteger& activeOuts)
{
stopTimer();
if (! isDeviceAlive())
return false;
// this collects all the new details from the device without any locking, then
// locks + swaps them afterwards.
auto newSampleRate = getNominalSampleRate();
auto newBufferSize = getFrameSizeFromDevice();
auto newBufferSizes = getBufferSizesFromDevice();
auto newSampleRates = getSampleRatesFromDevice();
auto newInput = rawToUniquePtr (inStream != nullptr ? new Stream (true, *this, activeIns) : nullptr);
auto newOutput = rawToUniquePtr (outStream != nullptr ? new Stream (false, *this, activeOuts) : nullptr);
auto newBitDepth = jmax (getBitDepth (newInput), getBitDepth (newOutput));
#if JUCE_AUDIOWORKGROUP_TYPES_AVAILABLE
audioWorkgroup = [this]() -> AudioWorkgroup
{
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyIOThreadOSWorkgroup;
pa.mScope = kAudioObjectPropertyScopeWildcard;
pa.mElement = juceAudioObjectPropertyElementMain;
return makeRealAudioWorkgroup (audioObjectGetProperty<os_workgroup_t> (deviceID, pa).value_or (nullptr));
}();
#endif
{
const ScopedLock sl (callbackLock);
bitDepth = newBitDepth > 0 ? newBitDepth : 32;
if (newSampleRate > 0)
sampleRate = newSampleRate;
bufferSize = newBufferSize;
sampleRates.swapWith (newSampleRates);
bufferSizes.swapWith (newBufferSizes);
std::swap (inStream, newInput);
std::swap (outStream, newOutput);
allocateTempBuffers();
}
return true;
}
bool updateDetailsFromDevice()
{
return updateDetailsFromDevice (getActiveChannels (inStream), getActiveChannels (outStream));
}
StringArray getDeviceDetails()
{
StringArray result;
String availableSampleRates ("Available sample rates:");
for (auto& s : sampleRates)
availableSampleRates << " " << s;
result.add (availableSampleRates);
result.add ("Sample rate: " + String (sampleRate));
String availableBufferSizes ("Available buffer sizes:");
for (auto& b : bufferSizes)
availableBufferSizes << " " << b;
result.add (availableBufferSizes);
result.add ("Buffer size: " + String (bufferSize));
result.add ("Bit depth: " + String (bitDepth));
result.add ("Input latency: " + String (getLatency (inStream)));
result.add ("Output latency: " + String (getLatency (outStream)));
result.add ("Input channel names: " + getChannelNames (inStream));
result.add ("Output channel names: " + getChannelNames (outStream));
return result;
}
static auto getScope (bool input)
{
return input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
}
//==============================================================================
StringArray getSources (bool input)
{
StringArray s;
auto types = audioObjectGetProperties<OSType> (deviceID, { kAudioDevicePropertyDataSources,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain });
for (auto type : types)
{
AudioValueTranslation avt;
char buffer[256];
avt.mInputData = &type;
avt.mInputDataSize = sizeof (UInt32);
avt.mOutputData = buffer;
avt.mOutputDataSize = 256;
UInt32 transSize = sizeof (avt);
AudioObjectPropertyAddress pa;
pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
pa.mScope = getScope (input);
pa.mElement = juceAudioObjectPropertyElementMain;
if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, nullptr, &transSize, &avt)))
s.add (buffer);
}
return s;
}
int getCurrentSourceIndex (bool input) const
{
if (deviceID != 0)
{
if (auto currentSourceID = audioObjectGetProperty<OSType> (deviceID, { kAudioDevicePropertyDataSource,
getScope (input),
juceAudioObjectPropertyElementMain }, err2log()))
{
auto types = audioObjectGetProperties<OSType> (deviceID, { kAudioDevicePropertyDataSources,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain });
if (auto it = std::find (types.begin(), types.end(), *currentSourceID); it != types.end())
return static_cast<int> (std::distance (types.begin(), it));
}
}
return -1;
}
void setCurrentSourceIndex (int index, bool input)
{
if (deviceID != 0)
{
auto types = audioObjectGetProperties<OSType> (deviceID, { kAudioDevicePropertyDataSources,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain });
if (isPositiveAndBelow (index, static_cast<int> (types.size())))
{
audioObjectSetProperty<OSType> (deviceID, { kAudioDevicePropertyDataSource,
getScope (input),
juceAudioObjectPropertyElementMain },
types[static_cast<std::size_t> (index)], err2log());
}
}
}
double getNominalSampleRate() const
{
return static_cast<double> (audioObjectGetProperty <Float64> (deviceID, { kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
juceAudioObjectPropertyElementMain },
err2log()).value_or (0.0));
}
bool setNominalSampleRate (double newSampleRate) const
{
if (std::abs (getNominalSampleRate() - newSampleRate) < 1.0)
return true;
return audioObjectSetProperty (deviceID, { kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeGlobal,
juceAudioObjectPropertyElementMain },
static_cast<Float64> (newSampleRate), err2log());
}
//==============================================================================
String reopen (const BigInteger& ins, const BigInteger& outs, double newSampleRate, int bufferSizeSamples)
{
callbacksAllowed = false;
const ScopeGuard scope { [&] { callbacksAllowed = true; } };
stopTimer();
stop (false);
if (! setNominalSampleRate (newSampleRate))
{
updateDetailsFromDevice (ins, outs);
return "Couldn't change sample rate";
}
if (! audioObjectSetProperty (deviceID, { kAudioDevicePropertyBufferFrameSize,
kAudioObjectPropertyScopeGlobal,
juceAudioObjectPropertyElementMain },
static_cast<UInt32> (bufferSizeSamples), err2log()))
{
updateDetailsFromDevice (ins, outs);
return "Couldn't change buffer size";
}
// Annoyingly, after changing the rate and buffer size, some devices fail to
// correctly report their new settings until some random time in the future, so
// after calling updateDetailsFromDevice, we need to manually bodge these values
// to make sure we're using the correct numbers..
updateDetailsFromDevice (ins, outs);
sampleRate = newSampleRate;
bufferSize = bufferSizeSamples;
if (sampleRates.size() == 0)
return "Device has no available sample-rates";
if (bufferSizes.size() == 0)
return "Device has no available buffer-sizes";
return {};
}
bool start (AudioIODeviceCallback* callbackToNotify)
{
const ScopedLock sl (callbackLock);
if (callback == nullptr && callbackToNotify != nullptr)
{
callback = callbackToNotify;
callback->audioDeviceAboutToStart (&owner);
}
for (auto* stream : getStreams())
if (stream != nullptr)
stream->previousSampleTime = invalidSampleTime;
owner.hadDiscontinuity = false;
if (scopedProcID.get() == nullptr && deviceID != 0)
{
scopedProcID = [&self = *this,
&lock = callbackLock,
nextProcID = ScopedAudioDeviceIOProcID { *this, deviceID, audioIOProc },
deviceID = deviceID]() mutable -> ScopedAudioDeviceIOProcID
{
// It *looks* like AudioDeviceStart may start the audio callback running, and then
// immediately lock an internal mutex.
// The same mutex is locked before calling the audioIOProc.
// If we get very unlucky, then we can end up with thread A taking the callbackLock
// and calling AudioDeviceStart, followed by thread B taking the CoreAudio lock
// and calling into audioIOProc, which waits on the callbackLock. When thread A
// continues it attempts to take the CoreAudio lock, and the program deadlocks.
if (auto* procID = nextProcID.get())
{
const ScopedUnlock su (lock);
if (self.OK (AudioDeviceStart (deviceID, procID)))
return std::move (nextProcID);
}
return {};
}();
}
playing = scopedProcID.get() != nullptr && callback != nullptr;
return scopedProcID.get() != nullptr;
}
AudioIODeviceCallback* stop (bool leaveInterruptRunning)
{
const ScopedLock sl (callbackLock);
auto result = std::exchange (callback, nullptr);
if (scopedProcID.get() != nullptr && (deviceID != 0) && ! leaveInterruptRunning)
{
audioDeviceStopPending = true;
// wait until AudioDeviceStop() has been called on the IO thread
for (int i = 40; --i >= 0;)
{
if (audioDeviceStopPending == false)
break;
const ScopedUnlock ul (callbackLock);
Thread::sleep (50);
}
scopedProcID = {};
playing = false;
}
return result;
}
double getSampleRate() const { return sampleRate; }
int getBufferSize() const { return bufferSize; }
void audioCallback (const AudioTimeStamp* inputTimestamp,
const AudioTimeStamp* outputTimestamp,
const AudioBufferList* inInputData,
AudioBufferList* outOutputData)
{
const ScopedLock sl (callbackLock);
if (audioDeviceStopPending)
{
if (OK (AudioDeviceStop (deviceID, scopedProcID.get())))
audioDeviceStopPending = false;
return;
}
const auto numInputChans = getChannels (inStream);
const auto numOutputChans = getChannels (outStream);
if (callback != nullptr)
{
for (int i = numInputChans; --i >= 0;)
{
auto& info = inStream->channelInfo.getReference (i);
auto dest = inStream->tempBuffers[i];
auto src = ((const float*) inInputData->mBuffers[info.streamNum].mData) + info.dataOffsetSamples;
auto stride = info.dataStrideSamples;
if (stride != 0) // if this is zero, info is invalid
{
for (int j = bufferSize; --j >= 0;)
{
*dest++ = *src;
src += stride;
}
}
}
for (auto* stream : getStreams())
if (stream != nullptr)
owner.hadDiscontinuity |= stream->checkTimestampsForDiscontinuity (stream == inStream.get() ? inputTimestamp
: outputTimestamp);
const auto* timeStamp = numOutputChans > 0 ? outputTimestamp : inputTimestamp;
const auto nanos = timeStamp != nullptr ? timeConversions.hostTimeToNanos (timeStamp->mHostTime) : 0;
const AudioIODeviceCallbackContext context
{
timeStamp != nullptr ? &nanos : nullptr,
};
callback->audioDeviceIOCallbackWithContext (getTempBuffers (inStream), numInputChans,
getTempBuffers (outStream), numOutputChans,
bufferSize,
context);
for (int i = numOutputChans; --i >= 0;)
{
auto& info = outStream->channelInfo.getReference (i);
auto src = outStream->tempBuffers[i];
auto dest = ((float*) outOutputData->mBuffers[info.streamNum].mData) + info.dataOffsetSamples;
auto stride = info.dataStrideSamples;
if (stride != 0) // if this is zero, info is invalid
{
for (int j = bufferSize; --j >= 0;)
{
*dest = *src++;
dest += stride;
}
}
}
}
else
{
for (UInt32 i = 0; i < outOutputData->mNumberBuffers; ++i)
zeromem (outOutputData->mBuffers[i].mData,
outOutputData->mBuffers[i].mDataByteSize);
}
for (auto* stream : getStreams())
if (stream != nullptr)
stream->previousSampleTime += static_cast<Float64> (bufferSize);
}
// called by callbacks (possibly off the main thread)
void deviceDetailsChanged()
{
if (callbacksAllowed.get() == 1)
startTimer (100);
}
// called by callbacks (possibly off the main thread)
void deviceRequestedRestart()
{
owner.restart();
triggerAsyncUpdate();
}
bool isPlaying() const { return playing.load(); }
//==============================================================================
struct Stream
{
Stream (bool isInput, CoreAudioInternal& parent, const BigInteger& activeRequested)
: input (isInput),
latency (getLatencyFromDevice (isInput, parent)),
bitDepth (getBitDepthFromDevice (isInput, parent)),
chanNames (getChannelNames (isInput, parent)),
activeChans ([&activeRequested, clearFrom = chanNames.size()]
{
auto result = activeRequested;
result.setRange (clearFrom, result.getHighestBit() + 1 - clearFrom, false);
return result;
}()),
channelInfo (getChannelInfos (isInput, parent, activeChans)),
channels (static_cast<int> (channelInfo.size()))
{}
int allocateTempBuffers (int tempBufSize, int channelCount, HeapBlock<float>& buffer)
{
tempBuffers.calloc (channels + 2);
for (int i = 0; i < channels; ++i)
tempBuffers[i] = buffer + channelCount++ * tempBufSize;
return channels;
}
template <typename Visitor>
static auto visitChannels (bool isInput, CoreAudioInternal& parent, Visitor&& visitor)
{
struct Args { int stream, channelIdx, chanNum, streamChannels; };
using VisitorResultType = typename std::invoke_result_t<Visitor, const Args&>::value_type;
Array<VisitorResultType> result;
int chanNum = 0;
if (auto bufList = audioObjectGetProperty<AudioBufferList> (parent.deviceID, { kAudioDevicePropertyStreamConfiguration,
getScope (isInput),
juceAudioObjectPropertyElementMain }, parent.err2log()))
{
const int numStreams = static_cast<int> (bufList->mNumberBuffers);
for (int i = 0; i < numStreams; ++i)
{
auto& b = bufList->mBuffers[i];
for (unsigned int j = 0; j < b.mNumberChannels; ++j)
{
// Passing an anonymous struct ensures that callback can't confuse the argument order
if (auto opt = visitor (Args { i, static_cast<int> (j), chanNum++, static_cast<int> (b.mNumberChannels) }))
result.add (std::move (*opt));
}
}
}
return result;
}
static Array<CallbackDetailsForChannel> getChannelInfos (bool isInput, CoreAudioInternal& parent, const BigInteger& active)
{
return visitChannels (isInput, parent,
[&] (const auto& args) -> std::optional<CallbackDetailsForChannel>
{
if (! active[args.chanNum])
return {};
return CallbackDetailsForChannel { args.stream, args.channelIdx, args.streamChannels };
});
}
static StringArray getChannelNames (bool isInput, CoreAudioInternal& parent)
{
auto names = visitChannels (isInput, parent,
[&] (const auto& args) -> std::optional<String>
{
String name;
const auto element = static_cast<AudioObjectPropertyElement> (args.chanNum + 1);
if (auto nameNSString = audioObjectGetProperty<NSString*> (parent.deviceID, { kAudioObjectPropertyElementName,
getScope (isInput),
element }).value_or (nullptr))
{
name = nsStringToJuce (nameNSString);
[nameNSString release];
}
if (name.isEmpty())
name << (isInput ? "Input " : "Output ") << (args.chanNum + 1);
return name;
});
return { names };
}
static int getBitDepthFromDevice (bool isInput, CoreAudioInternal& parent)
{
return static_cast<int> (audioObjectGetProperty<AudioStreamBasicDescription> (parent.deviceID, { kAudioStreamPropertyPhysicalFormat,
getScope (isInput),
juceAudioObjectPropertyElementMain }, parent.err2log())
.value_or (AudioStreamBasicDescription{}).mBitsPerChannel);
}
static int getLatencyFromDevice (bool isInput, CoreAudioInternal& parent)
{
const auto scope = getScope (isInput);
const auto deviceLatency = audioObjectGetProperty<UInt32> (parent.deviceID, { kAudioDevicePropertyLatency,
scope,
juceAudioObjectPropertyElementMain }).value_or (0);
const auto safetyOffset = audioObjectGetProperty<UInt32> (parent.deviceID, { kAudioDevicePropertySafetyOffset,
scope,
juceAudioObjectPropertyElementMain }).value_or (0);
const auto framesInBuffer = audioObjectGetProperty<UInt32> (parent.deviceID, { kAudioDevicePropertyBufferFrameSize,
kAudioObjectPropertyScopeWildcard,
juceAudioObjectPropertyElementMain }).value_or (0);
UInt32 streamLatency = 0;
if (auto streams = audioObjectGetProperties<AudioStreamID> (parent.deviceID, { kAudioDevicePropertyStreams,
scope,
juceAudioObjectPropertyElementMain }); ! streams.empty())
streamLatency = audioObjectGetProperty<UInt32> (streams.front(), { kAudioStreamPropertyLatency,
scope,
juceAudioObjectPropertyElementMain }).value_or (0);
return static_cast<int> (deviceLatency + safetyOffset + framesInBuffer + streamLatency);
}
bool checkTimestampsForDiscontinuity (const AudioTimeStamp* timestamp) noexcept
{
if (channels > 0)
{
jassert (timestamp == nullptr || (((timestamp->mFlags & kAudioTimeStampSampleTimeValid) != 0)
&& ((timestamp->mFlags & kAudioTimeStampHostTimeValid) != 0)));
if (exactlyEqual (previousSampleTime, invalidSampleTime))
previousSampleTime = timestamp != nullptr ? timestamp->mSampleTime : 0.0;
if (timestamp != nullptr && std::fabs (previousSampleTime - timestamp->mSampleTime) >= 1.0)
{
previousSampleTime = timestamp->mSampleTime;
return true;
}
}
return false;
}
//==============================================================================
const bool input;