-
Notifications
You must be signed in to change notification settings - Fork 230
/
coreaudio.c
1465 lines (1275 loc) · 56.2 KB
/
coreaudio.c
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
/*
* Copyright (c) 2015 Andrew Kelley
*
* This file is part of libsoundio, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
#include "coreaudio.h"
#include "soundio_private.h"
#include <assert.h>
static const int OUTPUT_ELEMENT = 0;
static const int INPUT_ELEMENT = 1;
static AudioObjectPropertyAddress device_listen_props[] = {
{
kAudioDevicePropertyDeviceHasChanged,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
},
{
kAudioObjectPropertyName,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyDeviceUID,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyStreamConfiguration,
kAudioObjectPropertyScopeInput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyStreamConfiguration,
kAudioObjectPropertyScopeOutput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyPreferredChannelLayout,
kAudioObjectPropertyScopeInput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyPreferredChannelLayout,
kAudioObjectPropertyScopeOutput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeInput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyNominalSampleRate,
kAudioObjectPropertyScopeOutput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyAvailableNominalSampleRates,
kAudioObjectPropertyScopeInput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyAvailableNominalSampleRates,
kAudioObjectPropertyScopeOutput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyBufferFrameSize,
kAudioObjectPropertyScopeInput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyBufferFrameSize,
kAudioObjectPropertyScopeOutput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyBufferFrameSizeRange,
kAudioObjectPropertyScopeInput,
kAudioObjectPropertyElementMaster
},
{
kAudioDevicePropertyBufferFrameSizeRange,
kAudioObjectPropertyScopeOutput,
kAudioObjectPropertyElementMaster
},
};
static enum SoundIoDeviceAim aims[] = {
SoundIoDeviceAimInput,
SoundIoDeviceAimOutput,
};
SOUNDIO_MAKE_LIST_DEF(AudioDeviceID, SoundIoListAudioDeviceID, SOUNDIO_LIST_STATIC)
static OSStatus on_devices_changed(AudioObjectID in_object_id, UInt32 in_number_addresses,
const AudioObjectPropertyAddress in_addresses[], void *in_client_data)
{
struct SoundIoPrivate *si = (struct SoundIoPrivate*)in_client_data;
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
SOUNDIO_ATOMIC_STORE(sica->device_scan_queued, true);
soundio_os_cond_signal(sica->scan_devices_cond, NULL);
return noErr;
}
static OSStatus on_service_restarted(AudioObjectID in_object_id, UInt32 in_number_addresses,
const AudioObjectPropertyAddress in_addresses[], void *in_client_data)
{
struct SoundIoPrivate *si = (struct SoundIoPrivate*)in_client_data;
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
SOUNDIO_ATOMIC_STORE(sica->service_restarted, true);
soundio_os_cond_signal(sica->scan_devices_cond, NULL);
return noErr;
}
static void unsubscribe_device_listeners(struct SoundIoPrivate *si) {
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
for (int device_index = 0; device_index < sica->registered_listeners.length; device_index += 1) {
AudioDeviceID device_id = SoundIoListAudioDeviceID_val_at(&sica->registered_listeners, device_index);
for (int i = 0; i < ARRAY_LENGTH(device_listen_props); i += 1) {
AudioObjectRemovePropertyListener(device_id, &device_listen_props[i],
on_devices_changed, si);
}
}
SoundIoListAudioDeviceID_clear(&sica->registered_listeners);
}
static void destroy_ca(struct SoundIoPrivate *si) {
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
AudioObjectPropertyAddress prop_address = {
kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &prop_address, on_devices_changed, si);
prop_address.mSelector = kAudioHardwarePropertyServiceRestarted;
AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &prop_address, on_service_restarted, si);
unsubscribe_device_listeners(si);
SoundIoListAudioDeviceID_deinit(&sica->registered_listeners);
if (sica->thread) {
SOUNDIO_ATOMIC_FLAG_CLEAR(sica->abort_flag);
soundio_os_cond_signal(sica->scan_devices_cond, NULL);
soundio_os_thread_destroy(sica->thread);
}
if (sica->cond)
soundio_os_cond_destroy(sica->cond);
if (sica->have_devices_cond)
soundio_os_cond_destroy(sica->have_devices_cond);
if (sica->scan_devices_cond)
soundio_os_cond_destroy(sica->scan_devices_cond);
if (sica->mutex)
soundio_os_mutex_destroy(sica->mutex);
soundio_destroy_devices_info(sica->ready_devices_info);
}
// Possible errors:
// * SoundIoErrorNoMem
// * SoundIoErrorEncodingString
static int from_cf_string(CFStringRef string_ref, char **out_str, int *out_str_len) {
assert(string_ref);
CFIndex length = CFStringGetLength(string_ref);
CFIndex max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
char *buf = ALLOCATE_NONZERO(char, max_size);
if (!buf)
return SoundIoErrorNoMem;
if (!CFStringGetCString(string_ref, buf, max_size, kCFStringEncodingUTF8)) {
free(buf);
return SoundIoErrorEncodingString;
}
*out_str = buf;
*out_str_len = strlen(buf);
return 0;
}
static int aim_to_scope(enum SoundIoDeviceAim aim) {
return (aim == SoundIoDeviceAimInput) ?
kAudioObjectPropertyScopeInput : kAudioObjectPropertyScopeOutput;
}
static enum SoundIoChannelId from_channel_descr(const AudioChannelDescription *descr) {
switch (descr->mChannelLabel) {
default: return SoundIoChannelIdInvalid;
case kAudioChannelLabel_Left: return SoundIoChannelIdFrontLeft;
case kAudioChannelLabel_Right: return SoundIoChannelIdFrontRight;
case kAudioChannelLabel_Center: return SoundIoChannelIdFrontCenter;
case kAudioChannelLabel_LFEScreen: return SoundIoChannelIdLfe;
case kAudioChannelLabel_LeftSurround: return SoundIoChannelIdBackLeft;
case kAudioChannelLabel_RightSurround: return SoundIoChannelIdBackRight;
case kAudioChannelLabel_LeftCenter: return SoundIoChannelIdFrontLeftCenter;
case kAudioChannelLabel_RightCenter: return SoundIoChannelIdFrontRightCenter;
case kAudioChannelLabel_CenterSurround: return SoundIoChannelIdBackCenter;
case kAudioChannelLabel_LeftSurroundDirect: return SoundIoChannelIdSideLeft;
case kAudioChannelLabel_RightSurroundDirect: return SoundIoChannelIdSideRight;
case kAudioChannelLabel_TopCenterSurround: return SoundIoChannelIdTopCenter;
case kAudioChannelLabel_VerticalHeightLeft: return SoundIoChannelIdTopFrontLeft;
case kAudioChannelLabel_VerticalHeightCenter: return SoundIoChannelIdTopFrontCenter;
case kAudioChannelLabel_VerticalHeightRight: return SoundIoChannelIdTopFrontRight;
case kAudioChannelLabel_TopBackLeft: return SoundIoChannelIdTopBackLeft;
case kAudioChannelLabel_TopBackCenter: return SoundIoChannelIdTopBackCenter;
case kAudioChannelLabel_TopBackRight: return SoundIoChannelIdTopBackRight;
case kAudioChannelLabel_RearSurroundLeft: return SoundIoChannelIdBackLeft;
case kAudioChannelLabel_RearSurroundRight: return SoundIoChannelIdBackRight;
case kAudioChannelLabel_LeftWide: return SoundIoChannelIdFrontLeftWide;
case kAudioChannelLabel_RightWide: return SoundIoChannelIdFrontRightWide;
case kAudioChannelLabel_LFE2: return SoundIoChannelIdLfe2;
case kAudioChannelLabel_LeftTotal: return SoundIoChannelIdFrontLeft;
case kAudioChannelLabel_RightTotal: return SoundIoChannelIdFrontRight;
case kAudioChannelLabel_HearingImpaired: return SoundIoChannelIdHearingImpaired;
case kAudioChannelLabel_Narration: return SoundIoChannelIdNarration;
case kAudioChannelLabel_Mono: return SoundIoChannelIdFrontCenter;
case kAudioChannelLabel_DialogCentricMix: return SoundIoChannelIdDialogCentricMix;
case kAudioChannelLabel_CenterSurroundDirect: return SoundIoChannelIdBackCenter;
case kAudioChannelLabel_Haptic: return SoundIoChannelIdHaptic;
case kAudioChannelLabel_Ambisonic_W: return SoundIoChannelIdAmbisonicW;
case kAudioChannelLabel_Ambisonic_X: return SoundIoChannelIdAmbisonicX;
case kAudioChannelLabel_Ambisonic_Y: return SoundIoChannelIdAmbisonicY;
case kAudioChannelLabel_Ambisonic_Z: return SoundIoChannelIdAmbisonicZ;
case kAudioChannelLabel_MS_Mid: return SoundIoChannelIdMsMid;
case kAudioChannelLabel_MS_Side: return SoundIoChannelIdMsSide;
case kAudioChannelLabel_XY_X: return SoundIoChannelIdXyX;
case kAudioChannelLabel_XY_Y: return SoundIoChannelIdXyY;
case kAudioChannelLabel_HeadphonesLeft: return SoundIoChannelIdHeadphonesLeft;
case kAudioChannelLabel_HeadphonesRight: return SoundIoChannelIdHeadphonesRight;
case kAudioChannelLabel_ClickTrack: return SoundIoChannelIdClickTrack;
case kAudioChannelLabel_ForeignLanguage: return SoundIoChannelIdForeignLanguage;
case kAudioChannelLabel_Discrete: return SoundIoChannelIdAux;
case kAudioChannelLabel_Discrete_0: return SoundIoChannelIdAux0;
case kAudioChannelLabel_Discrete_1: return SoundIoChannelIdAux1;
case kAudioChannelLabel_Discrete_2: return SoundIoChannelIdAux2;
case kAudioChannelLabel_Discrete_3: return SoundIoChannelIdAux3;
case kAudioChannelLabel_Discrete_4: return SoundIoChannelIdAux4;
case kAudioChannelLabel_Discrete_5: return SoundIoChannelIdAux5;
case kAudioChannelLabel_Discrete_6: return SoundIoChannelIdAux6;
case kAudioChannelLabel_Discrete_7: return SoundIoChannelIdAux7;
case kAudioChannelLabel_Discrete_8: return SoundIoChannelIdAux8;
case kAudioChannelLabel_Discrete_9: return SoundIoChannelIdAux9;
case kAudioChannelLabel_Discrete_10: return SoundIoChannelIdAux10;
case kAudioChannelLabel_Discrete_11: return SoundIoChannelIdAux11;
case kAudioChannelLabel_Discrete_12: return SoundIoChannelIdAux12;
case kAudioChannelLabel_Discrete_13: return SoundIoChannelIdAux13;
case kAudioChannelLabel_Discrete_14: return SoundIoChannelIdAux14;
case kAudioChannelLabel_Discrete_15: return SoundIoChannelIdAux15;
}
}
// See https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/CoreAudioDataTypesRef/#//apple_ref/doc/constant_group/Audio_Channel_Layout_Tags
// Possible Errors:
// * SoundIoErrorIncompatibleDevice
// This does not handle all the possible layout enum values and it does not
// handle channel bitmaps.
static int from_coreaudio_layout(const AudioChannelLayout *ca_layout, struct SoundIoChannelLayout *layout) {
switch (ca_layout->mChannelLayoutTag) {
case kAudioChannelLayoutTag_UseChannelDescriptions:
{
layout->channel_count = soundio_int_min(
SOUNDIO_MAX_CHANNELS,
ca_layout->mNumberChannelDescriptions
);
for (int i = 0; i < layout->channel_count; i += 1) {
layout->channels[i] = from_channel_descr(&ca_layout->mChannelDescriptions[i]);
}
break;
}
case kAudioChannelLayoutTag_UseChannelBitmap:
return SoundIoErrorIncompatibleDevice;
case kAudioChannelLayoutTag_Mono:
layout->channel_count = 1;
layout->channels[0] = SoundIoChannelIdFrontCenter;
break;
case kAudioChannelLayoutTag_Stereo:
case kAudioChannelLayoutTag_StereoHeadphones:
case kAudioChannelLayoutTag_MatrixStereo:
case kAudioChannelLayoutTag_Binaural:
layout->channel_count = 2;
layout->channels[0] = SoundIoChannelIdFrontLeft;
layout->channels[1] = SoundIoChannelIdFrontRight;
break;
case kAudioChannelLayoutTag_XY:
layout->channel_count = 2;
layout->channels[0] = SoundIoChannelIdXyX;
layout->channels[1] = SoundIoChannelIdXyY;
break;
case kAudioChannelLayoutTag_MidSide:
layout->channel_count = 2;
layout->channels[0] = SoundIoChannelIdMsMid;
layout->channels[1] = SoundIoChannelIdMsSide;
break;
case kAudioChannelLayoutTag_Ambisonic_B_Format:
layout->channel_count = 4;
layout->channels[0] = SoundIoChannelIdAmbisonicW;
layout->channels[1] = SoundIoChannelIdAmbisonicX;
layout->channels[2] = SoundIoChannelIdAmbisonicY;
layout->channels[3] = SoundIoChannelIdAmbisonicZ;
break;
case kAudioChannelLayoutTag_Quadraphonic:
layout->channel_count = 4;
layout->channels[0] = SoundIoChannelIdFrontLeft;
layout->channels[1] = SoundIoChannelIdFrontRight;
layout->channels[2] = SoundIoChannelIdBackLeft;
layout->channels[3] = SoundIoChannelIdBackRight;
break;
case kAudioChannelLayoutTag_Pentagonal:
layout->channel_count = 5;
layout->channels[0] = SoundIoChannelIdSideLeft;
layout->channels[1] = SoundIoChannelIdSideRight;
layout->channels[2] = SoundIoChannelIdBackLeft;
layout->channels[3] = SoundIoChannelIdBackRight;
layout->channels[4] = SoundIoChannelIdFrontCenter;
break;
case kAudioChannelLayoutTag_Hexagonal:
layout->channel_count = 6;
layout->channels[0] = SoundIoChannelIdFrontLeft;
layout->channels[1] = SoundIoChannelIdFrontRight;
layout->channels[2] = SoundIoChannelIdBackLeft;
layout->channels[3] = SoundIoChannelIdBackRight;
layout->channels[4] = SoundIoChannelIdFrontCenter;
layout->channels[5] = SoundIoChannelIdBackCenter;
break;
case kAudioChannelLayoutTag_Octagonal:
layout->channel_count = 8;
layout->channels[0] = SoundIoChannelIdFrontLeft;
layout->channels[1] = SoundIoChannelIdFrontRight;
layout->channels[2] = SoundIoChannelIdBackLeft;
layout->channels[3] = SoundIoChannelIdBackRight;
layout->channels[4] = SoundIoChannelIdFrontCenter;
layout->channels[5] = SoundIoChannelIdBackCenter;
layout->channels[6] = SoundIoChannelIdSideLeft;
layout->channels[7] = SoundIoChannelIdSideRight;
break;
case kAudioChannelLayoutTag_Cube:
layout->channel_count = 8;
layout->channels[0] = SoundIoChannelIdFrontLeft;
layout->channels[1] = SoundIoChannelIdFrontRight;
layout->channels[2] = SoundIoChannelIdBackLeft;
layout->channels[3] = SoundIoChannelIdBackRight;
layout->channels[4] = SoundIoChannelIdTopFrontLeft;
layout->channels[5] = SoundIoChannelIdTopFrontRight;
layout->channels[6] = SoundIoChannelIdTopBackLeft;
layout->channels[7] = SoundIoChannelIdTopBackRight;
break;
default:
return SoundIoErrorIncompatibleDevice;
}
soundio_channel_layout_detect_builtin(layout);
return 0;
}
static bool all_channels_invalid(const struct SoundIoChannelLayout *layout) {
for (int i = 0; i < layout->channel_count; i += 1) {
if (layout->channels[i] != SoundIoChannelIdInvalid)
return false;
}
return true;
}
struct RefreshDevices {
struct SoundIoPrivate *si;
struct SoundIoDevicesInfo *devices_info;
int devices_size;
AudioObjectID *devices;
CFStringRef string_ref;
char *device_name;
int device_name_len;
AudioBufferList *buffer_list;
struct SoundIoDevice *device;
AudioChannelLayout *audio_channel_layout;
char *device_uid;
int device_uid_len;
AudioValueRange *avr_array;
bool ok;
};
static void deinit_refresh_devices(struct RefreshDevices *rd) {
if (!rd->ok)
unsubscribe_device_listeners(rd->si);
soundio_destroy_devices_info(rd->devices_info);
free(rd->devices);
if (rd->string_ref)
CFRelease(rd->string_ref);
free(rd->device_name);
free(rd->buffer_list);
soundio_device_unref(rd->device);
free(rd->audio_channel_layout);
free(rd->device_uid);
free(rd->avr_array);
}
static int refresh_devices(struct SoundIoPrivate *si) {
struct SoundIo *soundio = &si->pub;
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
UInt32 io_size;
OSStatus os_err;
int err;
unsubscribe_device_listeners(si);
struct RefreshDevices rd = {0};
rd.si = si;
if (!(rd.devices_info = ALLOCATE(struct SoundIoDevicesInfo, 1))) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
AudioObjectPropertyAddress prop_address = {
kAudioHardwarePropertyDevices,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
if ((os_err = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject,
&prop_address, 0, NULL, &io_size)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
AudioObjectID default_input_id;
AudioObjectID default_output_id;
int device_count = io_size / (UInt32)sizeof(AudioObjectID);
if (device_count >= 1) {
rd.devices_size = io_size;
rd.devices = (AudioObjectID *)ALLOCATE(char, rd.devices_size);
if (!rd.devices) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
if ((os_err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop_address, 0, NULL,
&io_size, rd.devices)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
io_size = sizeof(AudioObjectID);
prop_address.mSelector = kAudioHardwarePropertyDefaultInputDevice;
if ((os_err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop_address,
0, NULL, &io_size, &default_input_id)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
io_size = sizeof(AudioObjectID);
prop_address.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
if ((os_err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop_address,
0, NULL, &io_size, &default_output_id)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
}
for (int device_i = 0; device_i < device_count; device_i += 1) {
AudioObjectID device_id = rd.devices[device_i];
for (int i = 0; i < ARRAY_LENGTH(device_listen_props); i += 1) {
if ((err = SoundIoListAudioDeviceID_add_one(&sica->registered_listeners))) {
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
if ((os_err = AudioObjectAddPropertyListener(device_id, &device_listen_props[i],
on_devices_changed, si)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
AudioDeviceID *last_device_id = SoundIoListAudioDeviceID_last_ptr(&sica->registered_listeners);
*last_device_id = device_id;
}
prop_address.mSelector = kAudioObjectPropertyName;
prop_address.mScope = kAudioObjectPropertyScopeGlobal;
prop_address.mElement = kAudioObjectPropertyElementMaster;
io_size = sizeof(CFStringRef);
if (rd.string_ref) {
CFRelease(rd.string_ref);
rd.string_ref = NULL;
}
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address,
0, NULL, &io_size, &rd.string_ref)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
free(rd.device_name);
rd.device_name = NULL;
if ((err = from_cf_string(rd.string_ref, &rd.device_name, &rd.device_name_len))) {
deinit_refresh_devices(&rd);
return err;
}
prop_address.mSelector = kAudioDevicePropertyDeviceUID;
prop_address.mScope = kAudioObjectPropertyScopeGlobal;
prop_address.mElement = kAudioObjectPropertyElementMaster;
io_size = sizeof(CFStringRef);
if (rd.string_ref) {
CFRelease(rd.string_ref);
rd.string_ref = NULL;
}
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address,
0, NULL, &io_size, &rd.string_ref)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
free(rd.device_uid);
rd.device_uid = NULL;
if ((err = from_cf_string(rd.string_ref, &rd.device_uid, &rd.device_uid_len))) {
deinit_refresh_devices(&rd);
return err;
}
for (int aim_i = 0; aim_i < ARRAY_LENGTH(aims); aim_i += 1) {
enum SoundIoDeviceAim aim = aims[aim_i];
io_size = 0;
prop_address.mSelector = kAudioDevicePropertyStreamConfiguration;
prop_address.mScope = aim_to_scope(aim);
prop_address.mElement = kAudioObjectPropertyElementMaster;
if ((os_err = AudioObjectGetPropertyDataSize(device_id, &prop_address, 0, NULL, &io_size))) {
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
free(rd.buffer_list);
rd.buffer_list = (AudioBufferList*)ALLOCATE_NONZERO(char, io_size);
if (!rd.buffer_list) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address, 0, NULL,
&io_size, rd.buffer_list)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
int channel_count = 0;
for (int i = 0; i < rd.buffer_list->mNumberBuffers; i += 1) {
channel_count += rd.buffer_list->mBuffers[i].mNumberChannels;
}
if (channel_count <= 0)
continue;
struct SoundIoDevicePrivate *dev = ALLOCATE(struct SoundIoDevicePrivate, 1);
if (!dev) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
struct SoundIoDeviceCoreAudio *dca = &dev->backend_data.coreaudio;
dca->device_id = device_id;
assert(!rd.device);
rd.device = &dev->pub;
rd.device->ref_count = 1;
rd.device->soundio = soundio;
rd.device->is_raw = false;
rd.device->aim = aim;
rd.device->id = soundio_str_dupe(rd.device_uid, rd.device_uid_len);
rd.device->name = soundio_str_dupe(rd.device_name, rd.device_name_len);
if (!rd.device->id || !rd.device->name) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
prop_address.mSelector = kAudioDevicePropertyPreferredChannelLayout;
prop_address.mScope = aim_to_scope(aim);
prop_address.mElement = kAudioObjectPropertyElementMaster;
if (!(os_err = AudioObjectGetPropertyDataSize(device_id, &prop_address,
0, NULL, &io_size)))
{
rd.audio_channel_layout = (AudioChannelLayout *)ALLOCATE(char, io_size);
if (!rd.audio_channel_layout) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address, 0, NULL,
&io_size, rd.audio_channel_layout)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
if ((err = from_coreaudio_layout(rd.audio_channel_layout, &rd.device->current_layout))) {
rd.device->current_layout.channel_count = channel_count;
}
}
if (all_channels_invalid(&rd.device->current_layout)) {
const struct SoundIoChannelLayout *guessed_layout =
soundio_channel_layout_get_default(channel_count);
if (guessed_layout)
rd.device->current_layout = *guessed_layout;
}
rd.device->layout_count = 1;
rd.device->layouts = &rd.device->current_layout;
rd.device->format_count = 4;
rd.device->formats = ALLOCATE(enum SoundIoFormat, rd.device->format_count);
if (!rd.device->formats)
return SoundIoErrorNoMem;
rd.device->formats[0] = SoundIoFormatS16LE;
rd.device->formats[1] = SoundIoFormatS32LE;
rd.device->formats[2] = SoundIoFormatFloat32LE;
rd.device->formats[3] = SoundIoFormatFloat64LE;
prop_address.mSelector = kAudioDevicePropertyNominalSampleRate;
prop_address.mScope = aim_to_scope(aim);
prop_address.mElement = kAudioObjectPropertyElementMaster;
io_size = sizeof(double);
double value;
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address, 0, NULL,
&io_size, &value)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
double floored_value = floor(value);
if (value != floored_value) {
deinit_refresh_devices(&rd);
return SoundIoErrorIncompatibleDevice;
}
rd.device->sample_rate_current = (int)floored_value;
// If you try to open an input stream with anything but the current
// nominal sample rate, AudioUnitRender returns an error.
if (aim == SoundIoDeviceAimInput) {
rd.device->sample_rate_count = 1;
rd.device->sample_rates = &dev->prealloc_sample_rate_range;
rd.device->sample_rates[0].min = rd.device->sample_rate_current;
rd.device->sample_rates[0].max = rd.device->sample_rate_current;
} else {
prop_address.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
prop_address.mScope = aim_to_scope(aim);
prop_address.mElement = kAudioObjectPropertyElementMaster;
if ((os_err = AudioObjectGetPropertyDataSize(device_id, &prop_address, 0, NULL,
&io_size)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
int avr_array_len = io_size / sizeof(AudioValueRange);
rd.avr_array = (AudioValueRange*)ALLOCATE(char, io_size);
if (!rd.avr_array) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address, 0, NULL,
&io_size, rd.avr_array)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
if (avr_array_len == 1) {
rd.device->sample_rate_count = 1;
rd.device->sample_rates = &dev->prealloc_sample_rate_range;
rd.device->sample_rates[0].min = ceil_dbl_to_int(rd.avr_array[0].mMinimum);
rd.device->sample_rates[0].max = (int)(rd.avr_array[0].mMaximum);
} else {
rd.device->sample_rate_count = avr_array_len;
rd.device->sample_rates = ALLOCATE(struct SoundIoSampleRateRange, avr_array_len);
if (!rd.device->sample_rates) {
deinit_refresh_devices(&rd);
return SoundIoErrorNoMem;
}
for (int i = 0; i < avr_array_len; i += 1) {
AudioValueRange *avr = &rd.avr_array[i];
int min_val = ceil_dbl_to_int(avr->mMinimum);
int max_val = (int)(avr->mMaximum);
rd.device->sample_rates[i].min = min_val;
rd.device->sample_rates[i].max = max_val;
}
}
}
prop_address.mSelector = kAudioDevicePropertyBufferFrameSize;
prop_address.mScope = aim_to_scope(aim);
prop_address.mElement = kAudioObjectPropertyElementMaster;
io_size = sizeof(UInt32);
UInt32 buffer_frame_size;
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address, 0, NULL,
&io_size, &buffer_frame_size)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
double use_sample_rate = rd.device->sample_rate_current;
rd.device->software_latency_current = buffer_frame_size / use_sample_rate;
prop_address.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
prop_address.mScope = aim_to_scope(aim);
prop_address.mElement = kAudioObjectPropertyElementMaster;
io_size = sizeof(AudioValueRange);
AudioValueRange avr;
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address, 0, NULL,
&io_size, &avr)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
rd.device->software_latency_min = avr.mMinimum / use_sample_rate;
rd.device->software_latency_max = avr.mMaximum / use_sample_rate;
prop_address.mSelector = kAudioDevicePropertyLatency;
prop_address.mScope = aim_to_scope(aim);
prop_address.mElement = kAudioObjectPropertyElementMaster;
io_size = sizeof(UInt32);
if ((os_err = AudioObjectGetPropertyData(device_id, &prop_address, 0, NULL,
&io_size, &dca->latency_frames)))
{
deinit_refresh_devices(&rd);
return SoundIoErrorOpeningDevice;
}
struct SoundIoListDevicePtr *device_list;
if (rd.device->aim == SoundIoDeviceAimOutput) {
device_list = &rd.devices_info->output_devices;
if (device_id == default_output_id)
rd.devices_info->default_output_index = device_list->length;
} else {
assert(rd.device->aim == SoundIoDeviceAimInput);
device_list = &rd.devices_info->input_devices;
if (device_id == default_input_id)
rd.devices_info->default_input_index = device_list->length;
}
if ((err = SoundIoListDevicePtr_append(device_list, rd.device))) {
deinit_refresh_devices(&rd);
return err;
}
rd.device = NULL;
}
}
soundio_os_mutex_lock(sica->mutex);
soundio_destroy_devices_info(sica->ready_devices_info);
sica->ready_devices_info = rd.devices_info;
soundio_os_mutex_unlock(sica->mutex);
rd.devices_info = NULL;
rd.ok = true;
deinit_refresh_devices(&rd);
return 0;
}
static void shutdown_backend(struct SoundIoPrivate *si, int err) {
struct SoundIo *soundio = &si->pub;
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
soundio_os_mutex_lock(sica->mutex);
sica->shutdown_err = err;
SOUNDIO_ATOMIC_STORE(sica->have_devices_flag, true);
soundio_os_mutex_unlock(sica->mutex);
soundio_os_cond_signal(sica->cond, NULL);
soundio_os_cond_signal(sica->have_devices_cond, NULL);
soundio->on_events_signal(soundio);
}
static void flush_events_ca(struct SoundIoPrivate *si) {
struct SoundIo *soundio = &si->pub;
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
// block until have devices
while (!SOUNDIO_ATOMIC_LOAD(sica->have_devices_flag))
soundio_os_cond_wait(sica->have_devices_cond, NULL);
bool change = false;
bool cb_shutdown = false;
struct SoundIoDevicesInfo *old_devices_info = NULL;
soundio_os_mutex_lock(sica->mutex);
if (sica->shutdown_err && !sica->emitted_shutdown_cb) {
sica->emitted_shutdown_cb = true;
cb_shutdown = true;
} else if (sica->ready_devices_info) {
old_devices_info = si->safe_devices_info;
si->safe_devices_info = sica->ready_devices_info;
sica->ready_devices_info = NULL;
change = true;
}
soundio_os_mutex_unlock(sica->mutex);
if (cb_shutdown)
soundio->on_backend_disconnect(soundio, sica->shutdown_err);
else if (change)
soundio->on_devices_change(soundio);
soundio_destroy_devices_info(old_devices_info);
}
static void wait_events_ca(struct SoundIoPrivate *si) {
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
flush_events_ca(si);
soundio_os_cond_wait(sica->cond, NULL);
}
static void wakeup_ca(struct SoundIoPrivate *si) {
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
soundio_os_cond_signal(sica->cond, NULL);
}
static void force_device_scan_ca(struct SoundIoPrivate *si) {
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
SOUNDIO_ATOMIC_STORE(sica->device_scan_queued, true);
soundio_os_cond_signal(sica->scan_devices_cond, NULL);
}
static void device_thread_run(void *arg) {
struct SoundIoPrivate *si = (struct SoundIoPrivate *)arg;
struct SoundIo *soundio = &si->pub;
struct SoundIoCoreAudio *sica = &si->backend_data.coreaudio;
int err;
for (;;) {
if (!SOUNDIO_ATOMIC_FLAG_TEST_AND_SET(sica->abort_flag))
break;
if (SOUNDIO_ATOMIC_LOAD(sica->service_restarted)) {
shutdown_backend(si, SoundIoErrorBackendDisconnected);
return;
}
if (SOUNDIO_ATOMIC_EXCHANGE(sica->device_scan_queued, false)) {
err = refresh_devices(si);
if (err) {
shutdown_backend(si, err);
return;
}
if (!SOUNDIO_ATOMIC_EXCHANGE(sica->have_devices_flag, true))
soundio_os_cond_signal(sica->have_devices_cond, NULL);
soundio_os_cond_signal(sica->cond, NULL);
soundio->on_events_signal(soundio);
}
soundio_os_cond_wait(sica->scan_devices_cond, NULL);
}
}
static OSStatus on_outstream_device_overload(AudioObjectID in_object_id, UInt32 in_number_addresses,
const AudioObjectPropertyAddress in_addresses[], void *in_client_data)
{
struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *)in_client_data;
struct SoundIoOutStream *outstream = &os->pub;
outstream->underflow_callback(outstream);
return noErr;
}
static void outstream_destroy_ca(struct SoundIoPrivate *si, struct SoundIoOutStreamPrivate *os) {
struct SoundIoOutStreamCoreAudio *osca = &os->backend_data.coreaudio;
struct SoundIoOutStream *outstream = &os->pub;
struct SoundIoDevice *device = outstream->device;
struct SoundIoDevicePrivate *dev = (struct SoundIoDevicePrivate *)device;
struct SoundIoDeviceCoreAudio *dca = &dev->backend_data.coreaudio;
AudioObjectPropertyAddress prop_address = {
kAudioDeviceProcessorOverload,
kAudioObjectPropertyScopeGlobal,
kAudioObjectPropertyElementMaster
};
AudioObjectRemovePropertyListener(dca->device_id, &prop_address, on_outstream_device_overload, os);
if (osca->instance) {
AudioOutputUnitStop(osca->instance);
AudioComponentInstanceDispose(osca->instance);
osca->instance = NULL;
}
}
static OSStatus write_callback_ca(void *userdata, AudioUnitRenderActionFlags *io_action_flags,
const AudioTimeStamp *in_time_stamp, UInt32 in_bus_number, UInt32 in_number_frames,
AudioBufferList *io_data)
{
struct SoundIoOutStreamPrivate *os = (struct SoundIoOutStreamPrivate *) userdata;
struct SoundIoOutStream *outstream = &os->pub;
struct SoundIoOutStreamCoreAudio *osca = &os->backend_data.coreaudio;
osca->io_data = io_data;
osca->buffer_index = 0;
osca->frames_left = in_number_frames;
outstream->write_callback(outstream, osca->frames_left, osca->frames_left);
osca->io_data = NULL;
return noErr;
}
static int set_ca_desc(enum SoundIoFormat fmt, AudioStreamBasicDescription *desc) {
switch (fmt) {
case SoundIoFormatFloat32LE:
desc->mFormatFlags = kAudioFormatFlagIsFloat;
desc->mBitsPerChannel = 32;
break;
case SoundIoFormatFloat64LE:
desc->mFormatFlags = kAudioFormatFlagIsFloat;
desc->mBitsPerChannel = 64;
break;
case SoundIoFormatS32LE:
desc->mFormatFlags = kAudioFormatFlagIsSignedInteger;
desc->mBitsPerChannel = 32;
break;
case SoundIoFormatS16LE:
desc->mFormatFlags = kAudioFormatFlagIsSignedInteger;
desc->mBitsPerChannel = 16;
break;
default:
return SoundIoErrorIncompatibleDevice;
}
return 0;
}
static int outstream_open_ca(struct SoundIoPrivate *si, struct SoundIoOutStreamPrivate *os) {
struct SoundIoOutStreamCoreAudio *osca = &os->backend_data.coreaudio;
struct SoundIoOutStream *outstream = &os->pub;
struct SoundIoDevice *device = outstream->device;
struct SoundIoDevicePrivate *dev = (struct SoundIoDevicePrivate *)device;
struct SoundIoDeviceCoreAudio *dca = &dev->backend_data.coreaudio;
if (outstream->software_latency == 0.0)
outstream->software_latency = device->software_latency_current;
outstream->software_latency = soundio_double_clamp(
device->software_latency_min,
outstream->software_latency,
device->software_latency_max);
AudioComponentDescription desc = {0};
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_HALOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
AudioComponent component = AudioComponentFindNext(NULL, &desc);
if (!component) {
outstream_destroy_ca(si, os);
return SoundIoErrorOpeningDevice;
}
OSStatus os_err;
if ((os_err = AudioComponentInstanceNew(component, &osca->instance))) {
outstream_destroy_ca(si, os);
return SoundIoErrorOpeningDevice;
}
if ((os_err = AudioUnitInitialize(osca->instance))) {
outstream_destroy_ca(si, os);
return SoundIoErrorOpeningDevice;
}
AudioStreamBasicDescription format = {0};
format.mSampleRate = outstream->sample_rate;
format.mFormatID = kAudioFormatLinearPCM;
int err;
if ((err = set_ca_desc(outstream->format, &format))) {
outstream_destroy_ca(si, os);
return err;
}
format.mBytesPerPacket = outstream->bytes_per_frame;
format.mFramesPerPacket = 1;
format.mBytesPerFrame = outstream->bytes_per_frame;
format.mChannelsPerFrame = outstream->layout.channel_count;
if ((os_err = AudioUnitSetProperty(osca->instance, kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Input, OUTPUT_ELEMENT, &dca->device_id, sizeof(AudioDeviceID))))