openal-soft/Alc/backends/wasapi.cpp

1955 lines
62 KiB
C++
Raw Normal View History

2011-05-15 20:26:25 -07:00
/**
* OpenAL cross platform audio library
* Copyright (C) 2011 by authors.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
2011-05-15 20:26:25 -07:00
* Or go to http://www.gnu.org/copyleft/lgpl.html
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <wtypes.h>
2011-05-16 04:13:37 -07:00
#include <mmdeviceapi.h>
#include <audioclient.h>
2011-05-15 20:26:25 -07:00
#include <cguid.h>
#include <devpropdef.h>
2011-05-15 20:26:25 -07:00
#include <mmreg.h>
#include <propsys.h>
#include <propkey.h>
#include <devpkey.h>
2011-05-15 20:26:25 -07:00
#ifndef _WAVEFORMATEXTENSIBLE_
#include <ks.h>
#include <ksmedia.h>
#endif
2018-11-01 21:39:34 -07:00
#include <atomic>
#include <thread>
#include <vector>
2018-11-01 21:39:34 -07:00
#include <string>
#include <algorithm>
2011-05-15 20:26:25 -07:00
#include "alMain.h"
2012-09-14 02:14:29 -07:00
#include "alu.h"
#include "ringbuffer.h"
2013-10-28 12:05:33 -07:00
#include "compat.h"
#include "alstring.h"
#include "converter.h"
2011-05-15 20:26:25 -07:00
#include "backends/base.h"
2011-05-15 20:26:25 -07:00
extern "C" {
extern const GUID KSDATAFORMAT_SUBTYPE_PCM;
extern const GUID KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
} // extern "C"
2011-05-15 20:26:25 -07:00
DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
2011-05-16 04:13:37 -07:00
#define MONO SPEAKER_FRONT_CENTER
#define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
#define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
#define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
#define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
2011-05-16 04:13:37 -07:00
#define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
#define X7DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
2015-01-15 09:27:37 -08:00
#define X7DOT1_WIDE (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_FRONT_LEFT_OF_CENTER|SPEAKER_FRONT_RIGHT_OF_CENTER)
2011-05-16 04:13:37 -07:00
2017-06-26 06:54:45 -07:00
#define REFTIME_PER_SEC ((REFERENCE_TIME)10000000)
2015-12-04 15:52:43 -08:00
#define DEVNAME_HEAD "OpenAL Soft on "
2011-05-16 04:13:37 -07:00
2018-01-11 22:42:25 -08:00
/* Scales the given value using 64-bit integer math, ceiling the result. */
2018-11-01 21:39:34 -07:00
static inline ALint64 ScaleCeil(ALint64 val, ALint64 new_scale, ALint64 old_scale)
2018-01-11 22:42:25 -08:00
{
return (val*new_scale + old_scale-1) / old_scale;
}
2018-11-01 21:39:34 -07:00
namespace {
struct DevMap {
std::string name;
std::string endpoint_guid; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
std::wstring devid;
template<typename T0, typename T1, typename T2>
DevMap(T0&& name_, T1&& guid_, T2&& devid_)
: name{std::forward<T0>(name_)}
, endpoint_guid{std::forward<T1>(guid_)}
, devid{std::forward<T2>(devid_)}
{ }
};
2018-11-01 21:39:34 -07:00
bool checkName(const std::vector<DevMap> &list, const std::string &name)
2014-04-24 04:02:05 -07:00
{
2018-11-01 21:39:34 -07:00
return std::find_if(list.cbegin(), list.cend(),
[&name](const DevMap &entry) -> bool
{ return entry.name == name; }
) != list.cend();
2014-04-24 04:02:05 -07:00
}
2018-11-01 21:39:34 -07:00
std::vector<DevMap> PlaybackDevices;
std::vector<DevMap> CaptureDevices;
2011-05-15 20:26:25 -07:00
2018-11-01 21:39:34 -07:00
std::string wstr_to_string(const WCHAR *wstr)
{
std::string ret;
2011-05-15 20:26:25 -07:00
2018-11-01 21:39:34 -07:00
int len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, nullptr, 0, nullptr, nullptr);
if(len > 0)
{
ret.resize(len);
WideCharToMultiByte(CP_UTF8, 0, wstr, -1, &ret[0], len, nullptr, nullptr);
ret.pop_back();
}
return ret;
}
2018-11-01 21:39:34 -07:00
HANDLE ThreadHdl;
DWORD ThreadID;
struct ThreadRequest {
HANDLE FinishedEvt;
HRESULT result;
2018-11-01 21:39:34 -07:00
};
} // namespace
#define WM_USER_First (WM_USER+0)
#define WM_USER_OpenDevice (WM_USER+0)
#define WM_USER_ResetDevice (WM_USER+1)
#define WM_USER_StartDevice (WM_USER+2)
#define WM_USER_StopDevice (WM_USER+3)
#define WM_USER_CloseDevice (WM_USER+4)
#define WM_USER_Enumerate (WM_USER+5)
#define WM_USER_Last (WM_USER+5)
static const char MessageStr[WM_USER_Last+1-WM_USER][20] = {
"Open Device",
"Reset Device",
"Start Device",
"Stop Device",
"Close Device",
"Enumerate Devices",
};
static inline void ReturnMsgResponse(ThreadRequest *req, HRESULT res)
{
req->result = res;
SetEvent(req->FinishedEvt);
}
static HRESULT WaitForResponse(ThreadRequest *req)
2011-05-15 20:26:25 -07:00
{
if(WaitForSingleObject(req->FinishedEvt, INFINITE) == WAIT_OBJECT_0)
return req->result;
ERR("Message response error: %lu\n", GetLastError());
return E_FAIL;
2011-05-16 04:13:37 -07:00
}
2018-11-01 21:39:34 -07:00
using NameGUIDPair = std::pair<std::string,std::string>;
static NameGUIDPair get_device_name_and_guid(IMMDevice *device)
{
2018-11-01 21:39:34 -07:00
std::string name{DEVNAME_HEAD};
2015-12-04 15:52:43 -08:00
2018-11-01 21:39:34 -07:00
IPropertyStore *ps;
HRESULT hr = device->OpenPropertyStore(STGM_READ, &ps);
if(FAILED(hr))
{
WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
2018-11-01 21:39:34 -07:00
return { name+"Unknown Device Name", "Unknown Device GUID" };
}
2018-11-01 21:39:34 -07:00
PROPVARIANT pvname;
PropVariantInit(&pvname);
hr = ps->GetValue(reinterpret_cast<const PROPERTYKEY&>(DEVPKEY_Device_FriendlyName), &pvname);
if(FAILED(hr))
2015-12-04 15:52:43 -08:00
{
WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr);
2018-11-01 21:39:34 -07:00
name += "Unknown Device Name";
2015-12-04 15:52:43 -08:00
}
2014-12-21 12:20:31 -08:00
else if(pvname.vt == VT_LPWSTR)
2018-11-01 21:39:34 -07:00
name += wstr_to_string(pvname.pwszVal);
2014-12-21 12:20:31 -08:00
else
2015-12-04 15:52:43 -08:00
{
2014-12-21 12:20:31 -08:00
WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvname.vt);
2018-11-01 21:39:34 -07:00
name += "Unknown Device Name";
2015-12-04 15:52:43 -08:00
}
PropVariantClear(&pvname);
2018-11-01 21:39:34 -07:00
std::string guid;
PROPVARIANT pvguid;
PropVariantInit(&pvguid);
2018-11-01 21:39:34 -07:00
hr = ps->GetValue(reinterpret_cast<const PROPERTYKEY&>(PKEY_AudioEndpoint_GUID), &pvguid);
if(FAILED(hr))
{
WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr);
guid = "Unknown Device GUID";
}
else if(pvname.vt == VT_LPWSTR)
guid = wstr_to_string(pvname.pwszVal);
else
{
WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvguid.vt);
guid = "Unknown Device GUID";
}
2018-11-01 21:39:34 -07:00
PropVariantClear(&pvguid);
ps->Release();
2018-11-01 21:39:34 -07:00
return {name, guid};
}
static void get_device_formfactor(IMMDevice *device, EndpointFormFactor *formfactor)
{
IPropertyStore *ps;
2018-11-01 21:39:34 -07:00
HRESULT hr = device->OpenPropertyStore(STGM_READ, &ps);
if(FAILED(hr))
{
WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
return;
}
2018-11-01 21:39:34 -07:00
PROPVARIANT pvform;
PropVariantInit(&pvform);
hr = ps->GetValue(reinterpret_cast<const PROPERTYKEY&>(PKEY_AudioEndpoint_FormFactor), &pvform);
if(FAILED(hr))
WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr);
2014-12-21 12:20:31 -08:00
else if(pvform.vt == VT_UI4)
*formfactor = static_cast<EndpointFormFactor>(pvform.ulVal);
2014-12-21 12:20:31 -08:00
else if(pvform.vt == VT_EMPTY)
*formfactor = UnknownFormFactor;
else
WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform.vt);
PropVariantClear(&pvform);
ps->Release();
}
2018-11-01 21:39:34 -07:00
static void add_device(IMMDevice *device, const WCHAR *devid, std::vector<DevMap> &list)
{
2018-11-01 21:39:34 -07:00
std::string basename, guidstr;
std::tie(basename, guidstr) = get_device_name_and_guid(device);
2018-11-01 21:39:34 -07:00
int count{1};
std::string newname{basename};
while(checkName(PlaybackDevices, newname))
{
2018-11-01 21:39:34 -07:00
newname = basename;
newname += " #";
newname += std::to_string(++count);
}
2018-11-01 21:39:34 -07:00
list.emplace_back(std::move(newname), std::move(guidstr), devid);
const DevMap &newentry = list.back();
2018-11-01 21:39:34 -07:00
TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry.name.c_str(),
newentry.endpoint_guid.c_str(), newentry.devid.c_str());
}
2017-01-10 05:12:54 -08:00
static WCHAR *get_device_id(IMMDevice *device)
{
2017-01-10 05:12:54 -08:00
WCHAR *devid;
2018-11-01 21:39:34 -07:00
HRESULT hr = device->GetId(&devid);
if(FAILED(hr))
{
ERR("Failed to get device id: %lx\n", hr);
return nullptr;
}
return devid;
}
2018-11-01 21:39:34 -07:00
static HRESULT probe_devices(IMMDeviceEnumerator *devenum, EDataFlow flowdir, std::vector<DevMap> &list)
{
IMMDeviceCollection *coll;
2018-11-01 21:39:34 -07:00
HRESULT hr = devenum->EnumAudioEndpoints(flowdir, DEVICE_STATE_ACTIVE, &coll);
if(FAILED(hr))
{
ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr);
2014-04-24 04:02:05 -07:00
return hr;
}
2018-11-01 21:39:34 -07:00
IMMDevice *defdev{nullptr};
WCHAR *defdevid{nullptr};
UINT count{0};
hr = coll->GetCount(&count);
if(SUCCEEDED(hr) && count > 0)
{
2018-11-01 21:39:34 -07:00
list.clear();
list.reserve(count);
hr = devenum->GetDefaultAudioEndpoint(flowdir, eMultimedia, &defdev);
}
if(SUCCEEDED(hr) && defdev != nullptr)
{
defdevid = get_device_id(defdev);
if(defdevid)
add_device(defdev, defdevid, list);
}
2018-11-01 21:39:34 -07:00
for(UINT i{0};i < count;++i)
{
IMMDevice *device;
hr = coll->Item(i, &device);
if(FAILED(hr)) continue;
2018-11-01 21:39:34 -07:00
WCHAR *devid = get_device_id(device);
if(devid)
{
if(wcscmp(devid, defdevid) != 0)
add_device(device, devid, list);
CoTaskMemFree(devid);
}
device->Release();
}
if(defdev) defdev->Release();
if(defdevid) CoTaskMemFree(defdevid);
coll->Release();
2014-04-24 04:02:05 -07:00
return S_OK;
}
/* Proxy interface used by the message handler. */
struct WasapiProxy {
virtual HRESULT openProxy() = 0;
virtual void closeProxy() = 0;
virtual HRESULT resetProxy() = 0;
virtual HRESULT startProxy() = 0;
virtual void stopProxy() = 0;
};
static DWORD CALLBACK WasapiProxy_messageHandler(void *ptr)
{
auto req = reinterpret_cast<ThreadRequest*>(ptr);
TRACE("Starting message thread\n");
2018-11-01 21:39:34 -07:00
HRESULT cohr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if(FAILED(cohr))
{
WARN("Failed to initialize COM: 0x%08lx\n", cohr);
ReturnMsgResponse(req, cohr);
return 0;
}
2018-11-01 21:39:34 -07:00
HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
IID_IMMDeviceEnumerator, &ptr);
if(FAILED(hr))
{
WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
CoUninitialize();
ReturnMsgResponse(req, hr);
return 0;
}
auto Enumerator = reinterpret_cast<IMMDeviceEnumerator*>(ptr);
Enumerator->Release();
Enumerator = nullptr;
CoUninitialize();
/* HACK: Force Windows to create a message queue for this thread before
* returning success, otherwise PostThreadMessage may fail if it gets
* called before GetMessage.
*/
2018-11-01 21:39:34 -07:00
MSG msg;
PeekMessage(&msg, nullptr, WM_USER, WM_USER, PM_NOREMOVE);
TRACE("Message thread initialization complete\n");
ReturnMsgResponse(req, S_OK);
TRACE("Starting message loop\n");
2018-11-01 21:39:34 -07:00
ALuint deviceCount{0};
while(GetMessage(&msg, nullptr, WM_USER_First, WM_USER_Last))
{
TRACE("Got message \"%s\" (0x%04x, lparam=%p, wparam=%p)\n",
(msg.message >= WM_USER && msg.message <= WM_USER_Last) ?
MessageStr[msg.message-WM_USER] : "Unknown",
msg.message, (void*)msg.lParam, (void*)msg.wParam
);
2018-11-01 21:39:34 -07:00
WasapiProxy *proxy{nullptr};
switch(msg.message)
{
case WM_USER_OpenDevice:
req = reinterpret_cast<ThreadRequest*>(msg.wParam);
proxy = reinterpret_cast<WasapiProxy*>(msg.lParam);
hr = cohr = S_OK;
if(++deviceCount == 1)
hr = cohr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if(SUCCEEDED(hr))
hr = proxy->openProxy();
if(FAILED(hr))
{
if(--deviceCount == 0 && SUCCEEDED(cohr))
CoUninitialize();
}
ReturnMsgResponse(req, hr);
continue;
case WM_USER_ResetDevice:
req = reinterpret_cast<ThreadRequest*>(msg.wParam);
proxy = reinterpret_cast<WasapiProxy*>(msg.lParam);
hr = proxy->resetProxy();
ReturnMsgResponse(req, hr);
continue;
case WM_USER_StartDevice:
req = reinterpret_cast<ThreadRequest*>(msg.wParam);
proxy = reinterpret_cast<WasapiProxy*>(msg.lParam);
hr = proxy->startProxy();
ReturnMsgResponse(req, hr);
continue;
case WM_USER_StopDevice:
req = reinterpret_cast<ThreadRequest*>(msg.wParam);
proxy = reinterpret_cast<WasapiProxy*>(msg.lParam);
proxy->stopProxy();
ReturnMsgResponse(req, S_OK);
continue;
case WM_USER_CloseDevice:
req = reinterpret_cast<ThreadRequest*>(msg.wParam);
proxy = reinterpret_cast<WasapiProxy*>(msg.lParam);
proxy->closeProxy();
if(--deviceCount == 0)
CoUninitialize();
ReturnMsgResponse(req, S_OK);
continue;
case WM_USER_Enumerate:
req = reinterpret_cast<ThreadRequest*>(msg.wParam);
hr = cohr = S_OK;
if(++deviceCount == 1)
hr = cohr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if(SUCCEEDED(hr))
hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER, IID_IMMDeviceEnumerator, &ptr);
if(SUCCEEDED(hr))
{
Enumerator = reinterpret_cast<IMMDeviceEnumerator*>(ptr);
if(msg.lParam == ALL_DEVICE_PROBE)
2018-11-01 21:39:34 -07:00
hr = probe_devices(Enumerator, eRender, PlaybackDevices);
else if(msg.lParam == CAPTURE_DEVICE_PROBE)
2018-11-01 21:39:34 -07:00
hr = probe_devices(Enumerator, eCapture, CaptureDevices);
Enumerator->Release();
Enumerator = nullptr;
}
if(--deviceCount == 0 && SUCCEEDED(cohr))
CoUninitialize();
ReturnMsgResponse(req, hr);
continue;
default:
ERR("Unexpected message: %u\n", msg.message);
continue;
}
}
TRACE("Message loop finished\n");
return 0;
}
struct ALCwasapiPlayback final : public ALCbackend, WasapiProxy {
HRESULT openProxy() override;
void closeProxy() override;
HRESULT resetProxy() override;
HRESULT startProxy() override;
void stopProxy() override;
std::wstring mDevId;
IMMDevice *mMMDev{nullptr};
IAudioClient *mClient{nullptr};
IAudioRenderClient *mRender{nullptr};
HANDLE mNotifyEvent{nullptr};
HANDLE mMsgEvent{nullptr};
std::atomic<UINT32> mPadding{0u};
std::atomic<ALenum> mKillNow{AL_TRUE};
std::thread mThread;
};
2018-03-09 18:56:24 -08:00
2018-11-01 21:39:34 -07:00
static int ALCwasapiPlayback_mixerProc(ALCwasapiPlayback *self);
2018-03-09 18:56:24 -08:00
static void ALCwasapiPlayback_Construct(ALCwasapiPlayback *self, ALCdevice *device);
static void ALCwasapiPlayback_Destruct(ALCwasapiPlayback *self);
static ALCenum ALCwasapiPlayback_open(ALCwasapiPlayback *self, const ALCchar *name);
static ALCboolean ALCwasapiPlayback_reset(ALCwasapiPlayback *self);
static ALCboolean ALCwasapiPlayback_start(ALCwasapiPlayback *self);
static void ALCwasapiPlayback_stop(ALCwasapiPlayback *self);
static DECLARE_FORWARD2(ALCwasapiPlayback, ALCbackend, ALCenum, captureSamples, ALCvoid*, ALCuint)
static DECLARE_FORWARD(ALCwasapiPlayback, ALCbackend, ALCuint, availableSamples)
static ClockLatency ALCwasapiPlayback_getClockLatency(ALCwasapiPlayback *self);
static DECLARE_FORWARD(ALCwasapiPlayback, ALCbackend, void, lock)
static DECLARE_FORWARD(ALCwasapiPlayback, ALCbackend, void, unlock)
DECLARE_DEFAULT_ALLOCATORS(ALCwasapiPlayback)
DEFINE_ALCBACKEND_VTABLE(ALCwasapiPlayback);
static void ALCwasapiPlayback_Construct(ALCwasapiPlayback *self, ALCdevice *device)
{
2018-11-01 21:39:34 -07:00
new (self) ALCwasapiPlayback{};
2018-03-09 18:56:24 -08:00
SET_VTABLE2(ALCwasapiPlayback, ALCbackend, self);
ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
}
2018-03-09 18:56:24 -08:00
static void ALCwasapiPlayback_Destruct(ALCwasapiPlayback *self)
{
if(self->mMsgEvent)
{
ThreadRequest req = { self->mMsgEvent, 0 };
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_CloseDevice, (WPARAM)&req, (LPARAM)proxy))
(void)WaitForResponse(&req);
CloseHandle(self->mMsgEvent);
self->mMsgEvent = nullptr;
}
if(self->mNotifyEvent != nullptr)
CloseHandle(self->mNotifyEvent);
self->mNotifyEvent = nullptr;
if(self->mMsgEvent != nullptr)
CloseHandle(self->mMsgEvent);
self->mMsgEvent = nullptr;
ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
2018-11-01 21:39:34 -07:00
self->~ALCwasapiPlayback();
}
2018-11-01 21:39:34 -07:00
FORCE_ALIGN static int ALCwasapiPlayback_mixerProc(ALCwasapiPlayback *self)
2011-05-16 04:13:37 -07:00
{
ALCdevice *device{STATIC_CAST(ALCbackend, self)->mDevice};
IAudioClient *client{self->mClient};
IAudioRenderClient *render{self->mRender};
2011-05-16 04:13:37 -07:00
2018-11-01 21:39:34 -07:00
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if(FAILED(hr))
{
ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr);
V0(device->Backend,lock)();
aluHandleDisconnect(device, "COM init failed: 0x%08lx", hr);
V0(device->Backend,unlock)();
return 1;
}
2011-05-16 04:13:37 -07:00
SetRTPriority();
2014-04-17 20:41:32 -07:00
althrd_setname(althrd_current(), MIXER_THREAD_NAME);
2011-05-16 04:13:37 -07:00
2018-11-01 21:39:34 -07:00
ALuint update_size{device->UpdateSize};
UINT32 buffer_len{update_size * device->NumUpdates};
while(!self->mKillNow.load(std::memory_order_relaxed))
2011-05-16 04:13:37 -07:00
{
2018-11-01 21:39:34 -07:00
UINT32 written;
hr = client->GetCurrentPadding(&written);
2011-05-16 04:13:37 -07:00
if(FAILED(hr))
{
2011-07-13 01:43:00 -07:00
ERR("Failed to get padding: 0x%08lx\n", hr);
V0(device->Backend,lock)();
aluHandleDisconnect(device, "Failed to retrieve buffer padding: 0x%08lx", hr);
V0(device->Backend,unlock)();
2011-05-16 04:13:37 -07:00
break;
}
self->mPadding.store(written, std::memory_order_relaxed);
2011-05-16 04:13:37 -07:00
2018-11-01 21:39:34 -07:00
ALuint len{buffer_len - written};
if(len < update_size)
2011-05-16 04:13:37 -07:00
{
DWORD res;
res = WaitForSingleObjectEx(self->mNotifyEvent, 2000, FALSE);
if(res != WAIT_OBJECT_0)
ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
2011-05-16 04:13:37 -07:00
continue;
}
len -= len%update_size;
2011-05-16 04:13:37 -07:00
2018-11-01 21:39:34 -07:00
BYTE *buffer;
hr = render->GetBuffer(len, &buffer);
2011-05-16 04:13:37 -07:00
if(SUCCEEDED(hr))
{
2018-03-09 18:56:24 -08:00
ALCwasapiPlayback_lock(self);
2011-05-16 04:13:37 -07:00
aluMixData(device, buffer, len);
self->mPadding.store(written + len, std::memory_order_relaxed);
2018-03-09 18:56:24 -08:00
ALCwasapiPlayback_unlock(self);
hr = render->ReleaseBuffer(len, 0);
2011-05-16 04:13:37 -07:00
}
if(FAILED(hr))
{
2011-07-13 01:43:00 -07:00
ERR("Failed to buffer data: 0x%08lx\n", hr);
V0(device->Backend,lock)();
aluHandleDisconnect(device, "Failed to send playback samples: 0x%08lx", hr);
V0(device->Backend,unlock)();
2011-05-16 04:13:37 -07:00
break;
}
}
self->mPadding.store(0u, std::memory_order_release);
2011-05-16 04:13:37 -07:00
CoUninitialize();
2011-05-16 04:13:37 -07:00
return 0;
2011-05-15 20:26:25 -07:00
}
static ALCboolean MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in)
2011-05-15 20:26:25 -07:00
{
memset(out, 0, sizeof(*out));
if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
2012-02-18 13:08:54 -08:00
*out = *(const WAVEFORMATEXTENSIBLE*)in;
else if(in->wFormatTag == WAVE_FORMAT_PCM)
2011-05-15 20:26:25 -07:00
{
out->Format = *in;
out->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
out->Format.cbSize = sizeof(*out) - sizeof(*in);
if(out->Format.nChannels == 1)
out->dwChannelMask = MONO;
else if(out->Format.nChannels == 2)
out->dwChannelMask = STEREO;
else
ERR("Unhandled PCM channel count: %d\n", out->Format.nChannels);
out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2011-05-15 20:26:25 -07:00
}
else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
2011-05-15 20:26:25 -07:00
{
out->Format = *in;
out->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
out->Format.cbSize = sizeof(*out) - sizeof(*in);
if(out->Format.nChannels == 1)
out->dwChannelMask = MONO;
else if(out->Format.nChannels == 2)
out->dwChannelMask = STEREO;
else
ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels);
out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
}
else
{
ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag);
2011-05-15 20:26:25 -07:00
return ALC_FALSE;
}
return ALC_TRUE;
}
2018-03-09 18:56:24 -08:00
static ALCenum ALCwasapiPlayback_open(ALCwasapiPlayback *self, const ALCchar *deviceName)
2011-05-15 20:26:25 -07:00
{
HRESULT hr = S_OK;
2011-05-16 04:13:37 -07:00
self->mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
self->mMsgEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if(self->mNotifyEvent == nullptr || self->mMsgEvent == nullptr)
{
ERR("Failed to create message events: %lu\n", GetLastError());
hr = E_FAIL;
}
if(SUCCEEDED(hr))
{
if(deviceName)
{
2018-11-01 21:39:34 -07:00
if(PlaybackDevices.empty())
{
ThreadRequest req = { self->mMsgEvent, 0 };
if(PostThreadMessage(ThreadID, WM_USER_Enumerate, (WPARAM)&req, ALL_DEVICE_PROBE))
(void)WaitForResponse(&req);
}
hr = E_FAIL;
2018-11-01 21:39:34 -07:00
auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
[deviceName](const DevMap &entry) -> bool
{ return entry.name == deviceName || entry.endpoint_guid == deviceName; }
);
if(iter == PlaybackDevices.cend())
{
int len;
if((len=MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, nullptr, 0)) > 0)
{
std::vector<WCHAR> wname(len);
MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, wname.data(), len);
2018-11-01 21:39:34 -07:00
iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
[&wname](const DevMap &entry) -> bool
{ return entry.devid == wname.data(); }
);
}
}
2018-11-01 21:39:34 -07:00
if(iter == PlaybackDevices.cend())
WARN("Failed to find device name matching \"%s\"\n", deviceName);
else
{
ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
self->mDevId = iter->devid;
2018-11-01 21:39:34 -07:00
alstr_copy_range(&device->DeviceName, &*iter->name.cbegin(), &*iter->name.cend());
hr = S_OK;
}
}
}
if(SUCCEEDED(hr))
2011-05-16 04:13:37 -07:00
{
ThreadRequest req{ self->mMsgEvent, 0 };
auto proxy = static_cast<WasapiProxy*>(self);
hr = E_FAIL;
if(PostThreadMessage(ThreadID, WM_USER_OpenDevice, (WPARAM)&req, (LPARAM)proxy))
hr = WaitForResponse(&req);
else
ERR("Failed to post thread message: %lu\n", GetLastError());
2011-05-16 04:13:37 -07:00
}
if(FAILED(hr))
2011-05-16 04:13:37 -07:00
{
if(self->mNotifyEvent != nullptr)
CloseHandle(self->mNotifyEvent);
self->mNotifyEvent = nullptr;
if(self->mMsgEvent != nullptr)
CloseHandle(self->mMsgEvent);
self->mMsgEvent = nullptr;
self->mDevId.clear();
ERR("Device init failed: 0x%08lx\n", hr);
return ALC_INVALID_VALUE;
2011-05-16 04:13:37 -07:00
}
return ALC_NO_ERROR;
}
HRESULT ALCwasapiPlayback::openProxy()
{
ALCdevice *device = STATIC_CAST(ALCbackend, this)->mDevice;
void *ptr;
HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER, IID_IMMDeviceEnumerator, &ptr);
if(SUCCEEDED(hr))
2011-05-16 04:13:37 -07:00
{
auto Enumerator = reinterpret_cast<IMMDeviceEnumerator*>(ptr);
if(mDevId.empty())
hr = Enumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, &mMMDev);
else
hr = Enumerator->GetDevice(mDevId.c_str(), &mMMDev);
Enumerator->Release();
}
if(SUCCEEDED(hr))
hr = mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr);
if(SUCCEEDED(hr))
{
mClient = reinterpret_cast<IAudioClient*>(ptr);
if(alstr_empty(device->DeviceName))
2018-11-01 21:39:34 -07:00
{
std::string devname;
std::tie(devname, std::ignore) = get_device_name_and_guid(mMMDev);
2018-11-01 21:39:34 -07:00
alstr_copy_range(&device->DeviceName, &*devname.cbegin(), &*devname.cend());
}
}
if(FAILED(hr))
{
if(mMMDev)
mMMDev->Release();
mMMDev = nullptr;
}
return hr;
}
void ALCwasapiPlayback::closeProxy()
{
if(mClient)
mClient->Release();
mClient = nullptr;
if(mMMDev)
mMMDev->Release();
mMMDev = nullptr;
}
2018-03-09 18:56:24 -08:00
static ALCboolean ALCwasapiPlayback_reset(ALCwasapiPlayback *self)
{
ThreadRequest req{ self->mMsgEvent, 0 };
2018-11-01 21:39:34 -07:00
HRESULT hr{E_FAIL};
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_ResetDevice, (WPARAM)&req, (LPARAM)proxy))
hr = WaitForResponse(&req);
return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE;
}
HRESULT ALCwasapiPlayback::resetProxy()
{
ALCdevice *device{STATIC_CAST(ALCbackend, this)->mDevice};
if(mClient)
mClient->Release();
mClient = nullptr;
void *ptr;
HRESULT hr = mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr);
if(FAILED(hr))
{
ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
return hr;
}
mClient = reinterpret_cast<IAudioClient*>(ptr);
WAVEFORMATEX *wfx;
hr = mClient->GetMixFormat(&wfx);
if(FAILED(hr))
{
ERR("Failed to get mix format: 0x%08lx\n", hr);
return hr;
}
WAVEFORMATEXTENSIBLE OutputType;
if(!MakeExtensible(&OutputType, wfx))
{
CoTaskMemFree(wfx);
return E_FAIL;
}
CoTaskMemFree(wfx);
wfx = nullptr;
REFERENCE_TIME buf_time{ScaleCeil(device->UpdateSize*device->NumUpdates, REFTIME_PER_SEC,
device->Frequency)};
if(!(device->Flags&DEVICE_FREQUENCY_REQUEST))
device->Frequency = OutputType.Format.nSamplesPerSec;
if(!(device->Flags&DEVICE_CHANNELS_REQUEST))
{
if(OutputType.Format.nChannels == 1 && OutputType.dwChannelMask == MONO)
device->FmtChans = DevFmtMono;
else if(OutputType.Format.nChannels == 2 && OutputType.dwChannelMask == STEREO)
device->FmtChans = DevFmtStereo;
else if(OutputType.Format.nChannels == 4 && OutputType.dwChannelMask == QUAD)
device->FmtChans = DevFmtQuad;
else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1)
device->FmtChans = DevFmtX51;
else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1REAR)
device->FmtChans = DevFmtX51Rear;
else if(OutputType.Format.nChannels == 7 && OutputType.dwChannelMask == X6DOT1)
device->FmtChans = DevFmtX61;
2015-01-15 09:27:37 -08:00
else if(OutputType.Format.nChannels == 8 && (OutputType.dwChannelMask == X7DOT1 || OutputType.dwChannelMask == X7DOT1_WIDE))
device->FmtChans = DevFmtX71;
else
2011-07-16 04:21:40 -07:00
ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType.Format.nChannels, OutputType.dwChannelMask);
2011-05-16 04:13:37 -07:00
}
switch(device->FmtChans)
{
case DevFmtMono:
OutputType.Format.nChannels = 1;
OutputType.dwChannelMask = MONO;
break;
case DevFmtAmbi3D:
device->FmtChans = DevFmtStereo;
/*fall-through*/
2011-05-16 04:13:37 -07:00
case DevFmtStereo:
OutputType.Format.nChannels = 2;
OutputType.dwChannelMask = STEREO;
break;
case DevFmtQuad:
OutputType.Format.nChannels = 4;
OutputType.dwChannelMask = QUAD;
break;
case DevFmtX51:
OutputType.Format.nChannels = 6;
OutputType.dwChannelMask = X5DOT1;
break;
case DevFmtX51Rear:
OutputType.Format.nChannels = 6;
OutputType.dwChannelMask = X5DOT1REAR;
break;
2011-05-16 04:13:37 -07:00
case DevFmtX61:
OutputType.Format.nChannels = 7;
OutputType.dwChannelMask = X6DOT1;
break;
case DevFmtX71:
OutputType.Format.nChannels = 8;
OutputType.dwChannelMask = X7DOT1;
break;
}
switch(device->FmtType)
{
case DevFmtByte:
device->FmtType = DevFmtUByte;
/* fall-through */
case DevFmtUByte:
OutputType.Format.wBitsPerSample = 8;
OutputType.Samples.wValidBitsPerSample = 8;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtUShort:
device->FmtType = DevFmtShort;
/* fall-through */
case DevFmtShort:
OutputType.Format.wBitsPerSample = 16;
OutputType.Samples.wValidBitsPerSample = 16;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtUInt:
device->FmtType = DevFmtInt;
/* fall-through */
case DevFmtInt:
OutputType.Format.wBitsPerSample = 32;
OutputType.Samples.wValidBitsPerSample = 32;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtFloat:
OutputType.Format.wBitsPerSample = 32;
OutputType.Samples.wValidBitsPerSample = 32;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
break;
}
2011-05-16 04:13:37 -07:00
OutputType.Format.nSamplesPerSec = device->Frequency;
OutputType.Format.nBlockAlign = OutputType.Format.nChannels *
OutputType.Format.wBitsPerSample / 8;
OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
OutputType.Format.nBlockAlign;
hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
if(FAILED(hr))
{
2011-07-13 01:43:00 -07:00
ERR("Failed to check format support: 0x%08lx\n", hr);
hr = mClient->GetMixFormat(&wfx);
}
if(FAILED(hr))
{
2011-07-13 01:43:00 -07:00
ERR("Failed to find a supported format: 0x%08lx\n", hr);
return hr;
}
if(wfx != nullptr)
{
if(!MakeExtensible(&OutputType, wfx))
{
CoTaskMemFree(wfx);
return E_FAIL;
}
CoTaskMemFree(wfx);
wfx = nullptr;
device->Frequency = OutputType.Format.nSamplesPerSec;
if(OutputType.Format.nChannels == 1 && OutputType.dwChannelMask == MONO)
device->FmtChans = DevFmtMono;
else if(OutputType.Format.nChannels == 2 && OutputType.dwChannelMask == STEREO)
device->FmtChans = DevFmtStereo;
else if(OutputType.Format.nChannels == 4 && OutputType.dwChannelMask == QUAD)
device->FmtChans = DevFmtQuad;
else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1)
device->FmtChans = DevFmtX51;
else if(OutputType.Format.nChannels == 6 && OutputType.dwChannelMask == X5DOT1REAR)
device->FmtChans = DevFmtX51Rear;
else if(OutputType.Format.nChannels == 7 && OutputType.dwChannelMask == X6DOT1)
device->FmtChans = DevFmtX61;
2015-01-15 09:27:37 -08:00
else if(OutputType.Format.nChannels == 8 && (OutputType.dwChannelMask == X7DOT1 || OutputType.dwChannelMask == X7DOT1_WIDE))
device->FmtChans = DevFmtX71;
else
{
ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels, OutputType.dwChannelMask);
device->FmtChans = DevFmtStereo;
OutputType.Format.nChannels = 2;
OutputType.dwChannelMask = STEREO;
}
if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
{
if(OutputType.Format.wBitsPerSample == 8)
device->FmtType = DevFmtUByte;
else if(OutputType.Format.wBitsPerSample == 16)
device->FmtType = DevFmtShort;
else if(OutputType.Format.wBitsPerSample == 32)
device->FmtType = DevFmtInt;
else
{
device->FmtType = DevFmtShort;
OutputType.Format.wBitsPerSample = 16;
}
}
else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
{
device->FmtType = DevFmtFloat;
OutputType.Format.wBitsPerSample = 32;
}
else
{
2011-07-13 01:43:00 -07:00
ERR("Unhandled format sub-type\n");
device->FmtType = DevFmtShort;
OutputType.Format.wBitsPerSample = 16;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
}
OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
}
EndpointFormFactor formfactor = UnknownFormFactor;
get_device_formfactor(mMMDev, &formfactor);
device->IsHeadphones = (device->FmtChans == DevFmtStereo &&
(formfactor == Headphones || formfactor == Headset)
);
SetDefaultWFXChannelOrder(device);
2011-05-16 04:13:37 -07:00
hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
buf_time, 0, &OutputType.Format, nullptr);
2011-05-16 04:13:37 -07:00
if(FAILED(hr))
{
2011-07-13 01:43:00 -07:00
ERR("Failed to initialize audio client: 0x%08lx\n", hr);
return hr;
2011-05-16 04:13:37 -07:00
}
UINT32 buffer_len, min_len;
REFERENCE_TIME min_per;
hr = mClient->GetDevicePeriod(&min_per, nullptr);
if(SUCCEEDED(hr))
{
2017-06-26 06:54:45 -07:00
min_len = (UINT32)ScaleCeil(min_per, device->Frequency, REFTIME_PER_SEC);
/* Find the nearest multiple of the period size to the update size */
if(min_len < device->UpdateSize)
min_len *= (device->UpdateSize + min_len/2)/min_len;
hr = mClient->GetBufferSize(&buffer_len);
}
if(FAILED(hr))
{
2011-07-13 01:43:00 -07:00
ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
return hr;
}
device->UpdateSize = min_len;
device->NumUpdates = buffer_len / device->UpdateSize;
if(device->NumUpdates <= 1)
{
ERR("Audio client returned buffer_len < period*2; expect break up\n");
device->NumUpdates = 2;
device->UpdateSize = buffer_len / device->NumUpdates;
}
hr = mClient->SetEventHandle(mNotifyEvent);
if(FAILED(hr))
{
ERR("Failed to set event handle: 0x%08lx\n", hr);
return hr;
}
return hr;
}
2018-03-09 18:56:24 -08:00
static ALCboolean ALCwasapiPlayback_start(ALCwasapiPlayback *self)
{
ThreadRequest req{ self->mMsgEvent, 0 };
2018-11-01 21:39:34 -07:00
HRESULT hr{E_FAIL};
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_StartDevice, (WPARAM)&req, (LPARAM)proxy))
hr = WaitForResponse(&req);
return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE;
}
2011-10-24 22:11:16 -07:00
HRESULT ALCwasapiPlayback::startProxy()
{
ResetEvent(mNotifyEvent);
HRESULT hr = mClient->Start();
if(FAILED(hr))
2018-11-01 21:39:34 -07:00
{
ERR("Failed to start audio client: 0x%08lx\n", hr);
2018-11-01 21:39:34 -07:00
return hr;
}
void *ptr;
hr = mClient->GetService(IID_IAudioRenderClient, &ptr);
if(SUCCEEDED(hr))
{
mRender = reinterpret_cast<IAudioRenderClient*>(ptr);
2018-11-01 21:39:34 -07:00
try {
mKillNow.store(AL_FALSE, std::memory_order_release);
mThread = std::thread(ALCwasapiPlayback_mixerProc, this);
2018-11-01 21:39:34 -07:00
}
catch(...) {
mRender->Release();
mRender = nullptr;
ERR("Failed to start thread\n");
hr = E_FAIL;
}
}
2018-11-01 21:39:34 -07:00
if(FAILED(hr))
mClient->Stop();
2018-11-01 21:39:34 -07:00
return hr;
}
2018-03-09 18:56:24 -08:00
static void ALCwasapiPlayback_stop(ALCwasapiPlayback *self)
{
ThreadRequest req{ self->mMsgEvent, 0 };
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_StopDevice, (WPARAM)&req, (LPARAM)proxy))
(void)WaitForResponse(&req);
}
void ALCwasapiPlayback::stopProxy()
{
if(!mRender || !mThread.joinable())
return;
mKillNow.store(AL_TRUE);
mThread.join();
mRender->Release();
mRender = nullptr;
mClient->Stop();
}
2018-03-09 18:56:24 -08:00
static ClockLatency ALCwasapiPlayback_getClockLatency(ALCwasapiPlayback *self)
{
ClockLatency ret;
2018-03-09 18:56:24 -08:00
ALCwasapiPlayback_lock(self);
ALCdevice *device{STATIC_CAST(ALCbackend, self)->mDevice};
ret.ClockTime = GetDeviceClockTime(device);
ret.Latency = self->mPadding.load(std::memory_order_relaxed) * DEVICE_CLOCK_RES /
device->Frequency;
2018-03-09 18:56:24 -08:00
ALCwasapiPlayback_unlock(self);
return ret;
}
struct ALCwasapiCapture final : public ALCbackend, WasapiProxy {
HRESULT openProxy() override;
void closeProxy() override;
2014-12-19 15:49:37 -08:00
HRESULT resetProxy() override;
HRESULT startProxy() override;
void stopProxy() override;
std::wstring mDevId;
2014-12-19 15:49:37 -08:00
IMMDevice *mMMDev{nullptr};
IAudioClient *mClient{nullptr};
IAudioCaptureClient *mCapture{nullptr};
HANDLE mNotifyEvent{nullptr};
2014-12-19 15:49:37 -08:00
HANDLE mMsgEvent{nullptr};
2014-12-19 15:49:37 -08:00
ChannelConverter *mChannelConv{nullptr};
SampleConverter *mSampleConv{nullptr};
ll_ringbuffer_t *mRing{nullptr};
2014-12-19 15:49:37 -08:00
std::atomic<int> mKillNow{AL_TRUE};
std::thread mThread;
};
2018-03-09 18:56:24 -08:00
2018-11-01 21:39:34 -07:00
static int ALCwasapiCapture_recordProc(ALCwasapiCapture *self);
2018-03-09 18:56:24 -08:00
static void ALCwasapiCapture_Construct(ALCwasapiCapture *self, ALCdevice *device);
static void ALCwasapiCapture_Destruct(ALCwasapiCapture *self);
static ALCenum ALCwasapiCapture_open(ALCwasapiCapture *self, const ALCchar *name);
static DECLARE_FORWARD(ALCwasapiCapture, ALCbackend, ALCboolean, reset)
static ALCboolean ALCwasapiCapture_start(ALCwasapiCapture *self);
static void ALCwasapiCapture_stop(ALCwasapiCapture *self);
static ALCenum ALCwasapiCapture_captureSamples(ALCwasapiCapture *self, ALCvoid *buffer, ALCuint samples);
static ALuint ALCwasapiCapture_availableSamples(ALCwasapiCapture *self);
static DECLARE_FORWARD(ALCwasapiCapture, ALCbackend, ClockLatency, getClockLatency)
static DECLARE_FORWARD(ALCwasapiCapture, ALCbackend, void, lock)
static DECLARE_FORWARD(ALCwasapiCapture, ALCbackend, void, unlock)
DECLARE_DEFAULT_ALLOCATORS(ALCwasapiCapture)
DEFINE_ALCBACKEND_VTABLE(ALCwasapiCapture);
static void ALCwasapiCapture_Construct(ALCwasapiCapture *self, ALCdevice *device)
2014-12-19 15:49:37 -08:00
{
2018-11-01 21:39:34 -07:00
new (self) ALCwasapiCapture{};
2018-03-09 18:56:24 -08:00
SET_VTABLE2(ALCwasapiCapture, ALCbackend, self);
2014-12-19 15:49:37 -08:00
ALCbackend_Construct(STATIC_CAST(ALCbackend, self), device);
}
2018-03-09 18:56:24 -08:00
static void ALCwasapiCapture_Destruct(ALCwasapiCapture *self)
2014-12-19 15:49:37 -08:00
{
if(self->mMsgEvent)
{
ThreadRequest req{ self->mMsgEvent, 0 };
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_CloseDevice, (WPARAM)&req, (LPARAM)proxy))
(void)WaitForResponse(&req);
CloseHandle(self->mMsgEvent);
self->mMsgEvent = nullptr;
}
if(self->mNotifyEvent != nullptr)
CloseHandle(self->mNotifyEvent);
self->mNotifyEvent = nullptr;
ll_ringbuffer_free(self->mRing);
self->mRing = nullptr;
2014-12-19 15:49:37 -08:00
DestroySampleConverter(&self->mSampleConv);
DestroyChannelConverter(&self->mChannelConv);
2014-12-19 15:49:37 -08:00
ALCbackend_Destruct(STATIC_CAST(ALCbackend, self));
2018-11-01 21:39:34 -07:00
self->~ALCwasapiCapture();
2014-12-19 15:49:37 -08:00
}
2018-11-01 21:39:34 -07:00
FORCE_ALIGN int ALCwasapiCapture_recordProc(ALCwasapiCapture *self)
2014-12-19 15:49:37 -08:00
{
2018-11-01 21:39:34 -07:00
ALCdevice *device{STATIC_CAST(ALCbackend, self)->mDevice};
IAudioCaptureClient *capture{self->mCapture};
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
HRESULT hr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
{
ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr);
2014-12-19 15:49:37 -08:00
V0(device->Backend,lock)();
aluHandleDisconnect(device, "COM init failed: 0x%08lx", hr);
2014-12-19 15:49:37 -08:00
V0(device->Backend,unlock)();
return 1;
}
2014-12-21 10:38:40 -08:00
althrd_setname(althrd_current(), RECORD_THREAD_NAME);
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
std::vector<float> samples;
while(!self->mKillNow.load(std::memory_order_relaxed))
2014-12-19 15:49:37 -08:00
{
UINT32 avail;
DWORD res;
hr = capture->GetNextPacketSize(&avail);
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
ERR("Failed to get next packet size: 0x%08lx\n", hr);
else if(avail > 0)
2014-12-19 15:49:37 -08:00
{
2015-01-11 15:02:26 -08:00
UINT32 numsamples;
DWORD flags;
BYTE *rdata;
2014-12-19 15:49:37 -08:00
hr = capture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
ERR("Failed to get capture buffer: 0x%08lx\n", hr);
else
{
if(self->mChannelConv)
{
2018-11-01 21:39:34 -07:00
samples.resize(numsamples*2);
ChannelConverterInput(self->mChannelConv, rdata, samples.data(), numsamples);
2018-11-01 21:39:34 -07:00
rdata = reinterpret_cast<BYTE*>(samples.data());
}
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
ll_ringbuffer_data_t data[2];
ll_ringbuffer_get_write_vector(self->mRing, data);
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
size_t dstframes;
if(self->mSampleConv)
{
const ALvoid *srcdata = rdata;
ALsizei srcframes = numsamples;
dstframes = SampleConverterInput(self->mSampleConv,
2018-01-16 09:40:34 -08:00
&srcdata, &srcframes, data[0].buf, (ALsizei)minz(data[0].len, INT_MAX)
);
if(srcframes > 0 && dstframes == data[0].len && data[1].len > 0)
{
/* If some source samples remain, all of the first dest
* block was filled, and there's space in the second
* dest block, do another run for the second block.
*/
dstframes += SampleConverterInput(self->mSampleConv,
2018-01-16 09:40:34 -08:00
&srcdata, &srcframes, data[1].buf, (ALsizei)minz(data[1].len, INT_MAX)
);
}
}
else
{
2018-01-16 09:40:34 -08:00
ALuint framesize = FrameSizeFromDevFmt(device->FmtChans, device->FmtType,
device->AmbiOrder);
2018-01-16 09:40:34 -08:00
size_t len1 = minz(data[0].len, numsamples);
size_t len2 = minz(data[1].len, numsamples-len1);
memcpy(data[0].buf, rdata, len1*framesize);
if(len2 > 0)
memcpy(data[1].buf, rdata+len1*framesize, len2*framesize);
dstframes = len1 + len2;
}
ll_ringbuffer_write_advance(self->mRing, dstframes);
hr = capture->ReleaseBuffer(numsamples);
if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
}
2014-12-19 15:49:37 -08:00
}
if(FAILED(hr))
{
V0(device->Backend,lock)();
aluHandleDisconnect(device, "Failed to capture samples: 0x%08lx", hr);
2014-12-19 15:49:37 -08:00
V0(device->Backend,unlock)();
break;
}
res = WaitForSingleObjectEx(self->mNotifyEvent, 2000, FALSE);
2014-12-19 15:49:37 -08:00
if(res != WAIT_OBJECT_0)
ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
}
CoUninitialize();
return 0;
}
2018-03-09 18:56:24 -08:00
static ALCenum ALCwasapiCapture_open(ALCwasapiCapture *self, const ALCchar *deviceName)
2014-12-19 15:49:37 -08:00
{
2018-11-01 21:39:34 -07:00
HRESULT hr{S_OK};
2014-12-19 15:49:37 -08:00
self->mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
self->mMsgEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if(self->mNotifyEvent == nullptr || self->mMsgEvent == nullptr)
2014-12-19 15:49:37 -08:00
{
ERR("Failed to create message events: %lu\n", GetLastError());
hr = E_FAIL;
}
if(SUCCEEDED(hr))
{
if(deviceName)
{
2018-11-01 21:39:34 -07:00
if(CaptureDevices.empty())
2014-12-19 15:49:37 -08:00
{
ThreadRequest req{ self->mMsgEvent, 0 };
2014-12-19 15:49:37 -08:00
if(PostThreadMessage(ThreadID, WM_USER_Enumerate, (WPARAM)&req, CAPTURE_DEVICE_PROBE))
(void)WaitForResponse(&req);
}
hr = E_FAIL;
2018-11-01 21:39:34 -07:00
auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
[deviceName](const DevMap &entry) -> bool
{ return entry.name == deviceName || entry.endpoint_guid == deviceName; }
);
if(iter == CaptureDevices.cend())
{
int len;
if((len=MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, nullptr, 0)) > 0)
{
std::vector<WCHAR> wname(len);
MultiByteToWideChar(CP_UTF8, 0, deviceName, -1, wname.data(), len);
2018-11-01 21:39:34 -07:00
iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
[&wname](const DevMap &entry) -> bool
{ return entry.devid == wname.data(); }
);
}
}
2018-11-01 21:39:34 -07:00
if(iter == CaptureDevices.cend())
2014-12-19 15:49:37 -08:00
WARN("Failed to find device name matching \"%s\"\n", deviceName);
else
{
ALCdevice *device = STATIC_CAST(ALCbackend,self)->mDevice;
self->mDevId = iter->devid;
2018-11-01 21:39:34 -07:00
alstr_copy_range(&device->DeviceName, &*iter->name.cbegin(), &*iter->name.cend());
2014-12-19 15:49:37 -08:00
hr = S_OK;
}
}
}
if(SUCCEEDED(hr))
{
ThreadRequest req{ self->mMsgEvent, 0 };
2014-12-19 15:49:37 -08:00
hr = E_FAIL;
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_OpenDevice, (WPARAM)&req, (LPARAM)proxy))
2014-12-19 15:49:37 -08:00
hr = WaitForResponse(&req);
else
ERR("Failed to post thread message: %lu\n", GetLastError());
}
if(FAILED(hr))
{
if(self->mNotifyEvent != nullptr)
CloseHandle(self->mNotifyEvent);
self->mNotifyEvent = nullptr;
if(self->mMsgEvent != nullptr)
CloseHandle(self->mMsgEvent);
self->mMsgEvent = nullptr;
2014-12-19 15:49:37 -08:00
self->mDevId.clear();
2014-12-19 15:49:37 -08:00
ERR("Device init failed: 0x%08lx\n", hr);
return ALC_INVALID_VALUE;
}
else
{
ThreadRequest req{ self->mMsgEvent, 0 };
2014-12-19 15:49:37 -08:00
hr = E_FAIL;
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_ResetDevice, (WPARAM)&req, (LPARAM)proxy))
2014-12-19 15:49:37 -08:00
hr = WaitForResponse(&req);
else
ERR("Failed to post thread message: %lu\n", GetLastError());
if(FAILED(hr))
{
if(hr == E_OUTOFMEMORY)
return ALC_OUT_OF_MEMORY;
return ALC_INVALID_VALUE;
}
}
return ALC_NO_ERROR;
}
HRESULT ALCwasapiCapture::openProxy()
2014-12-19 15:49:37 -08:00
{
ALCdevice *device{STATIC_CAST(ALCbackend, this)->mDevice};
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
void *ptr;
HRESULT hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
IID_IMMDeviceEnumerator, &ptr);
2014-12-19 15:49:37 -08:00
if(SUCCEEDED(hr))
{
auto Enumerator = reinterpret_cast<IMMDeviceEnumerator*>(ptr);
if(mDevId.empty())
hr = Enumerator->GetDefaultAudioEndpoint(eCapture, eMultimedia, &mMMDev);
2014-12-19 15:49:37 -08:00
else
hr = Enumerator->GetDevice(mDevId.c_str(), &mMMDev);
Enumerator->Release();
2014-12-19 15:49:37 -08:00
}
if(SUCCEEDED(hr))
hr = mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr);
2014-12-19 15:49:37 -08:00
if(SUCCEEDED(hr))
{
mClient = reinterpret_cast<IAudioClient*>(ptr);
if(alstr_empty(device->DeviceName))
2018-11-01 21:39:34 -07:00
{
std::string devname;
std::tie(devname, std::ignore) = get_device_name_and_guid(mMMDev);
2018-11-01 21:39:34 -07:00
alstr_copy_range(&device->DeviceName, &*devname.cbegin(), &*devname.cend());
}
2014-12-19 15:49:37 -08:00
}
if(FAILED(hr))
{
if(mMMDev)
mMMDev->Release();
mMMDev = nullptr;
2014-12-19 15:49:37 -08:00
}
return hr;
}
void ALCwasapiCapture::closeProxy()
2014-12-19 15:49:37 -08:00
{
if(mClient)
mClient->Release();
mClient = nullptr;
2014-12-19 15:49:37 -08:00
if(mMMDev)
mMMDev->Release();
mMMDev = nullptr;
2014-12-19 15:49:37 -08:00
}
HRESULT ALCwasapiCapture::resetProxy()
2014-12-19 15:49:37 -08:00
{
ALCdevice *device{STATIC_CAST(ALCbackend, this)->mDevice};
2014-12-19 15:49:37 -08:00
if(mClient)
mClient->Release();
mClient = nullptr;
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
void *ptr;
HRESULT hr{mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr)};
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
{
ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
return hr;
}
mClient = reinterpret_cast<IAudioClient*>(ptr);
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
REFERENCE_TIME buf_time{ScaleCeil(device->UpdateSize*device->NumUpdates, REFTIME_PER_SEC,
device->Frequency)};
// Make sure buffer is at least 100ms in size
2017-06-26 06:54:45 -07:00
buf_time = maxu64(buf_time, REFTIME_PER_SEC/10);
2017-06-29 10:25:33 -07:00
device->UpdateSize = (ALuint)ScaleCeil(buf_time, device->Frequency, REFTIME_PER_SEC) /
device->NumUpdates;
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
WAVEFORMATEXTENSIBLE OutputType;
2014-12-19 15:49:37 -08:00
OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
switch(device->FmtChans)
{
case DevFmtMono:
OutputType.Format.nChannels = 1;
OutputType.dwChannelMask = MONO;
break;
case DevFmtStereo:
OutputType.Format.nChannels = 2;
OutputType.dwChannelMask = STEREO;
break;
case DevFmtQuad:
OutputType.Format.nChannels = 4;
OutputType.dwChannelMask = QUAD;
break;
case DevFmtX51:
OutputType.Format.nChannels = 6;
OutputType.dwChannelMask = X5DOT1;
break;
case DevFmtX51Rear:
OutputType.Format.nChannels = 6;
OutputType.dwChannelMask = X5DOT1REAR;
break;
case DevFmtX61:
OutputType.Format.nChannels = 7;
OutputType.dwChannelMask = X6DOT1;
break;
case DevFmtX71:
OutputType.Format.nChannels = 8;
OutputType.dwChannelMask = X7DOT1;
break;
case DevFmtAmbi3D:
2014-12-19 15:49:37 -08:00
return E_FAIL;
}
switch(device->FmtType)
{
/* NOTE: Signedness doesn't matter, the converter will handle it. */
case DevFmtByte:
2014-12-19 15:49:37 -08:00
case DevFmtUByte:
OutputType.Format.wBitsPerSample = 8;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtShort:
case DevFmtUShort:
2014-12-19 15:49:37 -08:00
OutputType.Format.wBitsPerSample = 16;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtInt:
case DevFmtUInt:
2014-12-19 15:49:37 -08:00
OutputType.Format.wBitsPerSample = 32;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
break;
case DevFmtFloat:
OutputType.Format.wBitsPerSample = 32;
OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
break;
}
OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
2014-12-19 15:49:37 -08:00
OutputType.Format.nSamplesPerSec = device->Frequency;
OutputType.Format.nBlockAlign = OutputType.Format.nChannels *
OutputType.Format.wBitsPerSample / 8;
OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
OutputType.Format.nBlockAlign;
OutputType.Format.cbSize = sizeof(OutputType) - sizeof(OutputType.Format);
2014-12-19 15:49:37 -08:00
2018-11-01 21:39:34 -07:00
WAVEFORMATEX *wfx;
hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
{
ERR("Failed to check format support: 0x%08lx\n", hr);
return hr;
}
DestroySampleConverter(&mSampleConv);
DestroyChannelConverter(&mChannelConv);
if(wfx != nullptr)
{
if(!(wfx->nChannels == OutputType.Format.nChannels ||
(wfx->nChannels == 1 && OutputType.Format.nChannels == 2) ||
(wfx->nChannels == 2 && OutputType.Format.nChannels == 1)))
{
ERR("Failed to get matching format, wanted: %s %s %uhz, got: %d channel%s %d-bit %luhz\n",
DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
device->Frequency, wfx->nChannels, (wfx->nChannels==1)?"":"s", wfx->wBitsPerSample,
wfx->nSamplesPerSec);
CoTaskMemFree(wfx);
return E_FAIL;
}
if(!MakeExtensible(&OutputType, wfx))
{
CoTaskMemFree(wfx);
return E_FAIL;
}
CoTaskMemFree(wfx);
wfx = nullptr;
}
2018-11-01 21:39:34 -07:00
enum DevFmtType srcType;
if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
{
if(OutputType.Format.wBitsPerSample == 8)
srcType = DevFmtUByte;
else if(OutputType.Format.wBitsPerSample == 16)
srcType = DevFmtShort;
else if(OutputType.Format.wBitsPerSample == 32)
srcType = DevFmtInt;
else
{
ERR("Unhandled integer bit depth: %d\n", OutputType.Format.wBitsPerSample);
return E_FAIL;
}
}
else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
{
if(OutputType.Format.wBitsPerSample == 32)
srcType = DevFmtFloat;
else
{
ERR("Unhandled float bit depth: %d\n", OutputType.Format.wBitsPerSample);
return E_FAIL;
}
}
else
{
ERR("Unhandled format sub-type\n");
return E_FAIL;
}
if(device->FmtChans == DevFmtMono && OutputType.Format.nChannels == 2)
{
mChannelConv = CreateChannelConverter(srcType, DevFmtStereo, device->FmtChans);
if(!mChannelConv)
{
ERR("Failed to create %s stereo-to-mono converter\n", DevFmtTypeString(srcType));
return E_FAIL;
}
TRACE("Created %s stereo-to-mono converter\n", DevFmtTypeString(srcType));
/* The channel converter always outputs float, so change the input type
* for the resampler/type-converter.
*/
srcType = DevFmtFloat;
}
else if(device->FmtChans == DevFmtStereo && OutputType.Format.nChannels == 1)
{
mChannelConv = CreateChannelConverter(srcType, DevFmtMono, device->FmtChans);
if(!mChannelConv)
{
ERR("Failed to create %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
return E_FAIL;
}
TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
srcType = DevFmtFloat;
}
if(device->Frequency != OutputType.Format.nSamplesPerSec || device->FmtType != srcType)
{
mSampleConv = CreateSampleConverter(
srcType, device->FmtType, ChannelsFromDevFmt(device->FmtChans, device->AmbiOrder),
OutputType.Format.nSamplesPerSec, device->Frequency
);
if(!mSampleConv)
{
ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
device->Frequency, DevFmtTypeString(srcType), OutputType.Format.nSamplesPerSec);
return E_FAIL;
}
TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
device->Frequency, DevFmtTypeString(srcType), OutputType.Format.nSamplesPerSec);
}
hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
buf_time, 0, &OutputType.Format, nullptr);
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
{
ERR("Failed to initialize audio client: 0x%08lx\n", hr);
return hr;
}
2018-11-01 21:39:34 -07:00
UINT32 buffer_len;
hr = mClient->GetBufferSize(&buffer_len);
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
{
ERR("Failed to get buffer size: 0x%08lx\n", hr);
return hr;
}
buffer_len = maxu(device->UpdateSize*device->NumUpdates, buffer_len);
ll_ringbuffer_free(mRing);
mRing = ll_ringbuffer_create(buffer_len,
FrameSizeFromDevFmt(device->FmtChans, device->FmtType, device->AmbiOrder),
false
);
if(!mRing)
2014-12-19 15:49:37 -08:00
{
ERR("Failed to allocate capture ring buffer\n");
return E_OUTOFMEMORY;
}
hr = mClient->SetEventHandle(mNotifyEvent);
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
{
ERR("Failed to set event handle: 0x%08lx\n", hr);
return hr;
}
return hr;
}
2018-03-09 18:56:24 -08:00
static ALCboolean ALCwasapiCapture_start(ALCwasapiCapture *self)
2014-12-19 15:49:37 -08:00
{
ThreadRequest req{ self->mMsgEvent, 0 };
2018-11-01 21:39:34 -07:00
HRESULT hr{E_FAIL};
2014-12-19 15:49:37 -08:00
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_StartDevice, (WPARAM)&req, (LPARAM)proxy))
2014-12-19 15:49:37 -08:00
hr = WaitForResponse(&req);
return SUCCEEDED(hr) ? ALC_TRUE : ALC_FALSE;
}
HRESULT ALCwasapiCapture::startProxy()
2014-12-19 15:49:37 -08:00
{
ResetEvent(mNotifyEvent);
2018-11-01 21:39:34 -07:00
HRESULT hr{mClient->Start()};
2014-12-19 15:49:37 -08:00
if(FAILED(hr))
{
ERR("Failed to start audio client: 0x%08lx\n", hr);
return hr;
}
2018-11-01 21:39:34 -07:00
void *ptr;
hr = mClient->GetService(IID_IAudioCaptureClient, &ptr);
2014-12-19 15:49:37 -08:00
if(SUCCEEDED(hr))
{
mCapture = reinterpret_cast<IAudioCaptureClient*>(ptr);
2018-11-01 21:39:34 -07:00
try {
mKillNow.store(AL_FALSE, std::memory_order_release);
mThread = std::thread(ALCwasapiCapture_recordProc, this);
2018-11-01 21:39:34 -07:00
}
catch(...) {
mCapture->Release();
mCapture = nullptr;
2018-11-01 21:39:34 -07:00
ERR("Failed to start thread\n");
2014-12-19 15:49:37 -08:00
hr = E_FAIL;
}
}
if(FAILED(hr))
{
mClient->Stop();
mClient->Reset();
2014-12-19 15:49:37 -08:00
}
return hr;
}
2018-03-09 18:56:24 -08:00
static void ALCwasapiCapture_stop(ALCwasapiCapture *self)
2014-12-19 15:49:37 -08:00
{
ThreadRequest req{ self->mMsgEvent, 0 };
auto proxy = static_cast<WasapiProxy*>(self);
if(PostThreadMessage(ThreadID, WM_USER_StopDevice, (WPARAM)&req, (LPARAM)proxy))
2014-12-19 15:49:37 -08:00
(void)WaitForResponse(&req);
}
void ALCwasapiCapture::stopProxy()
2014-12-19 15:49:37 -08:00
{
if(!mCapture || !mThread.joinable())
2014-12-19 15:49:37 -08:00
return;
mKillNow.store(AL_TRUE);
mThread.join();
2014-12-19 15:49:37 -08:00
mCapture->Release();
mCapture = nullptr;
mClient->Stop();
mClient->Reset();
2014-12-19 15:49:37 -08:00
}
2018-11-01 21:39:34 -07:00
static ALuint ALCwasapiCapture_availableSamples(ALCwasapiCapture *self)
2014-12-19 15:49:37 -08:00
{
return (ALuint)ll_ringbuffer_read_space(self->mRing);
2014-12-19 15:49:37 -08:00
}
2018-11-01 21:39:34 -07:00
static ALCenum ALCwasapiCapture_captureSamples(ALCwasapiCapture *self, ALCvoid *buffer, ALCuint samples)
2014-12-19 15:49:37 -08:00
{
2018-03-09 18:56:24 -08:00
if(ALCwasapiCapture_availableSamples(self) < samples)
2014-12-19 15:49:37 -08:00
return ALC_INVALID_VALUE;
ll_ringbuffer_read(self->mRing, reinterpret_cast<char*>(buffer), samples);
2014-12-19 15:49:37 -08:00
return ALC_NO_ERROR;
}
struct ALCwasapiBackendFactory final : public ALCbackendFactory {
ALCwasapiBackendFactory() noexcept;
};
#define ALCWASAPIBACKENDFACTORY_INITIALIZER GET_VTABLE2(ALCwasapiBackendFactory, ALCbackendFactory)
2018-03-09 18:56:24 -08:00
static ALCboolean ALCwasapiBackendFactory_init(ALCwasapiBackendFactory *self);
static void ALCwasapiBackendFactory_deinit(ALCwasapiBackendFactory *self);
static ALCboolean ALCwasapiBackendFactory_querySupport(ALCwasapiBackendFactory *self, ALCbackend_Type type);
static void ALCwasapiBackendFactory_probe(ALCwasapiBackendFactory *self, enum DevProbe type, al_string *outnames);
2018-03-09 18:56:24 -08:00
static ALCbackend* ALCwasapiBackendFactory_createBackend(ALCwasapiBackendFactory *self, ALCdevice *device, ALCbackend_Type type);
2018-03-09 18:56:24 -08:00
DEFINE_ALCBACKENDFACTORY_VTABLE(ALCwasapiBackendFactory);
ALCwasapiBackendFactory::ALCwasapiBackendFactory() noexcept
: ALCbackendFactory{ALCWASAPIBACKENDFACTORY_INITIALIZER}
{
}
2018-03-09 18:56:24 -08:00
static ALCboolean ALCwasapiBackendFactory_init(ALCwasapiBackendFactory* UNUSED(self))
{
static HRESULT InitResult;
2018-03-09 18:56:24 -08:00
if(!ThreadHdl)
{
ThreadRequest req;
InitResult = E_FAIL;
req.FinishedEvt = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if(req.FinishedEvt == nullptr)
ERR("Failed to create event: %lu\n", GetLastError());
else
{
ThreadHdl = CreateThread(nullptr, 0, WasapiProxy_messageHandler, &req, 0, &ThreadID);
if(ThreadHdl != nullptr)
InitResult = WaitForResponse(&req);
CloseHandle(req.FinishedEvt);
}
}
2018-03-09 18:56:24 -08:00
return SUCCEEDED(InitResult) ? ALC_TRUE : ALC_FALSE;
2011-05-15 20:26:25 -07:00
}
2018-03-09 18:56:24 -08:00
static void ALCwasapiBackendFactory_deinit(ALCwasapiBackendFactory* UNUSED(self))
2011-05-15 20:26:25 -07:00
{
2018-11-01 21:39:34 -07:00
PlaybackDevices.clear();
CaptureDevices.clear();
if(ThreadHdl)
2011-05-15 20:26:25 -07:00
{
TRACE("Sending WM_QUIT to Thread %04lx\n", ThreadID);
PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
CloseHandle(ThreadHdl);
ThreadHdl = nullptr;
2011-05-15 20:26:25 -07:00
}
}
2018-03-09 18:56:24 -08:00
static ALCboolean ALCwasapiBackendFactory_querySupport(ALCwasapiBackendFactory* UNUSED(self), ALCbackend_Type type)
{
if(type == ALCbackend_Playback || type == ALCbackend_Capture)
return ALC_TRUE;
return ALC_FALSE;
}
static void ALCwasapiBackendFactory_probe(ALCwasapiBackendFactory* UNUSED(self), enum DevProbe type, al_string *outnames)
2011-05-15 20:26:25 -07:00
{
2018-11-01 21:39:34 -07:00
ThreadRequest req{ nullptr, 0 };
req.FinishedEvt = CreateEventW(nullptr, FALSE, FALSE, nullptr);
if(req.FinishedEvt == nullptr)
2014-04-24 04:02:05 -07:00
ERR("Failed to create event: %lu\n", GetLastError());
else
2011-06-14 04:02:58 -07:00
{
2018-11-01 21:39:34 -07:00
auto add_device = [outnames](const DevMap &entry) -> void
{
const char *name{entry.name.c_str()};
size_t namelen{entry.name.length()};
/* +1 to also append the null char (to ensure a null-separated list
* and double-null terminated list).
*/
alstr_append_range(outnames, name, name + namelen+1);
};
2014-04-30 12:30:02 -07:00
HRESULT hr = E_FAIL;
2014-04-24 04:02:05 -07:00
if(PostThreadMessage(ThreadID, WM_USER_Enumerate, (WPARAM)&req, type))
hr = WaitForResponse(&req);
if(SUCCEEDED(hr)) switch(type)
{
2011-06-14 04:02:58 -07:00
case ALL_DEVICE_PROBE:
2018-11-01 21:39:34 -07:00
std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
2011-06-14 04:02:58 -07:00
break;
2011-06-14 04:02:58 -07:00
case CAPTURE_DEVICE_PROBE:
2018-11-01 21:39:34 -07:00
std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
2011-06-14 04:02:58 -07:00
break;
2014-04-24 04:02:05 -07:00
}
2012-02-18 13:08:54 -08:00
CloseHandle(req.FinishedEvt);
req.FinishedEvt = nullptr;
2014-04-24 04:02:05 -07:00
}
2011-05-15 20:26:25 -07:00
}
2018-03-09 18:56:24 -08:00
static ALCbackend* ALCwasapiBackendFactory_createBackend(ALCwasapiBackendFactory* UNUSED(self), ALCdevice *device, ALCbackend_Type type)
{
if(type == ALCbackend_Playback)
{
2018-03-09 18:56:24 -08:00
ALCwasapiPlayback *backend;
NEW_OBJ(backend, ALCwasapiPlayback)(device);
if(!backend) return nullptr;
return STATIC_CAST(ALCbackend, backend);
}
2014-12-19 15:49:37 -08:00
if(type == ALCbackend_Capture)
{
2018-03-09 18:56:24 -08:00
ALCwasapiCapture *backend;
NEW_OBJ(backend, ALCwasapiCapture)(device);
if(!backend) return nullptr;
2014-12-19 15:49:37 -08:00
return STATIC_CAST(ALCbackend, backend);
}
return nullptr;
}
2018-03-09 18:56:24 -08:00
ALCbackendFactory *ALCwasapiBackendFactory_getFactory(void)
{
static ALCwasapiBackendFactory factory{};
return STATIC_CAST(ALCbackendFactory, &factory);
}