audio: Port WASAPI to WinRT, remove XAudio2 backend.

XAudio2 doesn't have capture support, so WASAPI was to replace it; the holdout
was WinRT, which still needed it as its primary audio target until the WASAPI
code code be made to work.

The support matrix now looks like:

WinXP: directsound by default, winmm as a fallback for buggy drivers.
Vista+: WASAPI (directsound and winmm as fallbacks for debugging).
WinRT: WASAPI
This commit is contained in:
Ryan C. Gordon
2017-12-06 12:24:32 -05:00
parent 083fe066d5
commit 351d6d4784
30 changed files with 958 additions and 1518 deletions

View File

@@ -37,14 +37,9 @@
#include "SDL_wasapi.h"
static const ERole SDL_WASAPI_role = eConsole; /* !!! FIXME: should this be eMultimedia? Should be a hint? */
/* This is global to the WASAPI target, to handle hotplug and default device lookup. */
static IMMDeviceEnumerator *enumerator = NULL;
/* these increment as default devices change. Opened default devices pick up changes in their threads. */
static SDL_atomic_t default_playback_generation;
static SDL_atomic_t default_capture_generation;
SDL_atomic_t WASAPI_DefaultPlaybackGeneration;
SDL_atomic_t WASAPI_DefaultCaptureGeneration;
/* This is a list of device id strings we have inflight, so we have consistent pointers to the same device. */
typedef struct DevIdList
@@ -55,173 +50,11 @@ typedef struct DevIdList
static DevIdList *deviceid_list = NULL;
/* handle to Avrt.dll--Vista and later!--for flagging the callback thread as "Pro Audio" (low latency). */
#ifndef __WINRT__
static HMODULE libavrt = NULL;
#endif
typedef HANDLE (WINAPI *pfnAvSetMmThreadCharacteristicsW)(LPWSTR,LPDWORD);
typedef BOOL (WINAPI *pfnAvRevertMmThreadCharacteristics)(HANDLE);
static pfnAvSetMmThreadCharacteristicsW pAvSetMmThreadCharacteristicsW = NULL;
static pfnAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
/* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c, { 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35, { 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85, { 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } };
static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089, { 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } };
static const IID SDL_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32, { 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } };
static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483, { 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0, { 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd, { 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 };
/* PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency. */
#ifdef PropVariantInit
#undef PropVariantInit
#endif
#define PropVariantInit(p) SDL_zerop(p)
static void AddWASAPIDevice(const SDL_bool iscapture, IMMDevice *device, LPCWSTR devid);
static void RemoveWASAPIDevice(const SDL_bool iscapture, LPCWSTR devid);
/* We need a COM subclass of IMMNotificationClient for hotplug support, which is
easy in C++, but we have to tapdance more to make work in C.
Thanks to this page for coaching on how to make this work:
https://www.codeproject.com/Articles/13601/COM-in-plain-C */
typedef struct SDLMMNotificationClient
{
const IMMNotificationClientVtbl *lpVtbl;
SDL_atomic_t refcount;
} SDLMMNotificationClient;
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid, void **ppv)
{
if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient)))
{
*ppv = this;
this->lpVtbl->AddRef(this);
return S_OK;
}
*ppv = NULL;
return E_NOINTERFACE;
}
static ULONG STDMETHODCALLTYPE
SDLMMNotificationClient_AddRef(IMMNotificationClient *ithis)
{
SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
return (ULONG) (SDL_AtomicIncRef(&this->refcount) + 1);
}
static ULONG STDMETHODCALLTYPE
SDLMMNotificationClient_Release(IMMNotificationClient *ithis)
{
/* this is a static object; we don't ever free it. */
SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
const ULONG retval = SDL_AtomicDecRef(&this->refcount);
if (retval == 0) {
SDL_AtomicSet(&this->refcount, 0); /* uhh... */
return 0;
}
return retval - 1;
}
/* These are the entry points called when WASAPI device endpoints change. */
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
{
if (role != SDL_WASAPI_role) {
return S_OK; /* ignore it. */
}
/* Increment the "generation," so opened devices will pick this up in their threads. */
switch (flow) {
case eRender:
SDL_AtomicAdd(&default_playback_generation, 1);
break;
case eCapture:
SDL_AtomicAdd(&default_capture_generation, 1);
break;
case eAll:
SDL_AtomicAdd(&default_playback_generation, 1);
SDL_AtomicAdd(&default_capture_generation, 1);
break;
default:
SDL_assert(!"uhoh, unexpected OnDefaultDeviceChange flow!");
break;
}
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
{
/* we ignore this; devices added here then progress to ACTIVE, if appropriate, in
OnDeviceStateChange, making that a better place to deal with device adds. More
importantly: the first time you plug in a USB audio device, this callback will
fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT).
Plugging it back in won't fire this callback again. */
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
{
/* See notes in OnDeviceAdded handler about why we ignore this. */
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId, DWORD dwNewState)
{
IMMDevice *device = NULL;
if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) {
IMMEndpoint *endpoint = NULL;
if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **) &endpoint))) {
EDataFlow flow;
if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) {
const SDL_bool iscapture = (flow == eCapture);
if (dwNewState == DEVICE_STATE_ACTIVE) {
AddWASAPIDevice(iscapture, device, pwstrDeviceId);
} else {
RemoveWASAPIDevice(iscapture, pwstrDeviceId);
}
}
IMMEndpoint_Release(endpoint);
}
IMMDevice_Release(device);
}
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *this, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
{
return S_OK; /* we don't care about these. */
}
static const IMMNotificationClientVtbl notification_client_vtbl = {
SDLMMNotificationClient_QueryInterface,
SDLMMNotificationClient_AddRef,
SDLMMNotificationClient_Release,
SDLMMNotificationClient_OnDeviceStateChanged,
SDLMMNotificationClient_OnDeviceAdded,
SDLMMNotificationClient_OnDeviceRemoved,
SDLMMNotificationClient_OnDefaultDeviceChanged,
SDLMMNotificationClient_OnPropertyValueChanged
};
static SDLMMNotificationClient notification_client = { &notification_client_vtbl, { 1 } };
static const IID SDL_IID_IAudioRenderClient = { 0xf294acfc, 0x3146, 0x4483,{ 0xa7, 0xbf, 0xad, 0xdc, 0xa7, 0xc2, 0x60, 0xe2 } };
static const IID SDL_IID_IAudioCaptureClient = { 0xc8adbd64, 0xe71e, 0x48a0,{ 0xa4, 0xde, 0x18, 0x5c, 0x39, 0x5c, 0xd3, 0x17 } };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_PCM = { 0x00000001, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static const GUID SDL_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = { 0x00000003, 0x0000, 0x0010,{ 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
static SDL_bool
WStrEqual(const WCHAR *a, const WCHAR *b)
@@ -236,10 +69,22 @@ WStrEqual(const WCHAR *a, const WCHAR *b)
return *b == 0;
}
static size_t
WStrLen(const WCHAR *wstr)
{
size_t retval = 0;
if (wstr) {
while (*(wstr++)) {
retval++;
}
}
return retval;
}
static WCHAR *
WStrDupe(const WCHAR *wstr)
{
const int len = (lstrlenW(wstr) + 1) * sizeof (WCHAR);
const int len = (WStrLen(wstr) + 1) * sizeof (WCHAR);
WCHAR *retval = (WCHAR *) SDL_malloc(len);
if (retval) {
SDL_memcpy(retval, wstr, len);
@@ -247,8 +92,9 @@ WStrDupe(const WCHAR *wstr)
return retval;
}
static void
RemoveWASAPIDevice(const SDL_bool iscapture, LPCWSTR devid)
void
WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid)
{
DevIdList *i;
DevIdList *next;
@@ -269,23 +115,16 @@ RemoveWASAPIDevice(const SDL_bool iscapture, LPCWSTR devid)
}
}
static void
AddWASAPIDevice(const SDL_bool iscapture, IMMDevice *device, LPCWSTR devid)
void
WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, LPCWSTR devid)
{
IPropertyStore *props = NULL;
char *utf8dev = NULL;
DevIdList *devidlist;
PROPVARIANT var;
/* You can have multiple endpoints on a device that are mutually exclusive ("Speakers" vs "Line Out" or whatever).
In a perfect world, things that are unplugged won't be in this collection. The only gotcha is probably for
phones and tablets, where you might have an internal speaker and a headphone jack and expect both to be
available and switch automatically. (!!! FIXME...?) */
/* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be
"SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in
its own UIs, like Volume Control, etc. */
/* see if we already have this one. */
for (devidlist = deviceid_list; devidlist; devidlist = devidlist->next) {
if (WStrEqual(devidlist->str, devid)) {
@@ -308,61 +147,13 @@ AddWASAPIDevice(const SDL_bool iscapture, IMMDevice *device, LPCWSTR devid)
devidlist->next = deviceid_list;
deviceid_list = devidlist;
if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) {
PropVariantInit(&var);
if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) {
utf8dev = WIN_StringToUTF8(var.pwszVal);
if (utf8dev) {
SDL_AddAudioDevice(iscapture, utf8dev, (void *) devid);
SDL_free(utf8dev);
}
}
PropVariantClear(&var);
IPropertyStore_Release(props);
}
}
static void
EnumerateEndpoints(const SDL_bool iscapture)
{
IMMDeviceCollection *collection = NULL;
UINT i, total;
/* Note that WASAPI separates "adapter devices" from "audio endpoint devices"
...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */
if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, iscapture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) {
return;
}
if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) {
IMMDeviceCollection_Release(collection);
return;
}
for (i = 0; i < total; i++) {
IMMDevice *device = NULL;
if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &device))) {
LPWSTR devid = NULL;
if (SUCCEEDED(IMMDevice_GetId(device, &devid))) {
AddWASAPIDevice(iscapture, device, devid);
CoTaskMemFree(devid);
}
IMMDevice_Release(device);
}
}
IMMDeviceCollection_Release(collection);
SDL_AddAudioDevice(iscapture, devname, (void *) devid);
}
static void
WASAPI_DetectDevices(void)
{
EnumerateEndpoints(SDL_FALSE); /* playback */
EnumerateEndpoints(SDL_TRUE); /* capture */
/* if this fails, we just won't get hotplug events. Carry on anyhow. */
IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
WASAPI_EnumerateEndpoints();
}
static int
@@ -372,10 +163,11 @@ WASAPI_GetPendingBytes(_THIS)
/* it's okay to fail here; we'll deal with failures in the audio thread. */
/* FIXME: need a lock around checking this->hidden->client */
if (!this->hidden->client || FAILED(IAudioClient_GetCurrentPadding(this->hidden->client, &frames))) {
return 0; /* oh well. */
if (this->hidden->client != NULL) { /* definitely activated? */
if (FAILED(IAudioClient_GetCurrentPadding(this->hidden->client, &frames))) {
return 0; /* oh well. */
}
}
return ((int) frames) * this->hidden->framesize;
}
@@ -397,41 +189,9 @@ WasapiFailed(_THIS, const HRESULT err)
return SDL_TRUE;
}
static int PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device);
static void ReleaseWasapiDevice(_THIS);
static SDL_bool
RecoverWasapiDevice(_THIS)
static int
UpdateAudioStream(_THIS, const SDL_AudioSpec *oldspec)
{
const SDL_AudioSpec oldspec = this->spec;
IMMDevice *device = NULL;
HRESULT ret = S_OK;
if (this->hidden->default_device_generation) {
const EDataFlow dataflow = this->iscapture ? eCapture : eRender;
ReleaseWasapiDevice(this); /* dump the lost device's handles. */
this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ? &default_capture_generation : &default_playback_generation);
ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device);
if (FAILED(ret)) {
return SDL_FALSE; /* can't find a new default device! */
}
} else {
device = this->hidden->device;
this->hidden->device = NULL; /* don't release this in ReleaseWasapiDevice(). */
ReleaseWasapiDevice(this); /* dump the lost device's handles. */
}
SDL_assert(device != NULL);
/* this can fail for lots of reasons, but the most likely is we had a
non-default device that was disconnected, so we can't recover. Default
devices try to reinitialize whatever the new default is, so it's more
likely to carry on here, but this handles a non-default device that
simply had its format changed in the Windows Control Panel. */
if (PrepWasapiDevice(this, this->iscapture, device) == -1) {
return SDL_FALSE;
}
/* Since WASAPI requires us to handle all audio conversion, and our
device format might have changed, we might have to add/remove/change
the audio stream that the higher level uses to convert data, so
@@ -444,9 +204,9 @@ RecoverWasapiDevice(_THIS)
/* no need to buffer/convert in an AudioStream! */
SDL_FreeAudioStream(this->stream);
this->stream = NULL;
} else if ( (oldspec.channels == this->spec.channels) &&
(oldspec.format == this->spec.format) &&
(oldspec.freq == this->spec.freq) ) {
} else if ( (oldspec->channels == this->spec.channels) &&
(oldspec->format == this->spec.format) &&
(oldspec->freq == this->spec.freq) ) {
/* The existing audio stream is okay to keep using. */
} else {
/* replace the audiostream for new format */
@@ -465,7 +225,7 @@ RecoverWasapiDevice(_THIS)
}
if (!this->stream) {
return SDL_FALSE;
return -1;
}
}
@@ -473,13 +233,37 @@ RecoverWasapiDevice(_THIS)
if (this->spec.size > this->work_buffer_len) {
Uint8 *ptr = (Uint8 *) SDL_realloc(this->work_buffer, this->spec.size);
if (ptr == NULL) {
SDL_OutOfMemory();
return SDL_FALSE;
return SDL_OutOfMemory();
}
this->work_buffer = ptr;
this->work_buffer_len = this->spec.size;
}
return 0;
}
static void ReleaseWasapiDevice(_THIS);
static SDL_bool
RecoverWasapiDevice(_THIS)
{
ReleaseWasapiDevice(this); /* dump the lost device's handles. */
if (this->hidden->default_device_generation) {
this->hidden->default_device_generation = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
}
/* this can fail for lots of reasons, but the most likely is we had a
non-default device that was disconnected, so we can't recover. Default
devices try to reinitialize whatever the new default is, so it's more
likely to carry on here, but this handles a non-default device that
simply had its format changed in the Windows Control Panel. */
if (WASAPI_ActivateDevice(this, SDL_TRUE) == -1) {
SDL_OpenedAudioDeviceDisconnected(this);
return SDL_FALSE;
}
this->hidden->device_lost = SDL_FALSE;
return SDL_TRUE; /* okay, carry on with new device details! */
@@ -495,8 +279,12 @@ RecoverWasapiIfLost(_THIS)
return SDL_FALSE; /* already failed. */
}
if (!this->hidden->client) {
return SDL_TRUE; /* still waiting for activation. */
}
if (!lost && (generation > 0)) { /* is a default device? */
const int newgen = SDL_AtomicGet(this->iscapture ? &default_capture_generation : &default_playback_generation);
const int newgen = SDL_AtomicGet(this->iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
if (generation != newgen) { /* the desired default device was changed, jump over to it. */
lost = SDL_TRUE;
}
@@ -511,7 +299,7 @@ WASAPI_GetDeviceBuf(_THIS)
/* get an endpoint buffer from WASAPI. */
BYTE *buffer = NULL;
while (RecoverWasapiIfLost(this)) {
while (RecoverWasapiIfLost(this) && this->hidden->render) {
if (!WasapiFailed(this, IAudioRenderClient_GetBuffer(this->hidden->render, this->spec.samples, &buffer))) {
return (Uint8 *) buffer;
}
@@ -524,17 +312,18 @@ WASAPI_GetDeviceBuf(_THIS)
static void
WASAPI_PlayDevice(_THIS)
{
/* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */
WasapiFailed(this, IAudioRenderClient_ReleaseBuffer(this->hidden->render, this->spec.samples, 0));
if (this->hidden->render != NULL) { /* definitely activated? */
/* WasapiFailed() will mark the device for reacquisition or removal elsewhere. */
WasapiFailed(this, IAudioRenderClient_ReleaseBuffer(this->hidden->render, this->spec.samples, 0));
}
}
static void
WASAPI_WaitDevice(_THIS)
{
const UINT32 maxpadding = this->spec.samples;
while (RecoverWasapiIfLost(this)) {
while (RecoverWasapiIfLost(this) && this->hidden->client) {
const UINT32 maxpadding = this->spec.samples;
UINT32 padding = 0;
if (!WasapiFailed(this, IAudioClient_GetCurrentPadding(this->hidden->client, &padding))) {
if (padding <= maxpadding) {
break;
@@ -562,6 +351,14 @@ WASAPI_CaptureFromDevice(_THIS, void *buffer, int buflen)
UINT32 frames = 0;
DWORD flags = 0;
/* uhoh, client isn't activated yet, just return silence. */
if (!this->hidden->capture) {
/* Delay so we run at about the speed that audio would be arriving. */
SDL_Delay(((this->spec.samples * 1000) / this->spec.freq));
SDL_memset(buffer, this->spec.silence, buflen);
return buflen;
}
ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
if (ret != AUDCLNT_S_BUFFER_EMPTY) {
WasapiFailed(this, ret); /* mark device lost/failed if necessary. */
@@ -609,6 +406,10 @@ WASAPI_FlushCapture(_THIS)
UINT32 frames = 0;
DWORD flags = 0;
if (!this->hidden->capture) {
return; /* not activated yet? */
}
/* just read until we stop getting packets, throwing them away. */
while (SDL_TRUE) {
const HRESULT ret = IAudioCaptureClient_GetBuffer(this->hidden->capture, &ptr, &frames, &flags, NULL, NULL);
@@ -646,30 +447,49 @@ ReleaseWasapiDevice(_THIS)
this->hidden->waveformat = NULL;
}
if (this->hidden->device) {
IMMDevice_Release(this->hidden->device);
this->hidden->device = NULL;
}
if (this->hidden->capturestream) {
SDL_FreeAudioStream(this->hidden->capturestream);
this->hidden->capturestream = NULL;
}
if (this->hidden->activation_handler) {
WASAPI_PlatformDeleteActivationHandler(this->hidden->activation_handler);
this->hidden->activation_handler = NULL;
}
}
static void
WASAPI_CloseDevice(_THIS)
{
WASAPI_UnrefDevice(this);
}
void
WASAPI_RefDevice(_THIS)
{
SDL_AtomicIncRef(&this->hidden->refcount);
}
void
WASAPI_UnrefDevice(_THIS)
{
if (!SDL_AtomicDecRef(&this->hidden->refcount)) {
return;
}
/* actual closing happens here. */
/* don't touch this->hidden->task in here; it has to be reverted from
our callback thread. We do that in WASAPI_ThreadDeinit().
(likewise for this->hidden->coinitialized). */
our callback thread. We do that in WASAPI_ThreadDeinit().
(likewise for this->hidden->coinitialized). */
ReleaseWasapiDevice(this);
SDL_free(this->hidden->devid);
SDL_free(this->hidden);
}
static int
PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
/* This is called once a device is activated, possibly asynchronously. */
int
WASAPI_PrepDevice(_THIS, const SDL_bool updatestream)
{
/* !!! FIXME: we could request an exclusive mode stream, which is lower latency;
!!! it will write into the kernel's audio buffer directly instead of
@@ -682,10 +502,11 @@ PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
!!! wins actually look like. Maybe add a hint to force exclusive mode at
!!! some point. To be sure, defaulting to shared mode is the right thing to
!!! do in any case. */
const SDL_AudioSpec oldspec = this->spec;
const AUDCLNT_SHAREMODE sharemode = AUDCLNT_SHAREMODE_SHARED;
UINT32 bufsize = 0; /* this is in sample frames, not samples, not bytes. */
REFERENCE_TIME duration = 0;
IAudioClient *client = NULL;
IAudioClient *client = this->hidden->client;
IAudioRenderClient *render = NULL;
IAudioCaptureClient *capture = NULL;
WAVEFORMATEX *waveformat = NULL;
@@ -694,15 +515,7 @@ PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
SDL_bool valid_format = SDL_FALSE;
HRESULT ret = S_OK;
this->hidden->device = device;
ret = IMMDevice_Activate(device, &SDL_IID_IAudioClient, CLSCTX_ALL, NULL, (void **) &client);
if (FAILED(ret)) {
return WIN_SetErrorFromHRESULT("WASAPI can't activate audio endpoint", ret);
}
SDL_assert(client != NULL);
this->hidden->client = client;
ret = IAudioClient_GetMixFormat(client, &waveformat);
if (FAILED(ret)) {
@@ -763,7 +576,7 @@ PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
}
this->spec.samples = (Uint16) bufsize;
if (!iscapture) {
if (!this->iscapture) {
this->spec.samples /= 2; /* fill half of the DMA buffer on each run. */
}
@@ -772,7 +585,7 @@ PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
this->hidden->framesize = (SDL_AUDIO_BITSIZE(this->spec.format) / 8) * this->spec.channels;
if (iscapture) {
if (this->iscapture) {
this->hidden->capturestream = SDL_NewAudioStream(this->spec.format, this->spec.channels, this->spec.freq, this->spec.format, this->spec.channels, this->spec.freq);
if (!this->hidden->capturestream) {
return -1; /* already set SDL_Error */
@@ -805,15 +618,20 @@ PrepWasapiDevice(_THIS, const int iscapture, IMMDevice *device)
}
}
if (updatestream) {
if (UpdateAudioStream(this, &oldspec) == -1) {
return -1;
}
}
return 0; /* good to go. */
}
static int
WASAPI_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
{
const SDL_bool is_default_device = (handle == NULL);
IMMDevice *device = NULL;
HRESULT ret = S_OK;
LPCWSTR devid = (LPCWSTR) handle;
/* Initialize all variables that we clean on shutdown */
this->hidden = (struct SDL_PrivateAudioData *)
@@ -823,49 +641,42 @@ WASAPI_OpenDevice(_THIS, void *handle, const char *devname, int iscapture)
}
SDL_zerop(this->hidden);
if (is_default_device) {
const EDataFlow dataflow = iscapture ? eCapture : eRender;
this->hidden->default_device_generation = SDL_AtomicGet(iscapture ? &default_capture_generation : &default_playback_generation);
ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device);
WASAPI_RefDevice(this); /* so CloseDevice() will unref to zero. */
if (!devid) { /* is default device? */
this->hidden->default_device_generation = SDL_AtomicGet(iscapture ? &WASAPI_DefaultCaptureGeneration : &WASAPI_DefaultPlaybackGeneration);
} else {
ret = IMMDeviceEnumerator_GetDevice(enumerator, (LPCWSTR) handle, &device);
this->hidden->devid = WStrDupe(devid);
if (!this->hidden->devid) {
return SDL_OutOfMemory();
}
}
if (FAILED(ret)) {
return WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret);
if (WASAPI_ActivateDevice(this, SDL_FALSE) == -1) {
return -1; /* already set error. */
}
SDL_assert(device != NULL);
return PrepWasapiDevice(this, iscapture, device);
/* Ready, but waiting for async device activation.
Until activation is successful, we will report silence from capture
devices and ignore data on playback devices.
Also, since we don't know the _actual_ device format until after
activation, we let the app have whatever it asks for. We set up
an SDL_AudioStream to convert, if necessary, once the activation
completes. */
return 0;
}
static void
WASAPI_ThreadInit(_THIS)
{
/* this thread uses COM. */
if (SUCCEEDED(WIN_CoInitialize())) { /* can't report errors, hope it worked! */
this->hidden->coinitialized = SDL_TRUE;
}
/* Set this thread to very high "Pro Audio" priority. */
if (pAvSetMmThreadCharacteristicsW) {
DWORD idx = 0;
this->hidden->task = pAvSetMmThreadCharacteristicsW(TEXT("Pro Audio"), &idx);
}
WASAPI_PlatformThreadInit(this);
}
static void
WASAPI_ThreadDeinit(_THIS)
{
/* Set this thread to very high "Pro Audio" priority. */
if (this->hidden->task && pAvRevertMmThreadCharacteristics) {
pAvRevertMmThreadCharacteristics(this->hidden->task);
this->hidden->task = NULL;
}
if (this->hidden->coinitialized) {
WIN_CoUninitialize();
}
WASAPI_PlatformThreadDeinit(this);
}
static void
@@ -874,21 +685,7 @@ WASAPI_Deinitialize(void)
DevIdList *devidlist;
DevIdList *next;
if (enumerator) {
IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
IMMDeviceEnumerator_Release(enumerator);
enumerator = NULL;
}
#ifndef __WINRT__
if (libavrt) {
FreeLibrary(libavrt);
libavrt = NULL;
}
#endif
pAvSetMmThreadCharacteristicsW = NULL;
pAvRevertMmThreadCharacteristics = NULL;
WASAPI_PlatformDeinit();
for (devidlist = deviceid_list; devidlist; devidlist = next) {
next = devidlist->next;
@@ -896,51 +693,23 @@ WASAPI_Deinitialize(void)
SDL_free(devidlist);
}
deviceid_list = NULL;
WIN_CoUninitialize();
}
static int
WASAPI_Init(SDL_AudioDriverImpl * impl)
{
HRESULT ret;
SDL_AtomicSet(&WASAPI_DefaultPlaybackGeneration, 1);
SDL_AtomicSet(&WASAPI_DefaultCaptureGeneration, 1);
/* just skip the discussion with COM here. */
if (!WIN_IsWindowsVistaOrGreater()) {
SDL_SetError("WASAPI support requires Windows Vista or later");
if (WASAPI_PlatformInit() == -1) {
return 0;
}
SDL_AtomicSet(&default_playback_generation, 1);
SDL_AtomicSet(&default_capture_generation, 1);
if (FAILED(WIN_CoInitialize())) {
SDL_SetError("WASAPI: CoInitialize() failed");
return 0;
}
ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID) &enumerator);
if (FAILED(ret)) {
WIN_CoUninitialize();
WIN_SetErrorFromHRESULT("WASAPI CoCreateInstance(MMDeviceEnumerator)", ret);
return 0; /* oh well. */
}
#ifdef __WINRT__
pAvSetMmThreadCharacteristicsW = AvSetMmThreadCharacteristicsW;
pAvRevertMmThreadCharacteristics = AvRevertMmThreadCharacteristics;
#else
libavrt = LoadLibraryW(L"avrt.dll"); /* this library is available in Vista and later. No WinXP, so have to LoadLibrary to use it for now! */
if (libavrt) {
pAvSetMmThreadCharacteristicsW = (pfnAvSetMmThreadCharacteristicsW) GetProcAddress(libavrt, "AvSetMmThreadCharacteristicsW");
pAvRevertMmThreadCharacteristics = (pfnAvRevertMmThreadCharacteristics) GetProcAddress(libavrt, "AvRevertMmThreadCharacteristics");
}
#endif
/* Set the function pointers */
impl->DetectDevices = WASAPI_DetectDevices;
impl->ThreadInit = WASAPI_ThreadInit;
impl->ThreadDeinit = WASAPI_ThreadDeinit;
impl->BeginLoopIteration = WASAPI_BeginLoopIteration;
impl->OpenDevice = WASAPI_OpenDevice;
impl->PlayDevice = WASAPI_PlayDevice;
impl->WaitDevice = WASAPI_WaitDevice;

View File

@@ -23,14 +23,23 @@
#ifndef SDL_wasapi_h_
#define SDL_wasapi_h_
#ifdef __cplusplus
extern "C" {
#endif
#include "../SDL_sysaudio.h"
/* Hidden "this" pointer for the audio functions */
#ifdef __cplusplus
#define _THIS SDL_AudioDevice *_this
#else
#define _THIS SDL_AudioDevice *this
#endif
struct SDL_PrivateAudioData
{
IMMDevice *device;
SDL_atomic_t refcount;
WCHAR *devid;
WAVEFORMATEX *waveformat;
IAudioClient *client;
IAudioRenderClient *render;
@@ -41,8 +50,35 @@ struct SDL_PrivateAudioData
int framesize;
int default_device_generation;
SDL_bool device_lost;
void *activation_handler;
SDL_atomic_t just_activated;
};
/* these increment as default devices change. Opened default devices pick up changes in their threads. */
extern SDL_atomic_t WASAPI_DefaultPlaybackGeneration;
extern SDL_atomic_t WASAPI_DefaultCaptureGeneration;
/* win32 and winrt implementations call into these. */
int WASAPI_PrepDevice(_THIS, const SDL_bool updatestream);
void WASAPI_RefDevice(_THIS);
void WASAPI_UnrefDevice(_THIS);
void WASAPI_AddDevice(const SDL_bool iscapture, const char *devname, LPCWSTR devid);
void WASAPI_RemoveDevice(const SDL_bool iscapture, LPCWSTR devid);
/* These are functions that are implemented differently for Windows vs WinRT. */
int WASAPI_PlatformInit(void);
void WASAPI_PlatformDeinit(void);
void WASAPI_EnumerateEndpoints(void);
int WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery);
void WASAPI_PlatformThreadInit(_THIS);
void WASAPI_PlatformThreadDeinit(_THIS);
void WASAPI_PlatformDeleteActivationHandler(void *handler);
void WASAPI_BeginLoopIteration(_THIS);
#ifdef __cplusplus
}
#endif
#endif /* SDL_wasapi_h_ */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,418 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2017 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
/* This is code that Windows uses to talk to WASAPI-related system APIs.
This is for non-WinRT desktop apps. The C++/CX implementation of these
functions, exclusive to WinRT, are in SDL_wasapi_winrt.cpp.
The code in SDL_wasapi.c is used by both standard Windows and WinRT builds
to deal with audio and calls into these functions. */
#if SDL_AUDIO_DRIVER_WASAPI && !defined(__WINRT__)
#include "../../core/windows/SDL_windows.h"
#include "SDL_audio.h"
#include "SDL_timer.h"
#include "../SDL_audio_c.h"
#include "../SDL_sysaudio.h"
#include "SDL_assert.h"
#include "SDL_log.h"
#define COBJMACROS
#include <mmdeviceapi.h>
#include <audioclient.h>
#include "SDL_wasapi.h"
static const ERole SDL_WASAPI_role = eConsole; /* !!! FIXME: should this be eMultimedia? Should be a hint? */
/* This is global to the WASAPI target, to handle hotplug and default device lookup. */
static IMMDeviceEnumerator *enumerator = NULL;
/* PropVariantInit() is an inline function/macro in PropIdl.h that calls the C runtime's memset() directly. Use ours instead, to avoid dependency. */
#ifdef PropVariantInit
#undef PropVariantInit
#endif
#define PropVariantInit(p) SDL_zerop(p)
/* handle to Avrt.dll--Vista and later!--for flagging the callback thread as "Pro Audio" (low latency). */
static HMODULE libavrt = NULL;
typedef HANDLE(WINAPI *pfnAvSetMmThreadCharacteristicsW)(LPWSTR, LPDWORD);
typedef BOOL(WINAPI *pfnAvRevertMmThreadCharacteristics)(HANDLE);
static pfnAvSetMmThreadCharacteristicsW pAvSetMmThreadCharacteristicsW = NULL;
static pfnAvRevertMmThreadCharacteristics pAvRevertMmThreadCharacteristics = NULL;
/* Some GUIDs we need to know without linking to libraries that aren't available before Vista. */
static const CLSID SDL_CLSID_MMDeviceEnumerator = { 0xbcde0395, 0xe52f, 0x467c,{ 0x8e, 0x3d, 0xc4, 0x57, 0x92, 0x91, 0x69, 0x2e } };
static const IID SDL_IID_IMMDeviceEnumerator = { 0xa95664d2, 0x9614, 0x4f35,{ 0xa7, 0x46, 0xde, 0x8d, 0xb6, 0x36, 0x17, 0xe6 } };
static const IID SDL_IID_IMMNotificationClient = { 0x7991eec9, 0x7e89, 0x4d85,{ 0x83, 0x90, 0x6c, 0x70, 0x3c, 0xec, 0x60, 0xc0 } };
static const IID SDL_IID_IMMEndpoint = { 0x1be09788, 0x6894, 0x4089,{ 0x85, 0x86, 0x9a, 0x2a, 0x6c, 0x26, 0x5a, 0xc5 } };
static const IID SDL_IID_IAudioClient = { 0x1cb9ad4c, 0xdbfa, 0x4c32,{ 0xb1, 0x78, 0xc2, 0xf5, 0x68, 0xa7, 0x03, 0xb2 } };
static const PROPERTYKEY SDL_PKEY_Device_FriendlyName = { { 0xa45c254e, 0xdf1c, 0x4efd,{ 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, } }, 14 };
static char *
GetWasapiDeviceName(IMMDevice *device)
{
/* PKEY_Device_FriendlyName gives you "Speakers (SoundBlaster Pro)" which drives me nuts. I'd rather it be
"SoundBlaster Pro (Speakers)" but I guess that's developers vs users. Windows uses the FriendlyName in
its own UIs, like Volume Control, etc. */
char *utf8dev = NULL;
IPropertyStore *props = NULL;
if (SUCCEEDED(IMMDevice_OpenPropertyStore(device, STGM_READ, &props))) {
PROPVARIANT var;
PropVariantInit(&var);
if (SUCCEEDED(IPropertyStore_GetValue(props, &SDL_PKEY_Device_FriendlyName, &var))) {
utf8dev = WIN_StringToUTF8(var.pwszVal);
}
PropVariantClear(&var);
IPropertyStore_Release(props);
}
return utf8dev;
}
/* We need a COM subclass of IMMNotificationClient for hotplug support, which is
easy in C++, but we have to tapdance more to make work in C.
Thanks to this page for coaching on how to make this work:
https://www.codeproject.com/Articles/13601/COM-in-plain-C */
typedef struct SDLMMNotificationClient
{
const IMMNotificationClientVtbl *lpVtbl;
SDL_atomic_t refcount;
} SDLMMNotificationClient;
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_QueryInterface(IMMNotificationClient *this, REFIID iid, void **ppv)
{
if ((WIN_IsEqualIID(iid, &IID_IUnknown)) || (WIN_IsEqualIID(iid, &SDL_IID_IMMNotificationClient)))
{
*ppv = this;
this->lpVtbl->AddRef(this);
return S_OK;
}
*ppv = NULL;
return E_NOINTERFACE;
}
static ULONG STDMETHODCALLTYPE
SDLMMNotificationClient_AddRef(IMMNotificationClient *ithis)
{
SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
return (ULONG) (SDL_AtomicIncRef(&this->refcount) + 1);
}
static ULONG STDMETHODCALLTYPE
SDLMMNotificationClient_Release(IMMNotificationClient *ithis)
{
/* this is a static object; we don't ever free it. */
SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
const ULONG retval = SDL_AtomicDecRef(&this->refcount);
if (retval == 0) {
SDL_AtomicSet(&this->refcount, 0); /* uhh... */
return 0;
}
return retval - 1;
}
/* These are the entry points called when WASAPI device endpoints change. */
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDefaultDeviceChanged(IMMNotificationClient *ithis, EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId)
{
if (role != SDL_WASAPI_role) {
return S_OK; /* ignore it. */
}
/* Increment the "generation," so opened devices will pick this up in their threads. */
switch (flow) {
case eRender:
SDL_AtomicAdd(&WASAPI_DefaultPlaybackGeneration, 1);
break;
case eCapture:
SDL_AtomicAdd(&WASAPI_DefaultCaptureGeneration, 1);
break;
case eAll:
SDL_AtomicAdd(&WASAPI_DefaultPlaybackGeneration, 1);
SDL_AtomicAdd(&WASAPI_DefaultCaptureGeneration, 1);
break;
default:
SDL_assert(!"uhoh, unexpected OnDefaultDeviceChange flow!");
break;
}
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDeviceAdded(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
{
/* we ignore this; devices added here then progress to ACTIVE, if appropriate, in
OnDeviceStateChange, making that a better place to deal with device adds. More
importantly: the first time you plug in a USB audio device, this callback will
fire, but when you unplug it, it isn't removed (it's state changes to NOTPRESENT).
Plugging it back in won't fire this callback again. */
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDeviceRemoved(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId)
{
/* See notes in OnDeviceAdded handler about why we ignore this. */
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnDeviceStateChanged(IMMNotificationClient *ithis, LPCWSTR pwstrDeviceId, DWORD dwNewState)
{
SDLMMNotificationClient *this = (SDLMMNotificationClient *) ithis;
IMMDevice *device = NULL;
if (SUCCEEDED(IMMDeviceEnumerator_GetDevice(enumerator, pwstrDeviceId, &device))) {
IMMEndpoint *endpoint = NULL;
if (SUCCEEDED(IMMDevice_QueryInterface(device, &SDL_IID_IMMEndpoint, (void **) &endpoint))) {
EDataFlow flow;
if (SUCCEEDED(IMMEndpoint_GetDataFlow(endpoint, &flow))) {
const SDL_bool iscapture = (flow == eCapture);
if (dwNewState == DEVICE_STATE_ACTIVE) {
char *utf8dev = GetWasapiDeviceName(device);
if (utf8dev) {
WASAPI_AddDevice(iscapture, utf8dev, pwstrDeviceId);
SDL_free(utf8dev);
}
} else {
WASAPI_RemoveDevice(iscapture, pwstrDeviceId);
}
}
IMMEndpoint_Release(endpoint);
}
IMMDevice_Release(device);
}
return S_OK;
}
static HRESULT STDMETHODCALLTYPE
SDLMMNotificationClient_OnPropertyValueChanged(IMMNotificationClient *this, LPCWSTR pwstrDeviceId, const PROPERTYKEY key)
{
return S_OK; /* we don't care about these. */
}
static const IMMNotificationClientVtbl notification_client_vtbl = {
SDLMMNotificationClient_QueryInterface,
SDLMMNotificationClient_AddRef,
SDLMMNotificationClient_Release,
SDLMMNotificationClient_OnDeviceStateChanged,
SDLMMNotificationClient_OnDeviceAdded,
SDLMMNotificationClient_OnDeviceRemoved,
SDLMMNotificationClient_OnDefaultDeviceChanged,
SDLMMNotificationClient_OnPropertyValueChanged
};
static SDLMMNotificationClient notification_client = { &notification_client_vtbl, 1 };
int
WASAPI_PlatformInit(void)
{
HRESULT ret;
/* just skip the discussion with COM here. */
if (!WIN_IsWindowsVistaOrGreater()) {
return SDL_SetError("WASAPI support requires Windows Vista or later");
}
if (FAILED(WIN_CoInitialize())) {
return SDL_SetError("WASAPI: CoInitialize() failed");
}
ret = CoCreateInstance(&SDL_CLSID_MMDeviceEnumerator, NULL, CLSCTX_INPROC_SERVER, &SDL_IID_IMMDeviceEnumerator, (LPVOID) &enumerator);
if (FAILED(ret)) {
WIN_CoUninitialize();
return WIN_SetErrorFromHRESULT("WASAPI CoCreateInstance(MMDeviceEnumerator)", ret);
}
libavrt = LoadLibraryW(L"avrt.dll"); /* this library is available in Vista and later. No WinXP, so have to LoadLibrary to use it for now! */
if (libavrt) {
pAvSetMmThreadCharacteristicsW = (pfnAvSetMmThreadCharacteristicsW) GetProcAddress(libavrt, "AvSetMmThreadCharacteristicsW");
pAvRevertMmThreadCharacteristics = (pfnAvRevertMmThreadCharacteristics) GetProcAddress(libavrt, "AvRevertMmThreadCharacteristics");
}
return 0;
}
void
WASAPI_PlatformDeinit(void)
{
if (enumerator) {
IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
IMMDeviceEnumerator_Release(enumerator);
enumerator = NULL;
}
if (libavrt) {
FreeLibrary(libavrt);
libavrt = NULL;
}
pAvSetMmThreadCharacteristicsW = NULL;
pAvRevertMmThreadCharacteristics = NULL;
WIN_CoUninitialize();
}
void
WASAPI_PlatformThreadInit(_THIS)
{
/* this thread uses COM. */
if (SUCCEEDED(WIN_CoInitialize())) { /* can't report errors, hope it worked! */
this->hidden->coinitialized = SDL_TRUE;
}
/* Set this thread to very high "Pro Audio" priority. */
if (pAvSetMmThreadCharacteristicsW) {
DWORD idx = 0;
this->hidden->task = pAvSetMmThreadCharacteristicsW(TEXT("Pro Audio"), &idx);
}
}
void
WASAPI_PlatformThreadDeinit(_THIS)
{
/* Set this thread back to normal priority. */
if (this->hidden->task && pAvRevertMmThreadCharacteristics) {
pAvRevertMmThreadCharacteristics(this->hidden->task);
this->hidden->task = NULL;
}
if (this->hidden->coinitialized) {
WIN_CoUninitialize();
this->hidden->coinitialized = SDL_FALSE;
}
}
int
WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
{
LPCWSTR devid = this->hidden->devid;
IMMDevice *device = NULL;
HRESULT ret;
if (devid == NULL) {
const EDataFlow dataflow = this->iscapture ? eCapture : eRender;
ret = IMMDeviceEnumerator_GetDefaultAudioEndpoint(enumerator, dataflow, SDL_WASAPI_role, &device);
} else {
ret = IMMDeviceEnumerator_GetDevice(enumerator, devid, &device);
}
if (FAILED(ret)) {
SDL_assert(device == NULL);
this->hidden->client = NULL;
return WIN_SetErrorFromHRESULT("WASAPI can't find requested audio endpoint", ret);
}
/* this is not async in standard win32, yay! */
ret = IMMDevice_Activate(device, &SDL_IID_IAudioClient, CLSCTX_ALL, NULL, (void **) &this->hidden->client);
IMMDevice_Release(device);
if (FAILED(ret)) {
SDL_assert(this->hidden->client == NULL);
return WIN_SetErrorFromHRESULT("WASAPI can't activate audio endpoint", ret);
}
SDL_assert(this->hidden->client != NULL);
if (WASAPI_PrepDevice(this, isrecovery) == -1) { /* not async, fire it right away. */
return -1;
}
return 0; /* good to go. */
}
static void
WASAPI_EnumerateEndpointsForFlow(const SDL_bool iscapture)
{
IMMDeviceCollection *collection = NULL;
UINT i, total;
/* Note that WASAPI separates "adapter devices" from "audio endpoint devices"
...one adapter device ("SoundBlaster Pro") might have multiple endpoint devices ("Speakers", "Line-Out"). */
if (FAILED(IMMDeviceEnumerator_EnumAudioEndpoints(enumerator, iscapture ? eCapture : eRender, DEVICE_STATE_ACTIVE, &collection))) {
return;
}
if (FAILED(IMMDeviceCollection_GetCount(collection, &total))) {
IMMDeviceCollection_Release(collection);
return;
}
for (i = 0; i < total; i++) {
IMMDevice *device = NULL;
if (SUCCEEDED(IMMDeviceCollection_Item(collection, i, &device))) {
LPWSTR devid = NULL;
if (SUCCEEDED(IMMDevice_GetId(device, &devid))) {
char *devname = GetWasapiDeviceName(device);
if (devname) {
WASAPI_AddDevice(iscapture, devname, devid);
SDL_free(devname);
}
CoTaskMemFree(devid);
}
IMMDevice_Release(device);
}
}
IMMDeviceCollection_Release(collection);
}
void
WASAPI_EnumerateEndpoints(void)
{
WASAPI_EnumerateEndpointsForFlow(SDL_FALSE); /* playback */
WASAPI_EnumerateEndpointsForFlow(SDL_TRUE); /* capture */
/* if this fails, we just won't get hotplug events. Carry on anyhow. */
IMMDeviceEnumerator_RegisterEndpointNotificationCallback(enumerator, (IMMNotificationClient *) &notification_client);
}
void
WASAPI_PlatformDeleteActivationHandler(void *handler)
{
/* not asynchronous. */
SDL_assert(!"This function should have only be called on WinRT.");
}
void
WASAPI_BeginLoopIteration(_THIS)
{
/* no-op. */
}
#endif /* SDL_AUDIO_DRIVER_WASAPI && !defined(__WINRT__) */
/* vi: set ts=4 sw=4 expandtab: */

View File

@@ -0,0 +1,276 @@
/*
Simple DirectMedia Layer
Copyright (C) 1997-2017 Sam Lantinga <slouken@libsdl.org>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "../../SDL_internal.h"
// This is C++/CX code that the WinRT port uses to talk to WASAPI-related
// system APIs. The C implementation of these functions, for non-WinRT apps,
// is in SDL_wasapi_win32.c. The code in SDL_wasapi.c is used by both standard
// Windows and WinRT builds to deal with audio and calls into these functions.
#if SDL_AUDIO_DRIVER_WASAPI && defined(__WINRT__)
#include <Windows.h>
#include <windows.ui.core.h>
#include <windows.devices.enumeration.h>
#include <windows.media.devices.h>
#include <wrl/implements.h>
extern "C" {
#include "../../core/windows/SDL_windows.h"
#include "SDL_audio.h"
#include "SDL_timer.h"
#include "../SDL_audio_c.h"
#include "../SDL_sysaudio.h"
#include "SDL_assert.h"
#include "SDL_log.h"
}
#define COBJMACROS
#include <mmdeviceapi.h>
#include <audioclient.h>
#include "SDL_wasapi.h"
using namespace Windows::Devices::Enumeration;
using namespace Windows::Media::Devices;
using namespace Windows::Foundation;
using namespace Microsoft::WRL;
class SDL_WasapiDeviceEventHandler
{
public:
SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture);
~SDL_WasapiDeviceEventHandler();
void OnDeviceAdded(DeviceWatcher^ sender, DeviceInformation^ args);
void OnDeviceRemoved(DeviceWatcher^ sender, DeviceInformationUpdate^ args);
void OnDeviceUpdated(DeviceWatcher^ sender, DeviceInformationUpdate^ args);
void OnDefaultRenderDeviceChanged(Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args);
void OnDefaultCaptureDeviceChanged(Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args);
private:
const SDL_bool iscapture;
DeviceWatcher^ watcher;
Windows::Foundation::EventRegistrationToken added_handler;
Windows::Foundation::EventRegistrationToken removed_handler;
Windows::Foundation::EventRegistrationToken updated_handler;
Windows::Foundation::EventRegistrationToken default_changed_handler;
};
SDL_WasapiDeviceEventHandler::SDL_WasapiDeviceEventHandler(const SDL_bool _iscapture)
: iscapture(_iscapture)
, watcher(DeviceInformation::CreateWatcher(_iscapture ? DeviceClass::AudioCapture : DeviceClass::AudioRender))
{
if (!watcher)
return; // uhoh.
// !!! FIXME: this doesn't need a lambda here, I think, if I make SDL_WasapiDeviceEventHandler a proper C++/CX class. --ryan.
added_handler = watcher->Added += ref new TypedEventHandler<DeviceWatcher^, DeviceInformation^>([this](DeviceWatcher^ sender, DeviceInformation^ args) { OnDeviceAdded(sender, args); } );
removed_handler = watcher->Removed += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>([this](DeviceWatcher^ sender, DeviceInformationUpdate^ args) { OnDeviceRemoved(sender, args); } );
updated_handler = watcher->Updated += ref new TypedEventHandler<DeviceWatcher^, DeviceInformationUpdate^>([this](DeviceWatcher^ sender, DeviceInformationUpdate^ args) { OnDeviceUpdated(sender, args); } );
if (iscapture) {
default_changed_handler = MediaDevice::DefaultAudioCaptureDeviceChanged += ref new TypedEventHandler<Platform::Object^, DefaultAudioCaptureDeviceChangedEventArgs^>([this](Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args) { OnDefaultCaptureDeviceChanged(sender, args); } );
} else {
default_changed_handler = MediaDevice::DefaultAudioRenderDeviceChanged += ref new TypedEventHandler<Platform::Object^, DefaultAudioRenderDeviceChangedEventArgs^>([this](Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args) { OnDefaultRenderDeviceChanged(sender, args); } );
}
watcher->Start();
}
SDL_WasapiDeviceEventHandler::~SDL_WasapiDeviceEventHandler()
{
if (watcher) {
watcher->Added -= added_handler;
watcher->Removed -= removed_handler;
watcher->Updated -= updated_handler;
watcher->Stop();
watcher = nullptr;
}
if (iscapture) {
MediaDevice::DefaultAudioCaptureDeviceChanged -= default_changed_handler;
} else {
MediaDevice::DefaultAudioRenderDeviceChanged -= default_changed_handler;
}
}
void
SDL_WasapiDeviceEventHandler::OnDeviceAdded(DeviceWatcher^ sender, DeviceInformation^ info)
{
SDL_assert(sender == this->watcher);
char *utf8dev = WIN_StringToUTF8(info->Name->Data());
if (utf8dev) {
WASAPI_AddDevice(this->iscapture, utf8dev, info->Id->Data());
SDL_free(utf8dev);
}
}
void
SDL_WasapiDeviceEventHandler::OnDeviceRemoved(DeviceWatcher^ sender, DeviceInformationUpdate^ info)
{
SDL_assert(sender == this->watcher);
WASAPI_RemoveDevice(this->iscapture, info->Id->Data());
}
void
SDL_WasapiDeviceEventHandler::OnDeviceUpdated(DeviceWatcher^ sender, DeviceInformationUpdate^ args)
{
SDL_assert(sender == this->watcher);
}
void
SDL_WasapiDeviceEventHandler::OnDefaultRenderDeviceChanged(Platform::Object^ sender, DefaultAudioRenderDeviceChangedEventArgs^ args)
{
SDL_assert(this->iscapture);
SDL_AtomicAdd(&WASAPI_DefaultPlaybackGeneration, 1);
}
void
SDL_WasapiDeviceEventHandler::OnDefaultCaptureDeviceChanged(Platform::Object^ sender, DefaultAudioCaptureDeviceChangedEventArgs^ args)
{
SDL_assert(!this->iscapture);
SDL_AtomicAdd(&WASAPI_DefaultCaptureGeneration, 1);
}
static SDL_WasapiDeviceEventHandler *playback_device_event_handler;
static SDL_WasapiDeviceEventHandler *capture_device_event_handler;
int WASAPI_PlatformInit(void)
{
return 0;
}
void WASAPI_PlatformDeinit(void)
{
delete playback_device_event_handler;
playback_device_event_handler = nullptr;
delete capture_device_event_handler;
capture_device_event_handler = nullptr;
}
void WASAPI_EnumerateEndpoints(void)
{
// DeviceWatchers will fire an Added event for each existing device at
// startup, so we don't need to enumerate them separately before
// listening for updates.
playback_device_event_handler = new SDL_WasapiDeviceEventHandler(SDL_FALSE);
capture_device_event_handler = new SDL_WasapiDeviceEventHandler(SDL_TRUE);
}
struct SDL_WasapiActivationHandler : public RuntimeClass< RuntimeClassFlags< ClassicCom >, FtmBase, IActivateAudioInterfaceCompletionHandler >
{
SDL_WasapiActivationHandler() : device(nullptr) {}
STDMETHOD(ActivateCompleted)(IActivateAudioInterfaceAsyncOperation *operation);
SDL_AudioDevice *device;
};
HRESULT
SDL_WasapiActivationHandler::ActivateCompleted(IActivateAudioInterfaceAsyncOperation *async)
{
HRESULT result = S_OK;
IUnknown *iunknown = nullptr;
const HRESULT ret = async->GetActivateResult(&result, &iunknown);
if (SUCCEEDED(ret) && SUCCEEDED(result)) {
iunknown->QueryInterface(IID_PPV_ARGS(&device->hidden->client));
if (device->hidden->client) {
// 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.
SDL_AtomicSet(&device->hidden->just_activated, 1);
}
}
WASAPI_UnrefDevice(device);
return S_OK;
}
void
WASAPI_PlatformDeleteActivationHandler(void *handler)
{
((SDL_WasapiActivationHandler *) handler)->Release();
}
int
WASAPI_ActivateDevice(_THIS, const SDL_bool isrecovery)
{
LPCWSTR devid = _this->hidden->devid;
Platform::String^ defdevid;
if (devid == nullptr) {
defdevid = _this->iscapture ? MediaDevice::GetDefaultAudioCaptureId(AudioDeviceRole::Default) : MediaDevice::GetDefaultAudioRenderId(AudioDeviceRole::Default);
if (defdevid) {
devid = defdevid->Data();
}
}
SDL_AtomicSet(&_this->hidden->just_activated, 0);
ComPtr<SDL_WasapiActivationHandler> handler = Make<SDL_WasapiActivationHandler>();
if (handler == nullptr) {
return SDL_SetError("Failed to allocate WASAPI activation handler");
}
handler.Get()->AddRef(); // we hold a reference after ComPtr destructs on return, causing a Release, and Release ourselves in WASAPI_PlatformDeleteActivationHandler(), etc.
handler.Get()->device = _this;
_this->hidden->activation_handler = handler.Get();
WASAPI_RefDevice(_this); /* completion handler will unref it. */
IActivateAudioInterfaceAsyncOperation *async = nullptr;
const HRESULT ret = ActivateAudioInterfaceAsync(devid, __uuidof(IAudioClient), nullptr, handler.Get(), &async);
if (async != nullptr) {
async->Release();
}
if (FAILED(ret)) {
handler.Get()->Release();
WASAPI_UnrefDevice(_this);
return WIN_SetErrorFromHRESULT("WASAPI can't activate requested audio endpoint", ret);
}
return 0;
}
void
WASAPI_BeginLoopIteration(_THIS)
{
if (SDL_AtomicCAS(&_this->hidden->just_activated, 1, 0)) {
if (WASAPI_PrepDevice(_this, SDL_TRUE) == -1) {
SDL_OpenedAudioDeviceDisconnected(_this);
}
}
}
void
WASAPI_PlatformThreadInit(_THIS)
{
// !!! FIXME: set this thread to "Pro Audio" priority.
}
void
WASAPI_PlatformThreadDeinit(_THIS)
{
// !!! FIXME: set this thread to "Pro Audio" priority.
}
#endif // SDL_AUDIO_DRIVER_WASAPI && defined(__WINRT__)
/* vi: set ts=4 sw=4 expandtab: */