Fix some Clazy warnings
[openal-soft.git] / alc / backends / wasapi.cpp
blob841dc8a3c202a5c89729602b882f21fbfc3c58f2
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 2011 by authors.
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Library General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Library General Public License for more details.
14 * You should have received a copy of the GNU Library General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 * Or go to http://www.gnu.org/copyleft/lgpl.html
21 #include "config.h"
23 #include "wasapi.h"
25 #define WIN32_LEAN_AND_MEAN
26 #include <windows.h>
28 #include <cstdio>
29 #include <cstdlib>
30 #include <memory.h>
32 #include <avrt.h>
33 #include <wtypes.h>
34 #include <mmdeviceapi.h>
35 #include <audiosessiontypes.h>
36 #include <audioclient.h>
37 #include <spatialaudioclient.h>
38 #include <cguid.h>
39 #include <devpropdef.h>
40 #include <mmreg.h>
41 #include <propsys.h>
42 #include <propkey.h>
43 #include <devpkey.h>
44 #ifndef _WAVEFORMATEXTENSIBLE_
45 #include <ks.h>
46 #include <ksmedia.h>
47 #endif
49 #include <algorithm>
50 #include <atomic>
51 #include <chrono>
52 #include <condition_variable>
53 #include <cstring>
54 #include <deque>
55 #include <functional>
56 #include <future>
57 #include <mutex>
58 #include <string>
59 #include <string_view>
60 #include <thread>
61 #include <vector>
63 #include "albit.h"
64 #include "alc/alconfig.h"
65 #include "alnumeric.h"
66 #include "alspan.h"
67 #include "alstring.h"
68 #include "althrd_setname.h"
69 #include "comptr.h"
70 #include "core/converter.h"
71 #include "core/device.h"
72 #include "core/helpers.h"
73 #include "core/logging.h"
74 #include "ringbuffer.h"
75 #include "strutils.h"
77 #if defined(ALSOFT_UWP)
79 #include <winrt/Windows.Media.Core.h> // !!This is important!!
80 #include <winrt/Windows.Foundation.Collections.h>
81 #include <winrt/Windows.Devices.h>
82 #include <winrt/Windows.Foundation.h>
83 #include <winrt/Windows.Devices.Enumeration.h>
84 #include <winrt/Windows.Media.Devices.h>
86 using namespace winrt;
87 using namespace Windows::Foundation;
88 using namespace Windows::Media::Devices;
89 using namespace Windows::Devices::Enumeration;
90 using namespace Windows::Media::Devices;
91 #endif
93 /* Some headers seem to define these as macros for __uuidof, which is annoying
94 * since some headers don't declare them at all. Hopefully the ifdef is enough
95 * to tell if they need to be declared.
97 #ifndef KSDATAFORMAT_SUBTYPE_PCM
98 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
99 #endif
100 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
101 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
102 #endif
103 #if !defined(ALSOFT_UWP)
104 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
105 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
106 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
107 #endif
109 namespace {
111 using namespace std::string_view_literals;
112 using std::chrono::nanoseconds;
113 using std::chrono::milliseconds;
114 using std::chrono::seconds;
116 using ReferenceTime = std::chrono::duration<REFERENCE_TIME,std::ratio<1,10'000'000>>;
119 #define MONO SPEAKER_FRONT_CENTER
120 #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
121 #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
122 #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
123 #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
124 #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
125 #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)
126 #define X7DOT1DOT4 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT|SPEAKER_TOP_FRONT_LEFT|SPEAKER_TOP_FRONT_RIGHT|SPEAKER_TOP_BACK_LEFT|SPEAKER_TOP_BACK_RIGHT)
128 constexpr inline DWORD MaskFromTopBits(DWORD b) noexcept
130 b |= b>>1;
131 b |= b>>2;
132 b |= b>>4;
133 b |= b>>8;
134 b |= b>>16;
135 return b;
137 constexpr DWORD MonoMask{MaskFromTopBits(MONO)};
138 constexpr DWORD StereoMask{MaskFromTopBits(STEREO)};
139 constexpr DWORD QuadMask{MaskFromTopBits(QUAD)};
140 constexpr DWORD X51Mask{MaskFromTopBits(X5DOT1)};
141 constexpr DWORD X51RearMask{MaskFromTopBits(X5DOT1REAR)};
142 constexpr DWORD X61Mask{MaskFromTopBits(X6DOT1)};
143 constexpr DWORD X71Mask{MaskFromTopBits(X7DOT1)};
144 constexpr DWORD X714Mask{MaskFromTopBits(X7DOT1DOT4)};
147 #ifndef _MSC_VER
148 constexpr AudioObjectType operator|(AudioObjectType lhs, AudioObjectType rhs) noexcept
149 { return static_cast<AudioObjectType>(lhs | al::to_underlying(rhs)); }
150 #endif
152 constexpr AudioObjectType ChannelMask_Mono{AudioObjectType_FrontCenter};
153 constexpr AudioObjectType ChannelMask_Stereo{AudioObjectType_FrontLeft
154 | AudioObjectType_FrontRight};
155 constexpr AudioObjectType ChannelMask_Quad{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
156 | AudioObjectType_BackLeft | AudioObjectType_BackRight};
157 constexpr AudioObjectType ChannelMask_X51{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
158 | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
159 | AudioObjectType_SideRight};
160 constexpr AudioObjectType ChannelMask_X61{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
161 | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
162 | AudioObjectType_SideRight | AudioObjectType_BackCenter};
163 constexpr AudioObjectType ChannelMask_X71{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
164 | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
165 | AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight};
166 constexpr AudioObjectType ChannelMask_X714{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
167 | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
168 | AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight
169 | AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft
170 | AudioObjectType_TopBackRight};
171 constexpr AudioObjectType ChannelMask_X7144{AudioObjectType_FrontLeft | AudioObjectType_FrontRight
172 | AudioObjectType_FrontCenter | AudioObjectType_LowFrequency | AudioObjectType_SideLeft
173 | AudioObjectType_SideRight | AudioObjectType_BackLeft | AudioObjectType_BackRight
174 | AudioObjectType_TopFrontLeft | AudioObjectType_TopFrontRight | AudioObjectType_TopBackLeft
175 | AudioObjectType_TopBackRight | AudioObjectType_BottomFrontLeft
176 | AudioObjectType_BottomFrontRight | AudioObjectType_BottomBackLeft
177 | AudioObjectType_BottomBackRight};
180 template<typename... Ts>
181 struct overloaded : Ts... { using Ts::operator()...; };
183 template<typename... Ts>
184 overloaded(Ts...) -> overloaded<Ts...>;
187 template<typename T>
188 constexpr auto as_unsigned(T value) noexcept
190 using UT = std::make_unsigned_t<T>;
191 return static_cast<UT>(value);
195 /* Scales the given reftime value, rounding the result. */
196 template<typename T>
197 constexpr uint RefTime2Samples(const ReferenceTime &val, T srate) noexcept
199 const auto retval = (val*srate + ReferenceTime{seconds{1}}/2) / seconds{1};
200 return static_cast<uint>(std::min<decltype(retval)>(retval, std::numeric_limits<uint>::max()));
204 class GuidPrinter {
205 std::array<char,64> mMsg{};
207 public:
208 GuidPrinter(const GUID &guid)
210 std::snprintf(mMsg.data(), mMsg.size(), "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
211 DWORD{guid.Data1}, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2],
212 guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]);
214 [[nodiscard]] auto c_str() const -> const char* { return mMsg.data(); }
217 struct PropVariant {
218 PROPVARIANT mProp{};
220 public:
221 PropVariant() { PropVariantInit(&mProp); }
222 PropVariant(const PropVariant &rhs) : PropVariant{} { PropVariantCopy(&mProp, &rhs.mProp); }
223 ~PropVariant() { clear(); }
225 auto operator=(const PropVariant &rhs) -> PropVariant&
227 if(this != &rhs)
228 PropVariantCopy(&mProp, &rhs.mProp);
229 return *this;
232 void clear() { PropVariantClear(&mProp); }
234 PROPVARIANT* get() noexcept { return &mProp; }
236 /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
237 [[nodiscard]]
238 auto type() const noexcept -> VARTYPE { return mProp.vt; }
240 template<typename T> [[nodiscard]]
241 auto value() const -> T
243 if constexpr(std::is_same_v<T,uint>)
245 alassert(mProp.vt == VT_UI4 || mProp.vt == VT_UINT);
246 return mProp.uintVal;
248 else if constexpr(std::is_same_v<T,std::wstring_view> || std::is_same_v<T,std::wstring>
249 || std::is_same_v<T,LPWSTR> || std::is_same_v<T,LPCWSTR>)
251 alassert(mProp.vt == VT_LPWSTR);
252 return mProp.pwszVal;
256 void setBlob(const al::span<BYTE> data)
258 if constexpr(sizeof(size_t) > sizeof(ULONG))
259 alassert(data.size() <= std::numeric_limits<ULONG>::max());
260 mProp.vt = VT_BLOB;
261 mProp.blob.cbSize = static_cast<ULONG>(data.size());
262 mProp.blob.pBlobData = data.data();
264 /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
267 struct DevMap {
268 std::string name;
269 std::string endpoint_guid; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
270 std::wstring devid;
272 template<typename T0, typename T1, typename T2>
273 DevMap(T0&& name_, T1&& guid_, T2&& devid_)
274 : name{std::forward<T0>(name_)}
275 , endpoint_guid{std::forward<T1>(guid_)}
276 , devid{std::forward<T2>(devid_)}
278 /* To prevent GCC from complaining it doesn't want to inline this. */
279 ~DevMap();
281 DevMap::~DevMap() = default;
283 bool checkName(const al::span<DevMap> list, const std::string_view name)
285 auto match_name = [name](const DevMap &entry) -> bool { return entry.name == name; };
286 return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
290 struct DeviceList {
291 auto lock() noexcept(noexcept(mMutex.lock())) { return mMutex.lock(); }
292 auto unlock() noexcept(noexcept(mMutex.unlock())) { return mMutex.unlock(); }
294 private:
295 std::mutex mMutex;
296 std::vector<DevMap> mPlayback;
297 std::vector<DevMap> mCapture;
298 std::wstring mPlaybackDefaultId;
299 std::wstring mCaptureDefaultId;
301 friend struct DeviceListLock;
303 struct DeviceListLock : public std::unique_lock<DeviceList> {
304 using std::unique_lock<DeviceList>::unique_lock;
306 [[nodiscard]] auto& getPlaybackList() const noexcept { return mutex()->mPlayback; }
307 [[nodiscard]] auto& getCaptureList() const noexcept { return mutex()->mCapture; }
309 void setPlaybackDefaultId(std::wstring_view devid) const { mutex()->mPlaybackDefaultId = devid; }
310 [[nodiscard]] auto getPlaybackDefaultId() const noexcept -> std::wstring_view { return mutex()->mPlaybackDefaultId; }
311 void setCaptureDefaultId(std::wstring_view devid) const { mutex()->mCaptureDefaultId = devid; }
312 [[nodiscard]] auto getCaptureDefaultId() const noexcept -> std::wstring_view { return mutex()->mCaptureDefaultId; }
315 DeviceList gDeviceList;
318 #ifdef AVRTAPI
319 struct AvrtHandleCloser {
320 void operator()(HANDLE handle) { AvRevertMmThreadCharacteristics(handle); }
322 using AvrtHandlePtr = std::unique_ptr<std::remove_pointer_t<HANDLE>,AvrtHandleCloser>;
323 #endif
325 #if defined(ALSOFT_UWP)
326 enum EDataFlow {
327 eRender = 0,
328 eCapture = (eRender + 1),
329 eAll = (eCapture + 1),
330 EDataFlow_enum_count = (eAll + 1)
332 #endif
334 #if defined(ALSOFT_UWP)
335 using DeviceHandle = Windows::Devices::Enumeration::DeviceInformation;
336 using EventRegistrationToken = winrt::event_token;
337 #else
338 using DeviceHandle = ComPtr<IMMDevice>;
339 #endif
342 struct NameGUIDPair { std::string mName; std::string mGuid; };
343 auto GetDeviceNameAndGuid(const DeviceHandle &device) -> NameGUIDPair
345 constexpr auto UnknownName = "Unknown Device Name"sv;
346 constexpr auto UnknownGuid = "Unknown Device GUID"sv;
348 #if !defined(ALSOFT_UWP)
349 std::string name, guid;
351 ComPtr<IPropertyStore> ps;
352 HRESULT hr{device->OpenPropertyStore(STGM_READ, al::out_ptr(ps))};
353 if(FAILED(hr))
355 WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
356 return {std::string{UnknownName}, std::string{UnknownGuid}};
359 PropVariant pvprop;
360 hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(DEVPKEY_Device_FriendlyName), pvprop.get());
361 if(FAILED(hr))
362 WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr);
363 else if(pvprop.type() == VT_LPWSTR)
364 name = wstr_to_utf8(pvprop.value<std::wstring_view>());
365 else
366 WARN("Unexpected Device_FriendlyName PROPVARIANT type: 0x%04x\n", pvprop.type());
368 pvprop.clear();
369 hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(PKEY_AudioEndpoint_GUID), pvprop.get());
370 if(FAILED(hr))
371 WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr);
372 else if(pvprop.type() == VT_LPWSTR)
373 guid = wstr_to_utf8(pvprop.value<std::wstring_view>());
374 else
375 WARN("Unexpected AudioEndpoint_GUID PROPVARIANT type: 0x%04x\n", pvprop.type());
376 #else
377 std::string name{wstr_to_utf8(device.Name())};
378 std::string guid;
379 // device->Id is DeviceInterfacePath: \\?\SWD#MMDEVAPI#{0.0.0.00000000}.{a21c17a0-fc1d-405e-ab5a-b513422b57d1}#{e6327cad-dcec-4949-ae8a-991e976a79d2}
380 auto devIfPath = device.Id();
381 if(auto devIdStart = wcsstr(devIfPath.data(), L"}."))
383 devIdStart += 2; // L"}."
384 if(auto devIdStartEnd = wcschr(devIdStart, L'#'))
386 std::wstring wDevId{devIdStart, static_cast<size_t>(devIdStartEnd - devIdStart)};
387 guid = wstr_to_utf8(wDevId.c_str());
388 std::transform(guid.begin(), guid.end(), guid.begin(),
389 [](char ch) { return static_cast<char>(std::toupper(ch)); });
392 #endif
393 if(name.empty()) name = UnknownName;
394 if(guid.empty()) guid = UnknownGuid;
395 return {std::move(name), std::move(guid)};
397 #if !defined(ALSOFT_UWP)
398 EndpointFormFactor GetDeviceFormfactor(IMMDevice *device)
400 ComPtr<IPropertyStore> ps;
401 HRESULT hr{device->OpenPropertyStore(STGM_READ, al::out_ptr(ps))};
402 if(FAILED(hr))
404 WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
405 return UnknownFormFactor;
408 EndpointFormFactor formfactor{UnknownFormFactor};
409 PropVariant pvform;
410 hr = ps->GetValue(PKEY_AudioEndpoint_FormFactor, pvform.get());
411 if(FAILED(hr))
412 WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr);
413 else if(pvform.type() == VT_UI4)
414 formfactor = static_cast<EndpointFormFactor>(pvform.value<uint>());
415 else if(pvform.type() != VT_EMPTY)
416 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform.type());
417 return formfactor;
419 #endif
422 #if defined(ALSOFT_UWP)
423 struct DeviceHelper final : public IActivateAudioInterfaceCompletionHandler
424 #else
425 struct DeviceHelper final : private IMMNotificationClient
426 #endif
428 #if defined(ALSOFT_UWP)
429 DeviceHelper()
431 /* TODO: UWP also needs to watch for device added/removed events and
432 * dynamically add/remove devices from the lists.
434 mActiveClientEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
436 mRenderDeviceChangedToken = MediaDevice::DefaultAudioRenderDeviceChanged([this](const IInspectable& /*sender*/, const DefaultAudioRenderDeviceChangedEventArgs& args) {
437 if (args.Role() == AudioDeviceRole::Default)
439 const std::string msg{ "Default playback device changed: " +
440 wstr_to_utf8(args.Id())};
441 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback,
442 msg);
446 mCaptureDeviceChangedToken = MediaDevice::DefaultAudioCaptureDeviceChanged([this](const IInspectable& /*sender*/, const DefaultAudioCaptureDeviceChangedEventArgs& args) {
447 if (args.Role() == AudioDeviceRole::Default)
449 const std::string msg{ "Default capture device changed: " +
450 wstr_to_utf8(args.Id()) };
451 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture,
452 msg);
456 #else
457 DeviceHelper() = default;
458 #endif
459 ~DeviceHelper()
461 #if defined(ALSOFT_UWP)
462 MediaDevice::DefaultAudioRenderDeviceChanged(mRenderDeviceChangedToken);
463 MediaDevice::DefaultAudioCaptureDeviceChanged(mCaptureDeviceChangedToken);
465 if(mActiveClientEvent != nullptr)
466 CloseHandle(mActiveClientEvent);
467 mActiveClientEvent = nullptr;
468 #else
469 if(mEnumerator)
470 mEnumerator->UnregisterEndpointNotificationCallback(this);
471 mEnumerator = nullptr;
472 #endif
475 template<typename T>
476 auto as() noexcept -> T { return T{this}; }
478 /** -------------------------- IUnknown ----------------------------- */
479 std::atomic<ULONG> mRefCount{1};
480 STDMETHODIMP_(ULONG) AddRef() noexcept override { return mRefCount.fetch_add(1u) + 1u; }
481 STDMETHODIMP_(ULONG) Release() noexcept override { return mRefCount.fetch_sub(1u) - 1u; }
483 STDMETHODIMP QueryInterface(const IID& IId, void **UnknownPtrPtr) noexcept override
485 // Three rules of QueryInterface:
486 // https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface
487 // 1. Objects must have identity.
488 // 2. The set of interfaces on an object instance must be static.
489 // 3. It must be possible to query successfully for any interface on an object from any other interface.
491 // If ppvObject(the address) is nullptr, then this method returns E_POINTER.
492 if(!UnknownPtrPtr)
493 return E_POINTER;
495 // https://docs.microsoft.com/en-us/windows/win32/com/implementing-reference-counting
496 // Whenever a client calls a method(or API function), such as QueryInterface, that returns a new interface
497 // pointer, the method being called is responsible for incrementing the reference count through the returned
498 // pointer. For example, when a client first creates an object, it receives an interface pointer to an object
499 // that, from the client's point of view, has a reference count of one. If the client then calls AddRef on the
500 // interface pointer, the reference count becomes two. The client must call Release twice on the interface
501 // pointer to drop all of its references to the object.
502 #if defined(ALSOFT_UWP)
503 if(IId == __uuidof(IActivateAudioInterfaceCompletionHandler))
505 *UnknownPtrPtr = as<IActivateAudioInterfaceCompletionHandler*>();
506 AddRef();
507 return S_OK;
509 #else
510 if(IId == __uuidof(IMMNotificationClient))
512 *UnknownPtrPtr = as<IMMNotificationClient*>();
513 AddRef();
514 return S_OK;
516 #endif
517 else if(IId == __uuidof(IAgileObject) || IId == __uuidof(IUnknown))
519 *UnknownPtrPtr = as<IUnknown*>();
520 AddRef();
521 return S_OK;
524 // This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise.
525 *UnknownPtrPtr = nullptr;
526 return E_NOINTERFACE;
529 #if defined(ALSOFT_UWP)
530 /** ----------------------- IActivateAudioInterfaceCompletionHandler ------------ */
531 HRESULT ActivateCompleted(IActivateAudioInterfaceAsyncOperation*) override
533 SetEvent(mActiveClientEvent);
535 // Need to return S_OK
536 return S_OK;
538 #else
539 /** ----------------------- IMMNotificationClient ------------ */
540 STDMETHODIMP OnDeviceStateChanged(LPCWSTR /*pwstrDeviceId*/, DWORD /*dwNewState*/) noexcept override { return S_OK; }
542 STDMETHODIMP OnDeviceAdded(LPCWSTR pwstrDeviceId) noexcept override
544 ComPtr<IMMDevice> device;
545 HRESULT hr{mEnumerator->GetDevice(pwstrDeviceId, al::out_ptr(device))};
546 if(FAILED(hr))
548 ERR("Failed to get device: 0x%08lx\n", hr);
549 return S_OK;
552 ComPtr<IMMEndpoint> endpoint;
553 hr = device->QueryInterface(__uuidof(IMMEndpoint), al::out_ptr(endpoint));
554 if(FAILED(hr))
556 ERR("Failed to get device endpoint: 0x%08lx\n", hr);
557 return S_OK;
560 EDataFlow flowdir{};
561 hr = endpoint->GetDataFlow(&flowdir);
562 if(FAILED(hr))
564 ERR("Failed to get endpoint data flow: 0x%08lx\n", hr);
565 return S_OK;
568 auto devlock = DeviceListLock{gDeviceList};
569 auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
571 if(AddDevice(device, pwstrDeviceId, list))
573 const auto devtype = (flowdir==eRender) ? alc::DeviceType::Playback
574 : alc::DeviceType::Capture;
575 const std::string msg{"Device added: "+list.back().name};
576 alc::Event(alc::EventType::DeviceAdded, devtype, msg);
579 return S_OK;
582 STDMETHODIMP OnDeviceRemoved(LPCWSTR pwstrDeviceId) noexcept override
584 auto devlock = DeviceListLock{gDeviceList};
585 for(auto flowdir : std::array{eRender, eCapture})
587 auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
588 auto devtype = (flowdir==eRender)?alc::DeviceType::Playback : alc::DeviceType::Capture;
590 /* Find the ID in the list to remove. */
591 auto iter = std::find_if(list.begin(), list.end(),
592 [pwstrDeviceId](const DevMap &entry) noexcept
593 { return pwstrDeviceId == entry.devid; });
594 if(iter == list.end()) continue;
596 TRACE("Removing device \"%s\", \"%s\", \"%ls\"\n", iter->name.c_str(),
597 iter->endpoint_guid.c_str(), iter->devid.c_str());
599 std::string msg{"Device removed: "+std::move(iter->name)};
600 list.erase(iter);
602 alc::Event(alc::EventType::DeviceRemoved, devtype, msg);
604 return S_OK;
607 /* NOLINTNEXTLINE(clazy-function-args-by-ref) */
608 STDMETHODIMP OnPropertyValueChanged(LPCWSTR /*pwstrDeviceId*/, const PROPERTYKEY /*key*/) noexcept override { return S_OK; }
610 STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) noexcept override
612 if(role != eMultimedia)
613 return S_OK;
615 const std::wstring_view devid{pwstrDefaultDeviceId ? pwstrDefaultDeviceId
616 : std::wstring_view{}};
617 if(flow == eRender)
619 DeviceListLock{gDeviceList}.setPlaybackDefaultId(devid);
620 const std::string msg{"Default playback device changed: " + wstr_to_utf8(devid)};
621 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
623 else if(flow == eCapture)
625 DeviceListLock{gDeviceList}.setCaptureDefaultId(devid);
626 const std::string msg{"Default capture device changed: " + wstr_to_utf8(devid)};
627 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
629 return S_OK;
631 #endif
633 /** -------------------------- DeviceHelper ----------------------------- */
634 HRESULT init()
636 #if !defined(ALSOFT_UWP)
637 HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
638 __uuidof(IMMDeviceEnumerator), al::out_ptr(mEnumerator))};
639 if(SUCCEEDED(hr))
640 mEnumerator->RegisterEndpointNotificationCallback(this);
641 else
642 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
643 return hr;
644 #else
645 return S_OK;
646 #endif
649 HRESULT openDevice(std::wstring_view devid, EDataFlow flow, DeviceHandle& device)
651 #if !defined(ALSOFT_UWP)
652 HRESULT hr{E_FAIL};
653 if(mEnumerator)
655 if(devid.empty())
656 hr = mEnumerator->GetDefaultAudioEndpoint(flow, eMultimedia, al::out_ptr(device));
657 else
658 hr = mEnumerator->GetDevice(devid.data(), al::out_ptr(device));
660 return hr;
661 #else
662 const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
663 auto devIfPath =
664 devid.empty() ? (flow == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole) : MediaDevice::GetDefaultAudioCaptureId(deviceRole))
665 : winrt::hstring(devid.data());
666 if (devIfPath.empty())
667 return E_POINTER;
669 auto&& deviceInfo = DeviceInformation::CreateFromIdAsync(devIfPath, nullptr, DeviceInformationKind::DeviceInterface).get();
670 if (!deviceInfo)
671 return E_NOINTERFACE;
672 device = deviceInfo;
673 return S_OK;
674 #endif
677 #if !defined(ALSOFT_UWP)
678 static HRESULT activateAudioClient(_In_ DeviceHandle &device, REFIID iid, void **ppv)
679 { return device->Activate(iid, CLSCTX_INPROC_SERVER, nullptr, ppv); }
680 #else
681 HRESULT activateAudioClient(_In_ DeviceHandle &device, _In_ REFIID iid, void **ppv)
683 ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
684 HRESULT hr{ActivateAudioInterfaceAsync(device.Id().data(), iid, nullptr, this,
685 al::out_ptr(asyncOp))};
686 if(FAILED(hr))
687 return hr;
689 /* I don't like waiting for INFINITE time, but the activate operation
690 * can take an indefinite amount of time since it can require user
691 * input.
693 DWORD res{WaitForSingleObjectEx(mActiveClientEvent, INFINITE, FALSE)};
694 if(res != WAIT_OBJECT_0)
696 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
697 return E_FAIL;
700 HRESULT hrActivateRes{E_FAIL};
701 ComPtr<IUnknown> punkAudioIface;
702 hr = asyncOp->GetActivateResult(&hrActivateRes, al::out_ptr(punkAudioIface));
703 if(SUCCEEDED(hr)) hr = hrActivateRes;
704 if(FAILED(hr)) return hr;
706 return punkAudioIface->QueryInterface(iid, ppv);
708 #endif
710 std::wstring probeDevices(EDataFlow flowdir, std::vector<DevMap> &list)
712 std::wstring defaultId;
713 std::vector<DevMap>{}.swap(list);
715 #if !defined(ALSOFT_UWP)
716 ComPtr<IMMDeviceCollection> coll;
717 HRESULT hr{mEnumerator->EnumAudioEndpoints(flowdir, DEVICE_STATE_ACTIVE,
718 al::out_ptr(coll))};
719 if(FAILED(hr))
721 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr);
722 return defaultId;
725 UINT count{0};
726 hr = coll->GetCount(&count);
727 if(SUCCEEDED(hr) && count > 0)
728 list.reserve(count);
730 ComPtr<IMMDevice> device;
731 hr = mEnumerator->GetDefaultAudioEndpoint(flowdir, eMultimedia, al::out_ptr(device));
732 if(SUCCEEDED(hr))
734 if(WCHAR *devid{GetDeviceId(device.get())})
736 defaultId = devid;
737 CoTaskMemFree(devid);
739 device = nullptr;
742 for(UINT i{0};i < count;++i)
744 hr = coll->Item(i, al::out_ptr(device));
745 if(FAILED(hr))
746 continue;
748 if(WCHAR *devid{GetDeviceId(device.get())})
750 std::ignore = AddDevice(device, devid, list);
751 CoTaskMemFree(devid);
753 device = nullptr;
755 #else
756 const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
757 auto DefaultAudioId = flowdir == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole)
758 : MediaDevice::GetDefaultAudioCaptureId(deviceRole);
759 if(!DefaultAudioId.empty())
761 auto deviceInfo = DeviceInformation::CreateFromIdAsync(DefaultAudioId, nullptr,
762 DeviceInformationKind::DeviceInterface).get();
763 if(deviceInfo)
764 defaultId = deviceInfo.Id().data();
767 // Get the string identifier of the audio renderer
768 auto AudioSelector = flowdir == eRender ? MediaDevice::GetAudioRenderSelector() : MediaDevice::GetAudioCaptureSelector();
770 // Setup the asynchronous callback
771 auto&& DeviceInfoCollection = DeviceInformation::FindAllAsync(AudioSelector, /*PropertyList*/nullptr, DeviceInformationKind::DeviceInterface).get();
772 if(DeviceInfoCollection)
774 try {
775 auto deviceCount = DeviceInfoCollection.Size();
776 for(unsigned int i{0};i < deviceCount;++i)
778 auto deviceInfo = DeviceInfoCollection.GetAt(i);
779 if(deviceInfo)
780 std::ignore = AddDevice(deviceInfo, deviceInfo.Id().data(), list);
783 catch (const winrt::hresult_error& /*ex*/) {
786 #endif
788 return defaultId;
791 private:
792 static bool AddDevice(const DeviceHandle &device, const WCHAR *devid, std::vector<DevMap> &list)
794 for(auto &entry : list)
796 if(entry.devid == devid)
797 return false;
800 auto name_guid = GetDeviceNameAndGuid(device);
801 int count{1};
802 std::string newname{name_guid.mName};
803 while(checkName(list, newname))
805 newname = name_guid.mName;
806 newname += " #";
807 newname += std::to_string(++count);
809 list.emplace_back(std::move(newname), std::move(name_guid.mGuid), devid);
810 const DevMap &newentry = list.back();
812 TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry.name.c_str(),
813 newentry.endpoint_guid.c_str(), newentry.devid.c_str());
814 return true;
817 #if !defined(ALSOFT_UWP)
818 static WCHAR *GetDeviceId(IMMDevice *device)
820 WCHAR *devid;
822 const HRESULT hr{device->GetId(&devid)};
823 if(FAILED(hr))
825 ERR("Failed to get device id: %lx\n", hr);
826 return nullptr;
829 return devid;
831 ComPtr<IMMDeviceEnumerator> mEnumerator{nullptr};
833 #else
835 HANDLE mActiveClientEvent{nullptr};
837 EventRegistrationToken mRenderDeviceChangedToken;
838 EventRegistrationToken mCaptureDeviceChangedToken;
839 #endif
842 bool MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in)
844 *out = WAVEFORMATEXTENSIBLE{};
845 if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
847 *out = *CONTAINING_RECORD(in, const WAVEFORMATEXTENSIBLE, Format);
848 out->Format.cbSize = sizeof(*out) - sizeof(out->Format);
850 else if(in->wFormatTag == WAVE_FORMAT_PCM)
852 out->Format = *in;
853 out->Format.cbSize = 0;
854 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
855 out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
856 if(out->Format.nChannels == 1)
857 out->dwChannelMask = MONO;
858 else if(out->Format.nChannels == 2)
859 out->dwChannelMask = STEREO;
860 else
861 ERR("Unhandled PCM channel count: %d\n", out->Format.nChannels);
862 out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
864 else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
866 out->Format = *in;
867 out->Format.cbSize = 0;
868 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
869 out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
870 if(out->Format.nChannels == 1)
871 out->dwChannelMask = MONO;
872 else if(out->Format.nChannels == 2)
873 out->dwChannelMask = STEREO;
874 else
875 ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels);
876 out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
878 else
880 ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag);
881 return false;
883 return true;
886 void TraceFormat(const char *msg, const WAVEFORMATEX *format)
888 constexpr size_t fmtex_extra_size{sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)};
889 if(format->wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->cbSize >= fmtex_extra_size)
891 const WAVEFORMATEXTENSIBLE *fmtex{
892 CONTAINING_RECORD(format, const WAVEFORMATEXTENSIBLE, Format)};
893 /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
894 TRACE("%s:\n"
895 " FormatTag = 0x%04x\n"
896 " Channels = %d\n"
897 " SamplesPerSec = %lu\n"
898 " AvgBytesPerSec = %lu\n"
899 " BlockAlign = %d\n"
900 " BitsPerSample = %d\n"
901 " Size = %d\n"
902 " Samples = %d\n"
903 " ChannelMask = 0x%lx\n"
904 " SubFormat = %s\n",
905 msg, fmtex->Format.wFormatTag, fmtex->Format.nChannels, fmtex->Format.nSamplesPerSec,
906 fmtex->Format.nAvgBytesPerSec, fmtex->Format.nBlockAlign, fmtex->Format.wBitsPerSample,
907 fmtex->Format.cbSize, fmtex->Samples.wReserved, fmtex->dwChannelMask,
908 GuidPrinter{fmtex->SubFormat}.c_str());
909 /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
911 else
912 TRACE("%s:\n"
913 " FormatTag = 0x%04x\n"
914 " Channels = %d\n"
915 " SamplesPerSec = %lu\n"
916 " AvgBytesPerSec = %lu\n"
917 " BlockAlign = %d\n"
918 " BitsPerSample = %d\n"
919 " Size = %d\n",
920 msg, format->wFormatTag, format->nChannels, format->nSamplesPerSec,
921 format->nAvgBytesPerSec, format->nBlockAlign, format->wBitsPerSample, format->cbSize);
925 enum class MsgType {
926 OpenDevice,
927 ResetDevice,
928 StartDevice,
929 StopDevice,
930 CloseDevice,
932 QuitThread
935 constexpr const char *GetMessageTypeName(MsgType type) noexcept
937 switch(type)
939 case MsgType::OpenDevice: return "Open Device";
940 case MsgType::ResetDevice: return "Reset Device";
941 case MsgType::StartDevice: return "Start Device";
942 case MsgType::StopDevice: return "Stop Device";
943 case MsgType::CloseDevice: return "Close Device";
944 case MsgType::QuitThread: break;
946 return "";
950 /* Proxy interface used by the message handler. */
951 struct WasapiProxy {
952 WasapiProxy() = default;
953 WasapiProxy(const WasapiProxy&) = delete;
954 WasapiProxy(WasapiProxy&&) = delete;
955 virtual ~WasapiProxy() = default;
957 void operator=(const WasapiProxy&) = delete;
958 void operator=(WasapiProxy&&) = delete;
960 virtual HRESULT openProxy(std::string_view name) = 0;
961 virtual void closeProxy() = 0;
963 virtual HRESULT resetProxy() = 0;
964 virtual HRESULT startProxy() = 0;
965 virtual void stopProxy() = 0;
967 struct Msg {
968 MsgType mType;
969 WasapiProxy *mProxy;
970 std::string_view mParam;
971 std::promise<HRESULT> mPromise;
973 explicit operator bool() const noexcept { return mType != MsgType::QuitThread; }
975 static inline std::deque<Msg> mMsgQueue;
976 static inline std::mutex mMsgQueueLock;
977 static inline std::condition_variable mMsgQueueCond;
978 static inline DWORD sAvIndex{};
980 static inline std::optional<DeviceHelper> sDeviceHelper;
982 std::future<HRESULT> pushMessage(MsgType type, std::string_view param={})
984 std::promise<HRESULT> promise;
985 std::future<HRESULT> future{promise.get_future()};
987 std::lock_guard<std::mutex> msglock{mMsgQueueLock};
988 mMsgQueue.emplace_back(Msg{type, this, param, std::move(promise)});
990 mMsgQueueCond.notify_one();
991 return future;
994 static std::future<HRESULT> pushMessageStatic(MsgType type)
996 std::promise<HRESULT> promise;
997 std::future<HRESULT> future{promise.get_future()};
999 std::lock_guard<std::mutex> msglock{mMsgQueueLock};
1000 mMsgQueue.emplace_back(Msg{type, nullptr, {}, std::move(promise)});
1002 mMsgQueueCond.notify_one();
1003 return future;
1006 static Msg popMessage()
1008 std::unique_lock<std::mutex> lock{mMsgQueueLock};
1009 mMsgQueueCond.wait(lock, []{return !mMsgQueue.empty();});
1010 Msg msg{std::move(mMsgQueue.front())};
1011 mMsgQueue.pop_front();
1012 return msg;
1015 static int messageHandler(std::promise<HRESULT> *promise);
1018 int WasapiProxy::messageHandler(std::promise<HRESULT> *promise)
1020 TRACE("Starting message thread\n");
1022 ComWrapper com{COINIT_MULTITHREADED};
1023 if(!com)
1025 WARN("Failed to initialize COM: 0x%08lx\n", com.status());
1026 promise->set_value(com.status());
1027 return 0;
1030 struct HelperResetter {
1031 HelperResetter() = default;
1032 HelperResetter(const HelperResetter&) = delete;
1033 auto operator=(const HelperResetter&) -> HelperResetter& = delete;
1034 ~HelperResetter() { sDeviceHelper.reset(); }
1036 HelperResetter scoped_watcher;
1038 HRESULT hr{sDeviceHelper.emplace().init()};
1039 promise->set_value(hr);
1040 promise = nullptr;
1041 if(FAILED(hr))
1042 return 0;
1045 auto devlock = DeviceListLock{gDeviceList};
1046 auto defaultId = sDeviceHelper->probeDevices(eRender, devlock.getPlaybackList());
1047 if(!defaultId.empty()) devlock.setPlaybackDefaultId(defaultId);
1048 defaultId = sDeviceHelper->probeDevices(eCapture, devlock.getCaptureList());
1049 if(!defaultId.empty()) devlock.setCaptureDefaultId(defaultId);
1052 TRACE("Starting message loop\n");
1053 while(Msg msg{popMessage()})
1055 TRACE("Got message \"%s\" (0x%04x, this=%p, param=\"%.*s\")\n",
1056 GetMessageTypeName(msg.mType), static_cast<uint>(msg.mType),
1057 static_cast<void*>(msg.mProxy), al::sizei(msg.mParam), msg.mParam.data());
1059 switch(msg.mType)
1061 case MsgType::OpenDevice:
1062 hr = msg.mProxy->openProxy(msg.mParam);
1063 msg.mPromise.set_value(hr);
1064 continue;
1066 case MsgType::ResetDevice:
1067 hr = msg.mProxy->resetProxy();
1068 msg.mPromise.set_value(hr);
1069 continue;
1071 case MsgType::StartDevice:
1072 hr = msg.mProxy->startProxy();
1073 msg.mPromise.set_value(hr);
1074 continue;
1076 case MsgType::StopDevice:
1077 msg.mProxy->stopProxy();
1078 msg.mPromise.set_value(S_OK);
1079 continue;
1081 case MsgType::CloseDevice:
1082 msg.mProxy->closeProxy();
1083 msg.mPromise.set_value(S_OK);
1084 continue;
1086 case MsgType::QuitThread:
1087 break;
1089 ERR("Unexpected message: %u\n", static_cast<uint>(msg.mType));
1090 msg.mPromise.set_value(E_FAIL);
1092 TRACE("Message loop finished\n");
1094 return 0;
1097 struct WasapiPlayback final : public BackendBase, WasapiProxy {
1098 WasapiPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
1099 ~WasapiPlayback() override;
1101 int mixerProc();
1102 int mixerSpatialProc();
1104 void open(std::string_view name) override;
1105 HRESULT openProxy(std::string_view name) override;
1106 void closeProxy() override;
1108 bool reset() override;
1109 HRESULT resetProxy() override;
1110 void start() override;
1111 HRESULT startProxy() override;
1112 void stop() override;
1113 void stopProxy() override;
1115 ClockLatency getClockLatency() override;
1117 void prepareFormat(WAVEFORMATEXTENSIBLE &OutputType);
1118 void finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType);
1120 auto initSpatial() -> bool;
1122 HRESULT mOpenStatus{E_FAIL};
1123 DeviceHandle mMMDev{nullptr};
1125 struct PlainDevice {
1126 ComPtr<IAudioClient> mClient{nullptr};
1127 ComPtr<IAudioRenderClient> mRender{nullptr};
1129 struct SpatialDevice {
1130 ComPtr<ISpatialAudioClient> mClient{nullptr};
1131 ComPtr<ISpatialAudioObjectRenderStream> mRender{nullptr};
1132 AudioObjectType mStaticMask{};
1134 std::variant<PlainDevice,SpatialDevice> mAudio{std::in_place_index_t<0>{}};
1135 HANDLE mNotifyEvent{nullptr};
1137 UINT32 mOutBufferSize{}, mOutUpdateSize{};
1138 std::vector<char> mResampleBuffer{};
1139 uint mBufferFilled{0};
1140 SampleConverterPtr mResampler;
1142 WAVEFORMATEXTENSIBLE mFormat{};
1143 std::atomic<UINT32> mPadding{0u};
1145 std::mutex mMutex;
1147 std::atomic<bool> mKillNow{true};
1148 std::thread mThread;
1151 WasapiPlayback::~WasapiPlayback()
1153 if(SUCCEEDED(mOpenStatus))
1154 pushMessage(MsgType::CloseDevice).wait();
1155 mOpenStatus = E_FAIL;
1157 if(mNotifyEvent != nullptr)
1158 CloseHandle(mNotifyEvent);
1159 mNotifyEvent = nullptr;
1163 FORCE_ALIGN int WasapiPlayback::mixerProc()
1165 ComWrapper com{COINIT_MULTITHREADED};
1166 if(!com)
1168 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
1169 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
1170 return 1;
1173 auto &audio = std::get<PlainDevice>(mAudio);
1175 SetRTPriority();
1176 althrd_setname(GetMixerThreadName());
1178 const uint frame_size{mFormat.Format.nChannels * mFormat.Format.wBitsPerSample / 8u};
1179 const uint update_size{mOutUpdateSize};
1180 const UINT32 buffer_len{mOutBufferSize};
1181 const void *resbufferptr{};
1183 #ifdef AVRTAPI
1184 /* TODO: "Audio" or "Pro Audio"? The suggestion is to use "Pro Audio" for
1185 * device periods less than 10ms, and "Audio" for greater than or equal to
1186 * 10ms.
1188 auto taskname = (update_size < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
1189 auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
1190 #endif
1192 mBufferFilled = 0;
1193 while(!mKillNow.load(std::memory_order_relaxed))
1195 UINT32 written;
1196 HRESULT hr{audio.mClient->GetCurrentPadding(&written)};
1197 if(FAILED(hr))
1199 ERR("Failed to get padding: 0x%08lx\n", hr);
1200 mDevice->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr);
1201 break;
1203 mPadding.store(written, std::memory_order_relaxed);
1205 uint len{buffer_len - written};
1206 if(len < update_size)
1208 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
1209 if(res != WAIT_OBJECT_0)
1210 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1211 continue;
1214 BYTE *buffer;
1215 hr = audio.mRender->GetBuffer(len, &buffer);
1216 if(SUCCEEDED(hr))
1218 if(mResampler)
1220 std::lock_guard<std::mutex> dlock{mMutex};
1221 auto dst = al::span{buffer, size_t{len}*frame_size};
1222 for(UINT32 done{0};done < len;)
1224 if(mBufferFilled == 0)
1226 mDevice->renderSamples(mResampleBuffer.data(), mDevice->UpdateSize,
1227 mFormat.Format.nChannels);
1228 resbufferptr = mResampleBuffer.data();
1229 mBufferFilled = mDevice->UpdateSize;
1232 uint got{mResampler->convert(&resbufferptr, &mBufferFilled, dst.data(),
1233 len-done)};
1234 dst = dst.subspan(size_t{got}*frame_size);
1235 done += got;
1237 mPadding.store(written + done, std::memory_order_relaxed);
1240 else
1242 std::lock_guard<std::mutex> dlock{mMutex};
1243 mDevice->renderSamples(buffer, len, mFormat.Format.nChannels);
1244 mPadding.store(written + len, std::memory_order_relaxed);
1246 hr = audio.mRender->ReleaseBuffer(len, 0);
1248 if(FAILED(hr))
1250 ERR("Failed to buffer data: 0x%08lx\n", hr);
1251 mDevice->handleDisconnect("Failed to send playback samples: 0x%08lx", hr);
1252 break;
1255 mPadding.store(0u, std::memory_order_release);
1257 return 0;
1260 FORCE_ALIGN int WasapiPlayback::mixerSpatialProc()
1262 ComWrapper com{COINIT_MULTITHREADED};
1263 if(!com)
1265 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
1266 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
1267 return 1;
1270 auto &audio = std::get<SpatialDevice>(mAudio);
1272 SetRTPriority();
1273 althrd_setname(GetMixerThreadName());
1275 std::vector<ComPtr<ISpatialAudioObject>> channels;
1276 std::vector<void*> buffers;
1277 std::vector<void*> resbuffers;
1278 std::vector<const void*> tmpbuffers;
1280 #ifdef AVRTAPI
1281 auto taskname = (mOutUpdateSize < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
1282 auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
1283 #endif
1285 /* TODO: Set mPadding appropriately. There doesn't seem to be a way to
1286 * update it dynamically based on the stream, so a fixed size may be the
1287 * best we can do.
1289 mPadding.store(mOutBufferSize-mOutUpdateSize, std::memory_order_release);
1291 mBufferFilled = 0;
1292 while(!mKillNow.load(std::memory_order_relaxed))
1294 if(DWORD res{WaitForSingleObjectEx(mNotifyEvent, 1000, FALSE)}; res != WAIT_OBJECT_0)
1296 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1298 HRESULT hr{audio.mRender->Reset()};
1299 if(FAILED(hr))
1301 ERR("ISpatialAudioObjectRenderStream::Reset failed: 0x%08lx\n", hr);
1302 mDevice->handleDisconnect("Device lost: 0x%08lx", hr);
1303 break;
1307 UINT32 dynamicCount{}, framesToDo{};
1308 HRESULT hr{audio.mRender->BeginUpdatingAudioObjects(&dynamicCount, &framesToDo)};
1309 if(SUCCEEDED(hr))
1311 if(channels.empty()) UNLIKELY
1313 auto flags = as_unsigned(audio.mStaticMask);
1314 channels.reserve(as_unsigned(al::popcount(flags)));
1315 while(flags)
1317 auto id = decltype(flags){1} << al::countr_zero(flags);
1318 flags &= ~id;
1320 channels.emplace_back();
1321 audio.mRender->ActivateSpatialAudioObject(static_cast<AudioObjectType>(id),
1322 al::out_ptr(channels.back()));
1324 buffers.resize(channels.size());
1325 if(mResampler)
1327 tmpbuffers.resize(buffers.size());
1328 resbuffers.resize(buffers.size());
1329 auto bufptr = mResampleBuffer.begin();
1330 for(size_t i{0};i < tmpbuffers.size();++i)
1332 resbuffers[i] = al::to_address(bufptr);
1333 bufptr += ptrdiff_t(mDevice->UpdateSize*sizeof(float));
1338 /* We have to call to get each channel's buffer individually every
1339 * update, unfortunately.
1341 std::transform(channels.cbegin(), channels.cend(), buffers.begin(),
1342 [](const ComPtr<ISpatialAudioObject> &obj) -> void*
1344 auto buffer = LPBYTE{};
1345 auto size = UINT32{};
1346 obj->GetBuffer(&buffer, &size);
1347 return buffer;
1350 if(!mResampler)
1351 mDevice->renderSamples(buffers, framesToDo);
1352 else
1354 std::lock_guard<std::mutex> dlock{mMutex};
1355 for(UINT32 pos{0};pos < framesToDo;)
1357 if(mBufferFilled == 0)
1359 mDevice->renderSamples(resbuffers, mDevice->UpdateSize);
1360 std::copy(resbuffers.cbegin(), resbuffers.cend(), tmpbuffers.begin());
1361 mBufferFilled = mDevice->UpdateSize;
1364 const uint got{mResampler->convertPlanar(tmpbuffers.data(), &mBufferFilled,
1365 buffers.data(), framesToDo-pos)};
1366 for(auto &buf : buffers)
1367 buf = static_cast<float*>(buf) + got; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
1368 pos += got;
1372 hr = audio.mRender->EndUpdatingAudioObjects();
1375 if(FAILED(hr))
1376 ERR("Failed to update playback objects: 0x%08lx\n", hr);
1378 mPadding.store(0u, std::memory_order_release);
1380 return 0;
1384 void WasapiPlayback::open(std::string_view name)
1386 if(SUCCEEDED(mOpenStatus))
1387 throw al::backend_exception{al::backend_error::DeviceError,
1388 "Unexpected duplicate open call"};
1390 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1391 if(mNotifyEvent == nullptr)
1393 ERR("Failed to create notify events: %lu\n", GetLastError());
1394 throw al::backend_exception{al::backend_error::DeviceError,
1395 "Failed to create notify events"};
1398 mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
1399 if(FAILED(mOpenStatus))
1400 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
1401 mOpenStatus};
1404 HRESULT WasapiPlayback::openProxy(std::string_view name)
1406 std::string devname;
1407 std::wstring devid;
1408 if(!name.empty())
1410 auto devlock = DeviceListLock{gDeviceList};
1411 auto list = al::span{devlock.getPlaybackList()};
1412 auto iter = std::find_if(list.cbegin(), list.cend(),
1413 [name](const DevMap &entry) -> bool
1414 { return entry.name == name || entry.endpoint_guid == name; });
1415 if(iter == list.cend())
1417 const std::wstring wname{utf8_to_wstr(name)};
1418 iter = std::find_if(list.cbegin(), list.cend(),
1419 [&wname](const DevMap &entry) -> bool
1420 { return entry.devid == wname; });
1422 if(iter == list.cend())
1424 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name), name.data());
1425 return E_FAIL;
1427 devname = iter->name;
1428 devid = iter->devid;
1431 HRESULT hr{sDeviceHelper->openDevice(devid, eRender, mMMDev)};
1432 if(FAILED(hr))
1434 WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
1435 return hr;
1437 if(!devname.empty())
1438 mDeviceName = std::move(devname);
1439 else
1440 mDeviceName = GetDeviceNameAndGuid(mMMDev).mName;
1442 return S_OK;
1445 void WasapiPlayback::closeProxy()
1447 mAudio.emplace<PlainDevice>();
1448 mMMDev = nullptr;
1452 void WasapiPlayback::prepareFormat(WAVEFORMATEXTENSIBLE &OutputType)
1454 bool isRear51{false};
1456 if(!mDevice->Flags.test(FrequencyRequest))
1457 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
1458 if(!mDevice->Flags.test(ChannelsRequest))
1460 /* If not requesting a channel configuration, auto-select given what
1461 * fits the mask's lsb (to ensure no gaps in the output channels). If
1462 * there's no mask, we can only assume mono or stereo.
1464 const uint32_t chancount{OutputType.Format.nChannels};
1465 const DWORD chanmask{OutputType.dwChannelMask};
1466 if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
1467 mDevice->FmtChans = DevFmtX714;
1468 else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1469 mDevice->FmtChans = DevFmtX71;
1470 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1471 mDevice->FmtChans = DevFmtX61;
1472 else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1)
1473 mDevice->FmtChans = DevFmtX51;
1474 else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR)
1476 mDevice->FmtChans = DevFmtX51;
1477 isRear51 = true;
1479 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1480 mDevice->FmtChans = DevFmtQuad;
1481 else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
1482 mDevice->FmtChans = DevFmtStereo;
1483 else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
1484 mDevice->FmtChans = DevFmtMono;
1485 else
1486 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask);
1488 else
1490 const uint32_t chancount{OutputType.Format.nChannels};
1491 const DWORD chanmask{OutputType.dwChannelMask};
1492 isRear51 = (chancount == 6 && (chanmask&X51RearMask) == X5DOT1REAR);
1495 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1496 switch(mDevice->FmtChans)
1498 case DevFmtMono:
1499 OutputType.Format.nChannels = 1;
1500 OutputType.dwChannelMask = MONO;
1501 break;
1502 case DevFmtAmbi3D:
1503 mDevice->FmtChans = DevFmtStereo;
1504 /*fall-through*/
1505 case DevFmtStereo:
1506 OutputType.Format.nChannels = 2;
1507 OutputType.dwChannelMask = STEREO;
1508 break;
1509 case DevFmtQuad:
1510 OutputType.Format.nChannels = 4;
1511 OutputType.dwChannelMask = QUAD;
1512 break;
1513 case DevFmtX51:
1514 OutputType.Format.nChannels = 6;
1515 OutputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
1516 break;
1517 case DevFmtX61:
1518 OutputType.Format.nChannels = 7;
1519 OutputType.dwChannelMask = X6DOT1;
1520 break;
1521 case DevFmtX71:
1522 case DevFmtX3D71:
1523 OutputType.Format.nChannels = 8;
1524 OutputType.dwChannelMask = X7DOT1;
1525 break;
1526 case DevFmtX7144:
1527 mDevice->FmtChans = DevFmtX714;
1528 /*fall-through*/
1529 case DevFmtX714:
1530 OutputType.Format.nChannels = 12;
1531 OutputType.dwChannelMask = X7DOT1DOT4;
1532 break;
1534 switch(mDevice->FmtType)
1536 case DevFmtByte:
1537 mDevice->FmtType = DevFmtUByte;
1538 /* fall-through */
1539 case DevFmtUByte:
1540 OutputType.Format.wBitsPerSample = 8;
1541 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1542 break;
1543 case DevFmtUShort:
1544 mDevice->FmtType = DevFmtShort;
1545 /* fall-through */
1546 case DevFmtShort:
1547 OutputType.Format.wBitsPerSample = 16;
1548 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1549 break;
1550 case DevFmtUInt:
1551 mDevice->FmtType = DevFmtInt;
1552 /* fall-through */
1553 case DevFmtInt:
1554 OutputType.Format.wBitsPerSample = 32;
1555 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1556 break;
1557 case DevFmtFloat:
1558 OutputType.Format.wBitsPerSample = 32;
1559 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1560 break;
1562 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1563 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1564 OutputType.Format.nSamplesPerSec = mDevice->Frequency;
1566 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
1567 OutputType.Format.wBitsPerSample / 8);
1568 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
1569 OutputType.Format.nBlockAlign;
1572 void WasapiPlayback::finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType)
1574 if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
1575 mDevice->Frequency = uint(OutputType.Format.nSamplesPerSec);
1576 else
1577 mDevice->Frequency = std::min(mDevice->Frequency, uint(OutputType.Format.nSamplesPerSec));
1579 const uint32_t chancount{OutputType.Format.nChannels};
1580 const DWORD chanmask{OutputType.dwChannelMask};
1581 /* Don't update the channel format if the requested format fits what's
1582 * supported.
1584 bool chansok{false};
1585 if(mDevice->Flags.test(ChannelsRequest))
1587 /* When requesting a channel configuration, make sure it fits the
1588 * mask's lsb (to ensure no gaps in the output channels). If there's no
1589 * mask, assume the request fits with enough channels.
1591 switch(mDevice->FmtChans)
1593 case DevFmtMono:
1594 chansok = (chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask));
1595 break;
1596 case DevFmtStereo:
1597 chansok = (chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask));
1598 break;
1599 case DevFmtQuad:
1600 chansok = (chancount >= 4 && ((chanmask&QuadMask) == QUAD || !chanmask));
1601 break;
1602 case DevFmtX51:
1603 chansok = (chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1604 || (chanmask&X51RearMask) == X5DOT1REAR || !chanmask));
1605 break;
1606 case DevFmtX61:
1607 chansok = (chancount >= 7 && ((chanmask&X61Mask) == X6DOT1 || !chanmask));
1608 break;
1609 case DevFmtX71:
1610 case DevFmtX3D71:
1611 chansok = (chancount >= 8 && ((chanmask&X71Mask) == X7DOT1 || !chanmask));
1612 break;
1613 case DevFmtX714:
1614 chansok = (chancount >= 12 && ((chanmask&X714Mask) == X7DOT1DOT4 || !chanmask));
1615 case DevFmtX7144:
1616 case DevFmtAmbi3D:
1617 break;
1620 if(!chansok)
1622 if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
1623 mDevice->FmtChans = DevFmtX714;
1624 else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1625 mDevice->FmtChans = DevFmtX71;
1626 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1627 mDevice->FmtChans = DevFmtX61;
1628 else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1629 || (chanmask&X51RearMask) == X5DOT1REAR))
1630 mDevice->FmtChans = DevFmtX51;
1631 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1632 mDevice->FmtChans = DevFmtQuad;
1633 else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
1634 mDevice->FmtChans = DevFmtStereo;
1635 else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
1636 mDevice->FmtChans = DevFmtMono;
1637 else
1639 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1640 OutputType.dwChannelMask);
1641 mDevice->FmtChans = DevFmtStereo;
1642 OutputType.Format.nChannels = 2;
1643 OutputType.dwChannelMask = STEREO;
1647 if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
1649 if(OutputType.Format.wBitsPerSample == 8)
1650 mDevice->FmtType = DevFmtUByte;
1651 else if(OutputType.Format.wBitsPerSample == 16)
1652 mDevice->FmtType = DevFmtShort;
1653 else if(OutputType.Format.wBitsPerSample == 32)
1654 mDevice->FmtType = DevFmtInt;
1655 else
1657 mDevice->FmtType = DevFmtShort;
1658 OutputType.Format.wBitsPerSample = 16;
1661 else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1663 mDevice->FmtType = DevFmtFloat;
1664 OutputType.Format.wBitsPerSample = 32;
1666 else
1668 ERR("Unhandled format sub-type: %s\n", GuidPrinter{OutputType.SubFormat}.c_str());
1669 mDevice->FmtType = DevFmtShort;
1670 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
1671 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
1672 OutputType.Format.wBitsPerSample = 16;
1673 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1675 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1676 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1680 auto WasapiPlayback::initSpatial() -> bool
1682 auto &audio = mAudio.emplace<SpatialDevice>();
1683 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(ISpatialAudioClient),
1684 al::out_ptr(audio.mClient))};
1685 if(FAILED(hr))
1687 ERR("Failed to activate spatial audio client: 0x%08lx\n", hr);
1688 return false;
1691 ComPtr<IAudioFormatEnumerator> fmtenum;
1692 hr = audio.mClient->GetSupportedAudioObjectFormatEnumerator(al::out_ptr(fmtenum));
1693 if(FAILED(hr))
1695 ERR("Failed to get format enumerator: 0x%08lx\n", hr);
1696 return false;
1699 UINT32 fmtcount{};
1700 hr = fmtenum->GetCount(&fmtcount);
1701 if(FAILED(hr) || fmtcount == 0)
1703 ERR("Failed to get format count: 0x%08lx\n", hr);
1704 return false;
1707 WAVEFORMATEX *preferredFormat{};
1708 hr = fmtenum->GetFormat(0, &preferredFormat);
1709 if(FAILED(hr))
1711 ERR("Failed to get preferred format: 0x%08lx\n", hr);
1712 return false;
1714 TraceFormat("Preferred mix format", preferredFormat);
1716 UINT32 maxFrames{};
1717 hr = audio.mClient->GetMaxFrameCount(preferredFormat, &maxFrames);
1718 if(FAILED(hr))
1719 ERR("Failed to get max frames: 0x%08lx\n", hr);
1720 else
1721 TRACE("Max sample frames: %u\n", maxFrames);
1722 for(UINT32 i{1};i < fmtcount;++i)
1724 WAVEFORMATEX *otherFormat{};
1725 hr = fmtenum->GetFormat(i, &otherFormat);
1726 if(FAILED(hr))
1727 ERR("Failed to format %u: 0x%08lx\n", i+1, hr);
1728 else
1730 TraceFormat("Other mix format", otherFormat);
1731 UINT32 otherMaxFrames{};
1732 hr = audio.mClient->GetMaxFrameCount(otherFormat, &otherMaxFrames);
1733 if(FAILED(hr))
1734 ERR("Failed to get max frames: 0x%08lx\n", hr);
1735 else
1736 TRACE("Max sample frames: %u\n", otherMaxFrames);
1740 WAVEFORMATEXTENSIBLE OutputType;
1741 if(!MakeExtensible(&OutputType, preferredFormat))
1742 return false;
1744 /* This seems to be the format of each "object", which should be mono. */
1745 if(!(OutputType.Format.nChannels == 1
1746 && (OutputType.dwChannelMask == MONO || !OutputType.dwChannelMask)))
1747 ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1748 OutputType.dwChannelMask);
1750 /* Force 32-bit float. This is currently required for planar output. */
1751 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE
1752 && OutputType.Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT)
1754 OutputType.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
1755 OutputType.Format.cbSize = 0;
1757 if(OutputType.Format.wBitsPerSample != 32)
1759 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nAvgBytesPerSec * 32u
1760 / OutputType.Format.wBitsPerSample;
1761 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nBlockAlign * 32
1762 / OutputType.Format.wBitsPerSample);
1763 OutputType.Format.wBitsPerSample = 32;
1765 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1766 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1767 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1769 /* Match the output rate if not requesting anything specific. */
1770 if(!mDevice->Flags.test(FrequencyRequest))
1771 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
1773 auto getTypeMask = [](DevFmtChannels chans) noexcept
1775 switch(chans)
1777 case DevFmtMono: return ChannelMask_Mono;
1778 case DevFmtStereo: return ChannelMask_Stereo;
1779 case DevFmtQuad: return ChannelMask_Quad;
1780 case DevFmtX51: return ChannelMask_X51;
1781 case DevFmtX61: return ChannelMask_X61;
1782 case DevFmtX3D71: [[fallthrough]];
1783 case DevFmtX71: return ChannelMask_X71;
1784 case DevFmtX714: return ChannelMask_X714;
1785 case DevFmtX7144: return ChannelMask_X7144;
1786 case DevFmtAmbi3D:
1787 break;
1789 return ChannelMask_Stereo;
1792 SpatialAudioObjectRenderStreamActivationParams streamParams{};
1793 streamParams.ObjectFormat = &OutputType.Format;
1794 streamParams.StaticObjectTypeMask = getTypeMask(mDevice->FmtChans);
1795 streamParams.Category = AudioCategory_Media;
1796 streamParams.EventHandle = mNotifyEvent;
1798 PropVariant paramProp{};
1799 paramProp.setBlob({reinterpret_cast<BYTE*>(&streamParams), sizeof(streamParams)});
1801 hr = audio.mClient->ActivateSpatialAudioStream(paramProp.get(),
1802 __uuidof(ISpatialAudioObjectRenderStream), al::out_ptr(audio.mRender));
1803 if(FAILED(hr))
1805 ERR("Failed to activate spatial audio stream: 0x%08lx\n", hr);
1806 return false;
1809 audio.mStaticMask = streamParams.StaticObjectTypeMask;
1810 mFormat = OutputType;
1812 mDevice->FmtType = DevFmtFloat;
1813 mDevice->Flags.reset(DirectEar).set(Virtualization);
1814 if(streamParams.StaticObjectTypeMask == ChannelMask_Stereo)
1815 mDevice->FmtChans = DevFmtStereo;
1816 if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
1817 mDevice->Frequency = uint(OutputType.Format.nSamplesPerSec);
1818 else
1819 mDevice->Frequency = std::min(mDevice->Frequency,
1820 uint(OutputType.Format.nSamplesPerSec));
1822 setDefaultWFXChannelOrder();
1824 /* FIXME: Get the real update and buffer size. Presumably the actual device
1825 * is configured once ActivateSpatialAudioStream succeeds, and an
1826 * IAudioClient from the same IMMDevice accesses the same device
1827 * configuration. This isn't obviously correct, but for now assume
1828 * IAudioClient::GetDevicePeriod returns the current device period time
1829 * that ISpatialAudioObjectRenderStream will try to wake up at.
1831 * Unfortunately this won't get the buffer size of the
1832 * ISpatialAudioObjectRenderStream, so we only assume there's two periods.
1834 mOutUpdateSize = mDevice->UpdateSize;
1835 mOutBufferSize = mOutUpdateSize*2;
1836 ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
1838 ComPtr<IAudioClient> tmpClient;
1839 hr = sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
1840 al::out_ptr(tmpClient));
1841 if(FAILED(hr))
1842 ERR("Failed to activate audio client: 0x%08lx\n", hr);
1843 else
1845 hr = tmpClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(per_time), nullptr);
1846 if(FAILED(hr))
1847 ERR("Failed to get device period: 0x%08lx\n", hr);
1848 else
1850 mOutUpdateSize = RefTime2Samples(per_time, mFormat.Format.nSamplesPerSec);
1851 mOutBufferSize = mOutUpdateSize*2;
1854 tmpClient = nullptr;
1856 mDevice->UpdateSize = RefTime2Samples(per_time, mDevice->Frequency);
1857 mDevice->BufferSize = mDevice->UpdateSize*2;
1859 mResampler = nullptr;
1860 mResampleBuffer.clear();
1861 mResampleBuffer.shrink_to_fit();
1862 mBufferFilled = 0;
1863 if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
1865 const auto flags = as_unsigned(streamParams.StaticObjectTypeMask);
1866 const auto channelCount = as_unsigned(al::popcount(flags));
1867 mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType, channelCount,
1868 mDevice->Frequency, mFormat.Format.nSamplesPerSec, Resampler::FastBSinc24);
1869 mResampleBuffer.resize(size_t{mDevice->UpdateSize} * channelCount *
1870 mFormat.Format.wBitsPerSample / 8);
1872 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
1873 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1874 mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->Frequency,
1875 mDevice->UpdateSize);
1878 return true;
1881 bool WasapiPlayback::reset()
1883 HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
1884 if(FAILED(hr))
1885 throw al::backend_exception{al::backend_error::DeviceError, "0x%08lx", hr};
1886 return true;
1889 HRESULT WasapiPlayback::resetProxy()
1891 if(GetConfigValueBool(mDevice->mDeviceName, "wasapi", "spatial-api", false))
1893 if(initSpatial())
1894 return S_OK;
1897 mDevice->Flags.reset(Virtualization);
1899 auto &audio = mAudio.emplace<PlainDevice>();
1900 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
1901 al::out_ptr(audio.mClient))};
1902 if(FAILED(hr))
1904 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
1905 return hr;
1908 WAVEFORMATEX *wfx;
1909 hr = audio.mClient->GetMixFormat(&wfx);
1910 if(FAILED(hr))
1912 ERR("Failed to get mix format: 0x%08lx\n", hr);
1913 return hr;
1915 TraceFormat("Device mix format", wfx);
1917 WAVEFORMATEXTENSIBLE OutputType;
1918 if(!MakeExtensible(&OutputType, wfx))
1920 CoTaskMemFree(wfx);
1921 return E_FAIL;
1923 CoTaskMemFree(wfx);
1924 wfx = nullptr;
1926 const ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
1927 const ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
1929 prepareFormat(OutputType);
1931 TraceFormat("Requesting playback format", &OutputType.Format);
1932 hr = audio.mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
1933 if(FAILED(hr))
1935 WARN("Failed to check format support: 0x%08lx\n", hr);
1936 hr = audio.mClient->GetMixFormat(&wfx);
1938 if(FAILED(hr))
1940 ERR("Failed to find a supported format: 0x%08lx\n", hr);
1941 return hr;
1944 if(wfx != nullptr)
1946 TraceFormat("Got playback format", wfx);
1947 if(!MakeExtensible(&OutputType, wfx))
1949 CoTaskMemFree(wfx);
1950 return E_FAIL;
1952 CoTaskMemFree(wfx);
1953 wfx = nullptr;
1955 finalizeFormat(OutputType);
1957 mFormat = OutputType;
1959 #if !defined(ALSOFT_UWP)
1960 const EndpointFormFactor formfactor{GetDeviceFormfactor(mMMDev.get())};
1961 mDevice->Flags.set(DirectEar, (formfactor == Headphones || formfactor == Headset));
1962 #else
1963 mDevice->Flags.set(DirectEar, false);
1964 #endif
1965 setDefaultWFXChannelOrder();
1967 hr = audio.mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
1968 buf_time.count(), 0, &OutputType.Format, nullptr);
1969 if(FAILED(hr))
1971 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
1972 return hr;
1975 UINT32 buffer_len{};
1976 ReferenceTime min_per{};
1977 hr = audio.mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
1978 if(SUCCEEDED(hr))
1979 hr = audio.mClient->GetBufferSize(&buffer_len);
1980 if(FAILED(hr))
1982 ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
1983 return hr;
1986 hr = audio.mClient->SetEventHandle(mNotifyEvent);
1987 if(FAILED(hr))
1989 ERR("Failed to set event handle: 0x%08lx\n", hr);
1990 return hr;
1993 hr = audio.mClient->GetService(__uuidof(IAudioRenderClient), al::out_ptr(audio.mRender));
1994 if(FAILED(hr))
1996 ERR("Failed to get IAudioRenderClient: 0x%08lx\n", hr);
1997 return hr;
2000 /* Find the nearest multiple of the period size to the update size */
2001 if(min_per < per_time)
2002 min_per *= std::max<int64_t>((per_time + min_per/2) / min_per, 1_i64);
2004 mOutBufferSize = buffer_len;
2005 mOutUpdateSize = std::min(RefTime2Samples(min_per, mFormat.Format.nSamplesPerSec),
2006 buffer_len/2u);
2008 mDevice->BufferSize = static_cast<uint>(uint64_t{buffer_len} * mDevice->Frequency /
2009 mFormat.Format.nSamplesPerSec);
2010 mDevice->UpdateSize = std::min(RefTime2Samples(min_per, mDevice->Frequency),
2011 mDevice->BufferSize/2u);
2013 mResampler = nullptr;
2014 mResampleBuffer.clear();
2015 mResampleBuffer.shrink_to_fit();
2016 mBufferFilled = 0;
2017 if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
2019 mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType,
2020 mFormat.Format.nChannels, mDevice->Frequency, mFormat.Format.nSamplesPerSec,
2021 Resampler::FastBSinc24);
2022 mResampleBuffer.resize(size_t{mDevice->UpdateSize} * mFormat.Format.nChannels *
2023 mFormat.Format.wBitsPerSample / 8);
2025 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
2026 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2027 mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->Frequency,
2028 mDevice->UpdateSize);
2031 return hr;
2035 void WasapiPlayback::start()
2037 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
2038 if(FAILED(hr))
2039 throw al::backend_exception{al::backend_error::DeviceError,
2040 "Failed to start playback: 0x%lx", hr};
2043 HRESULT WasapiPlayback::startProxy()
2045 ResetEvent(mNotifyEvent);
2047 auto start_plain = [&](PlainDevice &audio) -> HRESULT
2049 HRESULT hr{audio.mClient->Start()};
2050 if(FAILED(hr))
2052 ERR("Failed to start audio client: 0x%08lx\n", hr);
2053 return hr;
2056 try {
2057 mKillNow.store(false, std::memory_order_release);
2058 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerProc), this};
2060 catch(...) {
2061 ERR("Failed to start thread\n");
2062 audio.mClient->Stop();
2063 hr = E_FAIL;
2065 return hr;
2067 auto start_spatial = [&](SpatialDevice &audio) -> HRESULT
2069 HRESULT hr{audio.mRender->Start()};
2070 if(FAILED(hr))
2072 ERR("Failed to start spatial audio stream: 0x%08lx\n", hr);
2073 return hr;
2076 try {
2077 mKillNow.store(false, std::memory_order_release);
2078 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerSpatialProc), this};
2080 catch(...) {
2081 ERR("Failed to start thread\n");
2082 hr = E_FAIL;
2085 if(FAILED(hr))
2087 audio.mRender->Stop();
2088 audio.mRender->Reset();
2090 return hr;
2093 return std::visit(overloaded{start_plain, start_spatial}, mAudio);
2097 void WasapiPlayback::stop()
2098 { pushMessage(MsgType::StopDevice).wait(); }
2100 void WasapiPlayback::stopProxy()
2102 if(!mThread.joinable())
2103 return;
2105 mKillNow.store(true, std::memory_order_release);
2106 mThread.join();
2108 auto stop_plain = [](PlainDevice &audio) -> void
2109 { audio.mClient->Stop(); };
2110 auto stop_spatial = [](SpatialDevice &audio) -> void
2112 audio.mRender->Stop();
2113 audio.mRender->Reset();
2115 std::visit(overloaded{stop_plain, stop_spatial}, mAudio);
2119 ClockLatency WasapiPlayback::getClockLatency()
2121 std::lock_guard<std::mutex> dlock{mMutex};
2122 ClockLatency ret{};
2123 ret.ClockTime = mDevice->getClockTime();
2124 ret.Latency = seconds{mPadding.load(std::memory_order_relaxed)};
2125 ret.Latency /= mFormat.Format.nSamplesPerSec;
2126 if(mResampler)
2128 auto extra = mResampler->currentInputDelay();
2129 ret.Latency += std::chrono::duration_cast<nanoseconds>(extra) / mDevice->Frequency;
2130 ret.Latency += nanoseconds{seconds{mBufferFilled}} / mDevice->Frequency;
2133 return ret;
2137 struct WasapiCapture final : public BackendBase, WasapiProxy {
2138 WasapiCapture(DeviceBase *device) noexcept : BackendBase{device} { }
2139 ~WasapiCapture() override;
2141 int recordProc();
2143 void open(std::string_view name) override;
2144 HRESULT openProxy(std::string_view name) override;
2145 void closeProxy() override;
2147 HRESULT resetProxy() override;
2148 void start() override;
2149 HRESULT startProxy() override;
2150 void stop() override;
2151 void stopProxy() override;
2153 void captureSamples(std::byte *buffer, uint samples) override;
2154 uint availableSamples() override;
2156 HRESULT mOpenStatus{E_FAIL};
2157 DeviceHandle mMMDev{nullptr};
2158 ComPtr<IAudioClient> mClient{nullptr};
2159 ComPtr<IAudioCaptureClient> mCapture{nullptr};
2160 HANDLE mNotifyEvent{nullptr};
2162 ChannelConverter mChannelConv{};
2163 SampleConverterPtr mSampleConv;
2164 RingBufferPtr mRing;
2166 std::atomic<bool> mKillNow{true};
2167 std::thread mThread;
2170 WasapiCapture::~WasapiCapture()
2172 if(SUCCEEDED(mOpenStatus))
2173 pushMessage(MsgType::CloseDevice).wait();
2174 mOpenStatus = E_FAIL;
2176 if(mNotifyEvent != nullptr)
2177 CloseHandle(mNotifyEvent);
2178 mNotifyEvent = nullptr;
2182 FORCE_ALIGN int WasapiCapture::recordProc()
2184 ComWrapper com{COINIT_MULTITHREADED};
2185 if(!com)
2187 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
2188 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
2189 return 1;
2192 althrd_setname(GetRecordThreadName());
2194 std::vector<float> samples;
2195 while(!mKillNow.load(std::memory_order_relaxed))
2197 UINT32 avail;
2198 HRESULT hr{mCapture->GetNextPacketSize(&avail)};
2199 if(FAILED(hr))
2200 ERR("Failed to get next packet size: 0x%08lx\n", hr);
2201 else if(avail > 0)
2203 UINT32 numsamples;
2204 DWORD flags;
2205 BYTE *rdata;
2207 hr = mCapture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
2208 if(FAILED(hr))
2209 ERR("Failed to get capture buffer: 0x%08lx\n", hr);
2210 else
2212 if(mChannelConv.is_active())
2214 samples.resize(numsamples*2_uz);
2215 mChannelConv.convert(rdata, samples.data(), numsamples);
2216 rdata = reinterpret_cast<BYTE*>(samples.data());
2219 auto data = mRing->getWriteVector();
2221 size_t dstframes;
2222 if(mSampleConv)
2224 static constexpr auto lenlimit = size_t{std::numeric_limits<int>::max()};
2225 const void *srcdata{rdata};
2226 uint srcframes{numsamples};
2228 dstframes = mSampleConv->convert(&srcdata, &srcframes, data[0].buf,
2229 static_cast<uint>(std::min(data[0].len, lenlimit)));
2230 if(srcframes > 0 && dstframes == data[0].len && data[1].len > 0)
2232 /* If some source samples remain, all of the first dest
2233 * block was filled, and there's space in the second
2234 * dest block, do another run for the second block.
2236 dstframes += mSampleConv->convert(&srcdata, &srcframes, data[1].buf,
2237 static_cast<uint>(std::min(data[1].len, lenlimit)));
2240 else
2242 const uint framesize{mDevice->frameSizeFromFmt()};
2243 auto dst = al::span{rdata, size_t{numsamples}*framesize};
2244 size_t len1{std::min(data[0].len, size_t{numsamples})};
2245 size_t len2{std::min(data[1].len, numsamples-len1)};
2247 memcpy(data[0].buf, dst.data(), len1*framesize);
2248 if(len2 > 0)
2250 dst = dst.subspan(len1*framesize);
2251 memcpy(data[1].buf, dst.data(), len2*framesize);
2253 dstframes = len1 + len2;
2256 mRing->writeAdvance(dstframes);
2258 hr = mCapture->ReleaseBuffer(numsamples);
2259 if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
2263 if(FAILED(hr))
2265 mDevice->handleDisconnect("Failed to capture samples: 0x%08lx", hr);
2266 break;
2269 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
2270 if(res != WAIT_OBJECT_0)
2271 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
2274 return 0;
2278 void WasapiCapture::open(std::string_view name)
2280 if(SUCCEEDED(mOpenStatus))
2281 throw al::backend_exception{al::backend_error::DeviceError,
2282 "Unexpected duplicate open call"};
2284 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
2285 if(mNotifyEvent == nullptr)
2287 ERR("Failed to create notify events: %lu\n", GetLastError());
2288 throw al::backend_exception{al::backend_error::DeviceError,
2289 "Failed to create notify events"};
2292 mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
2293 if(FAILED(mOpenStatus))
2294 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
2295 mOpenStatus};
2297 HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
2298 if(FAILED(hr))
2300 if(hr == E_OUTOFMEMORY)
2301 throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"};
2302 throw al::backend_exception{al::backend_error::DeviceError, "Device reset failed"};
2306 HRESULT WasapiCapture::openProxy(std::string_view name)
2308 std::string devname;
2309 std::wstring devid;
2310 if(!name.empty())
2312 auto devlock = DeviceListLock{gDeviceList};
2313 auto devlist = al::span{devlock.getCaptureList()};
2314 auto iter = std::find_if(devlist.cbegin(), devlist.cend(),
2315 [name](const DevMap &entry) -> bool
2316 { return entry.name == name || entry.endpoint_guid == name; });
2317 if(iter == devlist.cend())
2319 const std::wstring wname{utf8_to_wstr(name)};
2320 iter = std::find_if(devlist.cbegin(), devlist.cend(),
2321 [&wname](const DevMap &entry) -> bool
2322 { return entry.devid == wname; });
2324 if(iter == devlist.cend())
2326 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name), name.data());
2327 return E_FAIL;
2329 devname = iter->name;
2330 devid = iter->devid;
2333 HRESULT hr{sDeviceHelper->openDevice(devid, eCapture, mMMDev)};
2334 if(FAILED(hr))
2336 WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
2337 return hr;
2339 mClient = nullptr;
2340 if(!devname.empty())
2341 mDeviceName = std::move(devname);
2342 else
2343 mDeviceName = GetDeviceNameAndGuid(mMMDev).mName;
2345 return S_OK;
2348 void WasapiCapture::closeProxy()
2350 mCapture = nullptr;
2351 mClient = nullptr;
2352 mMMDev = nullptr;
2355 HRESULT WasapiCapture::resetProxy()
2357 mCapture = nullptr;
2358 mClient = nullptr;
2360 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
2361 al::out_ptr(mClient))};
2362 if(FAILED(hr))
2364 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
2365 return hr;
2368 WAVEFORMATEX *wfx;
2369 hr = mClient->GetMixFormat(&wfx);
2370 if(FAILED(hr))
2372 ERR("Failed to get capture format: 0x%08lx\n", hr);
2373 return hr;
2375 TraceFormat("Device capture format", wfx);
2377 WAVEFORMATEXTENSIBLE InputType{};
2378 if(!MakeExtensible(&InputType, wfx))
2380 CoTaskMemFree(wfx);
2381 return E_FAIL;
2383 CoTaskMemFree(wfx);
2384 wfx = nullptr;
2386 const bool isRear51{InputType.Format.nChannels == 6
2387 && (InputType.dwChannelMask&X51RearMask) == X5DOT1REAR};
2389 // Make sure buffer is at least 100ms in size
2390 ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
2391 buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}});
2393 InputType = {};
2394 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
2395 switch(mDevice->FmtChans)
2397 case DevFmtMono:
2398 InputType.Format.nChannels = 1;
2399 InputType.dwChannelMask = MONO;
2400 break;
2401 case DevFmtStereo:
2402 InputType.Format.nChannels = 2;
2403 InputType.dwChannelMask = STEREO;
2404 break;
2405 case DevFmtQuad:
2406 InputType.Format.nChannels = 4;
2407 InputType.dwChannelMask = QUAD;
2408 break;
2409 case DevFmtX51:
2410 InputType.Format.nChannels = 6;
2411 InputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
2412 break;
2413 case DevFmtX61:
2414 InputType.Format.nChannels = 7;
2415 InputType.dwChannelMask = X6DOT1;
2416 break;
2417 case DevFmtX71:
2418 InputType.Format.nChannels = 8;
2419 InputType.dwChannelMask = X7DOT1;
2420 break;
2421 case DevFmtX714:
2422 InputType.Format.nChannels = 12;
2423 InputType.dwChannelMask = X7DOT1DOT4;
2424 break;
2426 case DevFmtX7144:
2427 case DevFmtX3D71:
2428 case DevFmtAmbi3D:
2429 return E_FAIL;
2431 switch(mDevice->FmtType)
2433 /* NOTE: Signedness doesn't matter, the converter will handle it. */
2434 case DevFmtByte:
2435 case DevFmtUByte:
2436 InputType.Format.wBitsPerSample = 8;
2437 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2438 break;
2439 case DevFmtShort:
2440 case DevFmtUShort:
2441 InputType.Format.wBitsPerSample = 16;
2442 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2443 break;
2444 case DevFmtInt:
2445 case DevFmtUInt:
2446 InputType.Format.wBitsPerSample = 32;
2447 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2448 break;
2449 case DevFmtFloat:
2450 InputType.Format.wBitsPerSample = 32;
2451 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
2452 break;
2454 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
2455 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
2456 InputType.Format.nSamplesPerSec = mDevice->Frequency;
2458 InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
2459 InputType.Format.wBitsPerSample / 8);
2460 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
2461 InputType.Format.nBlockAlign;
2462 InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format);
2464 TraceFormat("Requesting capture format", &InputType.Format);
2465 hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, &wfx);
2466 if(FAILED(hr))
2468 WARN("Failed to check capture format support: 0x%08lx\n", hr);
2469 hr = mClient->GetMixFormat(&wfx);
2471 if(FAILED(hr))
2473 ERR("Failed to find a supported capture format: 0x%08lx\n", hr);
2474 return hr;
2477 mSampleConv = nullptr;
2478 mChannelConv = {};
2480 if(wfx != nullptr)
2482 TraceFormat("Got capture format", wfx);
2483 if(!MakeExtensible(&InputType, wfx))
2485 CoTaskMemFree(wfx);
2486 return E_FAIL;
2488 CoTaskMemFree(wfx);
2489 wfx = nullptr;
2491 auto validate_fmt = [](DeviceBase *device, uint32_t chancount, DWORD chanmask) noexcept
2492 -> bool
2494 switch(device->FmtChans)
2496 /* If the device wants mono, we can handle any input. */
2497 case DevFmtMono:
2498 return true;
2499 /* If the device wants stereo, we can handle mono or stereo input. */
2500 case DevFmtStereo:
2501 return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO))
2502 || (chancount == 1 && (chanmask&MonoMask) == MONO);
2503 /* Otherwise, the device must match the input type. */
2504 case DevFmtQuad:
2505 return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD));
2506 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
2507 case DevFmtX51:
2508 return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1
2509 || (chanmask&X51RearMask) == X5DOT1REAR));
2510 case DevFmtX61:
2511 return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1));
2512 case DevFmtX71:
2513 case DevFmtX3D71:
2514 return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1));
2515 case DevFmtX714:
2516 return (chancount == 12 && (chanmask == 0 || (chanmask&X714Mask) == X7DOT1DOT4));
2517 case DevFmtX7144:
2518 return (chancount == 16 && chanmask == 0);
2519 case DevFmtAmbi3D:
2520 return (chanmask == 0 && chancount == device->channelsFromFmt());
2522 return false;
2524 if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask))
2526 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
2527 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2528 mDevice->Frequency, InputType.dwChannelMask, InputType.Format.nChannels,
2529 (InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample,
2530 InputType.Format.nSamplesPerSec);
2531 return E_FAIL;
2535 DevFmtType srcType{};
2536 if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
2538 if(InputType.Format.wBitsPerSample == 8)
2539 srcType = DevFmtUByte;
2540 else if(InputType.Format.wBitsPerSample == 16)
2541 srcType = DevFmtShort;
2542 else if(InputType.Format.wBitsPerSample == 32)
2543 srcType = DevFmtInt;
2544 else
2546 ERR("Unhandled integer bit depth: %d\n", InputType.Format.wBitsPerSample);
2547 return E_FAIL;
2550 else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
2552 if(InputType.Format.wBitsPerSample == 32)
2553 srcType = DevFmtFloat;
2554 else
2556 ERR("Unhandled float bit depth: %d\n", InputType.Format.wBitsPerSample);
2557 return E_FAIL;
2560 else
2562 ERR("Unhandled format sub-type: %s\n", GuidPrinter{InputType.SubFormat}.c_str());
2563 return E_FAIL;
2566 if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1)
2568 uint chanmask{(1u<<InputType.Format.nChannels) - 1u};
2569 /* Exclude LFE from the downmix. */
2570 if((InputType.dwChannelMask&SPEAKER_LOW_FREQUENCY))
2572 constexpr auto lfemask = MaskFromTopBits(SPEAKER_LOW_FREQUENCY);
2573 const int lfeidx{al::popcount(InputType.dwChannelMask&lfemask) - 1};
2574 chanmask &= ~(1u << lfeidx);
2577 mChannelConv = ChannelConverter{srcType, InputType.Format.nChannels, chanmask,
2578 mDevice->FmtChans};
2579 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType));
2580 /* The channel converter always outputs float, so change the input type
2581 * for the resampler/type-converter.
2583 srcType = DevFmtFloat;
2585 else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1)
2587 mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans};
2588 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
2589 srcType = DevFmtFloat;
2592 if(mDevice->Frequency != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType)
2594 mSampleConv = SampleConverter::Create(srcType, mDevice->FmtType,
2595 mDevice->channelsFromFmt(), InputType.Format.nSamplesPerSec, mDevice->Frequency,
2596 Resampler::FastBSinc24);
2597 if(!mSampleConv)
2599 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2600 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2601 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
2602 return E_FAIL;
2604 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2605 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2606 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
2609 hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
2610 buf_time.count(), 0, &InputType.Format, nullptr);
2611 if(FAILED(hr))
2613 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
2614 return hr;
2617 hr = mClient->GetService(__uuidof(IAudioCaptureClient), al::out_ptr(mCapture));
2618 if(FAILED(hr))
2620 ERR("Failed to get IAudioCaptureClient: 0x%08lx\n", hr);
2621 return hr;
2624 UINT32 buffer_len{};
2625 ReferenceTime min_per{};
2626 hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
2627 if(SUCCEEDED(hr))
2628 hr = mClient->GetBufferSize(&buffer_len);
2629 if(FAILED(hr))
2631 ERR("Failed to get buffer size: 0x%08lx\n", hr);
2632 return hr;
2634 mDevice->UpdateSize = RefTime2Samples(min_per, mDevice->Frequency);
2635 mDevice->BufferSize = buffer_len;
2637 mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false);
2639 hr = mClient->SetEventHandle(mNotifyEvent);
2640 if(FAILED(hr))
2642 ERR("Failed to set event handle: 0x%08lx\n", hr);
2643 return hr;
2646 return hr;
2650 void WasapiCapture::start()
2652 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
2653 if(FAILED(hr))
2654 throw al::backend_exception{al::backend_error::DeviceError,
2655 "Failed to start recording: 0x%lx", hr};
2658 HRESULT WasapiCapture::startProxy()
2660 ResetEvent(mNotifyEvent);
2662 HRESULT hr{mClient->Start()};
2663 if(FAILED(hr))
2665 ERR("Failed to start audio client: 0x%08lx\n", hr);
2666 return hr;
2669 try {
2670 mKillNow.store(false, std::memory_order_release);
2671 mThread = std::thread{std::mem_fn(&WasapiCapture::recordProc), this};
2673 catch(...) {
2674 ERR("Failed to start thread\n");
2675 mClient->Stop();
2676 mClient->Reset();
2677 hr = E_FAIL;
2680 return hr;
2684 void WasapiCapture::stop()
2685 { pushMessage(MsgType::StopDevice).wait(); }
2687 void WasapiCapture::stopProxy()
2689 if(!mThread.joinable())
2690 return;
2692 mKillNow.store(true, std::memory_order_release);
2693 mThread.join();
2695 mClient->Stop();
2696 mClient->Reset();
2700 void WasapiCapture::captureSamples(std::byte *buffer, uint samples)
2701 { std::ignore = mRing->read(buffer, samples); }
2703 uint WasapiCapture::availableSamples()
2704 { return static_cast<uint>(mRing->readSpace()); }
2706 } // namespace
2709 bool WasapiBackendFactory::init()
2711 static HRESULT InitResult{E_FAIL};
2712 if(FAILED(InitResult)) try
2714 std::promise<HRESULT> promise;
2715 auto future = promise.get_future();
2717 std::thread{&WasapiProxy::messageHandler, &promise}.detach();
2718 InitResult = future.get();
2720 catch(...) {
2723 return SUCCEEDED(InitResult);
2726 bool WasapiBackendFactory::querySupport(BackendType type)
2727 { return type == BackendType::Playback || type == BackendType::Capture; }
2729 auto WasapiBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
2731 std::vector<std::string> outnames;
2733 auto devlock = DeviceListLock{gDeviceList};
2734 switch(type)
2736 case BackendType::Playback:
2738 auto defaultId = devlock.getPlaybackDefaultId();
2739 for(const DevMap &entry : devlock.getPlaybackList())
2741 if(entry.devid != defaultId)
2743 outnames.emplace_back(entry.name);
2744 continue;
2746 /* Default device goes first. */
2747 outnames.emplace(outnames.cbegin(), entry.name);
2750 break;
2752 case BackendType::Capture:
2754 auto defaultId = devlock.getCaptureDefaultId();
2755 for(const DevMap &entry : devlock.getCaptureList())
2757 if(entry.devid != defaultId)
2759 outnames.emplace_back(entry.name);
2760 continue;
2762 outnames.emplace(outnames.cbegin(), entry.name);
2765 break;
2768 return outnames;
2771 BackendPtr WasapiBackendFactory::createBackend(DeviceBase *device, BackendType type)
2773 if(type == BackendType::Playback)
2774 return BackendPtr{new WasapiPlayback{device}};
2775 if(type == BackendType::Capture)
2776 return BackendPtr{new WasapiCapture{device}};
2777 return nullptr;
2780 BackendFactory &WasapiBackendFactory::getFactory()
2782 static WasapiBackendFactory factory{};
2783 return factory;
2786 alc::EventSupport WasapiBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
2788 switch(eventType)
2790 case alc::EventType::DefaultDeviceChanged:
2791 return alc::EventSupport::FullSupport;
2793 case alc::EventType::DeviceAdded:
2794 case alc::EventType::DeviceRemoved:
2795 #if !defined(ALSOFT_UWP)
2796 return alc::EventSupport::FullSupport;
2797 #endif
2799 case alc::EventType::Count:
2800 break;
2802 return alc::EventSupport::NoSupport;