audio_driver_wasapi.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. /*************************************************************************/
  2. /* audio_driver_wasapi.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
  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. #ifdef WASAPI_ENABLED
  31. #include "audio_driver_wasapi.h"
  32. #include "os/os.h"
  33. #include "project_settings.h"
  34. const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
  35. const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
  36. const IID IID_IAudioClient = __uuidof(IAudioClient);
  37. const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
  38. static bool default_device_changed = false;
  39. class CMMNotificationClient : public IMMNotificationClient {
  40. LONG _cRef;
  41. IMMDeviceEnumerator *_pEnumerator;
  42. public:
  43. CMMNotificationClient() :
  44. _cRef(1),
  45. _pEnumerator(NULL) {}
  46. ~CMMNotificationClient() {
  47. if ((_pEnumerator) != NULL) {
  48. (_pEnumerator)->Release();
  49. (_pEnumerator) = NULL;
  50. }
  51. }
  52. ULONG STDMETHODCALLTYPE AddRef() {
  53. return InterlockedIncrement(&_cRef);
  54. }
  55. ULONG STDMETHODCALLTYPE Release() {
  56. ULONG ulRef = InterlockedDecrement(&_cRef);
  57. if (0 == ulRef) {
  58. delete this;
  59. }
  60. return ulRef;
  61. }
  62. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) {
  63. if (IID_IUnknown == riid) {
  64. AddRef();
  65. *ppvInterface = (IUnknown *)this;
  66. } else if (__uuidof(IMMNotificationClient) == riid) {
  67. AddRef();
  68. *ppvInterface = (IMMNotificationClient *)this;
  69. } else {
  70. *ppvInterface = NULL;
  71. return E_NOINTERFACE;
  72. }
  73. return S_OK;
  74. }
  75. HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {
  76. return S_OK;
  77. };
  78. HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {
  79. return S_OK;
  80. }
  81. HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {
  82. return S_OK;
  83. }
  84. HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {
  85. if (flow == eRender && role == eConsole) {
  86. default_device_changed = true;
  87. }
  88. return S_OK;
  89. }
  90. HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {
  91. return S_OK;
  92. }
  93. };
  94. static CMMNotificationClient notif_client;
  95. Error AudioDriverWASAPI::init_device(bool reinit) {
  96. WAVEFORMATEX *pwfex;
  97. IMMDeviceEnumerator *enumerator = NULL;
  98. IMMDevice *device = NULL;
  99. CoInitialize(NULL);
  100. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  101. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  102. hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
  103. if (reinit) {
  104. // In case we're trying to re-initialize the device prevent throwing this error on the console,
  105. // otherwise if there is currently no device available this will spam the console.
  106. if (hr != S_OK) {
  107. return ERR_CANT_OPEN;
  108. }
  109. } else {
  110. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  111. }
  112. hr = enumerator->RegisterEndpointNotificationCallback(&notif_client);
  113. if (hr != S_OK) {
  114. ERR_PRINT("WASAPI: RegisterEndpointNotificationCallback error");
  115. }
  116. hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&audio_client);
  117. if (reinit) {
  118. if (hr != S_OK) {
  119. return ERR_CANT_OPEN;
  120. }
  121. } else {
  122. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  123. }
  124. hr = audio_client->GetMixFormat(&pwfex);
  125. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  126. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  127. wasapi_channels = pwfex->nChannels;
  128. format_tag = pwfex->wFormatTag;
  129. bits_per_sample = pwfex->wBitsPerSample;
  130. switch (wasapi_channels) {
  131. case 2: // Stereo
  132. case 4: // Surround 3.1
  133. case 6: // Surround 5.1
  134. case 8: // Surround 7.1
  135. channels = wasapi_channels;
  136. break;
  137. default:
  138. WARN_PRINTS("WASAPI: Unsupported number of channels: " + itos(wasapi_channels));
  139. channels = 2;
  140. break;
  141. }
  142. if (format_tag == WAVE_FORMAT_EXTENSIBLE) {
  143. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  144. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  145. format_tag = WAVE_FORMAT_PCM;
  146. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  147. format_tag = WAVE_FORMAT_IEEE_FLOAT;
  148. } else {
  149. ERR_PRINT("WASAPI: Format not supported");
  150. ERR_FAIL_V(ERR_CANT_OPEN);
  151. }
  152. } else {
  153. if (format_tag != WAVE_FORMAT_PCM && format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  154. ERR_PRINT("WASAPI: Format not supported");
  155. ERR_FAIL_V(ERR_CANT_OPEN);
  156. }
  157. }
  158. DWORD streamflags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  159. if (mix_rate != pwfex->nSamplesPerSec) {
  160. streamflags |= AUDCLNT_STREAMFLAGS_RATEADJUST;
  161. pwfex->nSamplesPerSec = mix_rate;
  162. pwfex->nAvgBytesPerSec = pwfex->nSamplesPerSec * pwfex->nChannels * (pwfex->wBitsPerSample / 8);
  163. }
  164. hr = audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, streamflags, 0, 0, pwfex, NULL);
  165. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  166. event = CreateEvent(NULL, FALSE, FALSE, NULL);
  167. ERR_FAIL_COND_V(event == NULL, ERR_CANT_OPEN);
  168. hr = audio_client->SetEventHandle(event);
  169. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  170. hr = audio_client->GetService(IID_IAudioRenderClient, (void **)&render_client);
  171. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  172. UINT32 max_frames;
  173. hr = audio_client->GetBufferSize(&max_frames);
  174. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  175. // Due to WASAPI Shared Mode we have no control of the buffer size
  176. buffer_frames = max_frames;
  177. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  178. buffer_size = buffer_frames * channels;
  179. samples_in.resize(buffer_size);
  180. if (OS::get_singleton()->is_stdout_verbose()) {
  181. print_line("WASAPI: detected " + itos(channels) + " channels");
  182. print_line("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  183. }
  184. return OK;
  185. }
  186. Error AudioDriverWASAPI::finish_device() {
  187. if (audio_client) {
  188. if (active) {
  189. audio_client->Stop();
  190. active = false;
  191. }
  192. audio_client->Release();
  193. audio_client = NULL;
  194. }
  195. if (render_client) {
  196. render_client->Release();
  197. render_client = NULL;
  198. }
  199. if (audio_client) {
  200. audio_client->Release();
  201. audio_client = NULL;
  202. }
  203. return OK;
  204. }
  205. Error AudioDriverWASAPI::init() {
  206. mix_rate = GLOBAL_DEF("audio/mix_rate", DEFAULT_MIX_RATE);
  207. Error err = init_device();
  208. if (err != OK) {
  209. ERR_PRINT("WASAPI: init_device error");
  210. }
  211. active = false;
  212. exit_thread = false;
  213. thread_exited = false;
  214. mutex = Mutex::create(true);
  215. thread = Thread::create(thread_func, this);
  216. return OK;
  217. }
  218. Error AudioDriverWASAPI::reopen() {
  219. Error err = finish_device();
  220. if (err != OK) {
  221. ERR_PRINT("WASAPI: finish_device error");
  222. } else {
  223. err = init_device();
  224. if (err != OK) {
  225. ERR_PRINT("WASAPI: init_device error");
  226. } else {
  227. start();
  228. }
  229. }
  230. return err;
  231. }
  232. int AudioDriverWASAPI::get_mix_rate() const {
  233. return mix_rate;
  234. }
  235. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  236. return get_speaker_mode_by_total_channels(channels);
  237. }
  238. void AudioDriverWASAPI::write_sample(AudioDriverWASAPI *ad, BYTE *buffer, int i, int32_t sample) {
  239. if (ad->format_tag == WAVE_FORMAT_PCM) {
  240. switch (ad->bits_per_sample) {
  241. case 8:
  242. ((int8_t *)buffer)[i] = sample >> 24;
  243. break;
  244. case 16:
  245. ((int16_t *)buffer)[i] = sample >> 16;
  246. break;
  247. case 24:
  248. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  249. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  250. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  251. break;
  252. case 32:
  253. ((int32_t *)buffer)[i] = sample;
  254. break;
  255. }
  256. } else if (ad->format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  257. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  258. } else {
  259. ERR_PRINT("WASAPI: Unknown format tag");
  260. ad->exit_thread = true;
  261. }
  262. }
  263. void AudioDriverWASAPI::thread_func(void *p_udata) {
  264. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  265. while (!ad->exit_thread) {
  266. if (ad->active) {
  267. ad->lock();
  268. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  269. ad->unlock();
  270. } else {
  271. for (unsigned int i = 0; i < ad->buffer_size; i++) {
  272. ad->samples_in[i] = 0;
  273. }
  274. }
  275. unsigned int left_frames = ad->buffer_frames;
  276. unsigned int buffer_idx = 0;
  277. while (left_frames > 0 && ad->audio_client) {
  278. WaitForSingleObject(ad->event, 1000);
  279. UINT32 cur_frames;
  280. HRESULT hr = ad->audio_client->GetCurrentPadding(&cur_frames);
  281. if (hr == S_OK) {
  282. // Check how much frames are available on the WASAPI buffer
  283. UINT32 avail_frames = ad->buffer_frames - cur_frames;
  284. UINT32 write_frames = avail_frames > left_frames ? left_frames : avail_frames;
  285. BYTE *buffer = NULL;
  286. hr = ad->render_client->GetBuffer(write_frames, &buffer);
  287. if (hr == S_OK) {
  288. // We're using WASAPI Shared Mode so we must convert the buffer
  289. if (ad->channels == ad->wasapi_channels) {
  290. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  291. ad->write_sample(ad, buffer, i, ad->samples_in[buffer_idx++]);
  292. }
  293. } else {
  294. for (unsigned int i = 0; i < write_frames; i++) {
  295. for (unsigned int j = 0; j < MIN(ad->channels, ad->wasapi_channels); j++) {
  296. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, ad->samples_in[buffer_idx++]);
  297. }
  298. if (ad->wasapi_channels > ad->channels) {
  299. for (unsigned int j = ad->channels; j < ad->wasapi_channels; j++) {
  300. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, 0);
  301. }
  302. }
  303. }
  304. }
  305. hr = ad->render_client->ReleaseBuffer(write_frames, 0);
  306. if (hr != S_OK) {
  307. ERR_PRINT("WASAPI: Release buffer error");
  308. }
  309. left_frames -= write_frames;
  310. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  311. // Device is not valid anymore, reopen it
  312. Error err = ad->finish_device();
  313. if (err != OK) {
  314. ERR_PRINT("WASAPI: finish_device error");
  315. } else {
  316. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  317. left_frames = 0;
  318. }
  319. } else {
  320. ERR_PRINT("WASAPI: Get buffer error");
  321. ad->exit_thread = true;
  322. }
  323. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  324. // Device is not valid anymore, reopen it
  325. Error err = ad->finish_device();
  326. if (err != OK) {
  327. ERR_PRINT("WASAPI: finish_device error");
  328. } else {
  329. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  330. left_frames = 0;
  331. }
  332. } else {
  333. ERR_PRINT("WASAPI: GetCurrentPadding error");
  334. }
  335. }
  336. if (default_device_changed) {
  337. Error err = ad->finish_device();
  338. if (err != OK) {
  339. ERR_PRINT("WASAPI: finish_device error");
  340. }
  341. default_device_changed = false;
  342. }
  343. if (!ad->audio_client) {
  344. Error err = ad->init_device(true);
  345. if (err == OK) {
  346. ad->start();
  347. }
  348. }
  349. }
  350. ad->thread_exited = true;
  351. }
  352. void AudioDriverWASAPI::start() {
  353. if (audio_client) {
  354. HRESULT hr = audio_client->Start();
  355. if (hr != S_OK) {
  356. ERR_PRINT("WASAPI: Start failed");
  357. } else {
  358. active = true;
  359. }
  360. }
  361. }
  362. void AudioDriverWASAPI::lock() {
  363. if (mutex)
  364. mutex->lock();
  365. }
  366. void AudioDriverWASAPI::unlock() {
  367. if (mutex)
  368. mutex->unlock();
  369. }
  370. void AudioDriverWASAPI::finish() {
  371. if (thread) {
  372. exit_thread = true;
  373. Thread::wait_to_finish(thread);
  374. memdelete(thread);
  375. thread = NULL;
  376. }
  377. finish_device();
  378. if (mutex) {
  379. memdelete(mutex);
  380. mutex = NULL;
  381. }
  382. }
  383. AudioDriverWASAPI::AudioDriverWASAPI() {
  384. audio_client = NULL;
  385. render_client = NULL;
  386. mutex = NULL;
  387. thread = NULL;
  388. format_tag = 0;
  389. bits_per_sample = 0;
  390. samples_in.clear();
  391. buffer_size = 0;
  392. channels = 0;
  393. wasapi_channels = 0;
  394. mix_rate = 0;
  395. buffer_frames = 0;
  396. thread_exited = false;
  397. exit_thread = false;
  398. active = false;
  399. }
  400. #endif