audio_driver_wasapi.cpp 13 KB

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