SDL_wasapi_winrt.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2021 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "../../SDL_internal.h"
  19. // This is C++/CX code that the WinRT port uses to talk to WASAPI-related
  20. // system APIs. The C implementation of these functions, for non-WinRT apps,
  21. // is in SDL_wasapi_win32.c. The code in SDL_wasapi.c is used by both standard
  22. // Windows and WinRT builds to deal with audio and calls into these functions.
  23. #if SDL_AUDIO_DRIVER_WASAPI && defined(__WINRT__)
  24. #include <Windows.h>
  25. #include <windows.ui.core.h>
  26. #include <windows.devices.enumeration.h>
  27. #include <windows.media.devices.h>
  28. #include <wrl/implements.h>
  29. #include <collection.h>
  30. extern "C" {
  31. #include "../../core/windows/SDL_windows.h"
  32. #include "SDL_audio.h"
  33. #include "SDL_timer.h"
  34. #include "../SDL_audio_c.h"
  35. #include "../SDL_sysaudio.h"
  36. }
  37. #define COBJMACROS
  38. #include <mmdeviceapi.h>
  39. #include <audioclient.h>
  40. #include "SDL_wasapi.h"
  41. using namespace Windows::Devices::Enumeration;
  42. using namespace Windows::Media::Devices;
  43. using namespace Windows::Foundation;
  44. using namespace Microsoft::WRL;
  45. static Platform::String^ SDL_PKEY_AudioEngine_DeviceFormat = L"{f19f064d-082c-4e27-bc73-6882a1bb8e4c} 0";
  46. class SDL_WasapiDeviceEventHandler
  47. {
  48. public:
  49. SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture);
  50. ~SDL_WasapiDeviceEventHandler();
  51. void OnDeviceAdded(DeviceWatcher^ sender, DeviceInformation^ args);
  52. void OnDeviceRemoved(DeviceWatcher^ sender, DeviceInformationUpdate^ args);
  53. void OnDeviceUpdated(DeviceWatcher^ sender, DeviceInformationUpdate^ args);
  54. void OnEnumerationCompleted(DeviceWatcher^ sender, Platform::Object^ args);
  55. void OnDefaultRenderDeviceChanged(Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args);
  56. void OnDefaultCaptureDeviceChanged(Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args);
  57. SDL_semaphore* completed;
  58. private:
  59. const SDL_bool iscapture;
  60. DeviceWatcher^ watcher;
  61. Windows::Foundation::EventRegistrationToken added_handler;
  62. Windows::Foundation::EventRegistrationToken removed_handler;
  63. Windows::Foundation::EventRegistrationToken updated_handler;
  64. Windows::Foundation::EventRegistrationToken completed_handler;
  65. Windows::Foundation::EventRegistrationToken default_changed_handler;
  66. };
  67. SDL_WasapiDeviceEventHandler::SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture)
  68. : iscapture(_iscapture)
  69. , completed(SDL_CreateSemaphore(0))
  70. {
  71. if (!completed)
  72. return; // uhoh.
  73. Platform::String^ selector = _iscapture ? MediaDevice::GetAudioCaptureSelector() :
  74. MediaDevice::GetAudioRenderSelector();
  75. Platform::Collections::Vector<Platform::String^> properties;
  76. properties.Append(SDL_PKEY_AudioEngine_DeviceFormat);
  77. watcher = DeviceInformation::CreateWatcher(selector, properties.GetView());
  78. if (!watcher)
  79. return; // uhoh.
  80. // !!! FIXME: this doesn't need a lambda here, I think, if I make SDL_WasapiDeviceEventHandler a proper C++/CX class. --ryan.
  81. added_handler = watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>([this](DeviceWatcher^ sender, DeviceInformation^ args) { OnDeviceAdded(sender, args); } );
  82. removed_handler = watcher->Removed += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>([this](DeviceWatcher^ sender, DeviceInformationUpdate^ args) { OnDeviceRemoved(sender, args); } );
  83. updated_handler = watcher->Updated += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>([this](DeviceWatcher^ sender, DeviceInformationUpdate^ args) { OnDeviceUpdated(sender, args); } );
  84. completed_handler = watcher->EnumerationCompleted += ref new TypedEventHandler<DeviceWatcher^, Platform::Object^>([this](DeviceWatcher^ sender, Platform::Object^ args) { OnEnumerationCompleted(sender, args); } );
  85. if (iscapture) {
  86. default_changed_handler = MediaDevice::DefaultAudioCaptureDeviceChanged += ref new TypedEventHandler<Platform::Object^, DefaultAudioCaptureDeviceChangedEventArgs^>([this](Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args) { OnDefaultCaptureDeviceChanged(sender, args); } );
  87. } else {
  88. default_changed_handler = MediaDevice::DefaultAudioRenderDeviceChanged += ref new TypedEventHandler<Platform::Object^, DefaultAudioRenderDeviceChangedEventArgs^>([this](Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args) { OnDefaultRenderDeviceChanged(sender, args); } );
  89. }
  90. watcher->Start();
  91. }
  92. SDL_WasapiDeviceEventHandler::~SDL_WasapiDeviceEventHandler()
  93. {
  94. if (watcher) {
  95. watcher->Added -= added_handler;
  96. watcher->Removed -= removed_handler;
  97. watcher->Updated -= updated_handler;
  98. watcher->EnumerationCompleted -= completed_handler;
  99. watcher->Stop();
  100. watcher = nullptr;
  101. }
  102. if (completed) {
  103. SDL_DestroySemaphore(completed);
  104. completed = nullptr;
  105. }
  106. if (iscapture) {
  107. MediaDevice::DefaultAudioCaptureDeviceChanged -= default_changed_handler;
  108. } else {
  109. MediaDevice::DefaultAudioRenderDeviceChanged -= default_changed_handler;
  110. }
  111. }
  112. void
  113. SDL_WasapiDeviceEventHandler::OnDeviceAdded(DeviceWatcher^ sender, DeviceInformation^ info)
  114. {
  115. SDL_assert(sender == this->watcher);
  116. char *utf8dev = WIN_StringToUTF8(info->Name->Data());
  117. if (utf8dev) {
  118. WAVEFORMATEXTENSIBLE fmt;
  119. Platform::Object^ obj = info->Properties->Lookup(SDL_PKEY_AudioEngine_DeviceFormat);
  120. if (obj) {
  121. IPropertyValue^ property = (IPropertyValue^) obj;
  122. Platform::Array<unsigned char>^ data;
  123. property->GetUInt8Array(&data);
  124. SDL_memcpy(&fmt, data->Data, SDL_min(data->Length, sizeof(WAVEFORMATEXTENSIBLE)));
  125. } else {
  126. SDL_zero(fmt);
  127. }
  128. WASAPI_AddDevice(this->iscapture, utf8dev, &fmt, info->Id->Data());
  129. SDL_free(utf8dev);
  130. }
  131. }
  132. void
  133. SDL_WasapiDeviceEventHandler::OnDeviceRemoved(DeviceWatcher^ sender, DeviceInformationUpdate^ info)
  134. {
  135. SDL_assert(sender == this->watcher);
  136. WASAPI_RemoveDevice(this->iscapture, info->Id->Data());
  137. }
  138. void
  139. SDL_WasapiDeviceEventHandler::OnDeviceUpdated(DeviceWatcher^ sender, DeviceInformationUpdate^ args)
  140. {
  141. SDL_assert(sender == this->watcher);
  142. }
  143. void
  144. SDL_WasapiDeviceEventHandler::OnEnumerationCompleted(DeviceWatcher^ sender, Platform::Object^ args)
  145. {
  146. SDL_assert(sender == this->watcher);
  147. SDL_SemPost(this->completed);
  148. }
  149. void
  150. SDL_WasapiDeviceEventHandler::OnDefaultRenderDeviceChanged(Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args)
  151. {
  152. SDL_assert(this->iscapture);
  153. SDL_AtomicAdd(&WASAPI_DefaultPlaybackGeneration, 1);
  154. }
  155. void
  156. SDL_WasapiDeviceEventHandler::OnDefaultCaptureDeviceChanged(Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args)
  157. {
  158. SDL_assert(!this->iscapture);
  159. SDL_AtomicAdd(&WASAPI_DefaultCaptureGeneration, 1);
  160. }
  161. static SDL_WasapiDeviceEventHandler *playback_device_event_handler;
  162. static SDL_WasapiDeviceEventHandler *capture_device_event_handler;
  163. int WASAPI_PlatformInit(void)
  164. {
  165. return 0;
  166. }
  167. void WASAPI_PlatformDeinit(void)
  168. {
  169. delete playback_device_event_handler;
  170. playback_device_event_handler = nullptr;
  171. delete capture_device_event_handler;
  172. capture_device_event_handler = nullptr;
  173. }
  174. void WASAPI_EnumerateEndpoints(void)
  175. {
  176. // DeviceWatchers will fire an Added event for each existing device at
  177. // startup, so we don't need to enumerate them separately before
  178. // listening for updates.
  179. playback_device_event_handler = new SDL_WasapiDeviceEventHandler(SDL_FALSE);
  180. capture_device_event_handler = new SDL_WasapiDeviceEventHandler(SDL_TRUE);
  181. SDL_SemWait(playback_device_event_handler->completed);
  182. SDL_SemWait(capture_device_event_handler->completed);
  183. }
  184. struct SDL_WasapiActivationHandler : public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler >
  185. {
  186. SDL_WasapiActivationHandler() : device(nullptr) {}
  187. STDMETHOD(ActivateCompleted)(IActivateAudioInterfaceAsyncOperation *operation);
  188. SDL_AudioDevice *device;
  189. };
  190. HRESULT
  191. SDL_WasapiActivationHandler::ActivateCompleted(IActivateAudioInterfaceAsyncOperation *async)
  192. {
  193. // Just set a flag, since we're probably in a different thread. We'll pick it up and init everything on our own thread to prevent races.
  194. SDL_AtomicSet(&device->hidden->just_activated, 1);
  195. WASAPI_UnrefDevice(device);
  196. return S_OK;
  197. }
  198. void
  199. WASAPI_PlatformDeleteActivationHandler(void *handler)
  200. {
  201. ((SDL_WasapiActivationHandler *) handler)->Release();
  202. }
  203. int
  204. WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
  205. {
  206. LPCWSTR devid = _this->hidden->devid;
  207. Platform::String^ defdevid;
  208. if (devid == nullptr) {
  209. defdevid = _this->iscapture ? MediaDevice::GetDefaultAudioCaptureId(AudioDeviceRole::Default) : MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default);
  210. if (defdevid) {
  211. devid = defdevid->Data();
  212. }
  213. }
  214. SDL_AtomicSet(&_this->hidden->just_activated, 0);
  215. ComPtr<SDL_WasapiActivationHandler> handler = Make<SDL_WasapiActivationHandler>();
  216. if (handler == nullptr) {
  217. return SDL_SetError("Failed to allocate WASAPI activation handler");
  218. }
  219. handler.Get()->AddRef(); // we hold a reference after ComPtr destructs on return, causing a Release, and Release ourselves in WASAPI_PlatformDeleteActivationHandler(), etc.
  220. handler.Get()->device = _this;
  221. _this->hidden->activation_handler = handler.Get();
  222. WASAPI_RefDevice(_this); /* completion handler will unref it. */
  223. IActivateAudioInterfaceAsyncOperation *async = nullptr;
  224. const HRESULT ret = ActivateAudioInterfaceAsync(devid, __uuidof(IAudioClient), nullptr, handler.Get(), &async);
  225. if (FAILED(ret) || async == nullptr) {
  226. if (async != nullptr) {
  227. async->Release();
  228. }
  229. handler.Get()->Release();
  230. WASAPI_UnrefDevice(_this);
  231. return WIN_SetErrorFromHRESULT("WASAPI can't activate requested audio endpoint", ret);
  232. }
  233. /* Spin until the async operation is complete.
  234. * If we don't PrepDevice before leaving this function, the bug list gets LONG:
  235. * - device.spec is not filled with the correct information
  236. * - The 'obtained' spec will be wrong for ALLOW_CHANGE properties
  237. * - SDL_AudioStreams will/will not be allocated at the right time
  238. * - SDL_assert(device->callbackspec.size == device->spec.size) will fail
  239. * - When the assert is ignored, skipping or a buffer overflow will occur
  240. */
  241. while (!SDL_AtomicCAS(&_this->hidden->just_activated, 1, 0)) {
  242. SDL_Delay(1);
  243. }
  244. HRESULT activateRes = S_OK;
  245. IUnknown *iunknown = nullptr;
  246. const HRESULT getActivateRes = async->GetActivateResult(&activateRes, &iunknown);
  247. async->Release();
  248. if (FAILED(getActivateRes)) {
  249. return WIN_SetErrorFromHRESULT("Failed to get WASAPI activate result", getActivateRes);
  250. } else if (FAILED(activateRes)) {
  251. return WIN_SetErrorFromHRESULT("Failed to activate WASAPI device", activateRes);
  252. }
  253. iunknown->QueryInterface(IID_PPV_ARGS(&_this->hidden->client));
  254. if (!_this->hidden->client) {
  255. return SDL_SetError("Failed to query WASAPI client interface");
  256. }
  257. if (WASAPI_PrepDevice(_this, isrecovery) == -1) {
  258. return -1;
  259. }
  260. return 0;
  261. }
  262. void
  263. WASAPI_PlatformThreadInit(_THIS)
  264. {
  265. // !!! FIXME: set this thread to "Pro Audio" priority.
  266. }
  267. void
  268. WASAPI_PlatformThreadDeinit(_THIS)
  269. {
  270. // !!! FIXME: set this thread to "Pro Audio" priority.
  271. }
  272. #endif // SDL_AUDIO_DRIVER_WASAPI && defined(__WINRT__)
  273. /* vi: set ts=4 sw=4 expandtab: */