audio_driver_wasapi.cpp 10 KB

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