Merge pull request #11438 from unknownbrackets/wasapi-switch

Allow WASAPI device switching
This commit is contained in:
Henrik Rydgård authored and GitHub committed 2018-10-01 09:15:36 +02:00
commit 669079454a
12 files changed
+566 -315

No files matched your search

+4
View File
@@ -1791,6 +1791,10 @@ add_dependencies(${CoreLibName} GitVersion)
set(WindowsFiles
Windows/DSoundStream.cpp
Windows/DSoundStream.h
Windows/WindowsAudio.cpp
Windows/WindowsAudio.h
Windows/WASAPIStream.cpp
Windows/WASAPIStream.h
Windows/Debugger/CPURegsInterface.h
Windows/Debugger/BreakpointWindow.cpp
Windows/Debugger/BreakpointWindow.h
+1 -1
View File
@@ -35,7 +35,7 @@
#include <thread>
#if defined(_WIN32)
#include "Windows/DSoundStream.h"
#include "Windows/WindowsAudio.h"
#include "Windows/MainWindow.h"
#endif
+5 -297
View File
@@ -1,5 +1,5 @@
#include "Common/CommonWindows.h"
#include <mmreg.h>
#include <MMReg.h>
#include <process.h>
#ifdef __MINGW32__
@@ -11,70 +11,14 @@
#endif
#include "thread/threadutil.h"
#include "Common/Log.h"
#include "Common/OSVersion.h"
#include "Core/ConfigValues.h"
#include "Core/Reporting.h"
#include "Core/Util/AudioFormat.h"
#include "Windows/W32Util/Misc.h"
#include "dsoundstream.h"
// WASAPI begin
#include <Objbase.h>
#include <Mmreg.h>
#include <MMDeviceAPI.h>
#include <AudioClient.h>
#include <AudioPolicy.h>
#pragma comment(lib, "ole32.lib")
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
const IID IID_IAudioClient = __uuidof(IAudioClient);
const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
// WASAPI end
#define BUFSIZE 0x4000
#define MAXWAIT 20 //ms
class DSoundAudioBackend : public WindowsAudioBackend {
public:
DSoundAudioBackend();
~DSoundAudioBackend() override;
bool Init(HWND window, StreamCallback callback, int sampleRate) override; // If fails, can safely delete the object
void Update() override;
int GetSampleRate() override { return sampleRate_; }
private:
inline int ModBufferSize(int x) { return (x + bufferSize_) % bufferSize_; }
int RunThread();
static unsigned int WINAPI soundThread(void *param);
bool CreateBuffer();
bool WriteDataToBuffer(DWORD offset, // Our own write cursor.
char* soundData, // Start of our data.
DWORD soundBytes); // Size of block to copy.
CRITICAL_SECTION soundCriticalSection;
HWND window_;
HANDLE soundSyncEvent_ = NULL;
HANDLE hThread_ = NULL;
StreamCallback callback_;
IDirectSound8 *ds_ = NULL;
IDirectSoundBuffer *dsBuffer_ = NULL;
int bufferSize_; // bytes
int totalRenderedBytes_;
int sampleRate_;
volatile int threadData_;
int currentPos_;
int lastPos_;
short realtimeBuffer_[BUFSIZE * 2];
};
#include "DSoundStream.h"
// TODO: Get rid of this
static DSoundAudioBackend *g_dsound;
@@ -161,7 +105,7 @@ int DSoundAudioBackend::RunThread() {
InitializeCriticalSection(&soundCriticalSection);
DWORD num1;
short *p1;
int16_t *p1;
dsBuffer_->Lock(0, bufferSize_, (void **)&p1, &num1, 0, 0, 0);
@@ -173,7 +117,7 @@ int DSoundAudioBackend::RunThread() {
currentPos_ = 0;
lastPos_ = 0;
dsBuffer_->Play(0,0,DSBPLAY_LOOPING);
dsBuffer_->Play(0, 0, DSBPLAY_LOOPING);
while (!threadData_) {
EnterCriticalSection(&soundCriticalSection);
@@ -250,239 +194,3 @@ void DSoundAudioBackend::Update() {
if (soundSyncEvent_ != NULL)
SetEvent(soundSyncEvent_);
}
class WASAPIAudioBackend : public WindowsAudioBackend {
public:
WASAPIAudioBackend();
~WASAPIAudioBackend() override;
bool Init(HWND window, StreamCallback callback, int sampleRate) override; // If fails, can safely delete the object
void Update() override {}
int GetSampleRate() override { return sampleRate_; }
private:
int RunThread();
static unsigned int WINAPI soundThread(void *param);
HANDLE hThread_;
StreamCallback callback_;
int sampleRate_;
volatile int threadData_;
};
// TODO: Make these adjustable. This is from the example in MSDN.
// 200 times/sec = 5ms, pretty good :) Wonder if all computers can handle it though.
#define REFTIMES_PER_SEC (10000000/200)
#define REFTIMES_PER_MILLISEC (REFTIMES_PER_SEC / 1000)
WASAPIAudioBackend::WASAPIAudioBackend() : hThread_(NULL), sampleRate_(0), callback_(nullptr), threadData_(0) {
}
WASAPIAudioBackend::~WASAPIAudioBackend() {
if (threadData_ == 0) {
threadData_ = 1;
}
if (hThread_ != NULL) {
WaitForSingleObject(hThread_, 1000);
CloseHandle(hThread_);
hThread_ = NULL;
}
if (threadData_ == 2) {
// blah.
}
}
unsigned int WINAPI WASAPIAudioBackend::soundThread(void *param) {
WASAPIAudioBackend *backend = (WASAPIAudioBackend *)param;
return backend->RunThread();
}
bool WASAPIAudioBackend::Init(HWND window, StreamCallback callback, int sampleRate) {
threadData_ = 0;
callback_ = callback;
sampleRate_ = sampleRate;
hThread_ = (HANDLE)_beginthreadex(0, 0, soundThread, (void *)this, 0, 0);
SetThreadPriority(hThread_, THREAD_PRIORITY_ABOVE_NORMAL);
return true;
}
int WASAPIAudioBackend::RunThread() {
// Adapted from http://msdn.microsoft.com/en-us/library/windows/desktop/dd316756(v=vs.85).aspx
CoInitializeEx(NULL, COINIT_MULTITHREADED);
setCurrentThreadName("WASAPI_audio");
IMMDeviceEnumerator *pDeviceEnumerator;
IMMDevice *pDevice;
IAudioClient *pAudioInterface;
IAudioRenderClient *pAudioRenderClient;
WAVEFORMATEXTENSIBLE *pDeviceFormat;
DWORD flags = 0;
REFERENCE_TIME hnsBufferDuration, hnsActualDuration;
UINT32 pNumBufferFrames;
UINT32 pNumPaddingFrames, pNumAvFrames;
short *shortBuf = nullptr;
int numSamples;
hnsBufferDuration = REFTIMES_PER_SEC;
enum {
UNKNOWN_FORMAT = 0,
IEEE_FLOAT = 1,
PCM16 = 2,
} format = UNKNOWN_FORMAT;
HRESULT hresult;
hresult = CoCreateInstance(CLSID_MMDeviceEnumerator,
NULL, /*Object is not created as the part of the aggregate */
CLSCTX_ALL, IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
if (FAILED(hresult)) goto bail;
hresult = pDeviceEnumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDevice);
if (FAILED(hresult)) {
pDeviceEnumerator->Release();
goto bail;
}
hresult = pDevice->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioInterface);
if (FAILED(hresult)) {
pDevice->Release();
pDeviceEnumerator->Release();
goto bail;
}
hresult = pAudioInterface->GetMixFormat((WAVEFORMATEX**)&pDeviceFormat);
hresult = pAudioInterface->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, hnsBufferDuration, 0, &pDeviceFormat->Format, NULL);
hresult = pAudioInterface->GetService(IID_IAudioRenderClient, (void**)&pAudioRenderClient);
if (FAILED(hresult)) {
pDevice->Release();
pDeviceEnumerator->Release();
pAudioInterface->Release();
goto bail;
}
hresult = pAudioInterface->GetBufferSize(&pNumBufferFrames);
if (FAILED(hresult)) {
pDevice->Release();
pDeviceEnumerator->Release();
pAudioInterface->Release();
goto bail;
}
sampleRate_ = pDeviceFormat->Format.nSamplesPerSec;
// Don't know if PCM16 ever shows up here, the documentation only talks about float... but let's blindly
// try to support it :P
if (pDeviceFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
if (!memcmp(&pDeviceFormat->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(pDeviceFormat->SubFormat))) {
format = IEEE_FLOAT;
// printf("float format\n");
} else {
ERROR_LOG_REPORT_ONCE(unexpectedformat, SCEAUDIO, "Got unexpected WASAPI 0xFFFE stream format, expected float!");
if (pDeviceFormat->Format.wBitsPerSample == 16 && pDeviceFormat->Format.nChannels == 2) {
format = PCM16;
}
}
} else {
ERROR_LOG_REPORT_ONCE(unexpectedformat2, SCEAUDIO, "Got unexpected non-extensible WASAPI stream format, expected extensible float!");
if (pDeviceFormat->Format.wBitsPerSample == 16 && pDeviceFormat->Format.nChannels == 2) {
format = PCM16;
}
}
BYTE *pData;
hresult = pAudioRenderClient->GetBuffer(pNumBufferFrames, &pData);
numSamples = pNumBufferFrames * pDeviceFormat->Format.nChannels;
if (format == IEEE_FLOAT) {
memset(pData, 0, sizeof(float) * numSamples);
shortBuf = new short[pNumBufferFrames * pDeviceFormat->Format.nChannels];
} else if (format == PCM16) {
memset(pData, 0, sizeof(short) * numSamples);
}
hresult = pAudioRenderClient->ReleaseBuffer(pNumBufferFrames, flags);
hnsActualDuration = (REFERENCE_TIME)((double)REFTIMES_PER_SEC * pNumBufferFrames / pDeviceFormat->Format.nSamplesPerSec);
hresult = pAudioInterface->Start();
while (flags != AUDCLNT_BUFFERFLAGS_SILENT) {
Sleep((DWORD)(hnsActualDuration / REFTIMES_PER_MILLISEC / 2));
hresult = pAudioInterface->GetCurrentPadding(&pNumPaddingFrames);
if (FAILED(hresult)) {
// What to do?
pNumPaddingFrames = 0;
}
pNumAvFrames = pNumBufferFrames - pNumPaddingFrames;
hresult = pAudioRenderClient->GetBuffer(pNumAvFrames, &pData);
if (FAILED(hresult)) {
// What to do?
} else if (pNumAvFrames) {
switch (format) {
case IEEE_FLOAT:
callback_(shortBuf, pNumAvFrames, 16, sampleRate_, 2);
if (pDeviceFormat->Format.nChannels == 2) {
ConvertS16ToF32((float *)pData, shortBuf, pNumAvFrames * pDeviceFormat->Format.nChannels);
} else {
float *ptr = (float *)pData;
int chans = pDeviceFormat->Format.nChannels;
memset(ptr, 0, pNumAvFrames * chans * sizeof(float));
for (UINT32 i = 0; i < pNumAvFrames; i++) {
ptr[i * chans + 0] = (float)shortBuf[i * 2] * (1.0f / 32768.0f);
ptr[i * chans + 1] = (float)shortBuf[i * 2 + 1] * (1.0f / 32768.0f);
}
}
break;
case PCM16:
callback_((short *)pData, pNumAvFrames, 16, sampleRate_, 2);
break;
}
}
if (threadData_ != 0) {
flags = AUDCLNT_BUFFERFLAGS_SILENT;
}
hresult = pAudioRenderClient->ReleaseBuffer(pNumAvFrames, flags);
if (FAILED(hresult)) {
// Not much to do here either...
}
}
// Wait for last data in buffer to play before stopping.
Sleep((DWORD)(hnsActualDuration / REFTIMES_PER_MILLISEC / 2));
delete[] shortBuf;
hresult = pAudioInterface->Stop();
CoTaskMemFree(pDeviceFormat);
pDeviceEnumerator->Release();
pDevice->Release();
pAudioInterface->Release();
pAudioRenderClient->Release();
bail:
threadData_ = 2;
CoUninitialize();
return 0;
}
WindowsAudioBackend *CreateAudioBackend(AudioBackendType type) {
if (IsVistaOrHigher()) {
switch (type) {
case AUDIO_BACKEND_WASAPI:
case AUDIO_BACKEND_AUTO:
return new WASAPIAudioBackend();
case AUDIO_BACKEND_DSOUND:
default:
return new DSoundAudioBackend();
}
} else {
return new DSoundAudioBackend();
}
}
+45 -15
View File
@@ -1,21 +1,51 @@
#pragma once
#include "Common/CommonWindows.h"
#include "Core/Config.h"
#include "Core/ConfigValues.h"
// This should only be included from WindowsAudio.cpp and DSoundStream.cpp.
typedef int (*StreamCallback)(short *buffer, int numSamples, int bits, int rate, int channels);
#include "WindowsAudio.h"
#include <mmreg.h>
#include <dsound.h>
// Note that the backend may override the passed in sample rate. The actual sample rate
// should be returned by GetSampleRate though.
class WindowsAudioBackend {
class DSoundAudioBackend : public WindowsAudioBackend {
public:
WindowsAudioBackend() {}
virtual ~WindowsAudioBackend() {}
virtual bool Init(HWND window, StreamCallback _callback, int sampleRate) = 0;
virtual void Update() {} // Doesn't have to do anything
virtual int GetSampleRate() = 0;
};
DSoundAudioBackend();
~DSoundAudioBackend() override;
// Factory
WindowsAudioBackend *CreateAudioBackend(AudioBackendType type);
bool Init(HWND window, StreamCallback callback, int sampleRate) override; // If fails, can safely delete the object
void Update() override;
int GetSampleRate() override { return sampleRate_; }
private:
inline int ModBufferSize(int x) { return (x + bufferSize_) % bufferSize_; }
int RunThread();
static unsigned int WINAPI soundThread(void *param);
bool CreateBuffer();
bool WriteDataToBuffer(DWORD offset, // Our own write cursor.
char* soundData, // Start of our data.
DWORD soundBytes); // Size of block to copy.
CRITICAL_SECTION soundCriticalSection;
HWND window_;
HANDLE soundSyncEvent_ = nullptr;
HANDLE hThread_ = nullptr;
StreamCallback callback_;
IDirectSound8 *ds_ = nullptr;
IDirectSoundBuffer *dsBuffer_ = nullptr;
int bufferSize_; // bytes
int totalRenderedBytes_;
int sampleRate_;
volatile int threadData_;
enum {
BUFSIZE = 0x4000,
MAXWAIT = 20, //ms
};
int currentPos_;
int lastPos_;
short realtimeBuffer_[BUFSIZE * 2];
};
+4
View File
@@ -398,6 +398,8 @@
<ClCompile Include="MainWindow.cpp" />
<ClCompile Include="DSoundStream.cpp" />
<ClCompile Include="GPU\WindowsGLContext.cpp" />
<ClCompile Include="WASAPIStream.cpp" />
<ClCompile Include="WindowsAudio.cpp" />
<ClCompile Include="WindowsHost.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="stdafx.cpp">
@@ -499,6 +501,8 @@
<ClInclude Include="MainWindow.h" />
<ClInclude Include="DSoundStream.h" />
<ClInclude Include="GPU\WindowsGLContext.h" />
<ClInclude Include="WASAPIStream.h" />
<ClInclude Include="WindowsAudio.h" />
<ClInclude Include="WindowsHost.h" />
<ClInclude Include="main.h" />
<ClInclude Include="resource.h" />
+12
View File
@@ -188,6 +188,12 @@
<ClCompile Include="..\UWP\UWPHost.cpp">
<Filter>Other Platforms</Filter>
</ClCompile>
<ClCompile Include="WindowsAudio.cpp">
<Filter>Windows\System</Filter>
</ClCompile>
<ClCompile Include="WASAPIStream.cpp">
<Filter>Windows\System</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Debugger\CtrlDisAsmView.h">
@@ -347,6 +353,12 @@
<ClInclude Include="..\UWP\UWPHost.h">
<Filter>Other Platforms</Filter>
</ClInclude>
<ClInclude Include="WindowsAudio.h">
<Filter>Windows\System</Filter>
</ClInclude>
<ClInclude Include="WASAPIStream.h">
<Filter>Windows\System</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="icon1.ico">
+429
View File
@@ -0,0 +1,429 @@
#include "WindowsAudio.h"
#include "WASAPIStream.h"
#include "Common/Log.h"
#include "Core/Reporting.h"
#include "Core/Util/AudioFormat.h"
#include "thread/threadutil.h"
#include <mutex>
#include <Objbase.h>
#include <Mmreg.h>
#include <MMDeviceAPI.h>
#include <AudioClient.h>
#include <AudioPolicy.h>
#include "Functiondiscoverykeys_devpkey.h"
// Includes some code from https://msdn.microsoft.com/en-us/library/dd370810%28VS.85%29.aspx?f=255&MSPPError=-2147217396
#pragma comment(lib, "ole32.lib")
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
const IID IID_IAudioClient = __uuidof(IAudioClient);
const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
// Adapted from a MSDN sample.
#define SAFE_RELEASE(punk) \
if ((punk) != NULL) \
{ (punk)->Release(); (punk) = NULL; }
class CMMNotificationClient : public IMMNotificationClient {
public:
CMMNotificationClient() {
}
~CMMNotificationClient() {
if (currentDevice_)
CoTaskMemFree(currentDevice_);
currentDevice_ = nullptr;
SAFE_RELEASE(_pEnumerator)
}
void SetCurrentDevice(IMMDevice *device) {
std::lock_guard<std::mutex> guard(lock_);
if (currentDevice_)
CoTaskMemFree(currentDevice_);
device->GetId(&currentDevice_);
deviceChanged_ = false;
}
bool HasDeviceChanged() {
return deviceChanged_;
}
// IUnknown methods -- AddRef, Release, and QueryInterface
ULONG STDMETHODCALLTYPE AddRef() override {
return InterlockedIncrement(&_cRef);
}
ULONG STDMETHODCALLTYPE Release() override {
ULONG ulRef = InterlockedDecrement(&_cRef);
if (0 == ulRef) {
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) override {
if (IID_IUnknown == riid) {
AddRef();
*ppvInterface = (IUnknown*)this;
} else if (__uuidof(IMMNotificationClient) == riid) {
AddRef();
*ppvInterface = (IMMNotificationClient*)this;
} else {
*ppvInterface = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
// Callback methods for device-event notifications.
HRESULT STDMETHODCALLTYPE OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDeviceId) {
std::lock_guard<std::mutex> guard(lock_);
if (flow != eRender || role != eMultimedia) {
// Not relevant to us.
return S_OK;
}
if (!wcscmp(currentDevice_, pwstrDeviceId)) {
// Already the current device, nothing to do.
return S_OK;
}
deviceChanged_ = true;
INFO_LOG(SCEAUDIO, "New default WASAPI audio device detected");
return S_OK;
}
HRESULT STDMETHODCALLTYPE OnDeviceAdded(LPCWSTR pwstrDeviceId) {
// Ignore.
return S_OK;
};
HRESULT STDMETHODCALLTYPE OnDeviceRemoved(LPCWSTR pwstrDeviceId) {
// Ignore.
return S_OK;
}
HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pwstrDeviceId, DWORD dwNewState) {
// Ignore.
return S_OK;
}
HRESULT STDMETHODCALLTYPE OnPropertyValueChanged(LPCWSTR pwstrDeviceId, const PROPERTYKEY key) {
INFO_LOG(SCEAUDIO, "Changed audio device property "
"{%8.8x-%4.4x-%4.4x-%2.2x%2.2x-%2.2x%2.2x%2.2x%2.2x%2.2x%2.2x}#%d",
key.fmtid.Data1, key.fmtid.Data2, key.fmtid.Data3,
key.fmtid.Data4[0], key.fmtid.Data4[1],
key.fmtid.Data4[2], key.fmtid.Data4[3],
key.fmtid.Data4[4], key.fmtid.Data4[5],
key.fmtid.Data4[6], key.fmtid.Data4[7],
key.pid);
return S_OK;
}
private:
std::mutex lock_;
LONG _cRef = 1;
IMMDeviceEnumerator *_pEnumerator = nullptr;
wchar_t *currentDevice_ = nullptr;
bool deviceChanged_ = false;
};
// TODO: Make these adjustable. This is from the example in MSDN.
// 200 times/sec = 5ms, pretty good :) Wonder if all computers can handle it though.
#define REFTIMES_PER_SEC (10000000/200)
#define REFTIMES_PER_MILLISEC (REFTIMES_PER_SEC / 1000)
WASAPIAudioBackend::WASAPIAudioBackend() {
}
WASAPIAudioBackend::~WASAPIAudioBackend() {
if (threadData_ == 0) {
threadData_ = 1;
}
if (hThread_) {
WaitForSingleObject(hThread_, 1000);
CloseHandle(hThread_);
hThread_ = nullptr;
}
if (threadData_ == 2) {
// blah.
}
}
unsigned int WINAPI WASAPIAudioBackend::soundThread(void *param) {
WASAPIAudioBackend *backend = (WASAPIAudioBackend *)param;
return backend->RunThread();
}
bool WASAPIAudioBackend::Init(HWND window, StreamCallback callback, int sampleRate) {
threadData_ = 0;
callback_ = callback;
sampleRate_ = sampleRate;
hThread_ = (HANDLE)_beginthreadex(0, 0, soundThread, (void *)this, 0, 0);
SetThreadPriority(hThread_, THREAD_PRIORITY_ABOVE_NORMAL);
return true;
}
// This to be run only on the thread.
class WASAPIAudioThread {
public:
WASAPIAudioThread(volatile int &threadData, int &sampleRate, StreamCallback &callback)
: threadData_(threadData), sampleRate_(sampleRate), callback_(callback) {
}
~WASAPIAudioThread();
void Run();
private:
bool ActivateDefaultDevice();
bool InitAudioDevice();
void ShutdownAudioDevice();
bool DetectFormat();
volatile int &threadData_;
int &sampleRate_;
StreamCallback &callback_;
IMMDeviceEnumerator *deviceEnumerator_ = nullptr;
IMMDevice *device_ = nullptr;
IAudioClient *audioInterface_ = nullptr;
CMMNotificationClient *notificationClient_ = nullptr;
WAVEFORMATEXTENSIBLE *deviceFormat_ = nullptr;
IAudioRenderClient *renderClient_ = nullptr;
short *shortBuf_ = nullptr;
enum class Format {
UNKNOWN = 0,
IEEE_FLOAT = 1,
PCM16 = 2,
};
uint32_t numBufferFrames = 0;
Format format_ = Format::UNKNOWN;
REFERENCE_TIME actualDuration_;
};
WASAPIAudioThread::~WASAPIAudioThread() {
delete [] shortBuf_;
shortBuf_ = nullptr;
ShutdownAudioDevice();
if (notificationClient_ && deviceEnumerator_)
deviceEnumerator_->UnregisterEndpointNotificationCallback(notificationClient_);
delete notificationClient_;
notificationClient_ = nullptr;
SAFE_RELEASE(deviceEnumerator_);
}
bool WASAPIAudioThread::ActivateDefaultDevice() {
HRESULT hresult = deviceEnumerator_->GetDefaultAudioEndpoint(eRender, eMultimedia, &device_);
if (FAILED(hresult))
return false;
hresult = device_->Activate(IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&audioInterface_);
if (FAILED(hresult))
return false;
return true;
}
bool WASAPIAudioThread::InitAudioDevice() {
REFERENCE_TIME hnsBufferDuration = REFTIMES_PER_SEC;
HRESULT hresult = audioInterface_->GetMixFormat((WAVEFORMATEX **)&deviceFormat_);
hresult = audioInterface_->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, hnsBufferDuration, 0, &deviceFormat_->Format, nullptr);
hresult = audioInterface_->GetService(IID_IAudioRenderClient, (void **)&renderClient_);
if (FAILED(hresult))
return false;
hresult = audioInterface_->GetBufferSize(&numBufferFrames);
if (FAILED(hresult))
return false;
sampleRate_ = deviceFormat_->Format.nSamplesPerSec;
return true;
}
void WASAPIAudioThread::ShutdownAudioDevice() {
SAFE_RELEASE(renderClient_);
CoTaskMemFree(deviceFormat_);
deviceFormat_ = nullptr;
SAFE_RELEASE(audioInterface_);
SAFE_RELEASE(device_);
}
bool WASAPIAudioThread::DetectFormat() {
// Don't know if PCM16 ever shows up here, the documentation only talks about float... but let's blindly
// try to support it :P
if (deviceFormat_->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
if (!memcmp(&deviceFormat_->SubFormat, &KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, sizeof(deviceFormat_->SubFormat))) {
format_ = Format::IEEE_FLOAT;
} else {
ERROR_LOG_REPORT_ONCE(unexpectedformat, SCEAUDIO, "Got unexpected WASAPI 0xFFFE stream format, expected float!");
if (deviceFormat_->Format.wBitsPerSample == 16 && deviceFormat_->Format.nChannels == 2) {
format_ = Format::PCM16;
}
}
} else if (deviceFormat_->Format.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
format_ = Format::IEEE_FLOAT;
} else {
ERROR_LOG_REPORT_ONCE(unexpectedformat2, SCEAUDIO, "Got unexpected non-extensible WASAPI stream format, expected extensible float!");
if (deviceFormat_->Format.wBitsPerSample == 16 && deviceFormat_->Format.nChannels == 2) {
format_ = Format::PCM16;
}
}
delete [] shortBuf_;
shortBuf_ = nullptr;
BYTE *pData;
HRESULT hresult = renderClient_->GetBuffer(numBufferFrames, &pData);
int numSamples = numBufferFrames * deviceFormat_->Format.nChannels;
if (format_ == Format::IEEE_FLOAT) {
memset(pData, 0, sizeof(float) * numSamples);
shortBuf_ = new short[numBufferFrames * deviceFormat_->Format.nChannels];
} else if (format_ == Format::PCM16) {
memset(pData, 0, sizeof(short) * numSamples);
}
hresult = renderClient_->ReleaseBuffer(numBufferFrames, 0);
actualDuration_ = (REFERENCE_TIME)((double)REFTIMES_PER_SEC * numBufferFrames / deviceFormat_->Format.nSamplesPerSec);
return true;
}
void WASAPIAudioThread::Run() {
// Adapted from http://msdn.microsoft.com/en-us/library/windows/desktop/dd316756(v=vs.85).aspx
HRESULT hresult;
hresult = CoCreateInstance(CLSID_MMDeviceEnumerator,
nullptr, /* Object is not created as the part of the aggregate */
CLSCTX_ALL, IID_IMMDeviceEnumerator, (void **)&deviceEnumerator_);
if (FAILED(hresult))
return;
if (!ActivateDefaultDevice()) {
ERROR_LOG(SCEAUDIO, "WASAPI: Could not activate default device");
return;
}
notificationClient_ = new CMMNotificationClient();
notificationClient_->SetCurrentDevice(device_);
hresult = deviceEnumerator_->RegisterEndpointNotificationCallback(notificationClient_);
if (FAILED(hresult)) {
// Let's just keep going, but release the client since it doesn't work.
delete notificationClient_;
notificationClient_ = nullptr;
}
if (!InitAudioDevice()) {
ERROR_LOG(SCEAUDIO, "WASAPI: Could not init audio device");
return;
}
if (!DetectFormat()) {
ERROR_LOG(SCEAUDIO, "WASAPI: Could not find a suitable audio output format");
return;
}
hresult = audioInterface_->Start();
DWORD flags = 0;
while (flags != AUDCLNT_BUFFERFLAGS_SILENT) {
Sleep((DWORD)(actualDuration_ / REFTIMES_PER_MILLISEC / 2));
uint32_t pNumPaddingFrames;
hresult = audioInterface_->GetCurrentPadding(&pNumPaddingFrames);
if (FAILED(hresult)) {
// What to do?
pNumPaddingFrames = 0;
}
uint32_t pNumAvFrames = numBufferFrames - pNumPaddingFrames;
BYTE *pData;
hresult = renderClient_->GetBuffer(pNumAvFrames, &pData);
if (FAILED(hresult)) {
// What to do?
} else if (pNumAvFrames) {
switch (format_) {
case Format::IEEE_FLOAT:
callback_(shortBuf_, pNumAvFrames, 16, sampleRate_, 2);
if (deviceFormat_->Format.nChannels == 2) {
ConvertS16ToF32((float *)pData, shortBuf_, pNumAvFrames * deviceFormat_->Format.nChannels);
} else {
float *ptr = (float *)pData;
int chans = deviceFormat_->Format.nChannels;
memset(ptr, 0, pNumAvFrames * chans * sizeof(float));
for (UINT32 i = 0; i < pNumAvFrames; i++) {
ptr[i * chans + 0] = (float)shortBuf_[i * 2] * (1.0f / 32768.0f);
ptr[i * chans + 1] = (float)shortBuf_[i * 2 + 1] * (1.0f / 32768.0f);
}
}
break;
case Format::PCM16:
callback_((short *)pData, pNumAvFrames, 16, sampleRate_, 2);
break;
}
}
if (threadData_ != 0) {
flags = AUDCLNT_BUFFERFLAGS_SILENT;
}
hresult = renderClient_->ReleaseBuffer(pNumAvFrames, flags);
if (FAILED(hresult)) {
// Not much to do here either...
}
// Check if we should use a new device.
if (notificationClient_ && notificationClient_->HasDeviceChanged()) {
hresult = audioInterface_->Stop();
ShutdownAudioDevice();
if (!ActivateDefaultDevice()) {
ERROR_LOG(SCEAUDIO, "WASAPI: Could not activate default device");
return;
}
notificationClient_->SetCurrentDevice(device_);
if (!InitAudioDevice()) {
ERROR_LOG(SCEAUDIO, "WASAPI: Could not init audio device");
return;
}
if (!DetectFormat()) {
ERROR_LOG(SCEAUDIO, "WASAPI: Could not find a suitable audio output format");
return;
}
hresult = audioInterface_->Start();
}
}
// Wait for last data in buffer to play before stopping.
Sleep((DWORD)(actualDuration_ / REFTIMES_PER_MILLISEC / 2));
hresult = audioInterface_->Stop();
}
int WASAPIAudioBackend::RunThread() {
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
setCurrentThreadName("WASAPI_audio");
if (threadData_ == 0) {
// This will free everything once it's done.
WASAPIAudioThread renderer(threadData_, sampleRate_, callback_);
renderer.Run();
}
threadData_ = 2;
CoUninitialize();
return 0;
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include "WindowsAudio.h"
// This should only be included from WindowsAudio.cpp and WASAPIStream.cpp.
class WASAPIAudioBackend : public WindowsAudioBackend {
public:
WASAPIAudioBackend();
~WASAPIAudioBackend() override;
bool Init(HWND window, StreamCallback callback, int sampleRate) override; // If fails, can safely delete the object
void Update() override {}
int GetSampleRate() override { return sampleRate_; }
private:
int RunThread();
static unsigned int WINAPI soundThread(void *param);
HANDLE hThread_ = nullptr;
StreamCallback callback_ = nullptr;
int sampleRate_ = 0;
volatile int threadData_ = 0;
};
+19
View File
@@ -0,0 +1,19 @@
#include "Common/OSVersion.h"
#include "WindowsAudio.h"
#include "DSoundStream.h"
#include "WASAPIStream.h"
WindowsAudioBackend *CreateAudioBackend(AudioBackendType type) {
if (IsVistaOrHigher()) {
switch (type) {
case AUDIO_BACKEND_WASAPI:
case AUDIO_BACKEND_AUTO:
return new WASAPIAudioBackend();
case AUDIO_BACKEND_DSOUND:
default:
return new DSoundAudioBackend();
}
} else {
return new DSoundAudioBackend();
}
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "Common/CommonWindows.h"
#include "Core/Config.h"
#include "Core/ConfigValues.h"
typedef int(*StreamCallback)(short *buffer, int numSamples, int bits, int rate, int channels);
// Note that the backend may override the passed in sample rate. The actual sample rate
// should be returned by GetSampleRate though.
class WindowsAudioBackend {
public:
WindowsAudioBackend() {}
virtual ~WindowsAudioBackend() {}
virtual bool Init(HWND window, StreamCallback _callback, int sampleRate) = 0;
virtual void Update() {} // Doesn't have to do anything
virtual int GetSampleRate() = 0;
};
// Factory
WindowsAudioBackend *CreateAudioBackend(AudioBackendType type);
+1 -1
View File
@@ -47,7 +47,7 @@
#include "Core/System.h"
#include "Core/Debugger/SymbolMap.h"
#include "Windows/EmuThread.h"
#include "Windows/DSoundStream.h"
#include "Windows/WindowsAudio.h"
#include "Windows/WindowsHost.h"
#include "Windows/MainWindow.h"
+1 -1
View File
@@ -39,7 +39,7 @@
#include "Core/ConfigValues.h"
#include "Core/SaveState.h"
#include "Windows/EmuThread.h"
#include "Windows/DSoundStream.h"
#include "Windows/WindowsAudio.h"
#include "ext/disarm.h"
#include "Common/LogManager.h"