audio_driver_coreaudio.mm 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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. #include "audio_driver_coreaudio.h"
  31. #ifdef COREAUDIO_ENABLED
  32. #include "core/config/project_settings.h"
  33. #include "core/os/os.h"
  34. #define kOutputBus 0
  35. #define kInputBus 1
  36. #ifdef MACOS_ENABLED
  37. OSStatus AudioDriverCoreAudio::input_device_address_cb(AudioObjectID inObjectID,
  38. UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses,
  39. void *inClientData) {
  40. AudioDriverCoreAudio *driver = static_cast<AudioDriverCoreAudio *>(inClientData);
  41. // If our selected input device is the Default, call set_input_device to update the
  42. // kAudioOutputUnitProperty_CurrentDevice property
  43. if (driver->input_device_name == "Default") {
  44. driver->set_input_device("Default");
  45. }
  46. return noErr;
  47. }
  48. OSStatus AudioDriverCoreAudio::output_device_address_cb(AudioObjectID inObjectID,
  49. UInt32 inNumberAddresses, const AudioObjectPropertyAddress *inAddresses,
  50. void *inClientData) {
  51. AudioDriverCoreAudio *driver = static_cast<AudioDriverCoreAudio *>(inClientData);
  52. // If our selected output device is the Default call set_output_device to update the
  53. // kAudioOutputUnitProperty_CurrentDevice property
  54. if (driver->output_device_name == "Default") {
  55. driver->set_output_device("Default");
  56. }
  57. return noErr;
  58. }
  59. // Switch to kAudioObjectPropertyElementMain everywhere to remove deprecated warnings.
  60. #if (TARGET_OS_OSX && __MAC_OS_X_VERSION_MAX_ALLOWED < 120000) || (TARGET_OS_IOS && __IPHONE_OS_VERSION_MAX_ALLOWED < 150000)
  61. #define kAudioObjectPropertyElementMain kAudioObjectPropertyElementMaster
  62. #endif
  63. #endif
  64. Error AudioDriverCoreAudio::init() {
  65. AudioComponentDescription desc;
  66. memset(&desc, 0, sizeof(desc));
  67. desc.componentType = kAudioUnitType_Output;
  68. #ifdef MACOS_ENABLED
  69. desc.componentSubType = kAudioUnitSubType_HALOutput;
  70. #else
  71. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  72. #endif
  73. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  74. AudioComponent comp = AudioComponentFindNext(nullptr, &desc);
  75. ERR_FAIL_NULL_V(comp, FAILED);
  76. OSStatus result = AudioComponentInstanceNew(comp, &audio_unit);
  77. ERR_FAIL_COND_V(result != noErr, FAILED);
  78. #ifdef MACOS_ENABLED
  79. AudioObjectPropertyAddress prop;
  80. prop.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  81. prop.mScope = kAudioObjectPropertyScopeGlobal;
  82. prop.mElement = kAudioObjectPropertyElementMain;
  83. result = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &prop, &output_device_address_cb, this);
  84. ERR_FAIL_COND_V(result != noErr, FAILED);
  85. #endif
  86. AudioStreamBasicDescription strdesc;
  87. memset(&strdesc, 0, sizeof(strdesc));
  88. UInt32 size = sizeof(strdesc);
  89. result = AudioUnitGetProperty(audio_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kOutputBus, &strdesc, &size);
  90. ERR_FAIL_COND_V(result != noErr, FAILED);
  91. switch (strdesc.mChannelsPerFrame) {
  92. case 2: // Stereo
  93. case 4: // Surround 3.1
  94. case 6: // Surround 5.1
  95. case 8: // Surround 7.1
  96. channels = strdesc.mChannelsPerFrame;
  97. break;
  98. default:
  99. // Unknown number of channels, default to stereo
  100. channels = 2;
  101. break;
  102. }
  103. #ifdef MACOS_ENABLED
  104. AudioDeviceID device_id;
  105. UInt32 dev_id_size = sizeof(AudioDeviceID);
  106. AudioObjectPropertyAddress property_dev_id = { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster };
  107. result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property_dev_id, 0, nullptr, &dev_id_size, &device_id);
  108. ERR_FAIL_COND_V(result != noErr, FAILED);
  109. double hw_mix_rate;
  110. UInt32 hw_mix_rate_size = sizeof(hw_mix_rate);
  111. AudioObjectPropertyAddress property_sr = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
  112. result = AudioObjectGetPropertyData(device_id, &property_sr, 0, nullptr, &hw_mix_rate_size, &hw_mix_rate);
  113. ERR_FAIL_COND_V(result != noErr, FAILED);
  114. #else
  115. double hw_mix_rate = [AVAudioSession sharedInstance].sampleRate;
  116. #endif
  117. mix_rate = hw_mix_rate;
  118. memset(&strdesc, 0, sizeof(strdesc));
  119. strdesc.mFormatID = kAudioFormatLinearPCM;
  120. strdesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  121. strdesc.mChannelsPerFrame = channels;
  122. strdesc.mSampleRate = mix_rate;
  123. strdesc.mFramesPerPacket = 1;
  124. strdesc.mBitsPerChannel = 16;
  125. strdesc.mBytesPerFrame = strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
  126. strdesc.mBytesPerPacket = strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
  127. result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, kOutputBus, &strdesc, sizeof(strdesc));
  128. ERR_FAIL_COND_V(result != noErr, FAILED);
  129. int latency = Engine::get_singleton()->get_audio_output_latency();
  130. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  131. buffer_frames = closest_power_of_2(latency * mix_rate / 1000);
  132. #ifdef MACOS_ENABLED
  133. result = AudioUnitSetProperty(audio_unit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, kOutputBus, &buffer_frames, sizeof(UInt32));
  134. ERR_FAIL_COND_V(result != noErr, FAILED);
  135. #endif
  136. unsigned int buffer_size = buffer_frames * channels;
  137. samples_in.resize(buffer_size);
  138. print_verbose("CoreAudio: detected " + itos(channels) + " channels");
  139. print_verbose("CoreAudio: output sampling rate: " + itos(mix_rate) + " Hz");
  140. print_verbose("CoreAudio: output audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  141. AURenderCallbackStruct callback;
  142. memset(&callback, 0, sizeof(AURenderCallbackStruct));
  143. callback.inputProc = &AudioDriverCoreAudio::output_callback;
  144. callback.inputProcRefCon = this;
  145. result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, kOutputBus, &callback, sizeof(callback));
  146. ERR_FAIL_COND_V(result != noErr, FAILED);
  147. result = AudioUnitInitialize(audio_unit);
  148. ERR_FAIL_COND_V(result != noErr, FAILED);
  149. if (GLOBAL_GET("audio/driver/enable_input")) {
  150. return init_input_device();
  151. }
  152. return OK;
  153. }
  154. OSStatus AudioDriverCoreAudio::output_callback(void *inRefCon,
  155. AudioUnitRenderActionFlags *ioActionFlags,
  156. const AudioTimeStamp *inTimeStamp,
  157. UInt32 inBusNumber, UInt32 inNumberFrames,
  158. AudioBufferList *ioData) {
  159. AudioDriverCoreAudio *ad = static_cast<AudioDriverCoreAudio *>(inRefCon);
  160. if (!ad->active || !ad->try_lock()) {
  161. for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
  162. AudioBuffer *abuf = &ioData->mBuffers[i];
  163. memset(abuf->mData, 0, abuf->mDataByteSize);
  164. }
  165. return 0;
  166. }
  167. ad->start_counting_ticks();
  168. for (unsigned int i = 0; i < ioData->mNumberBuffers; i++) {
  169. AudioBuffer *abuf = &ioData->mBuffers[i];
  170. unsigned int frames_left = inNumberFrames;
  171. int16_t *out = (int16_t *)abuf->mData;
  172. while (frames_left) {
  173. unsigned int frames = MIN(frames_left, ad->buffer_frames);
  174. ad->audio_server_process(frames, ad->samples_in.ptrw());
  175. for (unsigned int j = 0; j < frames * ad->channels; j++) {
  176. out[j] = ad->samples_in[j] >> 16;
  177. }
  178. frames_left -= frames;
  179. out += frames * ad->channels;
  180. }
  181. }
  182. ad->stop_counting_ticks();
  183. ad->unlock();
  184. return 0;
  185. }
  186. OSStatus AudioDriverCoreAudio::input_callback(void *inRefCon,
  187. AudioUnitRenderActionFlags *ioActionFlags,
  188. const AudioTimeStamp *inTimeStamp,
  189. UInt32 inBusNumber, UInt32 inNumberFrames,
  190. AudioBufferList *ioData) {
  191. AudioDriverCoreAudio *ad = static_cast<AudioDriverCoreAudio *>(inRefCon);
  192. if (!ad->active) {
  193. return 0;
  194. }
  195. ad->lock();
  196. ad->start_counting_ticks();
  197. AudioBufferList bufferList;
  198. bufferList.mNumberBuffers = 1;
  199. bufferList.mBuffers[0].mData = ad->input_buf.ptrw();
  200. bufferList.mBuffers[0].mNumberChannels = ad->capture_channels;
  201. bufferList.mBuffers[0].mDataByteSize = ad->input_buf.size() * sizeof(int16_t);
  202. OSStatus result = AudioUnitRender(ad->input_unit, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, &bufferList);
  203. if (result == noErr) {
  204. for (unsigned int i = 0; i < inNumberFrames * ad->capture_channels; i++) {
  205. int32_t sample = ad->input_buf[i] << 16;
  206. ad->input_buffer_write(sample);
  207. if (ad->capture_channels == 1) {
  208. // In case input device is single channel convert it to Stereo
  209. ad->input_buffer_write(sample);
  210. }
  211. }
  212. } else {
  213. ERR_PRINT("AudioUnitRender failed, code: " + itos(result));
  214. }
  215. ad->stop_counting_ticks();
  216. ad->unlock();
  217. return result;
  218. }
  219. void AudioDriverCoreAudio::start() {
  220. if (!active && audio_unit != nullptr) {
  221. OSStatus result = AudioOutputUnitStart(audio_unit);
  222. if (result != noErr) {
  223. ERR_PRINT("AudioOutputUnitStart failed, code: " + itos(result));
  224. } else {
  225. active = true;
  226. }
  227. }
  228. }
  229. void AudioDriverCoreAudio::stop() {
  230. if (active) {
  231. OSStatus result = AudioOutputUnitStop(audio_unit);
  232. if (result != noErr) {
  233. ERR_PRINT("AudioOutputUnitStop failed, code: " + itos(result));
  234. } else {
  235. active = false;
  236. }
  237. }
  238. }
  239. int AudioDriverCoreAudio::get_mix_rate() const {
  240. return mix_rate;
  241. }
  242. int AudioDriverCoreAudio::get_input_mix_rate() const {
  243. return capture_mix_rate;
  244. }
  245. AudioDriver::SpeakerMode AudioDriverCoreAudio::get_speaker_mode() const {
  246. return get_speaker_mode_by_total_channels(channels);
  247. }
  248. void AudioDriverCoreAudio::lock() {
  249. mutex.lock();
  250. }
  251. void AudioDriverCoreAudio::unlock() {
  252. mutex.unlock();
  253. }
  254. bool AudioDriverCoreAudio::try_lock() {
  255. return mutex.try_lock();
  256. }
  257. void AudioDriverCoreAudio::finish() {
  258. finish_input_device();
  259. if (audio_unit) {
  260. OSStatus result;
  261. lock();
  262. AURenderCallbackStruct callback;
  263. memset(&callback, 0, sizeof(AURenderCallbackStruct));
  264. result = AudioUnitSetProperty(audio_unit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, kOutputBus, &callback, sizeof(callback));
  265. if (result != noErr) {
  266. ERR_PRINT("AudioUnitSetProperty failed");
  267. }
  268. if (active) {
  269. result = AudioOutputUnitStop(audio_unit);
  270. if (result != noErr) {
  271. ERR_PRINT("AudioOutputUnitStop failed");
  272. }
  273. active = false;
  274. }
  275. result = AudioUnitUninitialize(audio_unit);
  276. if (result != noErr) {
  277. ERR_PRINT("AudioUnitUninitialize failed");
  278. }
  279. #ifdef MACOS_ENABLED
  280. AudioObjectPropertyAddress prop;
  281. prop.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  282. prop.mScope = kAudioObjectPropertyScopeGlobal;
  283. prop.mElement = kAudioObjectPropertyElementMain;
  284. result = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &prop, &output_device_address_cb, this);
  285. if (result != noErr) {
  286. ERR_PRINT("AudioObjectRemovePropertyListener failed");
  287. }
  288. #endif
  289. result = AudioComponentInstanceDispose(audio_unit);
  290. if (result != noErr) {
  291. ERR_PRINT("AudioComponentInstanceDispose failed");
  292. }
  293. audio_unit = nullptr;
  294. unlock();
  295. }
  296. }
  297. Error AudioDriverCoreAudio::init_input_device() {
  298. AudioComponentDescription desc;
  299. memset(&desc, 0, sizeof(desc));
  300. desc.componentType = kAudioUnitType_Output;
  301. #ifdef MACOS_ENABLED
  302. desc.componentSubType = kAudioUnitSubType_HALOutput;
  303. #else
  304. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  305. #endif
  306. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  307. AudioComponent comp = AudioComponentFindNext(nullptr, &desc);
  308. ERR_FAIL_NULL_V(comp, FAILED);
  309. OSStatus result = AudioComponentInstanceNew(comp, &input_unit);
  310. ERR_FAIL_COND_V(result != noErr, FAILED);
  311. #ifdef MACOS_ENABLED
  312. AudioObjectPropertyAddress prop;
  313. prop.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  314. prop.mScope = kAudioObjectPropertyScopeGlobal;
  315. prop.mElement = kAudioObjectPropertyElementMain;
  316. result = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &prop, &input_device_address_cb, this);
  317. ERR_FAIL_COND_V(result != noErr, FAILED);
  318. #endif
  319. UInt32 flag = 1;
  320. result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, kInputBus, &flag, sizeof(flag));
  321. ERR_FAIL_COND_V(result != noErr, FAILED);
  322. flag = 0;
  323. result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, kOutputBus, &flag, sizeof(flag));
  324. ERR_FAIL_COND_V(result != noErr, FAILED);
  325. UInt32 size;
  326. #ifdef MACOS_ENABLED
  327. AudioDeviceID device_id;
  328. size = sizeof(AudioDeviceID);
  329. AudioObjectPropertyAddress property = { kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
  330. result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, nullptr, &size, &device_id);
  331. ERR_FAIL_COND_V(result != noErr, FAILED);
  332. result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &device_id, sizeof(AudioDeviceID));
  333. ERR_FAIL_COND_V(result != noErr, FAILED);
  334. #endif
  335. AudioStreamBasicDescription strdesc;
  336. memset(&strdesc, 0, sizeof(strdesc));
  337. size = sizeof(strdesc);
  338. result = AudioUnitGetProperty(input_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kInputBus, &strdesc, &size);
  339. ERR_FAIL_COND_V(result != noErr, FAILED);
  340. switch (strdesc.mChannelsPerFrame) {
  341. case 1: // Mono
  342. capture_channels = 1;
  343. break;
  344. case 2: // Stereo
  345. capture_channels = 2;
  346. break;
  347. default:
  348. // Unknown number of channels, default to stereo
  349. capture_channels = 2;
  350. break;
  351. }
  352. #ifdef MACOS_ENABLED
  353. double hw_mix_rate;
  354. UInt32 hw_mix_rate_size = sizeof(hw_mix_rate);
  355. AudioObjectPropertyAddress property_sr = { kAudioDevicePropertyNominalSampleRate, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
  356. result = AudioObjectGetPropertyData(device_id, &property_sr, 0, nullptr, &hw_mix_rate_size, &hw_mix_rate);
  357. ERR_FAIL_COND_V(result != noErr, FAILED);
  358. #else
  359. double hw_mix_rate = [AVAudioSession sharedInstance].sampleRate;
  360. #endif
  361. capture_mix_rate = hw_mix_rate;
  362. memset(&strdesc, 0, sizeof(strdesc));
  363. strdesc.mFormatID = kAudioFormatLinearPCM;
  364. strdesc.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  365. strdesc.mChannelsPerFrame = capture_channels;
  366. strdesc.mSampleRate = capture_mix_rate;
  367. strdesc.mFramesPerPacket = 1;
  368. strdesc.mBitsPerChannel = 16;
  369. strdesc.mBytesPerFrame = strdesc.mBitsPerChannel * strdesc.mChannelsPerFrame / 8;
  370. strdesc.mBytesPerPacket = strdesc.mBytesPerFrame * strdesc.mFramesPerPacket;
  371. result = AudioUnitSetProperty(input_unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kInputBus, &strdesc, sizeof(strdesc));
  372. ERR_FAIL_COND_V(result != noErr, FAILED);
  373. int latency = Engine::get_singleton()->get_audio_output_latency();
  374. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  375. capture_buffer_frames = closest_power_of_2(latency * capture_mix_rate / 1000);
  376. unsigned int buffer_size = capture_buffer_frames * capture_channels;
  377. input_buf.resize(buffer_size);
  378. AURenderCallbackStruct callback;
  379. memset(&callback, 0, sizeof(AURenderCallbackStruct));
  380. callback.inputProc = &AudioDriverCoreAudio::input_callback;
  381. callback.inputProcRefCon = this;
  382. result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, kInputBus, &callback, sizeof(callback));
  383. ERR_FAIL_COND_V(result != noErr, FAILED);
  384. result = AudioUnitInitialize(input_unit);
  385. ERR_FAIL_COND_V(result != noErr, FAILED);
  386. print_verbose("CoreAudio: input sampling rate: " + itos(capture_mix_rate) + " Hz");
  387. print_verbose("CoreAudio: input audio buffer frames: " + itos(capture_buffer_frames) + " calculated latency: " + itos(capture_buffer_frames * 1000 / capture_mix_rate) + "ms");
  388. return OK;
  389. }
  390. void AudioDriverCoreAudio::finish_input_device() {
  391. if (input_unit) {
  392. lock();
  393. AURenderCallbackStruct callback;
  394. memset(&callback, 0, sizeof(AURenderCallbackStruct));
  395. OSStatus result = AudioUnitSetProperty(input_unit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callback, sizeof(callback));
  396. if (result != noErr) {
  397. ERR_PRINT("AudioUnitSetProperty failed");
  398. }
  399. result = AudioUnitUninitialize(input_unit);
  400. if (result != noErr) {
  401. ERR_PRINT("AudioUnitUninitialize failed");
  402. }
  403. #ifdef MACOS_ENABLED
  404. AudioObjectPropertyAddress prop;
  405. prop.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  406. prop.mScope = kAudioObjectPropertyScopeGlobal;
  407. prop.mElement = kAudioObjectPropertyElementMain;
  408. result = AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &prop, &input_device_address_cb, this);
  409. if (result != noErr) {
  410. ERR_PRINT("AudioObjectRemovePropertyListener failed");
  411. }
  412. #endif
  413. result = AudioComponentInstanceDispose(input_unit);
  414. if (result != noErr) {
  415. ERR_PRINT("AudioComponentInstanceDispose failed");
  416. }
  417. input_unit = nullptr;
  418. unlock();
  419. }
  420. }
  421. Error AudioDriverCoreAudio::input_start() {
  422. input_buffer_init(capture_buffer_frames);
  423. OSStatus result = AudioOutputUnitStart(input_unit);
  424. if (result != noErr) {
  425. ERR_PRINT("AudioOutputUnitStart failed, code: " + itos(result));
  426. }
  427. return OK;
  428. }
  429. Error AudioDriverCoreAudio::input_stop() {
  430. if (input_unit) {
  431. OSStatus result = AudioOutputUnitStop(input_unit);
  432. if (result != noErr) {
  433. ERR_PRINT("AudioOutputUnitStop failed, code: " + itos(result));
  434. }
  435. }
  436. return OK;
  437. }
  438. #ifdef MACOS_ENABLED
  439. PackedStringArray AudioDriverCoreAudio::_get_device_list(bool input) {
  440. PackedStringArray list;
  441. list.push_back("Default");
  442. AudioObjectPropertyAddress prop;
  443. prop.mSelector = kAudioHardwarePropertyDevices;
  444. prop.mScope = kAudioObjectPropertyScopeGlobal;
  445. prop.mElement = kAudioObjectPropertyElementMain;
  446. UInt32 size = 0;
  447. AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &prop, 0, nullptr, &size);
  448. AudioDeviceID *audioDevices = (AudioDeviceID *)memalloc(size);
  449. ERR_FAIL_NULL_V_MSG(audioDevices, list, "Out of memory.");
  450. AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop, 0, nullptr, &size, audioDevices);
  451. UInt32 deviceCount = size / sizeof(AudioDeviceID);
  452. for (UInt32 i = 0; i < deviceCount; i++) {
  453. prop.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  454. prop.mSelector = kAudioDevicePropertyStreamConfiguration;
  455. AudioObjectGetPropertyDataSize(audioDevices[i], &prop, 0, nullptr, &size);
  456. AudioBufferList *bufferList = (AudioBufferList *)memalloc(size);
  457. ERR_FAIL_NULL_V_MSG(bufferList, list, "Out of memory.");
  458. AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, bufferList);
  459. UInt32 channelCount = 0;
  460. for (UInt32 j = 0; j < bufferList->mNumberBuffers; j++) {
  461. channelCount += bufferList->mBuffers[j].mNumberChannels;
  462. }
  463. memfree(bufferList);
  464. if (channelCount >= 1) {
  465. CFStringRef cfname;
  466. size = sizeof(CFStringRef);
  467. prop.mSelector = kAudioObjectPropertyName;
  468. AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, &cfname);
  469. CFIndex length = CFStringGetLength(cfname);
  470. CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
  471. char *buffer = (char *)memalloc(maxSize);
  472. ERR_FAIL_NULL_V_MSG(buffer, list, "Out of memory.");
  473. if (CFStringGetCString(cfname, buffer, maxSize, kCFStringEncodingUTF8)) {
  474. // Append the ID to the name in case we have devices with duplicate name
  475. list.push_back(String::utf8(buffer) + " (" + itos(audioDevices[i]) + ")");
  476. }
  477. memfree(buffer);
  478. }
  479. }
  480. memfree(audioDevices);
  481. return list;
  482. }
  483. void AudioDriverCoreAudio::_set_device(const String &output_device, bool input) {
  484. AudioDeviceID device_id;
  485. bool found = false;
  486. if (output_device != "Default") {
  487. AudioObjectPropertyAddress prop;
  488. prop.mSelector = kAudioHardwarePropertyDevices;
  489. prop.mScope = kAudioObjectPropertyScopeGlobal;
  490. prop.mElement = kAudioObjectPropertyElementMain;
  491. UInt32 size = 0;
  492. AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &prop, 0, nullptr, &size);
  493. AudioDeviceID *audioDevices = (AudioDeviceID *)memalloc(size);
  494. ERR_FAIL_NULL_MSG(audioDevices, "Out of memory.");
  495. AudioObjectGetPropertyData(kAudioObjectSystemObject, &prop, 0, nullptr, &size, audioDevices);
  496. UInt32 deviceCount = size / sizeof(AudioDeviceID);
  497. for (UInt32 i = 0; i < deviceCount && !found; i++) {
  498. prop.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  499. prop.mSelector = kAudioDevicePropertyStreamConfiguration;
  500. AudioObjectGetPropertyDataSize(audioDevices[i], &prop, 0, nullptr, &size);
  501. AudioBufferList *bufferList = (AudioBufferList *)memalloc(size);
  502. ERR_FAIL_NULL_MSG(bufferList, "Out of memory.");
  503. AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, bufferList);
  504. UInt32 channelCount = 0;
  505. for (UInt32 j = 0; j < bufferList->mNumberBuffers; j++) {
  506. channelCount += bufferList->mBuffers[j].mNumberChannels;
  507. }
  508. memfree(bufferList);
  509. if (channelCount >= 1) {
  510. CFStringRef cfname;
  511. size = sizeof(CFStringRef);
  512. prop.mSelector = kAudioObjectPropertyName;
  513. AudioObjectGetPropertyData(audioDevices[i], &prop, 0, nullptr, &size, &cfname);
  514. CFIndex length = CFStringGetLength(cfname);
  515. CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1;
  516. char *buffer = (char *)memalloc(maxSize);
  517. ERR_FAIL_NULL_MSG(buffer, "Out of memory.");
  518. if (CFStringGetCString(cfname, buffer, maxSize, kCFStringEncodingUTF8)) {
  519. String name = String::utf8(buffer) + " (" + itos(audioDevices[i]) + ")";
  520. if (name == output_device) {
  521. device_id = audioDevices[i];
  522. found = true;
  523. }
  524. }
  525. memfree(buffer);
  526. }
  527. }
  528. memfree(audioDevices);
  529. }
  530. if (!found) {
  531. // If we haven't found the desired device get the system default one
  532. UInt32 size = sizeof(AudioDeviceID);
  533. UInt32 elem = input ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  534. AudioObjectPropertyAddress property = { elem, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain };
  535. OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, &property, 0, nullptr, &size, &device_id);
  536. ERR_FAIL_COND(result != noErr);
  537. found = true;
  538. }
  539. if (found) {
  540. OSStatus result = AudioUnitSetProperty(input ? input_unit : audio_unit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &device_id, sizeof(AudioDeviceID));
  541. ERR_FAIL_COND(result != noErr);
  542. if (input) {
  543. // Reset audio input to keep synchronization.
  544. input_position = 0;
  545. input_size = 0;
  546. }
  547. }
  548. }
  549. PackedStringArray AudioDriverCoreAudio::get_output_device_list() {
  550. return _get_device_list();
  551. }
  552. String AudioDriverCoreAudio::get_output_device() {
  553. return output_device_name;
  554. }
  555. void AudioDriverCoreAudio::set_output_device(const String &p_name) {
  556. output_device_name = p_name;
  557. if (active) {
  558. _set_device(output_device_name);
  559. }
  560. }
  561. PackedStringArray AudioDriverCoreAudio::get_input_device_list() {
  562. return _get_device_list(true);
  563. }
  564. String AudioDriverCoreAudio::get_input_device() {
  565. return input_device_name;
  566. }
  567. void AudioDriverCoreAudio::set_input_device(const String &p_name) {
  568. input_device_name = p_name;
  569. if (active) {
  570. _set_device(input_device_name, true);
  571. }
  572. }
  573. #endif
  574. AudioDriverCoreAudio::AudioDriverCoreAudio() {
  575. samples_in.clear();
  576. }
  577. #endif // COREAUDIO_ENABLED