audio_driver_wasapi.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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. mix_rate = pwfex->nSamplesPerSec;
  129. format_tag = pwfex->wFormatTag;
  130. bits_per_sample = pwfex->wBitsPerSample;
  131. switch (wasapi_channels) {
  132. case 2: // Stereo
  133. case 4: // Surround 3.1
  134. case 6: // Surround 5.1
  135. case 8: // Surround 7.1
  136. channels = wasapi_channels;
  137. break;
  138. default:
  139. WARN_PRINTS("WASAPI: Unsupported number of channels: " + itos(wasapi_channels));
  140. channels = 2;
  141. break;
  142. }
  143. if (format_tag == WAVE_FORMAT_EXTENSIBLE) {
  144. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  145. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  146. format_tag = WAVE_FORMAT_PCM;
  147. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  148. format_tag = WAVE_FORMAT_IEEE_FLOAT;
  149. } else {
  150. ERR_PRINT("WASAPI: Format not supported");
  151. ERR_FAIL_V(ERR_CANT_OPEN);
  152. }
  153. } else {
  154. if (format_tag != WAVE_FORMAT_PCM && format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  155. ERR_PRINT("WASAPI: Format not supported");
  156. ERR_FAIL_V(ERR_CANT_OPEN);
  157. }
  158. }
  159. hr = audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, pwfex, NULL);
  160. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  161. event = CreateEvent(NULL, FALSE, FALSE, NULL);
  162. ERR_FAIL_COND_V(event == NULL, ERR_CANT_OPEN);
  163. hr = audio_client->SetEventHandle(event);
  164. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  165. hr = audio_client->GetService(IID_IAudioRenderClient, (void **)&render_client);
  166. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  167. UINT32 max_frames;
  168. hr = audio_client->GetBufferSize(&max_frames);
  169. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  170. // Due to WASAPI Shared Mode we have no control of the buffer size
  171. buffer_frames = max_frames;
  172. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  173. buffer_size = buffer_frames * channels;
  174. samples_in.resize(buffer_size);
  175. if (OS::get_singleton()->is_stdout_verbose()) {
  176. print_line("WASAPI: detected " + itos(channels) + " channels");
  177. print_line("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  178. }
  179. return OK;
  180. }
  181. Error AudioDriverWASAPI::finish_device() {
  182. if (audio_client) {
  183. if (active) {
  184. audio_client->Stop();
  185. audio_client->Release();
  186. audio_client = NULL;
  187. active = false;
  188. }
  189. }
  190. if (render_client) {
  191. render_client->Release();
  192. render_client = NULL;
  193. }
  194. if (audio_client) {
  195. audio_client->Release();
  196. audio_client = NULL;
  197. }
  198. return OK;
  199. }
  200. Error AudioDriverWASAPI::init() {
  201. Error err = init_device();
  202. if (err != OK) {
  203. ERR_PRINT("WASAPI: init_device error");
  204. }
  205. active = false;
  206. exit_thread = false;
  207. thread_exited = false;
  208. mutex = Mutex::create(true);
  209. thread = Thread::create(thread_func, this);
  210. return OK;
  211. }
  212. Error AudioDriverWASAPI::reopen() {
  213. Error err = finish_device();
  214. if (err != OK) {
  215. ERR_PRINT("WASAPI: finish_device error");
  216. } else {
  217. err = init_device();
  218. if (err != OK) {
  219. ERR_PRINT("WASAPI: init_device error");
  220. } else {
  221. start();
  222. }
  223. }
  224. return err;
  225. }
  226. int AudioDriverWASAPI::get_mix_rate() const {
  227. return mix_rate;
  228. }
  229. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  230. return get_speaker_mode_by_total_channels(channels);
  231. }
  232. void AudioDriverWASAPI::write_sample(AudioDriverWASAPI *ad, BYTE *buffer, int i, int32_t sample) {
  233. if (ad->format_tag == WAVE_FORMAT_PCM) {
  234. switch (ad->bits_per_sample) {
  235. case 8:
  236. ((int8_t *)buffer)[i] = sample >> 24;
  237. break;
  238. case 16:
  239. ((int16_t *)buffer)[i] = sample >> 16;
  240. break;
  241. case 24:
  242. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  243. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  244. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  245. break;
  246. case 32:
  247. ((int32_t *)buffer)[i] = sample;
  248. break;
  249. }
  250. } else if (ad->format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  251. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  252. } else {
  253. ERR_PRINT("WASAPI: Unknown format tag");
  254. ad->exit_thread = true;
  255. }
  256. }
  257. void AudioDriverWASAPI::thread_func(void *p_udata) {
  258. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  259. while (!ad->exit_thread) {
  260. if (ad->active) {
  261. ad->lock();
  262. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  263. ad->unlock();
  264. } else {
  265. for (unsigned int i = 0; i < ad->buffer_size; i++) {
  266. ad->samples_in[i] = 0;
  267. }
  268. }
  269. unsigned int left_frames = ad->buffer_frames;
  270. unsigned int buffer_idx = 0;
  271. while (left_frames > 0 && ad->audio_client) {
  272. WaitForSingleObject(ad->event, 1000);
  273. UINT32 cur_frames;
  274. HRESULT hr = ad->audio_client->GetCurrentPadding(&cur_frames);
  275. if (hr == S_OK) {
  276. // Check how much frames are available on the WASAPI buffer
  277. UINT32 avail_frames = ad->buffer_frames - cur_frames;
  278. UINT32 write_frames = avail_frames > left_frames ? left_frames : avail_frames;
  279. BYTE *buffer = NULL;
  280. hr = ad->render_client->GetBuffer(write_frames, &buffer);
  281. if (hr == S_OK) {
  282. // We're using WASAPI Shared Mode so we must convert the buffer
  283. if (ad->channels == ad->wasapi_channels) {
  284. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  285. ad->write_sample(ad, buffer, i, ad->samples_in[buffer_idx++]);
  286. }
  287. } else {
  288. for (unsigned int i = 0; i < write_frames; i++) {
  289. for (unsigned int j = 0; j < MIN(ad->channels, ad->wasapi_channels); j++) {
  290. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, ad->samples_in[buffer_idx++]);
  291. }
  292. if (ad->wasapi_channels > ad->channels) {
  293. for (unsigned int j = ad->channels; j < ad->wasapi_channels; j++) {
  294. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, 0);
  295. }
  296. }
  297. }
  298. }
  299. hr = ad->render_client->ReleaseBuffer(write_frames, 0);
  300. if (hr != S_OK) {
  301. ERR_PRINT("WASAPI: Release buffer error");
  302. }
  303. left_frames -= write_frames;
  304. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  305. // Device is not valid anymore, reopen it
  306. Error err = ad->finish_device();
  307. if (err != OK) {
  308. ERR_PRINT("WASAPI: finish_device error");
  309. } else {
  310. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  311. left_frames = 0;
  312. }
  313. } else {
  314. ERR_PRINT("WASAPI: Get buffer error");
  315. ad->exit_thread = true;
  316. }
  317. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  318. // Device is not valid anymore, reopen it
  319. Error err = ad->finish_device();
  320. if (err != OK) {
  321. ERR_PRINT("WASAPI: finish_device error");
  322. } else {
  323. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  324. left_frames = 0;
  325. }
  326. } else {
  327. ERR_PRINT("WASAPI: GetCurrentPadding error");
  328. }
  329. }
  330. if (default_device_changed) {
  331. Error err = ad->finish_device();
  332. if (err != OK) {
  333. ERR_PRINT("WASAPI: finish_device error");
  334. }
  335. default_device_changed = false;
  336. }
  337. if (!ad->audio_client) {
  338. Error err = ad->init_device(true);
  339. if (err == OK) {
  340. ad->start();
  341. }
  342. }
  343. }
  344. ad->thread_exited = true;
  345. }
  346. void AudioDriverWASAPI::start() {
  347. if (audio_client) {
  348. HRESULT hr = audio_client->Start();
  349. if (hr != S_OK) {
  350. ERR_PRINT("WASAPI: Start failed");
  351. } else {
  352. active = true;
  353. }
  354. }
  355. }
  356. void AudioDriverWASAPI::lock() {
  357. if (mutex)
  358. mutex->lock();
  359. }
  360. void AudioDriverWASAPI::unlock() {
  361. if (mutex)
  362. mutex->unlock();
  363. }
  364. void AudioDriverWASAPI::finish() {
  365. if (thread) {
  366. exit_thread = true;
  367. Thread::wait_to_finish(thread);
  368. memdelete(thread);
  369. thread = NULL;
  370. }
  371. finish_device();
  372. if (mutex) {
  373. memdelete(mutex);
  374. mutex = NULL;
  375. }
  376. }
  377. AudioDriverWASAPI::AudioDriverWASAPI() {
  378. audio_client = NULL;
  379. render_client = NULL;
  380. mutex = NULL;
  381. thread = NULL;
  382. format_tag = 0;
  383. bits_per_sample = 0;
  384. samples_in.clear();
  385. buffer_size = 0;
  386. channels = 0;
  387. wasapi_channels = 0;
  388. mix_rate = 0;
  389. buffer_frames = 0;
  390. thread_exited = false;
  391. exit_thread = false;
  392. active = false;
  393. }
  394. #endif