Improve formatting for setting the UWP default device callback
[openal-soft.git] / alc / backends / wasapi.cpp
blob32e4dbd7382127796ba8ff756fd0a4d96137aad0
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 auto ps = ComPtr<IPropertyStore>{};
350 auto hr = device->OpenPropertyStore(STGM_READ, al::out_ptr(ps));
351 if(FAILED(hr))
353 WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
354 return NameGUIDPair{std::string{UnknownName}, std::string{UnknownGuid}};
357 auto ret = NameGUIDPair{};
358 auto pvprop = PropVariant{};
359 hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(DEVPKEY_Device_FriendlyName), pvprop.get());
360 if(FAILED(hr))
361 WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr);
362 else if(pvprop.type() == VT_LPWSTR)
363 ret.mName = wstr_to_utf8(pvprop.value<std::wstring_view>());
364 else
365 WARN("Unexpected Device_FriendlyName PROPVARIANT type: 0x%04x\n", pvprop.type());
367 pvprop.clear();
368 hr = ps->GetValue(al::bit_cast<PROPERTYKEY>(PKEY_AudioEndpoint_GUID), pvprop.get());
369 if(FAILED(hr))
370 WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr);
371 else if(pvprop.type() == VT_LPWSTR)
372 ret.mGuid = wstr_to_utf8(pvprop.value<std::wstring_view>());
373 else
374 WARN("Unexpected AudioEndpoint_GUID PROPVARIANT type: 0x%04x\n", pvprop.type());
375 #else
376 auto ret = NameGUIDPair{wstr_to_utf8(device.Name()), {}};
378 // device->Id is DeviceInterfacePath: \\?\SWD#MMDEVAPI#{0.0.0.00000000}.{a21c17a0-fc1d-405e-ab5a-b513422b57d1}#{e6327cad-dcec-4949-ae8a-991e976a79d2}
379 auto devIfPath = device.Id();
380 if(auto devIdStart = wcsstr(devIfPath.data(), L"}."))
382 devIdStart += 2; // L"}."
383 if(auto devIdStartEnd = wcschr(devIdStart, L'#'))
385 ret.mGuid = wstr_to_utf8(std::wstring_view{devIdStart, devIdStartEnd});
386 std::transform(ret.mGuid.begin(), ret.mGuid.end(), ret.mGuid.begin(),
387 [](char ch) { return static_cast<char>(std::toupper(ch)); });
390 #endif
391 if(ret.mName.empty()) ret.mName = UnknownName;
392 if(ret.mGuid.empty()) ret.mGuid = UnknownGuid;
393 return ret;
395 #if !defined(ALSOFT_UWP)
396 EndpointFormFactor GetDeviceFormfactor(IMMDevice *device)
398 ComPtr<IPropertyStore> ps;
399 HRESULT hr{device->OpenPropertyStore(STGM_READ, al::out_ptr(ps))};
400 if(FAILED(hr))
402 WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
403 return UnknownFormFactor;
406 EndpointFormFactor formfactor{UnknownFormFactor};
407 PropVariant pvform;
408 hr = ps->GetValue(PKEY_AudioEndpoint_FormFactor, pvform.get());
409 if(FAILED(hr))
410 WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr);
411 else if(pvform.type() == VT_UI4)
412 formfactor = static_cast<EndpointFormFactor>(pvform.value<uint>());
413 else if(pvform.type() != VT_EMPTY)
414 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform.type());
415 return formfactor;
417 #endif
420 #if defined(ALSOFT_UWP)
421 struct DeviceHelper final : public IActivateAudioInterfaceCompletionHandler
422 #else
423 struct DeviceHelper final : private IMMNotificationClient
424 #endif
426 #if defined(ALSOFT_UWP)
427 DeviceHelper()
429 /* TODO: UWP also needs to watch for device added/removed events and
430 * dynamically add/remove devices from the lists.
432 mActiveClientEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
434 static constexpr auto playback_cb = [](const IInspectable &sender [[maybe_unused]],
435 const DefaultAudioRenderDeviceChangedEventArgs &args)
437 if(args.Role() == AudioDeviceRole::Default)
439 const auto msg = std::string{"Default playback device changed: " +
440 wstr_to_utf8(args.Id())};
441 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
444 mRenderDeviceChangedToken = MediaDevice::DefaultAudioRenderDeviceChanged(playback_cb);
446 static constexpr auto capture_cb = [](const IInspectable &sender [[maybe_unused]],
447 const DefaultAudioRenderDeviceChangedEventArgs &args)
449 if(args.Role() == AudioDeviceRole::Default)
451 const auto msg = std::string{"Default capture device changed: " +
452 wstr_to_utf8(args.Id())};
453 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
456 mCaptureDeviceChangedToken = MediaDevice::DefaultAudioCaptureDeviceChanged(capture_cb);
458 #else
459 DeviceHelper() = default;
460 #endif
461 ~DeviceHelper()
463 #if defined(ALSOFT_UWP)
464 MediaDevice::DefaultAudioRenderDeviceChanged(mRenderDeviceChangedToken);
465 MediaDevice::DefaultAudioCaptureDeviceChanged(mCaptureDeviceChangedToken);
467 if(mActiveClientEvent != nullptr)
468 CloseHandle(mActiveClientEvent);
469 mActiveClientEvent = nullptr;
470 #else
471 if(mEnumerator)
472 mEnumerator->UnregisterEndpointNotificationCallback(this);
473 mEnumerator = nullptr;
474 #endif
477 template<typename T>
478 auto as() noexcept -> T { return T{this}; }
480 /** -------------------------- IUnknown ----------------------------- */
481 std::atomic<ULONG> mRefCount{1};
482 STDMETHODIMP_(ULONG) AddRef() noexcept override { return mRefCount.fetch_add(1u) + 1u; }
483 STDMETHODIMP_(ULONG) Release() noexcept override { return mRefCount.fetch_sub(1u) - 1u; }
485 STDMETHODIMP QueryInterface(const IID& IId, void **UnknownPtrPtr) noexcept override
487 // Three rules of QueryInterface:
488 // https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface
489 // 1. Objects must have identity.
490 // 2. The set of interfaces on an object instance must be static.
491 // 3. It must be possible to query successfully for any interface on an object from any other interface.
493 // If ppvObject(the address) is nullptr, then this method returns E_POINTER.
494 if(!UnknownPtrPtr)
495 return E_POINTER;
497 // https://docs.microsoft.com/en-us/windows/win32/com/implementing-reference-counting
498 // Whenever a client calls a method(or API function), such as QueryInterface, that returns a new interface
499 // pointer, the method being called is responsible for incrementing the reference count through the returned
500 // pointer. For example, when a client first creates an object, it receives an interface pointer to an object
501 // that, from the client's point of view, has a reference count of one. If the client then calls AddRef on the
502 // interface pointer, the reference count becomes two. The client must call Release twice on the interface
503 // pointer to drop all of its references to the object.
504 #if defined(ALSOFT_UWP)
505 if(IId == __uuidof(IActivateAudioInterfaceCompletionHandler))
507 *UnknownPtrPtr = as<IActivateAudioInterfaceCompletionHandler*>();
508 AddRef();
509 return S_OK;
511 #else
512 if(IId == __uuidof(IMMNotificationClient))
514 *UnknownPtrPtr = as<IMMNotificationClient*>();
515 AddRef();
516 return S_OK;
518 #endif
519 else if(IId == __uuidof(IAgileObject) || IId == __uuidof(IUnknown))
521 *UnknownPtrPtr = as<IUnknown*>();
522 AddRef();
523 return S_OK;
526 // This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise.
527 *UnknownPtrPtr = nullptr;
528 return E_NOINTERFACE;
531 #if defined(ALSOFT_UWP)
532 /** ----------------------- IActivateAudioInterfaceCompletionHandler ------------ */
533 HRESULT ActivateCompleted(IActivateAudioInterfaceAsyncOperation*) override
535 SetEvent(mActiveClientEvent);
537 // Need to return S_OK
538 return S_OK;
540 #else
541 /** ----------------------- IMMNotificationClient ------------ */
542 STDMETHODIMP OnDeviceStateChanged(LPCWSTR /*pwstrDeviceId*/, DWORD /*dwNewState*/) noexcept override { return S_OK; }
544 STDMETHODIMP OnDeviceAdded(LPCWSTR pwstrDeviceId) noexcept override
546 ComPtr<IMMDevice> device;
547 HRESULT hr{mEnumerator->GetDevice(pwstrDeviceId, al::out_ptr(device))};
548 if(FAILED(hr))
550 ERR("Failed to get device: 0x%08lx\n", hr);
551 return S_OK;
554 ComPtr<IMMEndpoint> endpoint;
555 hr = device->QueryInterface(__uuidof(IMMEndpoint), al::out_ptr(endpoint));
556 if(FAILED(hr))
558 ERR("Failed to get device endpoint: 0x%08lx\n", hr);
559 return S_OK;
562 EDataFlow flowdir{};
563 hr = endpoint->GetDataFlow(&flowdir);
564 if(FAILED(hr))
566 ERR("Failed to get endpoint data flow: 0x%08lx\n", hr);
567 return S_OK;
570 auto devlock = DeviceListLock{gDeviceList};
571 auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
573 if(AddDevice(device, pwstrDeviceId, list))
575 const auto devtype = (flowdir==eRender) ? alc::DeviceType::Playback
576 : alc::DeviceType::Capture;
577 const std::string msg{"Device added: "+list.back().name};
578 alc::Event(alc::EventType::DeviceAdded, devtype, msg);
581 return S_OK;
584 STDMETHODIMP OnDeviceRemoved(LPCWSTR pwstrDeviceId) noexcept override
586 auto devlock = DeviceListLock{gDeviceList};
587 for(auto flowdir : std::array{eRender, eCapture})
589 auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
590 auto devtype = (flowdir==eRender)?alc::DeviceType::Playback : alc::DeviceType::Capture;
592 /* Find the ID in the list to remove. */
593 auto iter = std::find_if(list.begin(), list.end(),
594 [pwstrDeviceId](const DevMap &entry) noexcept
595 { return pwstrDeviceId == entry.devid; });
596 if(iter == list.end()) continue;
598 TRACE("Removing device \"%s\", \"%s\", \"%ls\"\n", iter->name.c_str(),
599 iter->endpoint_guid.c_str(), iter->devid.c_str());
601 std::string msg{"Device removed: "+std::move(iter->name)};
602 list.erase(iter);
604 alc::Event(alc::EventType::DeviceRemoved, devtype, msg);
606 return S_OK;
609 /* NOLINTNEXTLINE(clazy-function-args-by-ref) */
610 STDMETHODIMP OnPropertyValueChanged(LPCWSTR /*pwstrDeviceId*/, const PROPERTYKEY /*key*/) noexcept override { return S_OK; }
612 STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) noexcept override
614 if(role != eMultimedia)
615 return S_OK;
617 const std::wstring_view devid{pwstrDefaultDeviceId ? pwstrDefaultDeviceId
618 : std::wstring_view{}};
619 if(flow == eRender)
621 DeviceListLock{gDeviceList}.setPlaybackDefaultId(devid);
622 const std::string msg{"Default playback device changed: " + wstr_to_utf8(devid)};
623 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
625 else if(flow == eCapture)
627 DeviceListLock{gDeviceList}.setCaptureDefaultId(devid);
628 const std::string msg{"Default capture device changed: " + wstr_to_utf8(devid)};
629 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
631 return S_OK;
633 #endif
635 /** -------------------------- DeviceHelper ----------------------------- */
636 HRESULT init()
638 #if !defined(ALSOFT_UWP)
639 HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
640 __uuidof(IMMDeviceEnumerator), al::out_ptr(mEnumerator))};
641 if(SUCCEEDED(hr))
642 mEnumerator->RegisterEndpointNotificationCallback(this);
643 else
644 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
645 return hr;
646 #else
647 return S_OK;
648 #endif
651 HRESULT openDevice(std::wstring_view devid, EDataFlow flow, DeviceHandle& device)
653 #if !defined(ALSOFT_UWP)
654 HRESULT hr{E_FAIL};
655 if(mEnumerator)
657 if(devid.empty())
658 hr = mEnumerator->GetDefaultAudioEndpoint(flow, eMultimedia, al::out_ptr(device));
659 else
660 hr = mEnumerator->GetDevice(devid.data(), al::out_ptr(device));
662 return hr;
663 #else
664 const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
665 auto devIfPath =
666 devid.empty() ? (flow == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole) : MediaDevice::GetDefaultAudioCaptureId(deviceRole))
667 : winrt::hstring(devid.data());
668 if (devIfPath.empty())
669 return E_POINTER;
671 auto&& deviceInfo = DeviceInformation::CreateFromIdAsync(devIfPath, nullptr, DeviceInformationKind::DeviceInterface).get();
672 if (!deviceInfo)
673 return E_NOINTERFACE;
674 device = deviceInfo;
675 return S_OK;
676 #endif
679 #if !defined(ALSOFT_UWP)
680 static HRESULT activateAudioClient(_In_ DeviceHandle &device, REFIID iid, void **ppv)
681 { return device->Activate(iid, CLSCTX_INPROC_SERVER, nullptr, ppv); }
682 #else
683 HRESULT activateAudioClient(_In_ DeviceHandle &device, _In_ REFIID iid, void **ppv)
685 ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
686 HRESULT hr{ActivateAudioInterfaceAsync(device.Id().data(), iid, nullptr, this,
687 al::out_ptr(asyncOp))};
688 if(FAILED(hr))
689 return hr;
691 /* I don't like waiting for INFINITE time, but the activate operation
692 * can take an indefinite amount of time since it can require user
693 * input.
695 DWORD res{WaitForSingleObjectEx(mActiveClientEvent, INFINITE, FALSE)};
696 if(res != WAIT_OBJECT_0)
698 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
699 return E_FAIL;
702 HRESULT hrActivateRes{E_FAIL};
703 ComPtr<IUnknown> punkAudioIface;
704 hr = asyncOp->GetActivateResult(&hrActivateRes, al::out_ptr(punkAudioIface));
705 if(SUCCEEDED(hr)) hr = hrActivateRes;
706 if(FAILED(hr)) return hr;
708 return punkAudioIface->QueryInterface(iid, ppv);
710 #endif
712 std::wstring probeDevices(EDataFlow flowdir, std::vector<DevMap> &list)
714 std::wstring defaultId;
715 std::vector<DevMap>{}.swap(list);
717 #if !defined(ALSOFT_UWP)
718 ComPtr<IMMDeviceCollection> coll;
719 HRESULT hr{mEnumerator->EnumAudioEndpoints(flowdir, DEVICE_STATE_ACTIVE,
720 al::out_ptr(coll))};
721 if(FAILED(hr))
723 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr);
724 return defaultId;
727 UINT count{0};
728 hr = coll->GetCount(&count);
729 if(SUCCEEDED(hr) && count > 0)
730 list.reserve(count);
732 ComPtr<IMMDevice> device;
733 hr = mEnumerator->GetDefaultAudioEndpoint(flowdir, eMultimedia, al::out_ptr(device));
734 if(SUCCEEDED(hr))
736 if(WCHAR *devid{GetDeviceId(device.get())})
738 defaultId = devid;
739 CoTaskMemFree(devid);
741 device = nullptr;
744 for(UINT i{0};i < count;++i)
746 hr = coll->Item(i, al::out_ptr(device));
747 if(FAILED(hr))
748 continue;
750 if(WCHAR *devid{GetDeviceId(device.get())})
752 std::ignore = AddDevice(device, devid, list);
753 CoTaskMemFree(devid);
755 device = nullptr;
757 #else
758 const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
759 auto DefaultAudioId = flowdir == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole)
760 : MediaDevice::GetDefaultAudioCaptureId(deviceRole);
761 if(!DefaultAudioId.empty())
763 auto deviceInfo = DeviceInformation::CreateFromIdAsync(DefaultAudioId, nullptr,
764 DeviceInformationKind::DeviceInterface).get();
765 if(deviceInfo)
766 defaultId = deviceInfo.Id().data();
769 // Get the string identifier of the audio renderer
770 auto AudioSelector = flowdir == eRender ? MediaDevice::GetAudioRenderSelector() : MediaDevice::GetAudioCaptureSelector();
772 // Setup the asynchronous callback
773 auto&& DeviceInfoCollection = DeviceInformation::FindAllAsync(AudioSelector, /*PropertyList*/nullptr, DeviceInformationKind::DeviceInterface).get();
774 if(DeviceInfoCollection)
776 try {
777 auto deviceCount = DeviceInfoCollection.Size();
778 for(unsigned int i{0};i < deviceCount;++i)
780 auto deviceInfo = DeviceInfoCollection.GetAt(i);
781 if(deviceInfo)
782 std::ignore = AddDevice(deviceInfo, deviceInfo.Id().data(), list);
785 catch (const winrt::hresult_error& /*ex*/) {
788 #endif
790 return defaultId;
793 private:
794 static bool AddDevice(const DeviceHandle &device, const WCHAR *devid, std::vector<DevMap> &list)
796 for(auto &entry : list)
798 if(entry.devid == devid)
799 return false;
802 auto name_guid = GetDeviceNameAndGuid(device);
803 int count{1};
804 std::string newname{name_guid.mName};
805 while(checkName(list, newname))
807 newname = name_guid.mName;
808 newname += " #";
809 newname += std::to_string(++count);
811 list.emplace_back(std::move(newname), std::move(name_guid.mGuid), devid);
812 const DevMap &newentry = list.back();
814 TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry.name.c_str(),
815 newentry.endpoint_guid.c_str(), newentry.devid.c_str());
816 return true;
819 #if !defined(ALSOFT_UWP)
820 static WCHAR *GetDeviceId(IMMDevice *device)
822 WCHAR *devid;
824 const HRESULT hr{device->GetId(&devid)};
825 if(FAILED(hr))
827 ERR("Failed to get device id: %lx\n", hr);
828 return nullptr;
831 return devid;
833 ComPtr<IMMDeviceEnumerator> mEnumerator{nullptr};
835 #else
837 HANDLE mActiveClientEvent{nullptr};
839 EventRegistrationToken mRenderDeviceChangedToken;
840 EventRegistrationToken mCaptureDeviceChangedToken;
841 #endif
844 bool MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in)
846 *out = WAVEFORMATEXTENSIBLE{};
847 if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
849 *out = *CONTAINING_RECORD(in, const WAVEFORMATEXTENSIBLE, Format);
850 out->Format.cbSize = sizeof(*out) - sizeof(out->Format);
852 else if(in->wFormatTag == WAVE_FORMAT_PCM)
854 out->Format = *in;
855 out->Format.cbSize = 0;
856 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
857 out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
858 if(out->Format.nChannels == 1)
859 out->dwChannelMask = MONO;
860 else if(out->Format.nChannels == 2)
861 out->dwChannelMask = STEREO;
862 else
863 ERR("Unhandled PCM channel count: %d\n", out->Format.nChannels);
864 out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
866 else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
868 out->Format = *in;
869 out->Format.cbSize = 0;
870 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
871 out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
872 if(out->Format.nChannels == 1)
873 out->dwChannelMask = MONO;
874 else if(out->Format.nChannels == 2)
875 out->dwChannelMask = STEREO;
876 else
877 ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels);
878 out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
880 else
882 ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag);
883 return false;
885 return true;
888 void TraceFormat(const char *msg, const WAVEFORMATEX *format)
890 constexpr size_t fmtex_extra_size{sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)};
891 if(format->wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->cbSize >= fmtex_extra_size)
893 const WAVEFORMATEXTENSIBLE *fmtex{
894 CONTAINING_RECORD(format, const WAVEFORMATEXTENSIBLE, Format)};
895 /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
896 TRACE("%s:\n"
897 " FormatTag = 0x%04x\n"
898 " Channels = %d\n"
899 " SamplesPerSec = %lu\n"
900 " AvgBytesPerSec = %lu\n"
901 " BlockAlign = %d\n"
902 " BitsPerSample = %d\n"
903 " Size = %d\n"
904 " Samples = %d\n"
905 " ChannelMask = 0x%lx\n"
906 " SubFormat = %s\n",
907 msg, fmtex->Format.wFormatTag, fmtex->Format.nChannels, fmtex->Format.nSamplesPerSec,
908 fmtex->Format.nAvgBytesPerSec, fmtex->Format.nBlockAlign, fmtex->Format.wBitsPerSample,
909 fmtex->Format.cbSize, fmtex->Samples.wReserved, fmtex->dwChannelMask,
910 GuidPrinter{fmtex->SubFormat}.c_str());
911 /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
913 else
914 TRACE("%s:\n"
915 " FormatTag = 0x%04x\n"
916 " Channels = %d\n"
917 " SamplesPerSec = %lu\n"
918 " AvgBytesPerSec = %lu\n"
919 " BlockAlign = %d\n"
920 " BitsPerSample = %d\n"
921 " Size = %d\n",
922 msg, format->wFormatTag, format->nChannels, format->nSamplesPerSec,
923 format->nAvgBytesPerSec, format->nBlockAlign, format->wBitsPerSample, format->cbSize);
927 enum class MsgType {
928 OpenDevice,
929 ResetDevice,
930 StartDevice,
931 StopDevice,
932 CloseDevice,
934 QuitThread
937 constexpr const char *GetMessageTypeName(MsgType type) noexcept
939 switch(type)
941 case MsgType::OpenDevice: return "Open Device";
942 case MsgType::ResetDevice: return "Reset Device";
943 case MsgType::StartDevice: return "Start Device";
944 case MsgType::StopDevice: return "Stop Device";
945 case MsgType::CloseDevice: return "Close Device";
946 case MsgType::QuitThread: break;
948 return "";
952 /* Proxy interface used by the message handler. */
953 struct WasapiProxy {
954 WasapiProxy() = default;
955 WasapiProxy(const WasapiProxy&) = delete;
956 WasapiProxy(WasapiProxy&&) = delete;
957 virtual ~WasapiProxy() = default;
959 void operator=(const WasapiProxy&) = delete;
960 void operator=(WasapiProxy&&) = delete;
962 virtual HRESULT openProxy(std::string_view name) = 0;
963 virtual void closeProxy() = 0;
965 virtual HRESULT resetProxy() = 0;
966 virtual HRESULT startProxy() = 0;
967 virtual void stopProxy() = 0;
969 struct Msg {
970 MsgType mType;
971 WasapiProxy *mProxy;
972 std::string_view mParam;
973 std::promise<HRESULT> mPromise;
975 explicit operator bool() const noexcept { return mType != MsgType::QuitThread; }
977 static inline std::deque<Msg> mMsgQueue;
978 static inline std::mutex mMsgQueueLock;
979 static inline std::condition_variable mMsgQueueCond;
980 static inline DWORD sAvIndex{};
982 static inline std::optional<DeviceHelper> sDeviceHelper;
984 std::future<HRESULT> pushMessage(MsgType type, std::string_view param={})
986 std::promise<HRESULT> promise;
987 std::future<HRESULT> future{promise.get_future()};
989 std::lock_guard<std::mutex> msglock{mMsgQueueLock};
990 mMsgQueue.emplace_back(Msg{type, this, param, std::move(promise)});
992 mMsgQueueCond.notify_one();
993 return future;
996 static std::future<HRESULT> pushMessageStatic(MsgType type)
998 std::promise<HRESULT> promise;
999 std::future<HRESULT> future{promise.get_future()};
1001 std::lock_guard<std::mutex> msglock{mMsgQueueLock};
1002 mMsgQueue.emplace_back(Msg{type, nullptr, {}, std::move(promise)});
1004 mMsgQueueCond.notify_one();
1005 return future;
1008 static Msg popMessage()
1010 std::unique_lock<std::mutex> lock{mMsgQueueLock};
1011 mMsgQueueCond.wait(lock, []{return !mMsgQueue.empty();});
1012 Msg msg{std::move(mMsgQueue.front())};
1013 mMsgQueue.pop_front();
1014 return msg;
1017 static int messageHandler(std::promise<HRESULT> *promise);
1020 int WasapiProxy::messageHandler(std::promise<HRESULT> *promise)
1022 TRACE("Starting message thread\n");
1024 ComWrapper com{COINIT_MULTITHREADED};
1025 if(!com)
1027 WARN("Failed to initialize COM: 0x%08lx\n", com.status());
1028 promise->set_value(com.status());
1029 return 0;
1032 struct HelperResetter {
1033 HelperResetter() = default;
1034 HelperResetter(const HelperResetter&) = delete;
1035 auto operator=(const HelperResetter&) -> HelperResetter& = delete;
1036 ~HelperResetter() { sDeviceHelper.reset(); }
1038 HelperResetter scoped_watcher;
1040 HRESULT hr{sDeviceHelper.emplace().init()};
1041 promise->set_value(hr);
1042 promise = nullptr;
1043 if(FAILED(hr))
1044 return 0;
1047 auto devlock = DeviceListLock{gDeviceList};
1048 auto defaultId = sDeviceHelper->probeDevices(eRender, devlock.getPlaybackList());
1049 if(!defaultId.empty()) devlock.setPlaybackDefaultId(defaultId);
1050 defaultId = sDeviceHelper->probeDevices(eCapture, devlock.getCaptureList());
1051 if(!defaultId.empty()) devlock.setCaptureDefaultId(defaultId);
1054 TRACE("Starting message loop\n");
1055 while(Msg msg{popMessage()})
1057 TRACE("Got message \"%s\" (0x%04x, this=%p, param=\"%.*s\")\n",
1058 GetMessageTypeName(msg.mType), static_cast<uint>(msg.mType),
1059 static_cast<void*>(msg.mProxy), al::sizei(msg.mParam), msg.mParam.data());
1061 switch(msg.mType)
1063 case MsgType::OpenDevice:
1064 hr = msg.mProxy->openProxy(msg.mParam);
1065 msg.mPromise.set_value(hr);
1066 continue;
1068 case MsgType::ResetDevice:
1069 hr = msg.mProxy->resetProxy();
1070 msg.mPromise.set_value(hr);
1071 continue;
1073 case MsgType::StartDevice:
1074 hr = msg.mProxy->startProxy();
1075 msg.mPromise.set_value(hr);
1076 continue;
1078 case MsgType::StopDevice:
1079 msg.mProxy->stopProxy();
1080 msg.mPromise.set_value(S_OK);
1081 continue;
1083 case MsgType::CloseDevice:
1084 msg.mProxy->closeProxy();
1085 msg.mPromise.set_value(S_OK);
1086 continue;
1088 case MsgType::QuitThread:
1089 break;
1091 ERR("Unexpected message: %u\n", static_cast<uint>(msg.mType));
1092 msg.mPromise.set_value(E_FAIL);
1094 TRACE("Message loop finished\n");
1096 return 0;
1099 struct WasapiPlayback final : public BackendBase, WasapiProxy {
1100 WasapiPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
1101 ~WasapiPlayback() override;
1103 int mixerProc();
1104 int mixerSpatialProc();
1106 void open(std::string_view name) override;
1107 HRESULT openProxy(std::string_view name) override;
1108 void closeProxy() override;
1110 bool reset() override;
1111 HRESULT resetProxy() override;
1112 void start() override;
1113 HRESULT startProxy() override;
1114 void stop() override;
1115 void stopProxy() override;
1117 ClockLatency getClockLatency() override;
1119 void prepareFormat(WAVEFORMATEXTENSIBLE &OutputType);
1120 void finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType);
1122 auto initSpatial() -> bool;
1124 HRESULT mOpenStatus{E_FAIL};
1125 DeviceHandle mMMDev{nullptr};
1127 struct PlainDevice {
1128 ComPtr<IAudioClient> mClient{nullptr};
1129 ComPtr<IAudioRenderClient> mRender{nullptr};
1131 struct SpatialDevice {
1132 ComPtr<ISpatialAudioClient> mClient{nullptr};
1133 ComPtr<ISpatialAudioObjectRenderStream> mRender{nullptr};
1134 AudioObjectType mStaticMask{};
1136 std::variant<PlainDevice,SpatialDevice> mAudio{std::in_place_index_t<0>{}};
1137 HANDLE mNotifyEvent{nullptr};
1139 UINT32 mOutBufferSize{}, mOutUpdateSize{};
1140 std::vector<char> mResampleBuffer{};
1141 uint mBufferFilled{0};
1142 SampleConverterPtr mResampler;
1144 WAVEFORMATEXTENSIBLE mFormat{};
1145 std::atomic<UINT32> mPadding{0u};
1147 std::mutex mMutex;
1149 std::atomic<bool> mKillNow{true};
1150 std::thread mThread;
1153 WasapiPlayback::~WasapiPlayback()
1155 if(SUCCEEDED(mOpenStatus))
1156 pushMessage(MsgType::CloseDevice).wait();
1157 mOpenStatus = E_FAIL;
1159 if(mNotifyEvent != nullptr)
1160 CloseHandle(mNotifyEvent);
1161 mNotifyEvent = nullptr;
1165 FORCE_ALIGN int WasapiPlayback::mixerProc()
1167 ComWrapper com{COINIT_MULTITHREADED};
1168 if(!com)
1170 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
1171 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
1172 return 1;
1175 auto &audio = std::get<PlainDevice>(mAudio);
1177 SetRTPriority();
1178 althrd_setname(GetMixerThreadName());
1180 const uint frame_size{mFormat.Format.nChannels * mFormat.Format.wBitsPerSample / 8u};
1181 const uint update_size{mOutUpdateSize};
1182 const UINT32 buffer_len{mOutBufferSize};
1183 const void *resbufferptr{};
1185 #ifdef AVRTAPI
1186 /* TODO: "Audio" or "Pro Audio"? The suggestion is to use "Pro Audio" for
1187 * device periods less than 10ms, and "Audio" for greater than or equal to
1188 * 10ms.
1190 auto taskname = (update_size < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
1191 auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
1192 #endif
1194 mBufferFilled = 0;
1195 while(!mKillNow.load(std::memory_order_relaxed))
1197 UINT32 written;
1198 HRESULT hr{audio.mClient->GetCurrentPadding(&written)};
1199 if(FAILED(hr))
1201 ERR("Failed to get padding: 0x%08lx\n", hr);
1202 mDevice->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr);
1203 break;
1205 mPadding.store(written, std::memory_order_relaxed);
1207 uint len{buffer_len - written};
1208 if(len < update_size)
1210 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
1211 if(res != WAIT_OBJECT_0)
1212 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1213 continue;
1216 BYTE *buffer;
1217 hr = audio.mRender->GetBuffer(len, &buffer);
1218 if(SUCCEEDED(hr))
1220 if(mResampler)
1222 std::lock_guard<std::mutex> dlock{mMutex};
1223 auto dst = al::span{buffer, size_t{len}*frame_size};
1224 for(UINT32 done{0};done < len;)
1226 if(mBufferFilled == 0)
1228 mDevice->renderSamples(mResampleBuffer.data(), mDevice->UpdateSize,
1229 mFormat.Format.nChannels);
1230 resbufferptr = mResampleBuffer.data();
1231 mBufferFilled = mDevice->UpdateSize;
1234 uint got{mResampler->convert(&resbufferptr, &mBufferFilled, dst.data(),
1235 len-done)};
1236 dst = dst.subspan(size_t{got}*frame_size);
1237 done += got;
1239 mPadding.store(written + done, std::memory_order_relaxed);
1242 else
1244 std::lock_guard<std::mutex> dlock{mMutex};
1245 mDevice->renderSamples(buffer, len, mFormat.Format.nChannels);
1246 mPadding.store(written + len, std::memory_order_relaxed);
1248 hr = audio.mRender->ReleaseBuffer(len, 0);
1250 if(FAILED(hr))
1252 ERR("Failed to buffer data: 0x%08lx\n", hr);
1253 mDevice->handleDisconnect("Failed to send playback samples: 0x%08lx", hr);
1254 break;
1257 mPadding.store(0u, std::memory_order_release);
1259 return 0;
1262 FORCE_ALIGN int WasapiPlayback::mixerSpatialProc()
1264 ComWrapper com{COINIT_MULTITHREADED};
1265 if(!com)
1267 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
1268 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
1269 return 1;
1272 auto &audio = std::get<SpatialDevice>(mAudio);
1274 SetRTPriority();
1275 althrd_setname(GetMixerThreadName());
1277 std::vector<ComPtr<ISpatialAudioObject>> channels;
1278 std::vector<void*> buffers;
1279 std::vector<void*> resbuffers;
1280 std::vector<const void*> tmpbuffers;
1282 #ifdef AVRTAPI
1283 auto taskname = (mOutUpdateSize < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
1284 auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
1285 #endif
1287 /* TODO: Set mPadding appropriately. There doesn't seem to be a way to
1288 * update it dynamically based on the stream, so a fixed size may be the
1289 * best we can do.
1291 mPadding.store(mOutBufferSize-mOutUpdateSize, std::memory_order_release);
1293 mBufferFilled = 0;
1294 while(!mKillNow.load(std::memory_order_relaxed))
1296 if(DWORD res{WaitForSingleObjectEx(mNotifyEvent, 1000, FALSE)}; res != WAIT_OBJECT_0)
1298 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1300 HRESULT hr{audio.mRender->Reset()};
1301 if(FAILED(hr))
1303 ERR("ISpatialAudioObjectRenderStream::Reset failed: 0x%08lx\n", hr);
1304 mDevice->handleDisconnect("Device lost: 0x%08lx", hr);
1305 break;
1309 UINT32 dynamicCount{}, framesToDo{};
1310 HRESULT hr{audio.mRender->BeginUpdatingAudioObjects(&dynamicCount, &framesToDo)};
1311 if(SUCCEEDED(hr))
1313 if(channels.empty()) UNLIKELY
1315 auto flags = as_unsigned(audio.mStaticMask);
1316 channels.reserve(as_unsigned(al::popcount(flags)));
1317 while(flags)
1319 auto id = decltype(flags){1} << al::countr_zero(flags);
1320 flags &= ~id;
1322 channels.emplace_back();
1323 audio.mRender->ActivateSpatialAudioObject(static_cast<AudioObjectType>(id),
1324 al::out_ptr(channels.back()));
1326 buffers.resize(channels.size());
1327 if(mResampler)
1329 tmpbuffers.resize(buffers.size());
1330 resbuffers.resize(buffers.size());
1331 auto bufptr = mResampleBuffer.begin();
1332 for(size_t i{0};i < tmpbuffers.size();++i)
1334 resbuffers[i] = al::to_address(bufptr);
1335 bufptr += ptrdiff_t(mDevice->UpdateSize*sizeof(float));
1340 /* We have to call to get each channel's buffer individually every
1341 * update, unfortunately.
1343 std::transform(channels.cbegin(), channels.cend(), buffers.begin(),
1344 [](const ComPtr<ISpatialAudioObject> &obj) -> void*
1346 auto buffer = LPBYTE{};
1347 auto size = UINT32{};
1348 obj->GetBuffer(&buffer, &size);
1349 return buffer;
1352 if(!mResampler)
1353 mDevice->renderSamples(buffers, framesToDo);
1354 else
1356 std::lock_guard<std::mutex> dlock{mMutex};
1357 for(UINT32 pos{0};pos < framesToDo;)
1359 if(mBufferFilled == 0)
1361 mDevice->renderSamples(resbuffers, mDevice->UpdateSize);
1362 std::copy(resbuffers.cbegin(), resbuffers.cend(), tmpbuffers.begin());
1363 mBufferFilled = mDevice->UpdateSize;
1366 const uint got{mResampler->convertPlanar(tmpbuffers.data(), &mBufferFilled,
1367 buffers.data(), framesToDo-pos)};
1368 for(auto &buf : buffers)
1369 buf = static_cast<float*>(buf) + got; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
1370 pos += got;
1374 hr = audio.mRender->EndUpdatingAudioObjects();
1377 if(FAILED(hr))
1378 ERR("Failed to update playback objects: 0x%08lx\n", hr);
1380 mPadding.store(0u, std::memory_order_release);
1382 return 0;
1386 void WasapiPlayback::open(std::string_view name)
1388 if(SUCCEEDED(mOpenStatus))
1389 throw al::backend_exception{al::backend_error::DeviceError,
1390 "Unexpected duplicate open call"};
1392 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1393 if(mNotifyEvent == nullptr)
1395 ERR("Failed to create notify events: %lu\n", GetLastError());
1396 throw al::backend_exception{al::backend_error::DeviceError,
1397 "Failed to create notify events"};
1400 mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
1401 if(FAILED(mOpenStatus))
1402 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
1403 mOpenStatus};
1406 HRESULT WasapiPlayback::openProxy(std::string_view name)
1408 std::string devname;
1409 std::wstring devid;
1410 if(!name.empty())
1412 auto devlock = DeviceListLock{gDeviceList};
1413 auto list = al::span{devlock.getPlaybackList()};
1414 auto iter = std::find_if(list.cbegin(), list.cend(),
1415 [name](const DevMap &entry) -> bool
1416 { return entry.name == name || entry.endpoint_guid == name; });
1417 if(iter == list.cend())
1419 const std::wstring wname{utf8_to_wstr(name)};
1420 iter = std::find_if(list.cbegin(), list.cend(),
1421 [&wname](const DevMap &entry) -> bool
1422 { return entry.devid == wname; });
1424 if(iter == list.cend())
1426 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name), name.data());
1427 return E_FAIL;
1429 devname = iter->name;
1430 devid = iter->devid;
1433 HRESULT hr{sDeviceHelper->openDevice(devid, eRender, mMMDev)};
1434 if(FAILED(hr))
1436 WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
1437 return hr;
1439 if(!devname.empty())
1440 mDeviceName = std::move(devname);
1441 else
1442 mDeviceName = GetDeviceNameAndGuid(mMMDev).mName;
1444 return S_OK;
1447 void WasapiPlayback::closeProxy()
1449 mAudio.emplace<PlainDevice>();
1450 mMMDev = nullptr;
1454 void WasapiPlayback::prepareFormat(WAVEFORMATEXTENSIBLE &OutputType)
1456 bool isRear51{false};
1458 if(!mDevice->Flags.test(FrequencyRequest))
1459 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
1460 if(!mDevice->Flags.test(ChannelsRequest))
1462 /* If not requesting a channel configuration, auto-select given what
1463 * fits the mask's lsb (to ensure no gaps in the output channels). If
1464 * there's no mask, we can only assume mono or stereo.
1466 const uint32_t chancount{OutputType.Format.nChannels};
1467 const DWORD chanmask{OutputType.dwChannelMask};
1468 if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
1469 mDevice->FmtChans = DevFmtX714;
1470 else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1471 mDevice->FmtChans = DevFmtX71;
1472 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1473 mDevice->FmtChans = DevFmtX61;
1474 else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1)
1475 mDevice->FmtChans = DevFmtX51;
1476 else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR)
1478 mDevice->FmtChans = DevFmtX51;
1479 isRear51 = true;
1481 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1482 mDevice->FmtChans = DevFmtQuad;
1483 else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
1484 mDevice->FmtChans = DevFmtStereo;
1485 else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
1486 mDevice->FmtChans = DevFmtMono;
1487 else
1488 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask);
1490 else
1492 const uint32_t chancount{OutputType.Format.nChannels};
1493 const DWORD chanmask{OutputType.dwChannelMask};
1494 isRear51 = (chancount == 6 && (chanmask&X51RearMask) == X5DOT1REAR);
1497 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1498 switch(mDevice->FmtChans)
1500 case DevFmtMono:
1501 OutputType.Format.nChannels = 1;
1502 OutputType.dwChannelMask = MONO;
1503 break;
1504 case DevFmtAmbi3D:
1505 mDevice->FmtChans = DevFmtStereo;
1506 /*fall-through*/
1507 case DevFmtStereo:
1508 OutputType.Format.nChannels = 2;
1509 OutputType.dwChannelMask = STEREO;
1510 break;
1511 case DevFmtQuad:
1512 OutputType.Format.nChannels = 4;
1513 OutputType.dwChannelMask = QUAD;
1514 break;
1515 case DevFmtX51:
1516 OutputType.Format.nChannels = 6;
1517 OutputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
1518 break;
1519 case DevFmtX61:
1520 OutputType.Format.nChannels = 7;
1521 OutputType.dwChannelMask = X6DOT1;
1522 break;
1523 case DevFmtX71:
1524 case DevFmtX3D71:
1525 OutputType.Format.nChannels = 8;
1526 OutputType.dwChannelMask = X7DOT1;
1527 break;
1528 case DevFmtX7144:
1529 mDevice->FmtChans = DevFmtX714;
1530 /*fall-through*/
1531 case DevFmtX714:
1532 OutputType.Format.nChannels = 12;
1533 OutputType.dwChannelMask = X7DOT1DOT4;
1534 break;
1536 switch(mDevice->FmtType)
1538 case DevFmtByte:
1539 mDevice->FmtType = DevFmtUByte;
1540 /* fall-through */
1541 case DevFmtUByte:
1542 OutputType.Format.wBitsPerSample = 8;
1543 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1544 break;
1545 case DevFmtUShort:
1546 mDevice->FmtType = DevFmtShort;
1547 /* fall-through */
1548 case DevFmtShort:
1549 OutputType.Format.wBitsPerSample = 16;
1550 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1551 break;
1552 case DevFmtUInt:
1553 mDevice->FmtType = DevFmtInt;
1554 /* fall-through */
1555 case DevFmtInt:
1556 OutputType.Format.wBitsPerSample = 32;
1557 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1558 break;
1559 case DevFmtFloat:
1560 OutputType.Format.wBitsPerSample = 32;
1561 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1562 break;
1564 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1565 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1566 OutputType.Format.nSamplesPerSec = mDevice->Frequency;
1568 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
1569 OutputType.Format.wBitsPerSample / 8);
1570 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
1571 OutputType.Format.nBlockAlign;
1574 void WasapiPlayback::finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType)
1576 if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
1577 mDevice->Frequency = uint(OutputType.Format.nSamplesPerSec);
1578 else
1579 mDevice->Frequency = std::min(mDevice->Frequency, uint(OutputType.Format.nSamplesPerSec));
1581 const uint32_t chancount{OutputType.Format.nChannels};
1582 const DWORD chanmask{OutputType.dwChannelMask};
1583 /* Don't update the channel format if the requested format fits what's
1584 * supported.
1586 bool chansok{false};
1587 if(mDevice->Flags.test(ChannelsRequest))
1589 /* When requesting a channel configuration, make sure it fits the
1590 * mask's lsb (to ensure no gaps in the output channels). If there's no
1591 * mask, assume the request fits with enough channels.
1593 switch(mDevice->FmtChans)
1595 case DevFmtMono:
1596 chansok = (chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask));
1597 break;
1598 case DevFmtStereo:
1599 chansok = (chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask));
1600 break;
1601 case DevFmtQuad:
1602 chansok = (chancount >= 4 && ((chanmask&QuadMask) == QUAD || !chanmask));
1603 break;
1604 case DevFmtX51:
1605 chansok = (chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1606 || (chanmask&X51RearMask) == X5DOT1REAR || !chanmask));
1607 break;
1608 case DevFmtX61:
1609 chansok = (chancount >= 7 && ((chanmask&X61Mask) == X6DOT1 || !chanmask));
1610 break;
1611 case DevFmtX71:
1612 case DevFmtX3D71:
1613 chansok = (chancount >= 8 && ((chanmask&X71Mask) == X7DOT1 || !chanmask));
1614 break;
1615 case DevFmtX714:
1616 chansok = (chancount >= 12 && ((chanmask&X714Mask) == X7DOT1DOT4 || !chanmask));
1617 case DevFmtX7144:
1618 case DevFmtAmbi3D:
1619 break;
1622 if(!chansok)
1624 if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
1625 mDevice->FmtChans = DevFmtX714;
1626 else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1627 mDevice->FmtChans = DevFmtX71;
1628 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1629 mDevice->FmtChans = DevFmtX61;
1630 else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1631 || (chanmask&X51RearMask) == X5DOT1REAR))
1632 mDevice->FmtChans = DevFmtX51;
1633 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1634 mDevice->FmtChans = DevFmtQuad;
1635 else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
1636 mDevice->FmtChans = DevFmtStereo;
1637 else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
1638 mDevice->FmtChans = DevFmtMono;
1639 else
1641 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1642 OutputType.dwChannelMask);
1643 mDevice->FmtChans = DevFmtStereo;
1644 OutputType.Format.nChannels = 2;
1645 OutputType.dwChannelMask = STEREO;
1649 if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
1651 if(OutputType.Format.wBitsPerSample == 8)
1652 mDevice->FmtType = DevFmtUByte;
1653 else if(OutputType.Format.wBitsPerSample == 16)
1654 mDevice->FmtType = DevFmtShort;
1655 else if(OutputType.Format.wBitsPerSample == 32)
1656 mDevice->FmtType = DevFmtInt;
1657 else
1659 mDevice->FmtType = DevFmtShort;
1660 OutputType.Format.wBitsPerSample = 16;
1663 else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1665 mDevice->FmtType = DevFmtFloat;
1666 OutputType.Format.wBitsPerSample = 32;
1668 else
1670 ERR("Unhandled format sub-type: %s\n", GuidPrinter{OutputType.SubFormat}.c_str());
1671 mDevice->FmtType = DevFmtShort;
1672 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
1673 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
1674 OutputType.Format.wBitsPerSample = 16;
1675 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1677 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1678 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1682 auto WasapiPlayback::initSpatial() -> bool
1684 auto &audio = mAudio.emplace<SpatialDevice>();
1685 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(ISpatialAudioClient),
1686 al::out_ptr(audio.mClient))};
1687 if(FAILED(hr))
1689 ERR("Failed to activate spatial audio client: 0x%08lx\n", hr);
1690 return false;
1693 ComPtr<IAudioFormatEnumerator> fmtenum;
1694 hr = audio.mClient->GetSupportedAudioObjectFormatEnumerator(al::out_ptr(fmtenum));
1695 if(FAILED(hr))
1697 ERR("Failed to get format enumerator: 0x%08lx\n", hr);
1698 return false;
1701 UINT32 fmtcount{};
1702 hr = fmtenum->GetCount(&fmtcount);
1703 if(FAILED(hr) || fmtcount == 0)
1705 ERR("Failed to get format count: 0x%08lx\n", hr);
1706 return false;
1709 WAVEFORMATEX *preferredFormat{};
1710 hr = fmtenum->GetFormat(0, &preferredFormat);
1711 if(FAILED(hr))
1713 ERR("Failed to get preferred format: 0x%08lx\n", hr);
1714 return false;
1716 TraceFormat("Preferred mix format", preferredFormat);
1718 UINT32 maxFrames{};
1719 hr = audio.mClient->GetMaxFrameCount(preferredFormat, &maxFrames);
1720 if(FAILED(hr))
1721 ERR("Failed to get max frames: 0x%08lx\n", hr);
1722 else
1723 TRACE("Max sample frames: %u\n", maxFrames);
1724 for(UINT32 i{1};i < fmtcount;++i)
1726 WAVEFORMATEX *otherFormat{};
1727 hr = fmtenum->GetFormat(i, &otherFormat);
1728 if(FAILED(hr))
1729 ERR("Failed to format %u: 0x%08lx\n", i+1, hr);
1730 else
1732 TraceFormat("Other mix format", otherFormat);
1733 UINT32 otherMaxFrames{};
1734 hr = audio.mClient->GetMaxFrameCount(otherFormat, &otherMaxFrames);
1735 if(FAILED(hr))
1736 ERR("Failed to get max frames: 0x%08lx\n", hr);
1737 else
1738 TRACE("Max sample frames: %u\n", otherMaxFrames);
1742 WAVEFORMATEXTENSIBLE OutputType;
1743 if(!MakeExtensible(&OutputType, preferredFormat))
1744 return false;
1746 /* This seems to be the format of each "object", which should be mono. */
1747 if(!(OutputType.Format.nChannels == 1
1748 && (OutputType.dwChannelMask == MONO || !OutputType.dwChannelMask)))
1749 ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1750 OutputType.dwChannelMask);
1752 /* Force 32-bit float. This is currently required for planar output. */
1753 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE
1754 && OutputType.Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT)
1756 OutputType.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
1757 OutputType.Format.cbSize = 0;
1759 if(OutputType.Format.wBitsPerSample != 32)
1761 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nAvgBytesPerSec * 32u
1762 / OutputType.Format.wBitsPerSample;
1763 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nBlockAlign * 32
1764 / OutputType.Format.wBitsPerSample);
1765 OutputType.Format.wBitsPerSample = 32;
1767 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1768 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1769 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1771 /* Match the output rate if not requesting anything specific. */
1772 if(!mDevice->Flags.test(FrequencyRequest))
1773 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
1775 auto getTypeMask = [](DevFmtChannels chans) noexcept
1777 switch(chans)
1779 case DevFmtMono: return ChannelMask_Mono;
1780 case DevFmtStereo: return ChannelMask_Stereo;
1781 case DevFmtQuad: return ChannelMask_Quad;
1782 case DevFmtX51: return ChannelMask_X51;
1783 case DevFmtX61: return ChannelMask_X61;
1784 case DevFmtX3D71: [[fallthrough]];
1785 case DevFmtX71: return ChannelMask_X71;
1786 case DevFmtX714: return ChannelMask_X714;
1787 case DevFmtX7144: return ChannelMask_X7144;
1788 case DevFmtAmbi3D:
1789 break;
1791 return ChannelMask_Stereo;
1794 SpatialAudioObjectRenderStreamActivationParams streamParams{};
1795 streamParams.ObjectFormat = &OutputType.Format;
1796 streamParams.StaticObjectTypeMask = getTypeMask(mDevice->FmtChans);
1797 streamParams.Category = AudioCategory_Media;
1798 streamParams.EventHandle = mNotifyEvent;
1800 PropVariant paramProp{};
1801 paramProp.setBlob({reinterpret_cast<BYTE*>(&streamParams), sizeof(streamParams)});
1803 hr = audio.mClient->ActivateSpatialAudioStream(paramProp.get(),
1804 __uuidof(ISpatialAudioObjectRenderStream), al::out_ptr(audio.mRender));
1805 if(FAILED(hr))
1807 ERR("Failed to activate spatial audio stream: 0x%08lx\n", hr);
1808 return false;
1811 audio.mStaticMask = streamParams.StaticObjectTypeMask;
1812 mFormat = OutputType;
1814 mDevice->FmtType = DevFmtFloat;
1815 mDevice->Flags.reset(DirectEar).set(Virtualization);
1816 if(streamParams.StaticObjectTypeMask == ChannelMask_Stereo)
1817 mDevice->FmtChans = DevFmtStereo;
1818 if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
1819 mDevice->Frequency = uint(OutputType.Format.nSamplesPerSec);
1820 else
1821 mDevice->Frequency = std::min(mDevice->Frequency,
1822 uint(OutputType.Format.nSamplesPerSec));
1824 setDefaultWFXChannelOrder();
1826 /* FIXME: Get the real update and buffer size. Presumably the actual device
1827 * is configured once ActivateSpatialAudioStream succeeds, and an
1828 * IAudioClient from the same IMMDevice accesses the same device
1829 * configuration. This isn't obviously correct, but for now assume
1830 * IAudioClient::GetDevicePeriod returns the current device period time
1831 * that ISpatialAudioObjectRenderStream will try to wake up at.
1833 * Unfortunately this won't get the buffer size of the
1834 * ISpatialAudioObjectRenderStream, so we only assume there's two periods.
1836 mOutUpdateSize = mDevice->UpdateSize;
1837 mOutBufferSize = mOutUpdateSize*2;
1838 ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
1840 ComPtr<IAudioClient> tmpClient;
1841 hr = sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
1842 al::out_ptr(tmpClient));
1843 if(FAILED(hr))
1844 ERR("Failed to activate audio client: 0x%08lx\n", hr);
1845 else
1847 hr = tmpClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(per_time), nullptr);
1848 if(FAILED(hr))
1849 ERR("Failed to get device period: 0x%08lx\n", hr);
1850 else
1852 mOutUpdateSize = RefTime2Samples(per_time, mFormat.Format.nSamplesPerSec);
1853 mOutBufferSize = mOutUpdateSize*2;
1856 tmpClient = nullptr;
1858 mDevice->UpdateSize = RefTime2Samples(per_time, mDevice->Frequency);
1859 mDevice->BufferSize = mDevice->UpdateSize*2;
1861 mResampler = nullptr;
1862 mResampleBuffer.clear();
1863 mResampleBuffer.shrink_to_fit();
1864 mBufferFilled = 0;
1865 if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
1867 const auto flags = as_unsigned(streamParams.StaticObjectTypeMask);
1868 const auto channelCount = as_unsigned(al::popcount(flags));
1869 mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType, channelCount,
1870 mDevice->Frequency, mFormat.Format.nSamplesPerSec, Resampler::FastBSinc24);
1871 mResampleBuffer.resize(size_t{mDevice->UpdateSize} * channelCount *
1872 mFormat.Format.wBitsPerSample / 8);
1874 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
1875 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1876 mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->Frequency,
1877 mDevice->UpdateSize);
1880 return true;
1883 bool WasapiPlayback::reset()
1885 HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
1886 if(FAILED(hr))
1887 throw al::backend_exception{al::backend_error::DeviceError, "0x%08lx", hr};
1888 return true;
1891 HRESULT WasapiPlayback::resetProxy()
1893 if(GetConfigValueBool(mDevice->mDeviceName, "wasapi", "spatial-api", false))
1895 if(initSpatial())
1896 return S_OK;
1899 mDevice->Flags.reset(Virtualization);
1901 auto &audio = mAudio.emplace<PlainDevice>();
1902 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
1903 al::out_ptr(audio.mClient))};
1904 if(FAILED(hr))
1906 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
1907 return hr;
1910 WAVEFORMATEX *wfx;
1911 hr = audio.mClient->GetMixFormat(&wfx);
1912 if(FAILED(hr))
1914 ERR("Failed to get mix format: 0x%08lx\n", hr);
1915 return hr;
1917 TraceFormat("Device mix format", wfx);
1919 WAVEFORMATEXTENSIBLE OutputType;
1920 if(!MakeExtensible(&OutputType, wfx))
1922 CoTaskMemFree(wfx);
1923 return E_FAIL;
1925 CoTaskMemFree(wfx);
1926 wfx = nullptr;
1928 const ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
1929 const ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
1931 prepareFormat(OutputType);
1933 TraceFormat("Requesting playback format", &OutputType.Format);
1934 hr = audio.mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
1935 if(FAILED(hr))
1937 WARN("Failed to check format support: 0x%08lx\n", hr);
1938 hr = audio.mClient->GetMixFormat(&wfx);
1940 if(FAILED(hr))
1942 ERR("Failed to find a supported format: 0x%08lx\n", hr);
1943 return hr;
1946 if(wfx != nullptr)
1948 TraceFormat("Got playback format", wfx);
1949 if(!MakeExtensible(&OutputType, wfx))
1951 CoTaskMemFree(wfx);
1952 return E_FAIL;
1954 CoTaskMemFree(wfx);
1955 wfx = nullptr;
1957 finalizeFormat(OutputType);
1959 mFormat = OutputType;
1961 #if !defined(ALSOFT_UWP)
1962 const EndpointFormFactor formfactor{GetDeviceFormfactor(mMMDev.get())};
1963 mDevice->Flags.set(DirectEar, (formfactor == Headphones || formfactor == Headset));
1964 #else
1965 mDevice->Flags.set(DirectEar, false);
1966 #endif
1967 setDefaultWFXChannelOrder();
1969 hr = audio.mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
1970 buf_time.count(), 0, &OutputType.Format, nullptr);
1971 if(FAILED(hr))
1973 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
1974 return hr;
1977 UINT32 buffer_len{};
1978 ReferenceTime min_per{};
1979 hr = audio.mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
1980 if(SUCCEEDED(hr))
1981 hr = audio.mClient->GetBufferSize(&buffer_len);
1982 if(FAILED(hr))
1984 ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
1985 return hr;
1988 hr = audio.mClient->SetEventHandle(mNotifyEvent);
1989 if(FAILED(hr))
1991 ERR("Failed to set event handle: 0x%08lx\n", hr);
1992 return hr;
1995 hr = audio.mClient->GetService(__uuidof(IAudioRenderClient), al::out_ptr(audio.mRender));
1996 if(FAILED(hr))
1998 ERR("Failed to get IAudioRenderClient: 0x%08lx\n", hr);
1999 return hr;
2002 /* Find the nearest multiple of the period size to the update size */
2003 if(min_per < per_time)
2004 min_per *= std::max<int64_t>((per_time + min_per/2) / min_per, 1_i64);
2006 mOutBufferSize = buffer_len;
2007 mOutUpdateSize = std::min(RefTime2Samples(min_per, mFormat.Format.nSamplesPerSec),
2008 buffer_len/2u);
2010 mDevice->BufferSize = static_cast<uint>(uint64_t{buffer_len} * mDevice->Frequency /
2011 mFormat.Format.nSamplesPerSec);
2012 mDevice->UpdateSize = std::min(RefTime2Samples(min_per, mDevice->Frequency),
2013 mDevice->BufferSize/2u);
2015 mResampler = nullptr;
2016 mResampleBuffer.clear();
2017 mResampleBuffer.shrink_to_fit();
2018 mBufferFilled = 0;
2019 if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
2021 mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType,
2022 mFormat.Format.nChannels, mDevice->Frequency, mFormat.Format.nSamplesPerSec,
2023 Resampler::FastBSinc24);
2024 mResampleBuffer.resize(size_t{mDevice->UpdateSize} * mFormat.Format.nChannels *
2025 mFormat.Format.wBitsPerSample / 8);
2027 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
2028 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2029 mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->Frequency,
2030 mDevice->UpdateSize);
2033 return hr;
2037 void WasapiPlayback::start()
2039 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
2040 if(FAILED(hr))
2041 throw al::backend_exception{al::backend_error::DeviceError,
2042 "Failed to start playback: 0x%lx", hr};
2045 HRESULT WasapiPlayback::startProxy()
2047 ResetEvent(mNotifyEvent);
2049 auto start_plain = [&](PlainDevice &audio) -> HRESULT
2051 HRESULT hr{audio.mClient->Start()};
2052 if(FAILED(hr))
2054 ERR("Failed to start audio client: 0x%08lx\n", hr);
2055 return hr;
2058 try {
2059 mKillNow.store(false, std::memory_order_release);
2060 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerProc), this};
2062 catch(...) {
2063 ERR("Failed to start thread\n");
2064 audio.mClient->Stop();
2065 hr = E_FAIL;
2067 return hr;
2069 auto start_spatial = [&](SpatialDevice &audio) -> HRESULT
2071 HRESULT hr{audio.mRender->Start()};
2072 if(FAILED(hr))
2074 ERR("Failed to start spatial audio stream: 0x%08lx\n", hr);
2075 return hr;
2078 try {
2079 mKillNow.store(false, std::memory_order_release);
2080 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerSpatialProc), this};
2082 catch(...) {
2083 ERR("Failed to start thread\n");
2084 hr = E_FAIL;
2087 if(FAILED(hr))
2089 audio.mRender->Stop();
2090 audio.mRender->Reset();
2092 return hr;
2095 return std::visit(overloaded{start_plain, start_spatial}, mAudio);
2099 void WasapiPlayback::stop()
2100 { pushMessage(MsgType::StopDevice).wait(); }
2102 void WasapiPlayback::stopProxy()
2104 if(!mThread.joinable())
2105 return;
2107 mKillNow.store(true, std::memory_order_release);
2108 mThread.join();
2110 auto stop_plain = [](PlainDevice &audio) -> void
2111 { audio.mClient->Stop(); };
2112 auto stop_spatial = [](SpatialDevice &audio) -> void
2114 audio.mRender->Stop();
2115 audio.mRender->Reset();
2117 std::visit(overloaded{stop_plain, stop_spatial}, mAudio);
2121 ClockLatency WasapiPlayback::getClockLatency()
2123 std::lock_guard<std::mutex> dlock{mMutex};
2124 ClockLatency ret{};
2125 ret.ClockTime = mDevice->getClockTime();
2126 ret.Latency = seconds{mPadding.load(std::memory_order_relaxed)};
2127 ret.Latency /= mFormat.Format.nSamplesPerSec;
2128 if(mResampler)
2130 auto extra = mResampler->currentInputDelay();
2131 ret.Latency += std::chrono::duration_cast<nanoseconds>(extra) / mDevice->Frequency;
2132 ret.Latency += nanoseconds{seconds{mBufferFilled}} / mDevice->Frequency;
2135 return ret;
2139 struct WasapiCapture final : public BackendBase, WasapiProxy {
2140 WasapiCapture(DeviceBase *device) noexcept : BackendBase{device} { }
2141 ~WasapiCapture() override;
2143 int recordProc();
2145 void open(std::string_view name) override;
2146 HRESULT openProxy(std::string_view name) override;
2147 void closeProxy() override;
2149 HRESULT resetProxy() override;
2150 void start() override;
2151 HRESULT startProxy() override;
2152 void stop() override;
2153 void stopProxy() override;
2155 void captureSamples(std::byte *buffer, uint samples) override;
2156 uint availableSamples() override;
2158 HRESULT mOpenStatus{E_FAIL};
2159 DeviceHandle mMMDev{nullptr};
2160 ComPtr<IAudioClient> mClient{nullptr};
2161 ComPtr<IAudioCaptureClient> mCapture{nullptr};
2162 HANDLE mNotifyEvent{nullptr};
2164 ChannelConverter mChannelConv{};
2165 SampleConverterPtr mSampleConv;
2166 RingBufferPtr mRing;
2168 std::atomic<bool> mKillNow{true};
2169 std::thread mThread;
2172 WasapiCapture::~WasapiCapture()
2174 if(SUCCEEDED(mOpenStatus))
2175 pushMessage(MsgType::CloseDevice).wait();
2176 mOpenStatus = E_FAIL;
2178 if(mNotifyEvent != nullptr)
2179 CloseHandle(mNotifyEvent);
2180 mNotifyEvent = nullptr;
2184 FORCE_ALIGN int WasapiCapture::recordProc()
2186 ComWrapper com{COINIT_MULTITHREADED};
2187 if(!com)
2189 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
2190 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
2191 return 1;
2194 althrd_setname(GetRecordThreadName());
2196 std::vector<float> samples;
2197 while(!mKillNow.load(std::memory_order_relaxed))
2199 UINT32 avail;
2200 HRESULT hr{mCapture->GetNextPacketSize(&avail)};
2201 if(FAILED(hr))
2202 ERR("Failed to get next packet size: 0x%08lx\n", hr);
2203 else if(avail > 0)
2205 UINT32 numsamples;
2206 DWORD flags;
2207 BYTE *rdata;
2209 hr = mCapture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
2210 if(FAILED(hr))
2211 ERR("Failed to get capture buffer: 0x%08lx\n", hr);
2212 else
2214 if(mChannelConv.is_active())
2216 samples.resize(numsamples*2_uz);
2217 mChannelConv.convert(rdata, samples.data(), numsamples);
2218 rdata = reinterpret_cast<BYTE*>(samples.data());
2221 auto data = mRing->getWriteVector();
2223 size_t dstframes;
2224 if(mSampleConv)
2226 static constexpr auto lenlimit = size_t{std::numeric_limits<int>::max()};
2227 const void *srcdata{rdata};
2228 uint srcframes{numsamples};
2230 dstframes = mSampleConv->convert(&srcdata, &srcframes, data[0].buf,
2231 static_cast<uint>(std::min(data[0].len, lenlimit)));
2232 if(srcframes > 0 && dstframes == data[0].len && data[1].len > 0)
2234 /* If some source samples remain, all of the first dest
2235 * block was filled, and there's space in the second
2236 * dest block, do another run for the second block.
2238 dstframes += mSampleConv->convert(&srcdata, &srcframes, data[1].buf,
2239 static_cast<uint>(std::min(data[1].len, lenlimit)));
2242 else
2244 const uint framesize{mDevice->frameSizeFromFmt()};
2245 auto dst = al::span{rdata, size_t{numsamples}*framesize};
2246 size_t len1{std::min(data[0].len, size_t{numsamples})};
2247 size_t len2{std::min(data[1].len, numsamples-len1)};
2249 memcpy(data[0].buf, dst.data(), len1*framesize);
2250 if(len2 > 0)
2252 dst = dst.subspan(len1*framesize);
2253 memcpy(data[1].buf, dst.data(), len2*framesize);
2255 dstframes = len1 + len2;
2258 mRing->writeAdvance(dstframes);
2260 hr = mCapture->ReleaseBuffer(numsamples);
2261 if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
2265 if(FAILED(hr))
2267 mDevice->handleDisconnect("Failed to capture samples: 0x%08lx", hr);
2268 break;
2271 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
2272 if(res != WAIT_OBJECT_0)
2273 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
2276 return 0;
2280 void WasapiCapture::open(std::string_view name)
2282 if(SUCCEEDED(mOpenStatus))
2283 throw al::backend_exception{al::backend_error::DeviceError,
2284 "Unexpected duplicate open call"};
2286 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
2287 if(mNotifyEvent == nullptr)
2289 ERR("Failed to create notify events: %lu\n", GetLastError());
2290 throw al::backend_exception{al::backend_error::DeviceError,
2291 "Failed to create notify events"};
2294 mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
2295 if(FAILED(mOpenStatus))
2296 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
2297 mOpenStatus};
2299 HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
2300 if(FAILED(hr))
2302 if(hr == E_OUTOFMEMORY)
2303 throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"};
2304 throw al::backend_exception{al::backend_error::DeviceError, "Device reset failed"};
2308 HRESULT WasapiCapture::openProxy(std::string_view name)
2310 std::string devname;
2311 std::wstring devid;
2312 if(!name.empty())
2314 auto devlock = DeviceListLock{gDeviceList};
2315 auto devlist = al::span{devlock.getCaptureList()};
2316 auto iter = std::find_if(devlist.cbegin(), devlist.cend(),
2317 [name](const DevMap &entry) -> bool
2318 { return entry.name == name || entry.endpoint_guid == name; });
2319 if(iter == devlist.cend())
2321 const std::wstring wname{utf8_to_wstr(name)};
2322 iter = std::find_if(devlist.cbegin(), devlist.cend(),
2323 [&wname](const DevMap &entry) -> bool
2324 { return entry.devid == wname; });
2326 if(iter == devlist.cend())
2328 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name), name.data());
2329 return E_FAIL;
2331 devname = iter->name;
2332 devid = iter->devid;
2335 HRESULT hr{sDeviceHelper->openDevice(devid, eCapture, mMMDev)};
2336 if(FAILED(hr))
2338 WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
2339 return hr;
2341 mClient = nullptr;
2342 if(!devname.empty())
2343 mDeviceName = std::move(devname);
2344 else
2345 mDeviceName = GetDeviceNameAndGuid(mMMDev).mName;
2347 return S_OK;
2350 void WasapiCapture::closeProxy()
2352 mCapture = nullptr;
2353 mClient = nullptr;
2354 mMMDev = nullptr;
2357 HRESULT WasapiCapture::resetProxy()
2359 mCapture = nullptr;
2360 mClient = nullptr;
2362 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
2363 al::out_ptr(mClient))};
2364 if(FAILED(hr))
2366 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
2367 return hr;
2370 WAVEFORMATEX *wfx;
2371 hr = mClient->GetMixFormat(&wfx);
2372 if(FAILED(hr))
2374 ERR("Failed to get capture format: 0x%08lx\n", hr);
2375 return hr;
2377 TraceFormat("Device capture format", wfx);
2379 WAVEFORMATEXTENSIBLE InputType{};
2380 if(!MakeExtensible(&InputType, wfx))
2382 CoTaskMemFree(wfx);
2383 return E_FAIL;
2385 CoTaskMemFree(wfx);
2386 wfx = nullptr;
2388 const bool isRear51{InputType.Format.nChannels == 6
2389 && (InputType.dwChannelMask&X51RearMask) == X5DOT1REAR};
2391 // Make sure buffer is at least 100ms in size
2392 ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
2393 buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}});
2395 InputType = {};
2396 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
2397 switch(mDevice->FmtChans)
2399 case DevFmtMono:
2400 InputType.Format.nChannels = 1;
2401 InputType.dwChannelMask = MONO;
2402 break;
2403 case DevFmtStereo:
2404 InputType.Format.nChannels = 2;
2405 InputType.dwChannelMask = STEREO;
2406 break;
2407 case DevFmtQuad:
2408 InputType.Format.nChannels = 4;
2409 InputType.dwChannelMask = QUAD;
2410 break;
2411 case DevFmtX51:
2412 InputType.Format.nChannels = 6;
2413 InputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
2414 break;
2415 case DevFmtX61:
2416 InputType.Format.nChannels = 7;
2417 InputType.dwChannelMask = X6DOT1;
2418 break;
2419 case DevFmtX71:
2420 InputType.Format.nChannels = 8;
2421 InputType.dwChannelMask = X7DOT1;
2422 break;
2423 case DevFmtX714:
2424 InputType.Format.nChannels = 12;
2425 InputType.dwChannelMask = X7DOT1DOT4;
2426 break;
2428 case DevFmtX7144:
2429 case DevFmtX3D71:
2430 case DevFmtAmbi3D:
2431 return E_FAIL;
2433 switch(mDevice->FmtType)
2435 /* NOTE: Signedness doesn't matter, the converter will handle it. */
2436 case DevFmtByte:
2437 case DevFmtUByte:
2438 InputType.Format.wBitsPerSample = 8;
2439 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2440 break;
2441 case DevFmtShort:
2442 case DevFmtUShort:
2443 InputType.Format.wBitsPerSample = 16;
2444 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2445 break;
2446 case DevFmtInt:
2447 case DevFmtUInt:
2448 InputType.Format.wBitsPerSample = 32;
2449 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2450 break;
2451 case DevFmtFloat:
2452 InputType.Format.wBitsPerSample = 32;
2453 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
2454 break;
2456 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
2457 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
2458 InputType.Format.nSamplesPerSec = mDevice->Frequency;
2460 InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
2461 InputType.Format.wBitsPerSample / 8);
2462 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
2463 InputType.Format.nBlockAlign;
2464 InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format);
2466 TraceFormat("Requesting capture format", &InputType.Format);
2467 hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, &wfx);
2468 if(FAILED(hr))
2470 WARN("Failed to check capture format support: 0x%08lx\n", hr);
2471 hr = mClient->GetMixFormat(&wfx);
2473 if(FAILED(hr))
2475 ERR("Failed to find a supported capture format: 0x%08lx\n", hr);
2476 return hr;
2479 mSampleConv = nullptr;
2480 mChannelConv = {};
2482 if(wfx != nullptr)
2484 TraceFormat("Got capture format", wfx);
2485 if(!MakeExtensible(&InputType, wfx))
2487 CoTaskMemFree(wfx);
2488 return E_FAIL;
2490 CoTaskMemFree(wfx);
2491 wfx = nullptr;
2493 auto validate_fmt = [](DeviceBase *device, uint32_t chancount, DWORD chanmask) noexcept
2494 -> bool
2496 switch(device->FmtChans)
2498 /* If the device wants mono, we can handle any input. */
2499 case DevFmtMono:
2500 return true;
2501 /* If the device wants stereo, we can handle mono or stereo input. */
2502 case DevFmtStereo:
2503 return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO))
2504 || (chancount == 1 && (chanmask&MonoMask) == MONO);
2505 /* Otherwise, the device must match the input type. */
2506 case DevFmtQuad:
2507 return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD));
2508 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
2509 case DevFmtX51:
2510 return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1
2511 || (chanmask&X51RearMask) == X5DOT1REAR));
2512 case DevFmtX61:
2513 return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1));
2514 case DevFmtX71:
2515 case DevFmtX3D71:
2516 return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1));
2517 case DevFmtX714:
2518 return (chancount == 12 && (chanmask == 0 || (chanmask&X714Mask) == X7DOT1DOT4));
2519 case DevFmtX7144:
2520 return (chancount == 16 && chanmask == 0);
2521 case DevFmtAmbi3D:
2522 return (chanmask == 0 && chancount == device->channelsFromFmt());
2524 return false;
2526 if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask))
2528 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
2529 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2530 mDevice->Frequency, InputType.dwChannelMask, InputType.Format.nChannels,
2531 (InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample,
2532 InputType.Format.nSamplesPerSec);
2533 return E_FAIL;
2537 DevFmtType srcType{};
2538 if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
2540 if(InputType.Format.wBitsPerSample == 8)
2541 srcType = DevFmtUByte;
2542 else if(InputType.Format.wBitsPerSample == 16)
2543 srcType = DevFmtShort;
2544 else if(InputType.Format.wBitsPerSample == 32)
2545 srcType = DevFmtInt;
2546 else
2548 ERR("Unhandled integer bit depth: %d\n", InputType.Format.wBitsPerSample);
2549 return E_FAIL;
2552 else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
2554 if(InputType.Format.wBitsPerSample == 32)
2555 srcType = DevFmtFloat;
2556 else
2558 ERR("Unhandled float bit depth: %d\n", InputType.Format.wBitsPerSample);
2559 return E_FAIL;
2562 else
2564 ERR("Unhandled format sub-type: %s\n", GuidPrinter{InputType.SubFormat}.c_str());
2565 return E_FAIL;
2568 if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1)
2570 uint chanmask{(1u<<InputType.Format.nChannels) - 1u};
2571 /* Exclude LFE from the downmix. */
2572 if((InputType.dwChannelMask&SPEAKER_LOW_FREQUENCY))
2574 constexpr auto lfemask = MaskFromTopBits(SPEAKER_LOW_FREQUENCY);
2575 const int lfeidx{al::popcount(InputType.dwChannelMask&lfemask) - 1};
2576 chanmask &= ~(1u << lfeidx);
2579 mChannelConv = ChannelConverter{srcType, InputType.Format.nChannels, chanmask,
2580 mDevice->FmtChans};
2581 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType));
2582 /* The channel converter always outputs float, so change the input type
2583 * for the resampler/type-converter.
2585 srcType = DevFmtFloat;
2587 else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1)
2589 mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans};
2590 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
2591 srcType = DevFmtFloat;
2594 if(mDevice->Frequency != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType)
2596 mSampleConv = SampleConverter::Create(srcType, mDevice->FmtType,
2597 mDevice->channelsFromFmt(), InputType.Format.nSamplesPerSec, mDevice->Frequency,
2598 Resampler::FastBSinc24);
2599 if(!mSampleConv)
2601 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2602 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2603 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
2604 return E_FAIL;
2606 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2607 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2608 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
2611 hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
2612 buf_time.count(), 0, &InputType.Format, nullptr);
2613 if(FAILED(hr))
2615 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
2616 return hr;
2619 hr = mClient->GetService(__uuidof(IAudioCaptureClient), al::out_ptr(mCapture));
2620 if(FAILED(hr))
2622 ERR("Failed to get IAudioCaptureClient: 0x%08lx\n", hr);
2623 return hr;
2626 UINT32 buffer_len{};
2627 ReferenceTime min_per{};
2628 hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
2629 if(SUCCEEDED(hr))
2630 hr = mClient->GetBufferSize(&buffer_len);
2631 if(FAILED(hr))
2633 ERR("Failed to get buffer size: 0x%08lx\n", hr);
2634 return hr;
2636 mDevice->UpdateSize = RefTime2Samples(min_per, mDevice->Frequency);
2637 mDevice->BufferSize = buffer_len;
2639 mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false);
2641 hr = mClient->SetEventHandle(mNotifyEvent);
2642 if(FAILED(hr))
2644 ERR("Failed to set event handle: 0x%08lx\n", hr);
2645 return hr;
2648 return hr;
2652 void WasapiCapture::start()
2654 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
2655 if(FAILED(hr))
2656 throw al::backend_exception{al::backend_error::DeviceError,
2657 "Failed to start recording: 0x%lx", hr};
2660 HRESULT WasapiCapture::startProxy()
2662 ResetEvent(mNotifyEvent);
2664 HRESULT hr{mClient->Start()};
2665 if(FAILED(hr))
2667 ERR("Failed to start audio client: 0x%08lx\n", hr);
2668 return hr;
2671 try {
2672 mKillNow.store(false, std::memory_order_release);
2673 mThread = std::thread{std::mem_fn(&WasapiCapture::recordProc), this};
2675 catch(...) {
2676 ERR("Failed to start thread\n");
2677 mClient->Stop();
2678 mClient->Reset();
2679 hr = E_FAIL;
2682 return hr;
2686 void WasapiCapture::stop()
2687 { pushMessage(MsgType::StopDevice).wait(); }
2689 void WasapiCapture::stopProxy()
2691 if(!mThread.joinable())
2692 return;
2694 mKillNow.store(true, std::memory_order_release);
2695 mThread.join();
2697 mClient->Stop();
2698 mClient->Reset();
2702 void WasapiCapture::captureSamples(std::byte *buffer, uint samples)
2703 { std::ignore = mRing->read(buffer, samples); }
2705 uint WasapiCapture::availableSamples()
2706 { return static_cast<uint>(mRing->readSpace()); }
2708 } // namespace
2711 bool WasapiBackendFactory::init()
2713 static HRESULT InitResult{E_FAIL};
2714 if(FAILED(InitResult)) try
2716 std::promise<HRESULT> promise;
2717 auto future = promise.get_future();
2719 std::thread{&WasapiProxy::messageHandler, &promise}.detach();
2720 InitResult = future.get();
2722 catch(...) {
2725 return SUCCEEDED(InitResult);
2728 bool WasapiBackendFactory::querySupport(BackendType type)
2729 { return type == BackendType::Playback || type == BackendType::Capture; }
2731 auto WasapiBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
2733 std::vector<std::string> outnames;
2735 auto devlock = DeviceListLock{gDeviceList};
2736 switch(type)
2738 case BackendType::Playback:
2740 auto defaultId = devlock.getPlaybackDefaultId();
2741 for(const DevMap &entry : devlock.getPlaybackList())
2743 if(entry.devid != defaultId)
2745 outnames.emplace_back(entry.name);
2746 continue;
2748 /* Default device goes first. */
2749 outnames.emplace(outnames.cbegin(), entry.name);
2752 break;
2754 case BackendType::Capture:
2756 auto defaultId = devlock.getCaptureDefaultId();
2757 for(const DevMap &entry : devlock.getCaptureList())
2759 if(entry.devid != defaultId)
2761 outnames.emplace_back(entry.name);
2762 continue;
2764 outnames.emplace(outnames.cbegin(), entry.name);
2767 break;
2770 return outnames;
2773 BackendPtr WasapiBackendFactory::createBackend(DeviceBase *device, BackendType type)
2775 if(type == BackendType::Playback)
2776 return BackendPtr{new WasapiPlayback{device}};
2777 if(type == BackendType::Capture)
2778 return BackendPtr{new WasapiCapture{device}};
2779 return nullptr;
2782 BackendFactory &WasapiBackendFactory::getFactory()
2784 static WasapiBackendFactory factory{};
2785 return factory;
2788 alc::EventSupport WasapiBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
2790 switch(eventType)
2792 case alc::EventType::DefaultDeviceChanged:
2793 return alc::EventSupport::FullSupport;
2795 case alc::EventType::DeviceAdded:
2796 case alc::EventType::DeviceRemoved:
2797 #if !defined(ALSOFT_UWP)
2798 return alc::EventSupport::FullSupport;
2799 #endif
2801 case alc::EventType::Count:
2802 break;
2804 return alc::EventSupport::NoSupport;