audio_driver_wasapi.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. /*************************************************************************/
  2. /* audio_driver_wasapi.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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. Error AudioDriverWASAPI::init_device(bool reinit) {
  39. WAVEFORMATEX *pwfex;
  40. IMMDeviceEnumerator *enumerator = NULL;
  41. IMMDevice *device = NULL;
  42. CoInitialize(NULL);
  43. HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&enumerator);
  44. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  45. hr = enumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
  46. if (reinit) {
  47. // In case we're trying to re-initialize the device prevent throwing this error on the console,
  48. // otherwise if there is currently no devie available this will spam the console.
  49. if (hr != S_OK) {
  50. return ERR_CANT_OPEN;
  51. }
  52. } else {
  53. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  54. }
  55. hr = device->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&audio_client);
  56. if (reinit) {
  57. if (hr != S_OK) {
  58. return ERR_CANT_OPEN;
  59. }
  60. } else {
  61. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  62. }
  63. hr = audio_client->GetMixFormat(&pwfex);
  64. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  65. // Since we're using WASAPI Shared Mode we can't control any of these, we just tag along
  66. wasapi_channels = pwfex->nChannels;
  67. mix_rate = pwfex->nSamplesPerSec;
  68. format_tag = pwfex->wFormatTag;
  69. bits_per_sample = pwfex->wBitsPerSample;
  70. switch (wasapi_channels) {
  71. case 2: // Stereo
  72. case 4: // Surround 3.1
  73. case 6: // Surround 5.1
  74. case 8: // Surround 7.1
  75. channels = wasapi_channels;
  76. break;
  77. default:
  78. WARN_PRINTS("WASAPI: Unsupported number of channels: " + itos(wasapi_channels));
  79. channels = 2;
  80. break;
  81. }
  82. if (format_tag == WAVE_FORMAT_EXTENSIBLE) {
  83. WAVEFORMATEXTENSIBLE *wfex = (WAVEFORMATEXTENSIBLE *)pwfex;
  84. if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_PCM) {
  85. format_tag = WAVE_FORMAT_PCM;
  86. } else if (wfex->SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT) {
  87. format_tag = WAVE_FORMAT_IEEE_FLOAT;
  88. } else {
  89. ERR_PRINT("WASAPI: Format not supported");
  90. ERR_FAIL_V(ERR_CANT_OPEN);
  91. }
  92. } else {
  93. if (format_tag != WAVE_FORMAT_PCM && format_tag != WAVE_FORMAT_IEEE_FLOAT) {
  94. ERR_PRINT("WASAPI: Format not supported");
  95. ERR_FAIL_V(ERR_CANT_OPEN);
  96. }
  97. }
  98. hr = audio_client->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK, 0, 0, pwfex, NULL);
  99. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  100. event = CreateEvent(NULL, FALSE, FALSE, NULL);
  101. ERR_FAIL_COND_V(event == NULL, ERR_CANT_OPEN);
  102. hr = audio_client->SetEventHandle(event);
  103. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  104. hr = audio_client->GetService(IID_IAudioRenderClient, (void **)&render_client);
  105. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  106. UINT32 max_frames;
  107. hr = audio_client->GetBufferSize(&max_frames);
  108. ERR_FAIL_COND_V(hr != S_OK, ERR_CANT_OPEN);
  109. // Due to WASAPI Shared Mode we have no control of the buffer size
  110. buffer_frames = max_frames;
  111. // Sample rate is independent of channels (ref: https://stackoverflow.com/questions/11048825/audio-sample-frequency-rely-on-channels)
  112. buffer_size = buffer_frames * channels;
  113. samples_in.resize(buffer_size);
  114. if (OS::get_singleton()->is_stdout_verbose()) {
  115. print_line("WASAPI: detected " + itos(channels) + " channels");
  116. print_line("WASAPI: audio buffer frames: " + itos(buffer_frames) + " calculated latency: " + itos(buffer_frames * 1000 / mix_rate) + "ms");
  117. }
  118. return OK;
  119. }
  120. Error AudioDriverWASAPI::finish_device() {
  121. if (audio_client) {
  122. if (active) {
  123. audio_client->Stop();
  124. active = false;
  125. }
  126. }
  127. if (render_client) {
  128. render_client->Release();
  129. render_client = NULL;
  130. }
  131. if (audio_client) {
  132. audio_client->Release();
  133. audio_client = NULL;
  134. }
  135. return OK;
  136. }
  137. Error AudioDriverWASAPI::init() {
  138. Error err = init_device();
  139. if (err != OK) {
  140. ERR_PRINT("WASAPI: init_device error");
  141. }
  142. active = false;
  143. exit_thread = false;
  144. thread_exited = false;
  145. mutex = Mutex::create(true);
  146. thread = Thread::create(thread_func, this);
  147. return OK;
  148. }
  149. Error AudioDriverWASAPI::reopen() {
  150. Error err = finish_device();
  151. if (err != OK) {
  152. ERR_PRINT("WASAPI: finish_device error");
  153. } else {
  154. err = init_device();
  155. if (err != OK) {
  156. ERR_PRINT("WASAPI: init_device error");
  157. } else {
  158. start();
  159. }
  160. }
  161. return err;
  162. }
  163. int AudioDriverWASAPI::get_mix_rate() const {
  164. return mix_rate;
  165. }
  166. AudioDriver::SpeakerMode AudioDriverWASAPI::get_speaker_mode() const {
  167. return get_speaker_mode_by_total_channels(channels);
  168. }
  169. void AudioDriverWASAPI::write_sample(AudioDriverWASAPI *ad, BYTE *buffer, int i, int32_t sample) {
  170. if (ad->format_tag == WAVE_FORMAT_PCM) {
  171. switch (ad->bits_per_sample) {
  172. case 8:
  173. ((int8_t *)buffer)[i] = sample >> 24;
  174. break;
  175. case 16:
  176. ((int16_t *)buffer)[i] = sample >> 16;
  177. break;
  178. case 24:
  179. ((int8_t *)buffer)[i * 3 + 2] = sample >> 24;
  180. ((int8_t *)buffer)[i * 3 + 1] = sample >> 16;
  181. ((int8_t *)buffer)[i * 3 + 0] = sample >> 8;
  182. break;
  183. case 32:
  184. ((int32_t *)buffer)[i] = sample;
  185. break;
  186. }
  187. } else if (ad->format_tag == WAVE_FORMAT_IEEE_FLOAT) {
  188. ((float *)buffer)[i] = (sample >> 16) / 32768.f;
  189. } else {
  190. ERR_PRINT("WASAPI: Unknown format tag");
  191. ad->exit_thread = true;
  192. }
  193. }
  194. void AudioDriverWASAPI::thread_func(void *p_udata) {
  195. AudioDriverWASAPI *ad = (AudioDriverWASAPI *)p_udata;
  196. while (!ad->exit_thread) {
  197. if (ad->active) {
  198. ad->lock();
  199. ad->audio_server_process(ad->buffer_frames, ad->samples_in.ptrw());
  200. ad->unlock();
  201. } else {
  202. for (unsigned int i = 0; i < ad->buffer_size; i++) {
  203. ad->samples_in[i] = 0;
  204. }
  205. }
  206. unsigned int left_frames = ad->buffer_frames;
  207. unsigned int buffer_idx = 0;
  208. while (left_frames > 0 && ad->audio_client) {
  209. WaitForSingleObject(ad->event, 1000);
  210. UINT32 cur_frames;
  211. HRESULT hr = ad->audio_client->GetCurrentPadding(&cur_frames);
  212. if (hr == S_OK) {
  213. // Check how much frames are available on the WASAPI buffer
  214. UINT32 avail_frames = ad->buffer_frames - cur_frames;
  215. UINT32 write_frames = avail_frames > left_frames ? left_frames : avail_frames;
  216. BYTE *buffer = NULL;
  217. hr = ad->render_client->GetBuffer(write_frames, &buffer);
  218. if (hr == S_OK) {
  219. // We're using WASAPI Shared Mode so we must convert the buffer
  220. if (ad->channels == ad->wasapi_channels) {
  221. for (unsigned int i = 0; i < write_frames * ad->channels; i++) {
  222. ad->write_sample(ad, buffer, i, ad->samples_in[buffer_idx++]);
  223. }
  224. } else {
  225. for (unsigned int i = 0; i < write_frames; i++) {
  226. for (unsigned int j = 0; j < MIN(ad->channels, ad->wasapi_channels); j++) {
  227. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, ad->samples_in[buffer_idx++]);
  228. }
  229. if (ad->wasapi_channels > ad->channels) {
  230. for (unsigned int j = ad->channels; j < ad->wasapi_channels; j++) {
  231. ad->write_sample(ad, buffer, i * ad->wasapi_channels + j, 0);
  232. }
  233. }
  234. }
  235. }
  236. hr = ad->render_client->ReleaseBuffer(write_frames, 0);
  237. if (hr != S_OK) {
  238. ERR_PRINT("WASAPI: Release buffer error");
  239. }
  240. left_frames -= write_frames;
  241. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  242. // Device is not valid anymore, reopen it
  243. Error err = ad->finish_device();
  244. if (err != OK) {
  245. ERR_PRINT("WASAPI: finish_device error");
  246. } else {
  247. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  248. left_frames = 0;
  249. }
  250. } else {
  251. ERR_PRINT("WASAPI: Get buffer error");
  252. ad->exit_thread = true;
  253. }
  254. } else if (hr == AUDCLNT_E_DEVICE_INVALIDATED) {
  255. // Device is not valid anymore, reopen it
  256. Error err = ad->finish_device();
  257. if (err != OK) {
  258. ERR_PRINT("WASAPI: finish_device error");
  259. } else {
  260. // We reopened the device and samples_in may have resized, so invalidate the current left_frames
  261. left_frames = 0;
  262. }
  263. } else {
  264. ERR_PRINT("WASAPI: GetCurrentPadding error");
  265. }
  266. }
  267. if (!ad->audio_client) {
  268. Error err = ad->init_device(true);
  269. if (err == OK) {
  270. ad->start();
  271. }
  272. }
  273. }
  274. ad->thread_exited = true;
  275. }
  276. void AudioDriverWASAPI::start() {
  277. if (audio_client) {
  278. HRESULT hr = audio_client->Start();
  279. if (hr != S_OK) {
  280. ERR_PRINT("WASAPI: Start failed");
  281. } else {
  282. active = true;
  283. }
  284. }
  285. }
  286. void AudioDriverWASAPI::lock() {
  287. if (mutex)
  288. mutex->lock();
  289. }
  290. void AudioDriverWASAPI::unlock() {
  291. if (mutex)
  292. mutex->unlock();
  293. }
  294. void AudioDriverWASAPI::finish() {
  295. if (thread) {
  296. exit_thread = true;
  297. Thread::wait_to_finish(thread);
  298. memdelete(thread);
  299. thread = NULL;
  300. }
  301. finish_device();
  302. if (mutex) {
  303. memdelete(mutex);
  304. mutex = NULL;
  305. }
  306. }
  307. AudioDriverWASAPI::AudioDriverWASAPI() {
  308. audio_client = NULL;
  309. render_client = NULL;
  310. mutex = NULL;
  311. thread = NULL;
  312. format_tag = 0;
  313. bits_per_sample = 0;
  314. samples_in.clear();
  315. buffer_size = 0;
  316. channels = 0;
  317. wasapi_channels = 0;
  318. mix_rate = 0;
  319. buffer_frames = 0;
  320. thread_exited = false;
  321. exit_thread = false;
  322. active = false;
  323. }
  324. #endif