audio_driver_wasapi.cpp 11 KB

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