Debian Codegraph @

drivers/coreaudio/audio_driver_coreaudio.mm

raw
1 /**************************************************************************/
2 /* audio_driver_coreaudio.mm */
3 /**************************************************************************/
4 /* This file is part of: */
5 /* GODOT ENGINE */
6 /* https://godotengine.org */
7 /**************************************************************************/
8 /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9 /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10 /* */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the */
13 /* "Software"), to deal in the Software without restriction, including */
14 /* without limitation the rights to use, copy, modify, merge, publish, */
15 /* distribute, sublicense, and/or sell copies of the Software, and to */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions: */
18 /* */
19 /* The above copyright notice and this permission notice shall be */
20 /* included in all copies or substantial portions of the Software. */
21 /* */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29 /**************************************************************************/
30
31 #import "audio_driver_coreaudio.h"
32
33 #ifdef COREAUDIO_ENABLED
34
35 #include "core/config/project_settings.h"
36 #include "core/os/os.h"
37
38 #define kOutputBus 0
39 #define kInputBus 1
40
41 #ifdef MACOS_ENABLED
42 OSStatus AudioDriverCoreAudio::input_device_address_cb(AudioObjectID inObjectID,
43 UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses,
44 void *inClientData) {
45 AudioDriverCoreAudio *driver = static_cast<AudioDriverCoreAudio *>(inClientData);
46
47 // If our selected input device is the Default, call set_input_device to update the
48 // kAudioOutputUnitProperty_CurrentDevice property
49 if (driver->input_device_name == "Default") {
50 driver->set_input_device("Default");
51 }
52
53 return noErr;
54 }
55
56 OSStatus AudioDriverCoreAudio::output_device_address_cb(AudioObjectID inObjectID,
57 UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses,
58 void *inClientData) {
59 AudioDriverCoreAudio *driver = static_cast<AudioDriverCoreAudio *>(inClientData);
60
61 // If our selected output device is the Default call set_output_device to update the
62 // kAudioOutputUnitProperty_CurrentDevice property
63 if (driver->output_device_name == "Default") {
64 driver->set_output_device("Default");
65 }
66
67 return noErr;
68 }
69
70 // Switch to kAudioObjectPropertyElementMain everywhere to remove deprecated warnings.
71 #if (TARGET_OS_OSX && __MAC_OS_X_VERSION_MAX_ALLOWED < 120000) || (TARGET_OS_IOS && __IPHONE_OS_VERSION_MAX_ALLOWED < 150000)
72 #define kAudioObjectPropertyElementMain kAudioObjectPropertyElementMaster
73 #endif
74 #endif
75
76 Error AudioDriverCoreAudio::init() {
77 AudioComponentDescription desc;
78 memset(&desc, 0, sizeof(desc));
79 desc.componentType = kAudioUnitType_Output;
80 #ifdef MACOS_ENABLED
81 desc.componentSubType = kAudioUnitSubType_HALOutput;
82 #else
83 desc.componentSubType = kAudioUnitSubType_RemoteIO;
84 #endif
85 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
86
87 AudioComponent comp = AudioComponentFindNext(nullptr, &desc);
88 ERR_FAIL_NULL_V(comp, FAILED);
89
90 OSStatus result = AudioComponentInstanceNew(comp, &audio_unit);
91 ERR_FAIL_COND_V(result != noErr, FAILED);
92
93 #ifdef MACOS_ENABLED
94 AudioObjectPropertyAddress prop;
95 prop.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
96 prop.mScope = kAudioObjectPropertyScopeGlobal;
97 prop.mElement = kAudioObjectPropertyElementMain;
98
99 result = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &prop, &output_device_address_cb, this);
100 ERR_FAIL_COND_V(result != noErr, FAILED);
101 #endif
102
103 AudioStreamBasicDescription strdesc;
104
105 memset(&strdesc, 0, sizeof(strdesc));
106 UInt32 size = sizeof(strdesc);
107 result = AudioUnitGetProperty(audio_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kOutputBus, &strdesc, &size);
108 ERR_FAIL_COND_V(result != noErr, FAILED);
109
110 switch (strdesc.mChannelsPerFrame) {
111 case 2: // Stereo
112 case 4: // Surround 3.1
113 case 6: // Surround 5.1
114 case 8: // Surround 7.1
115 channels = strdesc.mChannelsPerFrame;
116 break;
117
118 default:
119 // Unknown number of channels, default to stereo
120 channels = 2;
121 break;
122 }
123
124 #ifdef MACOS_ENABLED
125 AudioDeviceID device_id;
126 UInt32 dev_id_size = sizeof(AudioDeviceID);
127
128 AudioObjectPropertyAddress property_dev_id = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
129 result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property_dev_id, 0, nullptr, &dev_id_size, &device_id);
130 ERR_FAIL_COND_V(result != noErr, FAILED);
131
132 double hw_mix_rate;
133 UInt32 hw_mix_rate_size = sizeof(hw_mix_rate);
134
135 AudioObjectPropertyAddress property_sr = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
136 result = AudioObjectGetPropertyData(device_id, &property_sr, 0, nullptr, &hw_mix_rate_size, &hw_mix_rate);
137 ERR_FAIL_COND_V(result != noErr, FAILED);
138 #else
139 double hw_mix_rate = [AVAudioSession sharedInstance].sampleRate;
140 #endif
141 mix_rate = hw_mix_rate;
142
143 memset(&strdesc, 0, sizeof(strdesc));
144 strdesc.mFormatID = kAudioFormatLinearPCM;
145 strdesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
146 strdesc.mChannelsPerFrame = channels;
147 strdesc.mSampleRate = mix_rate;
148 strdesc.mFramesPerPacket = 1;
149 strdesc.mBitsPerChannel = 16;
150 strdesc.mBytesPerFrame = strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
151 strdesc.mBytesPerPacket = strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
152
153 result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, kOutputBus, &strdesc, sizeof(strdesc));
154 ERR_FAIL_COND_V(result != noErr, FAILED);
155
156 uint32_t latency = Engine::get_singleton()->get_audio_output_latency();
157 // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
158 buffer_frames = closest_power_of_2(latency * (uint32_t)mix_rate / (uint32_t)1000);
159
160 #ifdef MACOS_ENABLED
161 result = AudioUnitSetProperty(audio_unit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, kOutputBus, &buffer_frames, sizeof(UInt32));
162 ERR_FAIL_COND_V(result != noErr, FAILED);
163 #endif
164
165 unsigned int buffer_size = buffer_frames * channels;
166 samples_in.resize(buffer_size);
167
168 print_verbose("CoreAudio: detected " + itos(channels) + " channels");
169 print_verbose("CoreAudio: output sampling rate: " + itos(mix_rate) + " Hz");
170 print_verbose("CoreAudio: output audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
171
172 AURenderCallbackStruct callback;
173 memset(&callback, 0, sizeof(AURenderCallbackStruct));
174 callback.inputProc = &AudioDriverCoreAudio::output_callback;
175 callback.inputProcRefCon = this;
176 result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, kOutputBus, &callback, sizeof(callback));
177 ERR_FAIL_COND_V(result != noErr, FAILED);
178
179 result = AudioUnitInitialize(audio_unit);
180 ERR_FAIL_COND_V(result != noErr, FAILED);
181
182 if (GLOBAL_GET("audio/driver/enable_input")) {
183 return init_input_device();
184 }
185 return OK;
186 }
187
188 OSStatus AudioDriverCoreAudio::output_callback(void *inRefCon,
189 AudioUnitRenderActionFlags *ioActionFlags,
190 const AudioTimeStamp *inTimeStamp,
191 UInt32 inBusNumber, UInt32 inNumberFrames,
192 AudioBufferList *ioData) {
193 AudioDriverCoreAudio *ad = static_cast<AudioDriverCoreAudio *>(inRefCon);
194
195 if (!ad->active || !ad->try_lock()) {
196 for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
197 AudioBuffer *abuf = &ioData->mBuffers[i];
198 memset(abuf->mData, 0, abuf->mDataByteSize);
199 }
200 return 0;
201 }
202
203 ad->start_counting_ticks();
204
205 for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
206 AudioBuffer *abuf = &ioData->mBuffers[i];
207 unsigned int frames_left = inNumberFrames;
208 int16_t *out = (int16_t *)abuf->mData;
209
210 while (frames_left) {
211 unsigned int frames = MIN(frames_left, ad->buffer_frames);
212 ad->audio_server_process(frames, ad->samples_in.ptrw());
213
214 for (unsigned int j = 0; j < frames * ad->channels; j++) {
215 out[j] = ad->samples_in[j] >> 16;
216 }
217
218 frames_left -= frames;
219 out += frames * ad->channels;
220 }
221 }
222
223 ad->stop_counting_ticks();
224 ad->unlock();
225
226 return 0;
227 }
228
229 OSStatus AudioDriverCoreAudio::input_callback(void *inRefCon,
230 AudioUnitRenderActionFlags *ioActionFlags,
231 const AudioTimeStamp *inTimeStamp,
232 UInt32 inBusNumber, UInt32 inNumberFrames,
233 AudioBufferList *ioData) {
234 AudioDriverCoreAudio *ad = static_cast<AudioDriverCoreAudio *>(inRefCon);
235 if (!ad->active) {
236 return 0;
237 }
238
239 ad->lock();
240 ad->start_counting_ticks();
241
242 AudioBufferList bufferList;
243 bufferList.mNumberBuffers = 1;
244 bufferList.mBuffers[0].mData = nullptr;
245 bufferList.mBuffers[0].mNumberChannels = ad->capture_channels;
246 bufferList.mBuffers[0].mDataByteSize = ad->buffer_size * sizeof(int16_t);
247
248 OSStatus result = AudioUnitRender(ad->input_unit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, &bufferList);
249 if (result == noErr) {
250 int16_t *data = (int16_t *)bufferList.mBuffers[0].mData;
251 for (unsigned int i = 0; i < inNumberFrames * ad->capture_channels; i++) {
252 int32_t sample = data[i] << 16;
253 ad->input_buffer_write(sample);
254
255 if (ad->capture_channels == 1) {
256 // In case input device is single channel convert it to Stereo
257 ad->input_buffer_write(sample);
258 }
259 }
260 } else {
261 ERR_PRINT("AudioUnitRender failed, code: " + itos(result));
262 }
263
264 ad->stop_counting_ticks();
265 ad->unlock();
266
267 return result;
268 }
269
270 void AudioDriverCoreAudio::start() {
271 if (!active && audio_unit != nullptr) {
272 OSStatus result = AudioOutputUnitStart(audio_unit);
273 if (result != noErr) {
274 ERR_PRINT("AudioOutputUnitStart failed, code: " + itos(result));
275 } else {
276 active = true;
277 }
278 }
279 }
280
281 void AudioDriverCoreAudio::stop() {
282 if (active) {
283 OSStatus result = AudioOutputUnitStop(audio_unit);
284 if (result != noErr) {
285 ERR_PRINT("AudioOutputUnitStop failed, code: " + itos(result));
286 } else {
287 active = false;
288 }
289 }
290 }
291
292 int AudioDriverCoreAudio::get_mix_rate() const {
293 return mix_rate;
294 }
295
296 int AudioDriverCoreAudio::get_input_mix_rate() const {
297 return capture_mix_rate;
298 }
299
300 AudioDriver::SpeakerMode AudioDriverCoreAudio::get_speaker_mode() const {
301 return get_speaker_mode_by_total_channels(channels);
302 }
303
304 void AudioDriverCoreAudio::lock() {
305 mutex.lock();
306 }
307
308 void AudioDriverCoreAudio::unlock() {
309 mutex.unlock();
310 }
311
312 bool AudioDriverCoreAudio::try_lock() {
313 return mutex.try_lock();
314 }
315
316 void AudioDriverCoreAudio::finish() {
317 finish_input_device();
318
319 if (audio_unit) {
320 OSStatus result;
321
322 lock();
323
324 AURenderCallbackStruct callback;
325 memset(&callback, 0, sizeof(AURenderCallbackStruct));
326 result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, kOutputBus, &callback, sizeof(callback));
327 if (result != noErr) {
328 ERR_PRINT("AudioUnitSetProperty failed");
329 }
330
331 if (active) {
332 result = AudioOutputUnitStop(audio_unit);
333 if (result != noErr) {
334 ERR_PRINT("AudioOutputUnitStop failed");
335 }
336
337 active = false;
338 }
339
340 result = AudioUnitUninitialize(audio_unit);
341 if (result != noErr) {
342 ERR_PRINT("AudioUnitUninitialize failed");
343 }
344
345 #ifdef MACOS_ENABLED
346 AudioObjectPropertyAddress prop;
347 prop.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
348 prop.mScope = kAudioObjectPropertyScopeGlobal;
349 prop.mElement = kAudioObjectPropertyElementMain;
350
351 result = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &prop, &output_device_address_cb, this);
352 if (result != noErr) {
353 ERR_PRINT("AudioObjectRemovePropertyListener failed");
354 }
355 #endif
356
357 result = AudioComponentInstanceDispose(audio_unit);
358 if (result != noErr) {
359 ERR_PRINT("AudioComponentInstanceDispose failed");
360 }
361
362 audio_unit = nullptr;
363 unlock();
364 }
365 }
366
367 Error AudioDriverCoreAudio::init_input_device() {
368 AudioComponentDescription desc;
369 memset(&desc, 0, sizeof(desc));
370 desc.componentType = kAudioUnitType_Output;
371 #ifdef MACOS_ENABLED
372 desc.componentSubType = kAudioUnitSubType_HALOutput;
373 #else
374 desc.componentSubType = kAudioUnitSubType_RemoteIO;
375 #endif
376 desc.componentManufacturer = kAudioUnitManufacturer_Apple;
377
378 AudioComponent comp = AudioComponentFindNext(nullptr, &desc);
379 ERR_FAIL_NULL_V(comp, FAILED);
380
381 OSStatus result = AudioComponentInstanceNew(comp, &input_unit);
382 ERR_FAIL_COND_V(result != noErr, FAILED);
383
384 #ifdef MACOS_ENABLED
385 AudioObjectPropertyAddress prop;
386 prop.mSelector = kAudioHardwarePropertyDefaultInputDevice;
387 prop.mScope = kAudioObjectPropertyScopeGlobal;
388 prop.mElement = kAudioObjectPropertyElementMain;
389
390 result = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &prop, &input_device_address_cb, this);
391 ERR_FAIL_COND_V(result != noErr, FAILED);
392 #endif
393
394 UInt32 flag = 1;
395 result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, kInputBus, &flag, sizeof(flag));
396 ERR_FAIL_COND_V(result != noErr, FAILED);
397 #ifdef MACOS_ENABLED
398 flag = 0;
399 result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, kOutputBus, &flag, sizeof(flag));
400 ERR_FAIL_COND_V(result != noErr, FAILED);
401 #endif
402
403 UInt32 size;
404 #ifdef MACOS_ENABLED
405 AudioDeviceID device_id;
406 size = sizeof(AudioDeviceID);
407 AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
408
409 result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, nullptr, &size, &device_id);
410 ERR_FAIL_COND_V(result != noErr, FAILED);
411
412 result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &device_id, sizeof(AudioDeviceID));
413 ERR_FAIL_COND_V(result != noErr, FAILED);
414 #endif
415
416 AudioStreamBasicDescription strdesc;
417 memset(&strdesc, 0, sizeof(strdesc));
418 size = sizeof(strdesc);
419 result = AudioUnitGetProperty(input_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kInputBus, &strdesc, &size);
420 ERR_FAIL_COND_V(result != noErr, FAILED);
421
422 switch (strdesc.mChannelsPerFrame) {
423 case 1: // Mono
424 capture_channels = 1;
425 break;
426
427 case 2: // Stereo
428 capture_channels = 2;
429 break;
430
431 default:
432 // Unknown number of channels, default to stereo
433 capture_channels = 2;
434 break;
435 }
436
437 #ifdef MACOS_ENABLED
438 double hw_mix_rate;
439 UInt32 hw_mix_rate_size = sizeof(hw_mix_rate);
440
441 AudioObjectPropertyAddress property_sr = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
442 result = AudioObjectGetPropertyData(device_id, &property_sr, 0, nullptr, &hw_mix_rate_size, &hw_mix_rate);
443 ERR_FAIL_COND_V(result != noErr, FAILED);
444 #else
445 double hw_mix_rate = [AVAudioSession sharedInstance].sampleRate;
446 #endif
447 capture_mix_rate = hw_mix_rate;
448
449 memset(&strdesc, 0, sizeof(strdesc));
450 strdesc.mFormatID = kAudioFormatLinearPCM;
451 strdesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
452 strdesc.mChannelsPerFrame = capture_channels;
453 strdesc.mSampleRate = capture_mix_rate;
454 strdesc.mFramesPerPacket = 1;
455 strdesc.mBitsPerChannel = 16;
456 strdesc.mBytesPerFrame = strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
457 strdesc.mBytesPerPacket = strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
458
459 result = AudioUnitSetProperty(input_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kInputBus, &strdesc, sizeof(strdesc));
460 ERR_FAIL_COND_V(result != noErr, FAILED);
461
462 uint32_t latency = Engine::get_singleton()->get_audio_output_latency();
463 // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
464 capture_buffer_frames = closest_power_of_2(latency * (uint32_t)capture_mix_rate / (uint32_t)1000);
465
466 buffer_size = capture_buffer_frames * capture_channels;
467
468 AURenderCallbackStruct callback;
469 memset(&callback, 0, sizeof(AURenderCallbackStruct));
470 callback.inputProc = &AudioDriverCoreAudio::input_callback;
471 callback.inputProcRefCon = this;
472 result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, kInputBus, &callback, sizeof(callback));
473 ERR_FAIL_COND_V(result != noErr, FAILED);
474
475 result = AudioUnitInitialize(input_unit);
476 ERR_FAIL_COND_V(result != noErr, FAILED);
477
478 print_verbose("CoreAudio: input sampling rate: " + itos(capture_mix_rate) + " Hz");
479 print_verbose("CoreAudio: input audio buffer frames: " + itos(capture_buffer_frames) + " calculated latency: " + itos(capture_buffer_frames * 1000 / capture_mix_rate) + "ms");
480
481 return OK;
482 }
483
484 void AudioDriverCoreAudio::finish_input_device() {
485 if (input_unit) {
486 lock();
487
488 AURenderCallbackStruct callback;
489 memset(&callback, 0, sizeof(AURenderCallbackStruct));
490 OSStatus result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callback, sizeof(callback));
491 if (result != noErr) {
492 ERR_PRINT("AudioUnitSetProperty failed");
493 }
494
495 result = AudioUnitUninitialize(input_unit);
496 if (result != noErr) {
497 ERR_PRINT("AudioUnitUninitialize failed");
498 }
499
500 #ifdef MACOS_ENABLED
501 AudioObjectPropertyAddress prop;
502 prop.mSelector = kAudioHardwarePropertyDefaultInputDevice;
503 prop.mScope = kAudioObjectPropertyScopeGlobal;
504 prop.mElement = kAudioObjectPropertyElementMain;
505
506 result = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &prop, &input_device_address_cb, this);
507 if (result != noErr) {
508 ERR_PRINT("AudioObjectRemovePropertyListener failed");
509 }
510 #endif
511
512 result = AudioComponentInstanceDispose(input_unit);
513 if (result != noErr) {
514 ERR_PRINT("AudioComponentInstanceDispose failed");
515 }
516
517 input_unit = nullptr;
518 unlock();
519 }
520 }
521
522 Error AudioDriverCoreAudio::input_start() {
523 ERR_FAIL_NULL_V(input_unit, FAILED);
524
525 input_buffer_init(capture_buffer_frames);
526
527 OSStatus result = AudioOutputUnitStart(input_unit);
528 if (result != noErr) {
529 ERR_PRINT("AudioOutputUnitStart failed, code: " + itos(result));
530 }
531
532 return OK;
533 }
534
535 Error AudioDriverCoreAudio::input_stop() {
536 if (input_unit) {
537 OSStatus result = AudioOutputUnitStop(input_unit);
538 if (result != noErr) {
539 ERR_PRINT("AudioOutputUnitStop failed, code: " + itos(result));
540 }
541 }
542
543 return OK;
544 }
545
546 #ifdef MACOS_ENABLED
547
548 PackedStringArray AudioDriverCoreAudio::_get_device_list(bool input) {
549 PackedStringArray list;
550
551 list.push_back("Default");
552
553 AudioObjectPropertyAddress prop;
554
555 prop.mSelector = kAudioHardwarePropertyDevices;
556 prop.mScope = kAudioObjectPropertyScopeGlobal;
557 prop.mElement = kAudioObjectPropertyElementMain;
558
559 UInt32 size = 0;
560 AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &prop, 0, nullptr, &size);
561 AudioDeviceID *audioDevices = (AudioDeviceID *)memalloc(size);
562 ERR_FAIL_NULL_V_MSG(audioDevices, list, "Out of memory.");
563 AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop, 0, nullptr, &size, audioDevices);
564
565 UInt32 deviceCount = size / sizeof(AudioDeviceID);
566 for (UInt32 i = 0; i < deviceCount; i++) {
567 prop.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
568 prop.mSelector = kAudioDevicePropertyStreamConfiguration;
569
570 AudioObjectGetPropertyDataSize(audioDevices[i], &prop, 0, nullptr, &size);
571 AudioBufferList *bufferList = (AudioBufferList *)memalloc(size);
572 ERR_FAIL_NULL_V_MSG(bufferList, list, "Out of memory.");
573 AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, bufferList);
574
575 UInt32 channelCount = 0;
576 for (UInt32 j = 0; j < bufferList->mNumberBuffers; j++) {
577 channelCount += bufferList->mBuffers[j].mNumberChannels;
578 }
579
580 memfree(bufferList);
581
582 if (channelCount >= 1) {
583 CFStringRef cfname;
584
585 size = sizeof(CFStringRef);
586 prop.mSelector = kAudioObjectPropertyName;
587
588 AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, &cfname);
589
590 CFIndex length = CFStringGetLength(cfname);
591 CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
592 char *buffer = (char *)memalloc(maxSize);
593 ERR_FAIL_NULL_V_MSG(buffer, list, "Out of memory.");
594 if (CFStringGetCString(cfname, buffer, maxSize, kCFStringEncodingUTF8)) {
595 // Append the ID to the name in case we have devices with duplicate name
596 list.push_back(String::utf8(buffer) + " (" + itos(audioDevices[i]) + ")");
597 }
598
599 memfree(buffer);
600 }
601 }
602
603 memfree(audioDevices);
604
605 return list;
606 }
607
608 void AudioDriverCoreAudio::_set_device(const String &output_device, bool input) {
609 AudioDeviceID device_id;
610 bool found = false;
611 if (output_device != "Default") {
612 AudioObjectPropertyAddress prop;
613
614 prop.mSelector = kAudioHardwarePropertyDevices;
615 prop.mScope = kAudioObjectPropertyScopeGlobal;
616 prop.mElement = kAudioObjectPropertyElementMain;
617
618 UInt32 size = 0;
619 AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &prop, 0, nullptr, &size);
620 AudioDeviceID *audioDevices = (AudioDeviceID *)memalloc(size);
621 ERR_FAIL_NULL_MSG(audioDevices, "Out of memory.");
622 AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop, 0, nullptr, &size, audioDevices);
623
624 UInt32 deviceCount = size / sizeof(AudioDeviceID);
625 for (UInt32 i = 0; i < deviceCount && !found; i++) {
626 prop.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
627 prop.mSelector = kAudioDevicePropertyStreamConfiguration;
628
629 AudioObjectGetPropertyDataSize(audioDevices[i], &prop, 0, nullptr, &size);
630 AudioBufferList *bufferList = (AudioBufferList *)memalloc(size);
631 ERR_FAIL_NULL_MSG(bufferList, "Out of memory.");
632 AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, bufferList);
633
634 UInt32 channelCount = 0;
635 for (UInt32 j = 0; j < bufferList->mNumberBuffers; j++) {
636 channelCount += bufferList->mBuffers[j].mNumberChannels;
637 }
638
639 memfree(bufferList);
640
641 if (channelCount >= 1) {
642 CFStringRef cfname;
643
644 size = sizeof(CFStringRef);
645 prop.mSelector = kAudioObjectPropertyName;
646
647 AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, &cfname);
648
649 CFIndex length = CFStringGetLength(cfname);
650 CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
651 char *buffer = (char *)memalloc(maxSize);
652 ERR_FAIL_NULL_MSG(buffer, "Out of memory.");
653 if (CFStringGetCString(cfname, buffer, maxSize, kCFStringEncodingUTF8)) {
654 String name = String::utf8(buffer) + " (" + itos(audioDevices[i]) + ")";
655 if (name == output_device) {
656 device_id = audioDevices[i];
657 found = true;
658 }
659 }
660
661 memfree(buffer);
662 }
663 }
664
665 memfree(audioDevices);
666 }
667
668 if (!found) {
669 // If we haven't found the desired device get the system default one
670 UInt32 size = sizeof(AudioDeviceID);
671 UInt32 elem = input ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
672 AudioObjectPropertyAddress property = { elem, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
673
674 OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, nullptr, &size, &device_id);
675 ERR_FAIL_COND(result != noErr);
676
677 found = true;
678 }
679
680 if (found) {
681 OSStatus result = AudioUnitSetProperty(input ? input_unit : audio_unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &device_id, sizeof(AudioDeviceID));
682 ERR_FAIL_COND(result != noErr);
683
684 if (input) {
685 // Reset audio input to keep synchronization.
686 input_position = 0;
687 input_size = 0;
688 }
689 }
690 }
691
692 PackedStringArray AudioDriverCoreAudio::get_output_device_list() {
693 return _get_device_list();
694 }
695
696 String AudioDriverCoreAudio::get_output_device() {
697 return output_device_name;
698 }
699
700 void AudioDriverCoreAudio::set_output_device(const String &p_name) {
701 output_device_name = p_name;
702 if (active) {
703 _set_device(output_device_name);
704 }
705 }
706
707 PackedStringArray AudioDriverCoreAudio::get_input_device_list() {
708 return _get_device_list(true);
709 }
710
711 String AudioDriverCoreAudio::get_input_device() {
712 return input_device_name;
713 }
714
715 void AudioDriverCoreAudio::set_input_device(const String &p_name) {
716 input_device_name = p_name;
717 if (active) {
718 _set_device(input_device_name, true);
719 }
720 }
721
722 #endif
723
724 AudioDriverCoreAudio::AudioDriverCoreAudio() {
725 samples_in.clear();
726 }
727
728 #endif // COREAUDIO_ENABLED