Recogmize jack64 for finding the JACK library name
[openal-soft.git] / alc / backends / wasapi.cpp
blobee8116e4f19423182a2cc32f3586bd24d0027b99
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 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 !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 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 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 !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,
386 static_cast<size_t>(devIdStartEnd - devIdStart)});
387 std::transform(ret.mGuid.begin(), ret.mGuid.end(), ret.mGuid.begin(),
388 [](char ch) { return static_cast<char>(std::toupper(ch)); });
391 #endif
392 if(ret.mName.empty()) ret.mName = UnknownName;
393 if(ret.mGuid.empty()) ret.mGuid = UnknownGuid;
394 return ret;
396 #if !ALSOFT_UWP
397 EndpointFormFactor GetDeviceFormfactor(IMMDevice *device)
399 ComPtr<IPropertyStore> ps;
400 HRESULT hr{device->OpenPropertyStore(STGM_READ, al::out_ptr(ps))};
401 if(FAILED(hr))
403 WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
404 return UnknownFormFactor;
407 EndpointFormFactor formfactor{UnknownFormFactor};
408 PropVariant pvform;
409 hr = ps->GetValue(PKEY_AudioEndpoint_FormFactor, pvform.get());
410 if(FAILED(hr))
411 WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr);
412 else if(pvform.type() == VT_UI4)
413 formfactor = static_cast<EndpointFormFactor>(pvform.value<uint>());
414 else if(pvform.type() != VT_EMPTY)
415 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform.type());
416 return formfactor;
418 #endif
421 #if ALSOFT_UWP
422 struct DeviceHelper final : public IActivateAudioInterfaceCompletionHandler
423 #else
424 struct DeviceHelper final : private IMMNotificationClient
425 #endif
427 #if ALSOFT_UWP
428 DeviceHelper()
430 /* TODO: UWP also needs to watch for device added/removed events and
431 * dynamically add/remove devices from the lists.
433 mActiveClientEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
435 static constexpr auto playback_cb = [](const IInspectable &sender [[maybe_unused]],
436 const DefaultAudioRenderDeviceChangedEventArgs &args)
438 if(args.Role() == AudioDeviceRole::Default)
440 const auto msg = std::string{"Default playback device changed: " +
441 wstr_to_utf8(args.Id())};
442 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
445 mRenderDeviceChangedToken = MediaDevice::DefaultAudioRenderDeviceChanged(playback_cb);
447 static constexpr auto capture_cb = [](const IInspectable &sender [[maybe_unused]],
448 const DefaultAudioCaptureDeviceChangedEventArgs &args)
450 if(args.Role() == AudioDeviceRole::Default)
452 const auto msg = std::string{"Default capture device changed: " +
453 wstr_to_utf8(args.Id())};
454 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
457 mCaptureDeviceChangedToken = MediaDevice::DefaultAudioCaptureDeviceChanged(capture_cb);
459 #else
460 DeviceHelper() = default;
461 #endif
462 ~DeviceHelper()
464 #if ALSOFT_UWP
465 MediaDevice::DefaultAudioRenderDeviceChanged(mRenderDeviceChangedToken);
466 MediaDevice::DefaultAudioCaptureDeviceChanged(mCaptureDeviceChangedToken);
468 if(mActiveClientEvent != nullptr)
469 CloseHandle(mActiveClientEvent);
470 mActiveClientEvent = nullptr;
471 #else
472 if(mEnumerator)
473 mEnumerator->UnregisterEndpointNotificationCallback(this);
474 mEnumerator = nullptr;
475 #endif
478 template<typename T>
479 auto as() noexcept -> T { return T{this}; }
481 /** -------------------------- IUnknown ----------------------------- */
482 std::atomic<ULONG> mRefCount{1};
483 STDMETHODIMP_(ULONG) AddRef() noexcept override { return mRefCount.fetch_add(1u) + 1u; }
484 STDMETHODIMP_(ULONG) Release() noexcept override { return mRefCount.fetch_sub(1u) - 1u; }
486 STDMETHODIMP QueryInterface(const IID& IId, void **UnknownPtrPtr) noexcept override
488 // Three rules of QueryInterface:
489 // https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface
490 // 1. Objects must have identity.
491 // 2. The set of interfaces on an object instance must be static.
492 // 3. It must be possible to query successfully for any interface on an object from any other interface.
494 // If ppvObject(the address) is nullptr, then this method returns E_POINTER.
495 if(!UnknownPtrPtr)
496 return E_POINTER;
498 // https://docs.microsoft.com/en-us/windows/win32/com/implementing-reference-counting
499 // Whenever a client calls a method(or API function), such as QueryInterface, that returns a new interface
500 // pointer, the method being called is responsible for incrementing the reference count through the returned
501 // pointer. For example, when a client first creates an object, it receives an interface pointer to an object
502 // that, from the client's point of view, has a reference count of one. If the client then calls AddRef on the
503 // interface pointer, the reference count becomes two. The client must call Release twice on the interface
504 // pointer to drop all of its references to the object.
505 #if ALSOFT_UWP
506 if(IId == __uuidof(IActivateAudioInterfaceCompletionHandler))
508 *UnknownPtrPtr = as<IActivateAudioInterfaceCompletionHandler*>();
509 AddRef();
510 return S_OK;
512 #else
513 if(IId == __uuidof(IMMNotificationClient))
515 *UnknownPtrPtr = as<IMMNotificationClient*>();
516 AddRef();
517 return S_OK;
519 #endif
520 else if(IId == __uuidof(IAgileObject) || IId == __uuidof(IUnknown))
522 *UnknownPtrPtr = as<IUnknown*>();
523 AddRef();
524 return S_OK;
527 // This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise.
528 *UnknownPtrPtr = nullptr;
529 return E_NOINTERFACE;
532 #if ALSOFT_UWP
533 /** ----------------------- IActivateAudioInterfaceCompletionHandler ------------ */
534 HRESULT ActivateCompleted(IActivateAudioInterfaceAsyncOperation*) override
536 SetEvent(mActiveClientEvent);
538 // Need to return S_OK
539 return S_OK;
541 #else
542 /** ----------------------- IMMNotificationClient ------------ */
543 STDMETHODIMP OnDeviceStateChanged(LPCWSTR /*pwstrDeviceId*/, DWORD /*dwNewState*/) noexcept override { return S_OK; }
545 STDMETHODIMP OnDeviceAdded(LPCWSTR pwstrDeviceId) noexcept override
547 ComPtr<IMMDevice> device;
548 HRESULT hr{mEnumerator->GetDevice(pwstrDeviceId, al::out_ptr(device))};
549 if(FAILED(hr))
551 ERR("Failed to get device: 0x%08lx\n", hr);
552 return S_OK;
555 ComPtr<IMMEndpoint> endpoint;
556 hr = device->QueryInterface(__uuidof(IMMEndpoint), al::out_ptr(endpoint));
557 if(FAILED(hr))
559 ERR("Failed to get device endpoint: 0x%08lx\n", hr);
560 return S_OK;
563 EDataFlow flowdir{};
564 hr = endpoint->GetDataFlow(&flowdir);
565 if(FAILED(hr))
567 ERR("Failed to get endpoint data flow: 0x%08lx\n", hr);
568 return S_OK;
571 auto devlock = DeviceListLock{gDeviceList};
572 auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
574 if(AddDevice(device, pwstrDeviceId, list))
576 const auto devtype = (flowdir==eRender) ? alc::DeviceType::Playback
577 : alc::DeviceType::Capture;
578 const std::string msg{"Device added: "+list.back().name};
579 alc::Event(alc::EventType::DeviceAdded, devtype, msg);
582 return S_OK;
585 STDMETHODIMP OnDeviceRemoved(LPCWSTR pwstrDeviceId) noexcept override
587 auto devlock = DeviceListLock{gDeviceList};
588 for(auto flowdir : std::array{eRender, eCapture})
590 auto &list = (flowdir==eRender) ? devlock.getPlaybackList() : devlock.getCaptureList();
591 auto devtype = (flowdir==eRender)?alc::DeviceType::Playback : alc::DeviceType::Capture;
593 /* Find the ID in the list to remove. */
594 auto iter = std::find_if(list.begin(), list.end(),
595 [pwstrDeviceId](const DevMap &entry) noexcept
596 { return pwstrDeviceId == entry.devid; });
597 if(iter == list.end()) continue;
599 TRACE("Removing device \"%s\", \"%s\", \"%ls\"\n", iter->name.c_str(),
600 iter->endpoint_guid.c_str(), iter->devid.c_str());
602 std::string msg{"Device removed: "+std::move(iter->name)};
603 list.erase(iter);
605 alc::Event(alc::EventType::DeviceRemoved, devtype, msg);
607 return S_OK;
610 /* NOLINTNEXTLINE(clazy-function-args-by-ref) */
611 STDMETHODIMP OnPropertyValueChanged(LPCWSTR /*pwstrDeviceId*/, const PROPERTYKEY /*key*/) noexcept override { return S_OK; }
613 STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) noexcept override
615 if(role != eMultimedia)
616 return S_OK;
618 const std::wstring_view devid{pwstrDefaultDeviceId ? pwstrDefaultDeviceId
619 : std::wstring_view{}};
620 if(flow == eRender)
622 DeviceListLock{gDeviceList}.setPlaybackDefaultId(devid);
623 const std::string msg{"Default playback device changed: " + wstr_to_utf8(devid)};
624 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
626 else if(flow == eCapture)
628 DeviceListLock{gDeviceList}.setCaptureDefaultId(devid);
629 const std::string msg{"Default capture device changed: " + wstr_to_utf8(devid)};
630 alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
632 return S_OK;
634 #endif
636 /** -------------------------- DeviceHelper ----------------------------- */
637 HRESULT init()
639 #if !ALSOFT_UWP
640 HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
641 __uuidof(IMMDeviceEnumerator), al::out_ptr(mEnumerator))};
642 if(SUCCEEDED(hr))
643 mEnumerator->RegisterEndpointNotificationCallback(this);
644 else
645 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
646 return hr;
647 #else
648 return S_OK;
649 #endif
652 HRESULT openDevice(std::wstring_view devid, EDataFlow flow, DeviceHandle& device)
654 #if !ALSOFT_UWP
655 HRESULT hr{E_FAIL};
656 if(mEnumerator)
658 if(devid.empty())
659 hr = mEnumerator->GetDefaultAudioEndpoint(flow, eMultimedia, al::out_ptr(device));
660 else
661 hr = mEnumerator->GetDevice(devid.data(), al::out_ptr(device));
663 return hr;
664 #else
665 const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
666 auto devIfPath =
667 devid.empty() ? (flow == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole) : MediaDevice::GetDefaultAudioCaptureId(deviceRole))
668 : winrt::hstring(devid.data());
669 if (devIfPath.empty())
670 return E_POINTER;
672 auto&& deviceInfo = DeviceInformation::CreateFromIdAsync(devIfPath, nullptr, DeviceInformationKind::DeviceInterface).get();
673 if (!deviceInfo)
674 return E_NOINTERFACE;
675 device = deviceInfo;
676 return S_OK;
677 #endif
680 #if !ALSOFT_UWP
681 static HRESULT activateAudioClient(_In_ DeviceHandle &device, REFIID iid, void **ppv)
682 { return device->Activate(iid, CLSCTX_INPROC_SERVER, nullptr, ppv); }
683 #else
684 HRESULT activateAudioClient(_In_ DeviceHandle &device, _In_ REFIID iid, void **ppv)
686 ComPtr<IActivateAudioInterfaceAsyncOperation> asyncOp;
687 HRESULT hr{ActivateAudioInterfaceAsync(device.Id().data(), iid, nullptr, this,
688 al::out_ptr(asyncOp))};
689 if(FAILED(hr))
690 return hr;
692 /* I don't like waiting for INFINITE time, but the activate operation
693 * can take an indefinite amount of time since it can require user
694 * input.
696 DWORD res{WaitForSingleObjectEx(mActiveClientEvent, INFINITE, FALSE)};
697 if(res != WAIT_OBJECT_0)
699 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
700 return E_FAIL;
703 HRESULT hrActivateRes{E_FAIL};
704 ComPtr<IUnknown> punkAudioIface;
705 hr = asyncOp->GetActivateResult(&hrActivateRes, al::out_ptr(punkAudioIface));
706 if(SUCCEEDED(hr)) hr = hrActivateRes;
707 if(FAILED(hr)) return hr;
709 return punkAudioIface->QueryInterface(iid, ppv);
711 #endif
713 std::wstring probeDevices(EDataFlow flowdir, std::vector<DevMap> &list)
715 std::wstring defaultId;
716 std::vector<DevMap>{}.swap(list);
718 #if !ALSOFT_UWP
719 ComPtr<IMMDeviceCollection> coll;
720 HRESULT hr{mEnumerator->EnumAudioEndpoints(flowdir, DEVICE_STATE_ACTIVE,
721 al::out_ptr(coll))};
722 if(FAILED(hr))
724 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr);
725 return defaultId;
728 UINT count{0};
729 hr = coll->GetCount(&count);
730 if(SUCCEEDED(hr) && count > 0)
731 list.reserve(count);
733 ComPtr<IMMDevice> device;
734 hr = mEnumerator->GetDefaultAudioEndpoint(flowdir, eMultimedia, al::out_ptr(device));
735 if(SUCCEEDED(hr))
737 if(WCHAR *devid{GetDeviceId(device.get())})
739 defaultId = devid;
740 CoTaskMemFree(devid);
742 device = nullptr;
745 for(UINT i{0};i < count;++i)
747 hr = coll->Item(i, al::out_ptr(device));
748 if(FAILED(hr))
749 continue;
751 if(WCHAR *devid{GetDeviceId(device.get())})
753 std::ignore = AddDevice(device, devid, list);
754 CoTaskMemFree(devid);
756 device = nullptr;
758 #else
759 const auto deviceRole = Windows::Media::Devices::AudioDeviceRole::Default;
760 auto DefaultAudioId = flowdir == eRender ? MediaDevice::GetDefaultAudioRenderId(deviceRole)
761 : MediaDevice::GetDefaultAudioCaptureId(deviceRole);
762 if(!DefaultAudioId.empty())
764 auto deviceInfo = DeviceInformation::CreateFromIdAsync(DefaultAudioId, nullptr,
765 DeviceInformationKind::DeviceInterface).get();
766 if(deviceInfo)
767 defaultId = deviceInfo.Id().data();
770 // Get the string identifier of the audio renderer
771 auto AudioSelector = flowdir == eRender ? MediaDevice::GetAudioRenderSelector() : MediaDevice::GetAudioCaptureSelector();
773 // Setup the asynchronous callback
774 auto&& DeviceInfoCollection = DeviceInformation::FindAllAsync(AudioSelector, /*PropertyList*/nullptr, DeviceInformationKind::DeviceInterface).get();
775 if(DeviceInfoCollection)
777 try {
778 auto deviceCount = DeviceInfoCollection.Size();
779 for(unsigned int i{0};i < deviceCount;++i)
781 auto deviceInfo = DeviceInfoCollection.GetAt(i);
782 if(deviceInfo)
783 std::ignore = AddDevice(deviceInfo, deviceInfo.Id().data(), list);
786 catch (const winrt::hresult_error& /*ex*/) {
789 #endif
791 return defaultId;
794 private:
795 static bool AddDevice(const DeviceHandle &device, const WCHAR *devid, std::vector<DevMap> &list)
797 for(auto &entry : list)
799 if(entry.devid == devid)
800 return false;
803 auto name_guid = GetDeviceNameAndGuid(device);
804 int count{1};
805 std::string newname{name_guid.mName};
806 while(checkName(list, newname))
808 newname = name_guid.mName;
809 newname += " #";
810 newname += std::to_string(++count);
812 list.emplace_back(std::move(newname), std::move(name_guid.mGuid), devid);
813 const DevMap &newentry = list.back();
815 TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry.name.c_str(),
816 newentry.endpoint_guid.c_str(), newentry.devid.c_str());
817 return true;
820 #if !ALSOFT_UWP
821 static WCHAR *GetDeviceId(IMMDevice *device)
823 WCHAR *devid;
825 const HRESULT hr{device->GetId(&devid)};
826 if(FAILED(hr))
828 ERR("Failed to get device id: %lx\n", hr);
829 return nullptr;
832 return devid;
834 ComPtr<IMMDeviceEnumerator> mEnumerator{nullptr};
836 #else
838 HANDLE mActiveClientEvent{nullptr};
840 EventRegistrationToken mRenderDeviceChangedToken;
841 EventRegistrationToken mCaptureDeviceChangedToken;
842 #endif
845 bool MakeExtensible(WAVEFORMATEXTENSIBLE *out, const WAVEFORMATEX *in)
847 *out = WAVEFORMATEXTENSIBLE{};
848 if(in->wFormatTag == WAVE_FORMAT_EXTENSIBLE)
850 *out = *CONTAINING_RECORD(in, const WAVEFORMATEXTENSIBLE, Format);
851 out->Format.cbSize = sizeof(*out) - sizeof(out->Format);
853 else if(in->wFormatTag == WAVE_FORMAT_PCM)
855 out->Format = *in;
856 out->Format.cbSize = 0;
857 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
858 out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
859 if(out->Format.nChannels == 1)
860 out->dwChannelMask = MONO;
861 else if(out->Format.nChannels == 2)
862 out->dwChannelMask = STEREO;
863 else
864 ERR("Unhandled PCM channel count: %d\n", out->Format.nChannels);
865 out->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
867 else if(in->wFormatTag == WAVE_FORMAT_IEEE_FLOAT)
869 out->Format = *in;
870 out->Format.cbSize = 0;
871 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
872 out->Samples.wValidBitsPerSample = out->Format.wBitsPerSample;
873 if(out->Format.nChannels == 1)
874 out->dwChannelMask = MONO;
875 else if(out->Format.nChannels == 2)
876 out->dwChannelMask = STEREO;
877 else
878 ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels);
879 out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
881 else
883 ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag);
884 return false;
886 return true;
889 void TraceFormat(const char *msg, const WAVEFORMATEX *format)
891 constexpr size_t fmtex_extra_size{sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX)};
892 if(format->wFormatTag == WAVE_FORMAT_EXTENSIBLE && format->cbSize >= fmtex_extra_size)
894 const WAVEFORMATEXTENSIBLE *fmtex{
895 CONTAINING_RECORD(format, const WAVEFORMATEXTENSIBLE, Format)};
896 /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
897 TRACE("%s:\n"
898 " FormatTag = 0x%04x\n"
899 " Channels = %d\n"
900 " SamplesPerSec = %lu\n"
901 " AvgBytesPerSec = %lu\n"
902 " BlockAlign = %d\n"
903 " BitsPerSample = %d\n"
904 " Size = %d\n"
905 " Samples = %d\n"
906 " ChannelMask = 0x%lx\n"
907 " SubFormat = %s\n",
908 msg, fmtex->Format.wFormatTag, fmtex->Format.nChannels, fmtex->Format.nSamplesPerSec,
909 fmtex->Format.nAvgBytesPerSec, fmtex->Format.nBlockAlign, fmtex->Format.wBitsPerSample,
910 fmtex->Format.cbSize, fmtex->Samples.wReserved, fmtex->dwChannelMask,
911 GuidPrinter{fmtex->SubFormat}.c_str());
912 /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
914 else
915 TRACE("%s:\n"
916 " FormatTag = 0x%04x\n"
917 " Channels = %d\n"
918 " SamplesPerSec = %lu\n"
919 " AvgBytesPerSec = %lu\n"
920 " BlockAlign = %d\n"
921 " BitsPerSample = %d\n"
922 " Size = %d\n",
923 msg, format->wFormatTag, format->nChannels, format->nSamplesPerSec,
924 format->nAvgBytesPerSec, format->nBlockAlign, format->wBitsPerSample, format->cbSize);
928 enum class MsgType {
929 OpenDevice,
930 ResetDevice,
931 StartDevice,
932 StopDevice,
933 CloseDevice,
935 QuitThread
938 constexpr const char *GetMessageTypeName(MsgType type) noexcept
940 switch(type)
942 case MsgType::OpenDevice: return "Open Device";
943 case MsgType::ResetDevice: return "Reset Device";
944 case MsgType::StartDevice: return "Start Device";
945 case MsgType::StopDevice: return "Stop Device";
946 case MsgType::CloseDevice: return "Close Device";
947 case MsgType::QuitThread: break;
949 return "";
953 /* Proxy interface used by the message handler. */
954 struct WasapiProxy {
955 WasapiProxy() = default;
956 WasapiProxy(const WasapiProxy&) = delete;
957 WasapiProxy(WasapiProxy&&) = delete;
958 virtual ~WasapiProxy() = default;
960 void operator=(const WasapiProxy&) = delete;
961 void operator=(WasapiProxy&&) = delete;
963 virtual HRESULT openProxy(std::string_view name) = 0;
964 virtual void closeProxy() = 0;
966 virtual HRESULT resetProxy() = 0;
967 virtual HRESULT startProxy() = 0;
968 virtual void stopProxy() = 0;
970 struct Msg {
971 MsgType mType;
972 WasapiProxy *mProxy;
973 std::string_view mParam;
974 std::promise<HRESULT> mPromise;
976 explicit operator bool() const noexcept { return mType != MsgType::QuitThread; }
978 static inline std::deque<Msg> mMsgQueue;
979 static inline std::mutex mMsgQueueLock;
980 static inline std::condition_variable mMsgQueueCond;
981 static inline DWORD sAvIndex{};
983 static inline std::optional<DeviceHelper> sDeviceHelper;
985 std::future<HRESULT> pushMessage(MsgType type, std::string_view param={})
987 std::promise<HRESULT> promise;
988 std::future<HRESULT> future{promise.get_future()};
990 std::lock_guard<std::mutex> msglock{mMsgQueueLock};
991 mMsgQueue.emplace_back(Msg{type, this, param, std::move(promise)});
993 mMsgQueueCond.notify_one();
994 return future;
997 static std::future<HRESULT> pushMessageStatic(MsgType type)
999 std::promise<HRESULT> promise;
1000 std::future<HRESULT> future{promise.get_future()};
1002 std::lock_guard<std::mutex> msglock{mMsgQueueLock};
1003 mMsgQueue.emplace_back(Msg{type, nullptr, {}, std::move(promise)});
1005 mMsgQueueCond.notify_one();
1006 return future;
1009 static Msg popMessage()
1011 std::unique_lock<std::mutex> lock{mMsgQueueLock};
1012 mMsgQueueCond.wait(lock, []{return !mMsgQueue.empty();});
1013 Msg msg{std::move(mMsgQueue.front())};
1014 mMsgQueue.pop_front();
1015 return msg;
1018 static int messageHandler(std::promise<HRESULT> *promise);
1021 int WasapiProxy::messageHandler(std::promise<HRESULT> *promise)
1023 TRACE("Starting message thread\n");
1025 ComWrapper com{COINIT_MULTITHREADED};
1026 if(!com)
1028 WARN("Failed to initialize COM: 0x%08lx\n", com.status());
1029 promise->set_value(com.status());
1030 return 0;
1033 struct HelperResetter {
1034 HelperResetter() = default;
1035 HelperResetter(const HelperResetter&) = delete;
1036 auto operator=(const HelperResetter&) -> HelperResetter& = delete;
1037 ~HelperResetter() { sDeviceHelper.reset(); }
1039 HelperResetter scoped_watcher;
1041 HRESULT hr{sDeviceHelper.emplace().init()};
1042 promise->set_value(hr);
1043 promise = nullptr;
1044 if(FAILED(hr))
1045 return 0;
1048 auto devlock = DeviceListLock{gDeviceList};
1049 auto defaultId = sDeviceHelper->probeDevices(eRender, devlock.getPlaybackList());
1050 if(!defaultId.empty()) devlock.setPlaybackDefaultId(defaultId);
1051 defaultId = sDeviceHelper->probeDevices(eCapture, devlock.getCaptureList());
1052 if(!defaultId.empty()) devlock.setCaptureDefaultId(defaultId);
1055 TRACE("Starting message loop\n");
1056 while(Msg msg{popMessage()})
1058 TRACE("Got message \"%s\" (0x%04x, this=%p, param=\"%.*s\")\n",
1059 GetMessageTypeName(msg.mType), static_cast<uint>(msg.mType),
1060 static_cast<void*>(msg.mProxy), al::sizei(msg.mParam), msg.mParam.data());
1062 switch(msg.mType)
1064 case MsgType::OpenDevice:
1065 hr = msg.mProxy->openProxy(msg.mParam);
1066 msg.mPromise.set_value(hr);
1067 continue;
1069 case MsgType::ResetDevice:
1070 hr = msg.mProxy->resetProxy();
1071 msg.mPromise.set_value(hr);
1072 continue;
1074 case MsgType::StartDevice:
1075 hr = msg.mProxy->startProxy();
1076 msg.mPromise.set_value(hr);
1077 continue;
1079 case MsgType::StopDevice:
1080 msg.mProxy->stopProxy();
1081 msg.mPromise.set_value(S_OK);
1082 continue;
1084 case MsgType::CloseDevice:
1085 msg.mProxy->closeProxy();
1086 msg.mPromise.set_value(S_OK);
1087 continue;
1089 case MsgType::QuitThread:
1090 break;
1092 ERR("Unexpected message: %u\n", static_cast<uint>(msg.mType));
1093 msg.mPromise.set_value(E_FAIL);
1095 TRACE("Message loop finished\n");
1097 return 0;
1100 struct WasapiPlayback final : public BackendBase, WasapiProxy {
1101 WasapiPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
1102 ~WasapiPlayback() override;
1104 int mixerProc();
1105 int mixerSpatialProc();
1107 void open(std::string_view name) override;
1108 HRESULT openProxy(std::string_view name) override;
1109 void closeProxy() override;
1111 bool reset() override;
1112 HRESULT resetProxy() override;
1113 void start() override;
1114 HRESULT startProxy() override;
1115 void stop() override;
1116 void stopProxy() override;
1118 ClockLatency getClockLatency() override;
1120 void prepareFormat(WAVEFORMATEXTENSIBLE &OutputType);
1121 void finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType);
1123 auto initSpatial() -> bool;
1125 HRESULT mOpenStatus{E_FAIL};
1126 DeviceHandle mMMDev{nullptr};
1128 struct PlainDevice {
1129 ComPtr<IAudioClient> mClient{nullptr};
1130 ComPtr<IAudioRenderClient> mRender{nullptr};
1132 struct SpatialDevice {
1133 ComPtr<ISpatialAudioClient> mClient{nullptr};
1134 ComPtr<ISpatialAudioObjectRenderStream> mRender{nullptr};
1135 AudioObjectType mStaticMask{};
1137 std::variant<PlainDevice,SpatialDevice> mAudio{std::in_place_index_t<0>{}};
1138 HANDLE mNotifyEvent{nullptr};
1140 UINT32 mOutBufferSize{}, mOutUpdateSize{};
1141 std::vector<char> mResampleBuffer{};
1142 uint mBufferFilled{0};
1143 SampleConverterPtr mResampler;
1145 WAVEFORMATEXTENSIBLE mFormat{};
1146 std::atomic<UINT32> mPadding{0u};
1148 std::mutex mMutex;
1150 std::atomic<bool> mKillNow{true};
1151 std::thread mThread;
1154 WasapiPlayback::~WasapiPlayback()
1156 if(SUCCEEDED(mOpenStatus))
1157 pushMessage(MsgType::CloseDevice).wait();
1158 mOpenStatus = E_FAIL;
1160 if(mNotifyEvent != nullptr)
1161 CloseHandle(mNotifyEvent);
1162 mNotifyEvent = nullptr;
1166 FORCE_ALIGN int WasapiPlayback::mixerProc()
1168 ComWrapper com{COINIT_MULTITHREADED};
1169 if(!com)
1171 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
1172 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
1173 return 1;
1176 auto &audio = std::get<PlainDevice>(mAudio);
1178 SetRTPriority();
1179 althrd_setname(GetMixerThreadName());
1181 const uint frame_size{mFormat.Format.nChannels * mFormat.Format.wBitsPerSample / 8u};
1182 const uint update_size{mOutUpdateSize};
1183 const UINT32 buffer_len{mOutBufferSize};
1184 const void *resbufferptr{};
1186 #ifdef AVRTAPI
1187 /* TODO: "Audio" or "Pro Audio"? The suggestion is to use "Pro Audio" for
1188 * device periods less than 10ms, and "Audio" for greater than or equal to
1189 * 10ms.
1191 auto taskname = (update_size < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
1192 auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
1193 #endif
1195 mBufferFilled = 0;
1196 while(!mKillNow.load(std::memory_order_relaxed))
1198 UINT32 written;
1199 HRESULT hr{audio.mClient->GetCurrentPadding(&written)};
1200 if(FAILED(hr))
1202 ERR("Failed to get padding: 0x%08lx\n", hr);
1203 mDevice->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr);
1204 break;
1206 mPadding.store(written, std::memory_order_relaxed);
1208 uint len{buffer_len - written};
1209 if(len < update_size)
1211 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
1212 if(res != WAIT_OBJECT_0)
1213 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1214 continue;
1217 BYTE *buffer;
1218 hr = audio.mRender->GetBuffer(len, &buffer);
1219 if(SUCCEEDED(hr))
1221 if(mResampler)
1223 std::lock_guard<std::mutex> dlock{mMutex};
1224 auto dst = al::span{buffer, size_t{len}*frame_size};
1225 for(UINT32 done{0};done < len;)
1227 if(mBufferFilled == 0)
1229 mDevice->renderSamples(mResampleBuffer.data(), mDevice->UpdateSize,
1230 mFormat.Format.nChannels);
1231 resbufferptr = mResampleBuffer.data();
1232 mBufferFilled = mDevice->UpdateSize;
1235 uint got{mResampler->convert(&resbufferptr, &mBufferFilled, dst.data(),
1236 len-done)};
1237 dst = dst.subspan(size_t{got}*frame_size);
1238 done += got;
1240 mPadding.store(written + done, std::memory_order_relaxed);
1243 else
1245 std::lock_guard<std::mutex> dlock{mMutex};
1246 mDevice->renderSamples(buffer, len, mFormat.Format.nChannels);
1247 mPadding.store(written + len, std::memory_order_relaxed);
1249 hr = audio.mRender->ReleaseBuffer(len, 0);
1251 if(FAILED(hr))
1253 ERR("Failed to buffer data: 0x%08lx\n", hr);
1254 mDevice->handleDisconnect("Failed to send playback samples: 0x%08lx", hr);
1255 break;
1258 mPadding.store(0u, std::memory_order_release);
1260 return 0;
1263 FORCE_ALIGN int WasapiPlayback::mixerSpatialProc()
1265 ComWrapper com{COINIT_MULTITHREADED};
1266 if(!com)
1268 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
1269 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
1270 return 1;
1273 auto &audio = std::get<SpatialDevice>(mAudio);
1275 SetRTPriority();
1276 althrd_setname(GetMixerThreadName());
1278 std::vector<ComPtr<ISpatialAudioObject>> channels;
1279 std::vector<void*> buffers;
1280 std::vector<void*> resbuffers;
1281 std::vector<const void*> tmpbuffers;
1283 #ifdef AVRTAPI
1284 auto taskname = (mOutUpdateSize < mFormat.Format.nSamplesPerSec/100) ? L"Pro Audio" : L"Audio";
1285 auto avhandle = AvrtHandlePtr{AvSetMmThreadCharacteristicsW(taskname, &sAvIndex)};
1286 #endif
1288 /* TODO: Set mPadding appropriately. There doesn't seem to be a way to
1289 * update it dynamically based on the stream, so a fixed size may be the
1290 * best we can do.
1292 mPadding.store(mOutBufferSize-mOutUpdateSize, std::memory_order_release);
1294 mBufferFilled = 0;
1295 while(!mKillNow.load(std::memory_order_relaxed))
1297 if(DWORD res{WaitForSingleObjectEx(mNotifyEvent, 1000, FALSE)}; res != WAIT_OBJECT_0)
1299 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1301 HRESULT hr{audio.mRender->Reset()};
1302 if(FAILED(hr))
1304 ERR("ISpatialAudioObjectRenderStream::Reset failed: 0x%08lx\n", hr);
1305 mDevice->handleDisconnect("Device lost: 0x%08lx", hr);
1306 break;
1310 UINT32 dynamicCount{}, framesToDo{};
1311 HRESULT hr{audio.mRender->BeginUpdatingAudioObjects(&dynamicCount, &framesToDo)};
1312 if(SUCCEEDED(hr))
1314 if(channels.empty()) UNLIKELY
1316 auto flags = as_unsigned(audio.mStaticMask);
1317 channels.reserve(as_unsigned(al::popcount(flags)));
1318 while(flags)
1320 auto id = decltype(flags){1} << al::countr_zero(flags);
1321 flags &= ~id;
1323 channels.emplace_back();
1324 audio.mRender->ActivateSpatialAudioObject(static_cast<AudioObjectType>(id),
1325 al::out_ptr(channels.back()));
1327 buffers.resize(channels.size());
1328 if(mResampler)
1330 tmpbuffers.resize(buffers.size());
1331 resbuffers.resize(buffers.size());
1332 auto bufptr = mResampleBuffer.begin();
1333 for(size_t i{0};i < tmpbuffers.size();++i)
1335 resbuffers[i] = al::to_address(bufptr);
1336 bufptr += ptrdiff_t(mDevice->UpdateSize*sizeof(float));
1341 /* We have to call to get each channel's buffer individually every
1342 * update, unfortunately.
1344 std::transform(channels.cbegin(), channels.cend(), buffers.begin(),
1345 [](const ComPtr<ISpatialAudioObject> &obj) -> void*
1347 auto buffer = LPBYTE{};
1348 auto size = UINT32{};
1349 obj->GetBuffer(&buffer, &size);
1350 return buffer;
1353 if(!mResampler)
1354 mDevice->renderSamples(buffers, framesToDo);
1355 else
1357 std::lock_guard<std::mutex> dlock{mMutex};
1358 for(UINT32 pos{0};pos < framesToDo;)
1360 if(mBufferFilled == 0)
1362 mDevice->renderSamples(resbuffers, mDevice->UpdateSize);
1363 std::copy(resbuffers.cbegin(), resbuffers.cend(), tmpbuffers.begin());
1364 mBufferFilled = mDevice->UpdateSize;
1367 const uint got{mResampler->convertPlanar(tmpbuffers.data(), &mBufferFilled,
1368 buffers.data(), framesToDo-pos)};
1369 for(auto &buf : buffers)
1370 buf = static_cast<float*>(buf) + got; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
1371 pos += got;
1375 hr = audio.mRender->EndUpdatingAudioObjects();
1378 if(FAILED(hr))
1379 ERR("Failed to update playback objects: 0x%08lx\n", hr);
1381 mPadding.store(0u, std::memory_order_release);
1383 return 0;
1387 void WasapiPlayback::open(std::string_view name)
1389 if(SUCCEEDED(mOpenStatus))
1390 throw al::backend_exception{al::backend_error::DeviceError,
1391 "Unexpected duplicate open call"};
1393 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1394 if(mNotifyEvent == nullptr)
1396 ERR("Failed to create notify events: %lu\n", GetLastError());
1397 throw al::backend_exception{al::backend_error::DeviceError,
1398 "Failed to create notify events"};
1401 mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
1402 if(FAILED(mOpenStatus))
1403 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
1404 mOpenStatus};
1407 HRESULT WasapiPlayback::openProxy(std::string_view name)
1409 std::string devname;
1410 std::wstring devid;
1411 if(!name.empty())
1413 auto devlock = DeviceListLock{gDeviceList};
1414 auto list = al::span{devlock.getPlaybackList()};
1415 auto iter = std::find_if(list.cbegin(), list.cend(),
1416 [name](const DevMap &entry) -> bool
1417 { return entry.name == name || entry.endpoint_guid == name; });
1418 if(iter == list.cend())
1420 const std::wstring wname{utf8_to_wstr(name)};
1421 iter = std::find_if(list.cbegin(), list.cend(),
1422 [&wname](const DevMap &entry) -> bool
1423 { return entry.devid == wname; });
1425 if(iter == list.cend())
1427 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name), name.data());
1428 return E_FAIL;
1430 devname = iter->name;
1431 devid = iter->devid;
1434 HRESULT hr{sDeviceHelper->openDevice(devid, eRender, mMMDev)};
1435 if(FAILED(hr))
1437 WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
1438 return hr;
1440 if(!devname.empty())
1441 mDeviceName = std::move(devname);
1442 else
1443 mDeviceName = GetDeviceNameAndGuid(mMMDev).mName;
1445 return S_OK;
1448 void WasapiPlayback::closeProxy()
1450 mAudio.emplace<PlainDevice>();
1451 mMMDev = nullptr;
1455 void WasapiPlayback::prepareFormat(WAVEFORMATEXTENSIBLE &OutputType)
1457 bool isRear51{false};
1459 if(!mDevice->Flags.test(FrequencyRequest))
1460 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
1461 if(!mDevice->Flags.test(ChannelsRequest))
1463 /* If not requesting a channel configuration, auto-select given what
1464 * fits the mask's lsb (to ensure no gaps in the output channels). If
1465 * there's no mask, we can only assume mono or stereo.
1467 const uint32_t chancount{OutputType.Format.nChannels};
1468 const DWORD chanmask{OutputType.dwChannelMask};
1469 if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
1470 mDevice->FmtChans = DevFmtX714;
1471 else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1472 mDevice->FmtChans = DevFmtX71;
1473 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1474 mDevice->FmtChans = DevFmtX61;
1475 else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1)
1476 mDevice->FmtChans = DevFmtX51;
1477 else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR)
1479 mDevice->FmtChans = DevFmtX51;
1480 isRear51 = true;
1482 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1483 mDevice->FmtChans = DevFmtQuad;
1484 else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
1485 mDevice->FmtChans = DevFmtStereo;
1486 else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
1487 mDevice->FmtChans = DevFmtMono;
1488 else
1489 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask);
1491 else
1493 const uint32_t chancount{OutputType.Format.nChannels};
1494 const DWORD chanmask{OutputType.dwChannelMask};
1495 isRear51 = (chancount == 6 && (chanmask&X51RearMask) == X5DOT1REAR);
1498 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1499 switch(mDevice->FmtChans)
1501 case DevFmtMono:
1502 OutputType.Format.nChannels = 1;
1503 OutputType.dwChannelMask = MONO;
1504 break;
1505 case DevFmtAmbi3D:
1506 mDevice->FmtChans = DevFmtStereo;
1507 /*fall-through*/
1508 case DevFmtStereo:
1509 OutputType.Format.nChannels = 2;
1510 OutputType.dwChannelMask = STEREO;
1511 break;
1512 case DevFmtQuad:
1513 OutputType.Format.nChannels = 4;
1514 OutputType.dwChannelMask = QUAD;
1515 break;
1516 case DevFmtX51:
1517 OutputType.Format.nChannels = 6;
1518 OutputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
1519 break;
1520 case DevFmtX61:
1521 OutputType.Format.nChannels = 7;
1522 OutputType.dwChannelMask = X6DOT1;
1523 break;
1524 case DevFmtX71:
1525 case DevFmtX3D71:
1526 OutputType.Format.nChannels = 8;
1527 OutputType.dwChannelMask = X7DOT1;
1528 break;
1529 case DevFmtX7144:
1530 mDevice->FmtChans = DevFmtX714;
1531 /*fall-through*/
1532 case DevFmtX714:
1533 OutputType.Format.nChannels = 12;
1534 OutputType.dwChannelMask = X7DOT1DOT4;
1535 break;
1537 switch(mDevice->FmtType)
1539 case DevFmtByte:
1540 mDevice->FmtType = DevFmtUByte;
1541 /* fall-through */
1542 case DevFmtUByte:
1543 OutputType.Format.wBitsPerSample = 8;
1544 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1545 break;
1546 case DevFmtUShort:
1547 mDevice->FmtType = DevFmtShort;
1548 /* fall-through */
1549 case DevFmtShort:
1550 OutputType.Format.wBitsPerSample = 16;
1551 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1552 break;
1553 case DevFmtUInt:
1554 mDevice->FmtType = DevFmtInt;
1555 /* fall-through */
1556 case DevFmtInt:
1557 OutputType.Format.wBitsPerSample = 32;
1558 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1559 break;
1560 case DevFmtFloat:
1561 OutputType.Format.wBitsPerSample = 32;
1562 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1563 break;
1565 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1566 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1567 OutputType.Format.nSamplesPerSec = mDevice->Frequency;
1569 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
1570 OutputType.Format.wBitsPerSample / 8);
1571 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
1572 OutputType.Format.nBlockAlign;
1575 void WasapiPlayback::finalizeFormat(WAVEFORMATEXTENSIBLE &OutputType)
1577 if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
1578 mDevice->Frequency = uint(OutputType.Format.nSamplesPerSec);
1579 else
1580 mDevice->Frequency = std::min(mDevice->Frequency, uint(OutputType.Format.nSamplesPerSec));
1582 const uint32_t chancount{OutputType.Format.nChannels};
1583 const DWORD chanmask{OutputType.dwChannelMask};
1584 /* Don't update the channel format if the requested format fits what's
1585 * supported.
1587 bool chansok{false};
1588 if(mDevice->Flags.test(ChannelsRequest))
1590 /* When requesting a channel configuration, make sure it fits the
1591 * mask's lsb (to ensure no gaps in the output channels). If there's no
1592 * mask, assume the request fits with enough channels.
1594 switch(mDevice->FmtChans)
1596 case DevFmtMono:
1597 chansok = (chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask));
1598 break;
1599 case DevFmtStereo:
1600 chansok = (chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask));
1601 break;
1602 case DevFmtQuad:
1603 chansok = (chancount >= 4 && ((chanmask&QuadMask) == QUAD || !chanmask));
1604 break;
1605 case DevFmtX51:
1606 chansok = (chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1607 || (chanmask&X51RearMask) == X5DOT1REAR || !chanmask));
1608 break;
1609 case DevFmtX61:
1610 chansok = (chancount >= 7 && ((chanmask&X61Mask) == X6DOT1 || !chanmask));
1611 break;
1612 case DevFmtX71:
1613 case DevFmtX3D71:
1614 chansok = (chancount >= 8 && ((chanmask&X71Mask) == X7DOT1 || !chanmask));
1615 break;
1616 case DevFmtX714:
1617 chansok = (chancount >= 12 && ((chanmask&X714Mask) == X7DOT1DOT4 || !chanmask));
1618 case DevFmtX7144:
1619 case DevFmtAmbi3D:
1620 break;
1623 if(!chansok)
1625 if(chancount >= 12 && (chanmask&X714Mask) == X7DOT1DOT4)
1626 mDevice->FmtChans = DevFmtX714;
1627 else if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1628 mDevice->FmtChans = DevFmtX71;
1629 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1630 mDevice->FmtChans = DevFmtX61;
1631 else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1632 || (chanmask&X51RearMask) == X5DOT1REAR))
1633 mDevice->FmtChans = DevFmtX51;
1634 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1635 mDevice->FmtChans = DevFmtQuad;
1636 else if(chancount >= 2 && ((chanmask&StereoMask) == STEREO || !chanmask))
1637 mDevice->FmtChans = DevFmtStereo;
1638 else if(chancount >= 1 && ((chanmask&MonoMask) == MONO || !chanmask))
1639 mDevice->FmtChans = DevFmtMono;
1640 else
1642 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1643 OutputType.dwChannelMask);
1644 mDevice->FmtChans = DevFmtStereo;
1645 OutputType.Format.nChannels = 2;
1646 OutputType.dwChannelMask = STEREO;
1650 if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
1652 if(OutputType.Format.wBitsPerSample == 8)
1653 mDevice->FmtType = DevFmtUByte;
1654 else if(OutputType.Format.wBitsPerSample == 16)
1655 mDevice->FmtType = DevFmtShort;
1656 else if(OutputType.Format.wBitsPerSample == 32)
1657 mDevice->FmtType = DevFmtInt;
1658 else
1660 mDevice->FmtType = DevFmtShort;
1661 OutputType.Format.wBitsPerSample = 16;
1664 else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1666 mDevice->FmtType = DevFmtFloat;
1667 OutputType.Format.wBitsPerSample = 32;
1669 else
1671 ERR("Unhandled format sub-type: %s\n", GuidPrinter{OutputType.SubFormat}.c_str());
1672 mDevice->FmtType = DevFmtShort;
1673 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
1674 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
1675 OutputType.Format.wBitsPerSample = 16;
1676 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1678 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1679 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1683 auto WasapiPlayback::initSpatial() -> bool
1685 auto &audio = mAudio.emplace<SpatialDevice>();
1686 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(ISpatialAudioClient),
1687 al::out_ptr(audio.mClient))};
1688 if(FAILED(hr))
1690 ERR("Failed to activate spatial audio client: 0x%08lx\n", hr);
1691 return false;
1694 ComPtr<IAudioFormatEnumerator> fmtenum;
1695 hr = audio.mClient->GetSupportedAudioObjectFormatEnumerator(al::out_ptr(fmtenum));
1696 if(FAILED(hr))
1698 ERR("Failed to get format enumerator: 0x%08lx\n", hr);
1699 return false;
1702 UINT32 fmtcount{};
1703 hr = fmtenum->GetCount(&fmtcount);
1704 if(FAILED(hr) || fmtcount == 0)
1706 ERR("Failed to get format count: 0x%08lx\n", hr);
1707 return false;
1710 WAVEFORMATEX *preferredFormat{};
1711 hr = fmtenum->GetFormat(0, &preferredFormat);
1712 if(FAILED(hr))
1714 ERR("Failed to get preferred format: 0x%08lx\n", hr);
1715 return false;
1717 TraceFormat("Preferred mix format", preferredFormat);
1719 UINT32 maxFrames{};
1720 hr = audio.mClient->GetMaxFrameCount(preferredFormat, &maxFrames);
1721 if(FAILED(hr))
1722 ERR("Failed to get max frames: 0x%08lx\n", hr);
1723 else
1724 TRACE("Max sample frames: %u\n", maxFrames);
1725 for(UINT32 i{1};i < fmtcount;++i)
1727 WAVEFORMATEX *otherFormat{};
1728 hr = fmtenum->GetFormat(i, &otherFormat);
1729 if(FAILED(hr))
1730 ERR("Failed to format %u: 0x%08lx\n", i+1, hr);
1731 else
1733 TraceFormat("Other mix format", otherFormat);
1734 UINT32 otherMaxFrames{};
1735 hr = audio.mClient->GetMaxFrameCount(otherFormat, &otherMaxFrames);
1736 if(FAILED(hr))
1737 ERR("Failed to get max frames: 0x%08lx\n", hr);
1738 else
1739 TRACE("Max sample frames: %u\n", otherMaxFrames);
1743 WAVEFORMATEXTENSIBLE OutputType;
1744 if(!MakeExtensible(&OutputType, preferredFormat))
1745 return false;
1747 /* This seems to be the format of each "object", which should be mono. */
1748 if(!(OutputType.Format.nChannels == 1
1749 && (OutputType.dwChannelMask == MONO || !OutputType.dwChannelMask)))
1750 ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1751 OutputType.dwChannelMask);
1753 /* Force 32-bit float. This is currently required for planar output. */
1754 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE
1755 && OutputType.Format.wFormatTag != WAVE_FORMAT_IEEE_FLOAT)
1757 OutputType.Format.wFormatTag = WAVE_FORMAT_IEEE_FLOAT;
1758 OutputType.Format.cbSize = 0;
1760 if(OutputType.Format.wBitsPerSample != 32)
1762 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nAvgBytesPerSec * 32u
1763 / OutputType.Format.wBitsPerSample;
1764 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nBlockAlign * 32
1765 / OutputType.Format.wBitsPerSample);
1766 OutputType.Format.wBitsPerSample = 32;
1768 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1769 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1770 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1772 /* Match the output rate if not requesting anything specific. */
1773 if(!mDevice->Flags.test(FrequencyRequest))
1774 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
1776 auto getTypeMask = [](DevFmtChannels chans) noexcept
1778 switch(chans)
1780 case DevFmtMono: return ChannelMask_Mono;
1781 case DevFmtStereo: return ChannelMask_Stereo;
1782 case DevFmtQuad: return ChannelMask_Quad;
1783 case DevFmtX51: return ChannelMask_X51;
1784 case DevFmtX61: return ChannelMask_X61;
1785 case DevFmtX3D71: [[fallthrough]];
1786 case DevFmtX71: return ChannelMask_X71;
1787 case DevFmtX714: return ChannelMask_X714;
1788 case DevFmtX7144: return ChannelMask_X7144;
1789 case DevFmtAmbi3D:
1790 break;
1792 return ChannelMask_Stereo;
1795 SpatialAudioObjectRenderStreamActivationParams streamParams{};
1796 streamParams.ObjectFormat = &OutputType.Format;
1797 streamParams.StaticObjectTypeMask = getTypeMask(mDevice->FmtChans);
1798 streamParams.Category = AudioCategory_Media;
1799 streamParams.EventHandle = mNotifyEvent;
1801 PropVariant paramProp{};
1802 paramProp.setBlob({reinterpret_cast<BYTE*>(&streamParams), sizeof(streamParams)});
1804 hr = audio.mClient->ActivateSpatialAudioStream(paramProp.get(),
1805 __uuidof(ISpatialAudioObjectRenderStream), al::out_ptr(audio.mRender));
1806 if(FAILED(hr))
1808 ERR("Failed to activate spatial audio stream: 0x%08lx\n", hr);
1809 return false;
1812 audio.mStaticMask = streamParams.StaticObjectTypeMask;
1813 mFormat = OutputType;
1815 mDevice->FmtType = DevFmtFloat;
1816 mDevice->Flags.reset(DirectEar).set(Virtualization);
1817 if(streamParams.StaticObjectTypeMask == ChannelMask_Stereo)
1818 mDevice->FmtChans = DevFmtStereo;
1819 if(!GetConfigValueBool(mDevice->mDeviceName, "wasapi", "allow-resampler", true))
1820 mDevice->Frequency = uint(OutputType.Format.nSamplesPerSec);
1821 else
1822 mDevice->Frequency = std::min(mDevice->Frequency,
1823 uint(OutputType.Format.nSamplesPerSec));
1825 setDefaultWFXChannelOrder();
1827 /* FIXME: Get the real update and buffer size. Presumably the actual device
1828 * is configured once ActivateSpatialAudioStream succeeds, and an
1829 * IAudioClient from the same IMMDevice accesses the same device
1830 * configuration. This isn't obviously correct, but for now assume
1831 * IAudioClient::GetDevicePeriod returns the current device period time
1832 * that ISpatialAudioObjectRenderStream will try to wake up at.
1834 * Unfortunately this won't get the buffer size of the
1835 * ISpatialAudioObjectRenderStream, so we only assume there's two periods.
1837 mOutUpdateSize = mDevice->UpdateSize;
1838 mOutBufferSize = mOutUpdateSize*2;
1839 ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
1841 ComPtr<IAudioClient> tmpClient;
1842 hr = sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
1843 al::out_ptr(tmpClient));
1844 if(FAILED(hr))
1845 ERR("Failed to activate audio client: 0x%08lx\n", hr);
1846 else
1848 hr = tmpClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(per_time), nullptr);
1849 if(FAILED(hr))
1850 ERR("Failed to get device period: 0x%08lx\n", hr);
1851 else
1853 mOutUpdateSize = RefTime2Samples(per_time, mFormat.Format.nSamplesPerSec);
1854 mOutBufferSize = mOutUpdateSize*2;
1857 tmpClient = nullptr;
1859 mDevice->UpdateSize = RefTime2Samples(per_time, mDevice->Frequency);
1860 mDevice->BufferSize = mDevice->UpdateSize*2;
1862 mResampler = nullptr;
1863 mResampleBuffer.clear();
1864 mResampleBuffer.shrink_to_fit();
1865 mBufferFilled = 0;
1866 if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
1868 const auto flags = as_unsigned(streamParams.StaticObjectTypeMask);
1869 const auto channelCount = as_unsigned(al::popcount(flags));
1870 mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType, channelCount,
1871 mDevice->Frequency, mFormat.Format.nSamplesPerSec, Resampler::FastBSinc24);
1872 mResampleBuffer.resize(size_t{mDevice->UpdateSize} * channelCount *
1873 mFormat.Format.wBitsPerSample / 8);
1875 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
1876 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1877 mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->Frequency,
1878 mDevice->UpdateSize);
1881 return true;
1884 bool WasapiPlayback::reset()
1886 HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
1887 if(FAILED(hr))
1888 throw al::backend_exception{al::backend_error::DeviceError, "0x%08lx", hr};
1889 return true;
1892 HRESULT WasapiPlayback::resetProxy()
1894 if(GetConfigValueBool(mDevice->mDeviceName, "wasapi", "spatial-api", false))
1896 if(initSpatial())
1897 return S_OK;
1900 mDevice->Flags.reset(Virtualization);
1902 auto &audio = mAudio.emplace<PlainDevice>();
1903 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
1904 al::out_ptr(audio.mClient))};
1905 if(FAILED(hr))
1907 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
1908 return hr;
1911 WAVEFORMATEX *wfx;
1912 hr = audio.mClient->GetMixFormat(&wfx);
1913 if(FAILED(hr))
1915 ERR("Failed to get mix format: 0x%08lx\n", hr);
1916 return hr;
1918 TraceFormat("Device mix format", wfx);
1920 WAVEFORMATEXTENSIBLE OutputType;
1921 if(!MakeExtensible(&OutputType, wfx))
1923 CoTaskMemFree(wfx);
1924 return E_FAIL;
1926 CoTaskMemFree(wfx);
1927 wfx = nullptr;
1929 const ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
1930 const ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
1932 prepareFormat(OutputType);
1934 TraceFormat("Requesting playback format", &OutputType.Format);
1935 hr = audio.mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
1936 if(FAILED(hr))
1938 WARN("Failed to check format support: 0x%08lx\n", hr);
1939 hr = audio.mClient->GetMixFormat(&wfx);
1941 if(FAILED(hr))
1943 ERR("Failed to find a supported format: 0x%08lx\n", hr);
1944 return hr;
1947 if(wfx != nullptr)
1949 TraceFormat("Got playback format", wfx);
1950 if(!MakeExtensible(&OutputType, wfx))
1952 CoTaskMemFree(wfx);
1953 return E_FAIL;
1955 CoTaskMemFree(wfx);
1956 wfx = nullptr;
1958 finalizeFormat(OutputType);
1960 mFormat = OutputType;
1962 #if !ALSOFT_UWP
1963 const EndpointFormFactor formfactor{GetDeviceFormfactor(mMMDev.get())};
1964 mDevice->Flags.set(DirectEar, (formfactor == Headphones || formfactor == Headset));
1965 #else
1966 mDevice->Flags.set(DirectEar, false);
1967 #endif
1968 setDefaultWFXChannelOrder();
1970 hr = audio.mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
1971 buf_time.count(), 0, &OutputType.Format, nullptr);
1972 if(FAILED(hr))
1974 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
1975 return hr;
1978 UINT32 buffer_len{};
1979 ReferenceTime min_per{};
1980 hr = audio.mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
1981 if(SUCCEEDED(hr))
1982 hr = audio.mClient->GetBufferSize(&buffer_len);
1983 if(FAILED(hr))
1985 ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
1986 return hr;
1989 hr = audio.mClient->SetEventHandle(mNotifyEvent);
1990 if(FAILED(hr))
1992 ERR("Failed to set event handle: 0x%08lx\n", hr);
1993 return hr;
1996 hr = audio.mClient->GetService(__uuidof(IAudioRenderClient), al::out_ptr(audio.mRender));
1997 if(FAILED(hr))
1999 ERR("Failed to get IAudioRenderClient: 0x%08lx\n", hr);
2000 return hr;
2003 /* Find the nearest multiple of the period size to the update size */
2004 if(min_per < per_time)
2005 min_per *= std::max<int64_t>((per_time + min_per/2) / min_per, 1_i64);
2007 mOutBufferSize = buffer_len;
2008 mOutUpdateSize = std::min(RefTime2Samples(min_per, mFormat.Format.nSamplesPerSec),
2009 buffer_len/2u);
2011 mDevice->BufferSize = static_cast<uint>(uint64_t{buffer_len} * mDevice->Frequency /
2012 mFormat.Format.nSamplesPerSec);
2013 mDevice->UpdateSize = std::min(RefTime2Samples(min_per, mDevice->Frequency),
2014 mDevice->BufferSize/2u);
2016 mResampler = nullptr;
2017 mResampleBuffer.clear();
2018 mResampleBuffer.shrink_to_fit();
2019 mBufferFilled = 0;
2020 if(mDevice->Frequency != mFormat.Format.nSamplesPerSec)
2022 mResampler = SampleConverter::Create(mDevice->FmtType, mDevice->FmtType,
2023 mFormat.Format.nChannels, mDevice->Frequency, mFormat.Format.nSamplesPerSec,
2024 Resampler::FastBSinc24);
2025 mResampleBuffer.resize(size_t{mDevice->UpdateSize} * mFormat.Format.nChannels *
2026 mFormat.Format.wBitsPerSample / 8);
2028 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
2029 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2030 mFormat.Format.nSamplesPerSec, mOutUpdateSize, mDevice->Frequency,
2031 mDevice->UpdateSize);
2034 return hr;
2038 void WasapiPlayback::start()
2040 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
2041 if(FAILED(hr))
2042 throw al::backend_exception{al::backend_error::DeviceError,
2043 "Failed to start playback: 0x%lx", hr};
2046 HRESULT WasapiPlayback::startProxy()
2048 ResetEvent(mNotifyEvent);
2050 auto start_plain = [&](PlainDevice &audio) -> HRESULT
2052 HRESULT hr{audio.mClient->Start()};
2053 if(FAILED(hr))
2055 ERR("Failed to start audio client: 0x%08lx\n", hr);
2056 return hr;
2059 try {
2060 mKillNow.store(false, std::memory_order_release);
2061 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerProc), this};
2063 catch(...) {
2064 ERR("Failed to start thread\n");
2065 audio.mClient->Stop();
2066 hr = E_FAIL;
2068 return hr;
2070 auto start_spatial = [&](SpatialDevice &audio) -> HRESULT
2072 HRESULT hr{audio.mRender->Start()};
2073 if(FAILED(hr))
2075 ERR("Failed to start spatial audio stream: 0x%08lx\n", hr);
2076 return hr;
2079 try {
2080 mKillNow.store(false, std::memory_order_release);
2081 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerSpatialProc), this};
2083 catch(...) {
2084 ERR("Failed to start thread\n");
2085 hr = E_FAIL;
2088 if(FAILED(hr))
2090 audio.mRender->Stop();
2091 audio.mRender->Reset();
2093 return hr;
2096 return std::visit(overloaded{start_plain, start_spatial}, mAudio);
2100 void WasapiPlayback::stop()
2101 { pushMessage(MsgType::StopDevice).wait(); }
2103 void WasapiPlayback::stopProxy()
2105 if(!mThread.joinable())
2106 return;
2108 mKillNow.store(true, std::memory_order_release);
2109 mThread.join();
2111 auto stop_plain = [](PlainDevice &audio) -> void
2112 { audio.mClient->Stop(); };
2113 auto stop_spatial = [](SpatialDevice &audio) -> void
2115 audio.mRender->Stop();
2116 audio.mRender->Reset();
2118 std::visit(overloaded{stop_plain, stop_spatial}, mAudio);
2122 ClockLatency WasapiPlayback::getClockLatency()
2124 std::lock_guard<std::mutex> dlock{mMutex};
2125 ClockLatency ret{};
2126 ret.ClockTime = mDevice->getClockTime();
2127 ret.Latency = seconds{mPadding.load(std::memory_order_relaxed)};
2128 ret.Latency /= mFormat.Format.nSamplesPerSec;
2129 if(mResampler)
2131 auto extra = mResampler->currentInputDelay();
2132 ret.Latency += std::chrono::duration_cast<nanoseconds>(extra) / mDevice->Frequency;
2133 ret.Latency += nanoseconds{seconds{mBufferFilled}} / mDevice->Frequency;
2136 return ret;
2140 struct WasapiCapture final : public BackendBase, WasapiProxy {
2141 WasapiCapture(DeviceBase *device) noexcept : BackendBase{device} { }
2142 ~WasapiCapture() override;
2144 int recordProc();
2146 void open(std::string_view name) override;
2147 HRESULT openProxy(std::string_view name) override;
2148 void closeProxy() override;
2150 HRESULT resetProxy() override;
2151 void start() override;
2152 HRESULT startProxy() override;
2153 void stop() override;
2154 void stopProxy() override;
2156 void captureSamples(std::byte *buffer, uint samples) override;
2157 uint availableSamples() override;
2159 HRESULT mOpenStatus{E_FAIL};
2160 DeviceHandle mMMDev{nullptr};
2161 ComPtr<IAudioClient> mClient{nullptr};
2162 ComPtr<IAudioCaptureClient> mCapture{nullptr};
2163 HANDLE mNotifyEvent{nullptr};
2165 ChannelConverter mChannelConv{};
2166 SampleConverterPtr mSampleConv;
2167 RingBufferPtr mRing;
2169 std::atomic<bool> mKillNow{true};
2170 std::thread mThread;
2173 WasapiCapture::~WasapiCapture()
2175 if(SUCCEEDED(mOpenStatus))
2176 pushMessage(MsgType::CloseDevice).wait();
2177 mOpenStatus = E_FAIL;
2179 if(mNotifyEvent != nullptr)
2180 CloseHandle(mNotifyEvent);
2181 mNotifyEvent = nullptr;
2185 FORCE_ALIGN int WasapiCapture::recordProc()
2187 ComWrapper com{COINIT_MULTITHREADED};
2188 if(!com)
2190 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com.status());
2191 mDevice->handleDisconnect("COM init failed: 0x%08lx", com.status());
2192 return 1;
2195 althrd_setname(GetRecordThreadName());
2197 std::vector<float> samples;
2198 while(!mKillNow.load(std::memory_order_relaxed))
2200 UINT32 avail;
2201 HRESULT hr{mCapture->GetNextPacketSize(&avail)};
2202 if(FAILED(hr))
2203 ERR("Failed to get next packet size: 0x%08lx\n", hr);
2204 else if(avail > 0)
2206 UINT32 numsamples;
2207 DWORD flags;
2208 BYTE *rdata;
2210 hr = mCapture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
2211 if(FAILED(hr))
2212 ERR("Failed to get capture buffer: 0x%08lx\n", hr);
2213 else
2215 if(mChannelConv.is_active())
2217 samples.resize(numsamples*2_uz);
2218 mChannelConv.convert(rdata, samples.data(), numsamples);
2219 rdata = reinterpret_cast<BYTE*>(samples.data());
2222 auto data = mRing->getWriteVector();
2224 size_t dstframes;
2225 if(mSampleConv)
2227 static constexpr auto lenlimit = size_t{std::numeric_limits<int>::max()};
2228 const void *srcdata{rdata};
2229 uint srcframes{numsamples};
2231 dstframes = mSampleConv->convert(&srcdata, &srcframes, data[0].buf,
2232 static_cast<uint>(std::min(data[0].len, lenlimit)));
2233 if(srcframes > 0 && dstframes == data[0].len && data[1].len > 0)
2235 /* If some source samples remain, all of the first dest
2236 * block was filled, and there's space in the second
2237 * dest block, do another run for the second block.
2239 dstframes += mSampleConv->convert(&srcdata, &srcframes, data[1].buf,
2240 static_cast<uint>(std::min(data[1].len, lenlimit)));
2243 else
2245 const uint framesize{mDevice->frameSizeFromFmt()};
2246 auto dst = al::span{rdata, size_t{numsamples}*framesize};
2247 size_t len1{std::min(data[0].len, size_t{numsamples})};
2248 size_t len2{std::min(data[1].len, numsamples-len1)};
2250 memcpy(data[0].buf, dst.data(), len1*framesize);
2251 if(len2 > 0)
2253 dst = dst.subspan(len1*framesize);
2254 memcpy(data[1].buf, dst.data(), len2*framesize);
2256 dstframes = len1 + len2;
2259 mRing->writeAdvance(dstframes);
2261 hr = mCapture->ReleaseBuffer(numsamples);
2262 if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
2266 if(FAILED(hr))
2268 mDevice->handleDisconnect("Failed to capture samples: 0x%08lx", hr);
2269 break;
2272 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
2273 if(res != WAIT_OBJECT_0)
2274 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
2277 return 0;
2281 void WasapiCapture::open(std::string_view name)
2283 if(SUCCEEDED(mOpenStatus))
2284 throw al::backend_exception{al::backend_error::DeviceError,
2285 "Unexpected duplicate open call"};
2287 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
2288 if(mNotifyEvent == nullptr)
2290 ERR("Failed to create notify events: %lu\n", GetLastError());
2291 throw al::backend_exception{al::backend_error::DeviceError,
2292 "Failed to create notify events"};
2295 mOpenStatus = pushMessage(MsgType::OpenDevice, name).get();
2296 if(FAILED(mOpenStatus))
2297 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
2298 mOpenStatus};
2300 HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
2301 if(FAILED(hr))
2303 if(hr == E_OUTOFMEMORY)
2304 throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"};
2305 throw al::backend_exception{al::backend_error::DeviceError, "Device reset failed"};
2309 HRESULT WasapiCapture::openProxy(std::string_view name)
2311 std::string devname;
2312 std::wstring devid;
2313 if(!name.empty())
2315 auto devlock = DeviceListLock{gDeviceList};
2316 auto devlist = al::span{devlock.getCaptureList()};
2317 auto iter = std::find_if(devlist.cbegin(), devlist.cend(),
2318 [name](const DevMap &entry) -> bool
2319 { return entry.name == name || entry.endpoint_guid == name; });
2320 if(iter == devlist.cend())
2322 const std::wstring wname{utf8_to_wstr(name)};
2323 iter = std::find_if(devlist.cbegin(), devlist.cend(),
2324 [&wname](const DevMap &entry) -> bool
2325 { return entry.devid == wname; });
2327 if(iter == devlist.cend())
2329 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name), name.data());
2330 return E_FAIL;
2332 devname = iter->name;
2333 devid = iter->devid;
2336 HRESULT hr{sDeviceHelper->openDevice(devid, eCapture, mMMDev)};
2337 if(FAILED(hr))
2339 WARN("Failed to open device \"%s\"\n", devname.empty() ? "(default)" : devname.c_str());
2340 return hr;
2342 mClient = nullptr;
2343 if(!devname.empty())
2344 mDeviceName = std::move(devname);
2345 else
2346 mDeviceName = GetDeviceNameAndGuid(mMMDev).mName;
2348 return S_OK;
2351 void WasapiCapture::closeProxy()
2353 mCapture = nullptr;
2354 mClient = nullptr;
2355 mMMDev = nullptr;
2358 HRESULT WasapiCapture::resetProxy()
2360 mCapture = nullptr;
2361 mClient = nullptr;
2363 HRESULT hr{sDeviceHelper->activateAudioClient(mMMDev, __uuidof(IAudioClient),
2364 al::out_ptr(mClient))};
2365 if(FAILED(hr))
2367 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
2368 return hr;
2371 WAVEFORMATEX *wfx;
2372 hr = mClient->GetMixFormat(&wfx);
2373 if(FAILED(hr))
2375 ERR("Failed to get capture format: 0x%08lx\n", hr);
2376 return hr;
2378 TraceFormat("Device capture format", wfx);
2380 WAVEFORMATEXTENSIBLE InputType{};
2381 if(!MakeExtensible(&InputType, wfx))
2383 CoTaskMemFree(wfx);
2384 return E_FAIL;
2386 CoTaskMemFree(wfx);
2387 wfx = nullptr;
2389 const bool isRear51{InputType.Format.nChannels == 6
2390 && (InputType.dwChannelMask&X51RearMask) == X5DOT1REAR};
2392 // Make sure buffer is at least 100ms in size
2393 ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
2394 buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}});
2396 InputType = {};
2397 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
2398 switch(mDevice->FmtChans)
2400 case DevFmtMono:
2401 InputType.Format.nChannels = 1;
2402 InputType.dwChannelMask = MONO;
2403 break;
2404 case DevFmtStereo:
2405 InputType.Format.nChannels = 2;
2406 InputType.dwChannelMask = STEREO;
2407 break;
2408 case DevFmtQuad:
2409 InputType.Format.nChannels = 4;
2410 InputType.dwChannelMask = QUAD;
2411 break;
2412 case DevFmtX51:
2413 InputType.Format.nChannels = 6;
2414 InputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
2415 break;
2416 case DevFmtX61:
2417 InputType.Format.nChannels = 7;
2418 InputType.dwChannelMask = X6DOT1;
2419 break;
2420 case DevFmtX71:
2421 InputType.Format.nChannels = 8;
2422 InputType.dwChannelMask = X7DOT1;
2423 break;
2424 case DevFmtX714:
2425 InputType.Format.nChannels = 12;
2426 InputType.dwChannelMask = X7DOT1DOT4;
2427 break;
2429 case DevFmtX7144:
2430 case DevFmtX3D71:
2431 case DevFmtAmbi3D:
2432 return E_FAIL;
2434 switch(mDevice->FmtType)
2436 /* NOTE: Signedness doesn't matter, the converter will handle it. */
2437 case DevFmtByte:
2438 case DevFmtUByte:
2439 InputType.Format.wBitsPerSample = 8;
2440 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2441 break;
2442 case DevFmtShort:
2443 case DevFmtUShort:
2444 InputType.Format.wBitsPerSample = 16;
2445 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2446 break;
2447 case DevFmtInt:
2448 case DevFmtUInt:
2449 InputType.Format.wBitsPerSample = 32;
2450 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
2451 break;
2452 case DevFmtFloat:
2453 InputType.Format.wBitsPerSample = 32;
2454 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
2455 break;
2457 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
2458 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
2459 InputType.Format.nSamplesPerSec = mDevice->Frequency;
2461 InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
2462 InputType.Format.wBitsPerSample / 8);
2463 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
2464 InputType.Format.nBlockAlign;
2465 InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format);
2467 TraceFormat("Requesting capture format", &InputType.Format);
2468 hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, &wfx);
2469 if(FAILED(hr))
2471 WARN("Failed to check capture format support: 0x%08lx\n", hr);
2472 hr = mClient->GetMixFormat(&wfx);
2474 if(FAILED(hr))
2476 ERR("Failed to find a supported capture format: 0x%08lx\n", hr);
2477 return hr;
2480 mSampleConv = nullptr;
2481 mChannelConv = {};
2483 if(wfx != nullptr)
2485 TraceFormat("Got capture format", wfx);
2486 if(!MakeExtensible(&InputType, wfx))
2488 CoTaskMemFree(wfx);
2489 return E_FAIL;
2491 CoTaskMemFree(wfx);
2492 wfx = nullptr;
2494 auto validate_fmt = [](DeviceBase *device, uint32_t chancount, DWORD chanmask) noexcept
2495 -> bool
2497 switch(device->FmtChans)
2499 /* If the device wants mono, we can handle any input. */
2500 case DevFmtMono:
2501 return true;
2502 /* If the device wants stereo, we can handle mono or stereo input. */
2503 case DevFmtStereo:
2504 return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO))
2505 || (chancount == 1 && (chanmask&MonoMask) == MONO);
2506 /* Otherwise, the device must match the input type. */
2507 case DevFmtQuad:
2508 return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD));
2509 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
2510 case DevFmtX51:
2511 return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1
2512 || (chanmask&X51RearMask) == X5DOT1REAR));
2513 case DevFmtX61:
2514 return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1));
2515 case DevFmtX71:
2516 case DevFmtX3D71:
2517 return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1));
2518 case DevFmtX714:
2519 return (chancount == 12 && (chanmask == 0 || (chanmask&X714Mask) == X7DOT1DOT4));
2520 case DevFmtX7144:
2521 return (chancount == 16 && chanmask == 0);
2522 case DevFmtAmbi3D:
2523 return (chanmask == 0 && chancount == device->channelsFromFmt());
2525 return false;
2527 if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask))
2529 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
2530 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2531 mDevice->Frequency, InputType.dwChannelMask, InputType.Format.nChannels,
2532 (InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample,
2533 InputType.Format.nSamplesPerSec);
2534 return E_FAIL;
2538 DevFmtType srcType{};
2539 if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
2541 if(InputType.Format.wBitsPerSample == 8)
2542 srcType = DevFmtUByte;
2543 else if(InputType.Format.wBitsPerSample == 16)
2544 srcType = DevFmtShort;
2545 else if(InputType.Format.wBitsPerSample == 32)
2546 srcType = DevFmtInt;
2547 else
2549 ERR("Unhandled integer bit depth: %d\n", InputType.Format.wBitsPerSample);
2550 return E_FAIL;
2553 else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
2555 if(InputType.Format.wBitsPerSample == 32)
2556 srcType = DevFmtFloat;
2557 else
2559 ERR("Unhandled float bit depth: %d\n", InputType.Format.wBitsPerSample);
2560 return E_FAIL;
2563 else
2565 ERR("Unhandled format sub-type: %s\n", GuidPrinter{InputType.SubFormat}.c_str());
2566 return E_FAIL;
2569 if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1)
2571 uint chanmask{(1u<<InputType.Format.nChannels) - 1u};
2572 /* Exclude LFE from the downmix. */
2573 if((InputType.dwChannelMask&SPEAKER_LOW_FREQUENCY))
2575 constexpr auto lfemask = MaskFromTopBits(SPEAKER_LOW_FREQUENCY);
2576 const int lfeidx{al::popcount(InputType.dwChannelMask&lfemask) - 1};
2577 chanmask &= ~(1u << lfeidx);
2580 mChannelConv = ChannelConverter{srcType, InputType.Format.nChannels, chanmask,
2581 mDevice->FmtChans};
2582 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType));
2583 /* The channel converter always outputs float, so change the input type
2584 * for the resampler/type-converter.
2586 srcType = DevFmtFloat;
2588 else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1)
2590 mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans};
2591 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
2592 srcType = DevFmtFloat;
2595 if(mDevice->Frequency != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType)
2597 mSampleConv = SampleConverter::Create(srcType, mDevice->FmtType,
2598 mDevice->channelsFromFmt(), InputType.Format.nSamplesPerSec, mDevice->Frequency,
2599 Resampler::FastBSinc24);
2600 if(!mSampleConv)
2602 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2603 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2604 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
2605 return E_FAIL;
2607 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2608 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
2609 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
2612 hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
2613 buf_time.count(), 0, &InputType.Format, nullptr);
2614 if(FAILED(hr))
2616 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
2617 return hr;
2620 hr = mClient->GetService(__uuidof(IAudioCaptureClient), al::out_ptr(mCapture));
2621 if(FAILED(hr))
2623 ERR("Failed to get IAudioCaptureClient: 0x%08lx\n", hr);
2624 return hr;
2627 UINT32 buffer_len{};
2628 ReferenceTime min_per{};
2629 hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
2630 if(SUCCEEDED(hr))
2631 hr = mClient->GetBufferSize(&buffer_len);
2632 if(FAILED(hr))
2634 ERR("Failed to get buffer size: 0x%08lx\n", hr);
2635 return hr;
2637 mDevice->UpdateSize = RefTime2Samples(min_per, mDevice->Frequency);
2638 mDevice->BufferSize = buffer_len;
2640 mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false);
2642 hr = mClient->SetEventHandle(mNotifyEvent);
2643 if(FAILED(hr))
2645 ERR("Failed to set event handle: 0x%08lx\n", hr);
2646 return hr;
2649 return hr;
2653 void WasapiCapture::start()
2655 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
2656 if(FAILED(hr))
2657 throw al::backend_exception{al::backend_error::DeviceError,
2658 "Failed to start recording: 0x%lx", hr};
2661 HRESULT WasapiCapture::startProxy()
2663 ResetEvent(mNotifyEvent);
2665 HRESULT hr{mClient->Start()};
2666 if(FAILED(hr))
2668 ERR("Failed to start audio client: 0x%08lx\n", hr);
2669 return hr;
2672 try {
2673 mKillNow.store(false, std::memory_order_release);
2674 mThread = std::thread{std::mem_fn(&WasapiCapture::recordProc), this};
2676 catch(...) {
2677 ERR("Failed to start thread\n");
2678 mClient->Stop();
2679 mClient->Reset();
2680 hr = E_FAIL;
2683 return hr;
2687 void WasapiCapture::stop()
2688 { pushMessage(MsgType::StopDevice).wait(); }
2690 void WasapiCapture::stopProxy()
2692 if(!mThread.joinable())
2693 return;
2695 mKillNow.store(true, std::memory_order_release);
2696 mThread.join();
2698 mClient->Stop();
2699 mClient->Reset();
2703 void WasapiCapture::captureSamples(std::byte *buffer, uint samples)
2704 { std::ignore = mRing->read(buffer, samples); }
2706 uint WasapiCapture::availableSamples()
2707 { return static_cast<uint>(mRing->readSpace()); }
2709 } // namespace
2712 bool WasapiBackendFactory::init()
2714 static HRESULT InitResult{E_FAIL};
2715 if(FAILED(InitResult)) try
2717 std::promise<HRESULT> promise;
2718 auto future = promise.get_future();
2720 std::thread{&WasapiProxy::messageHandler, &promise}.detach();
2721 InitResult = future.get();
2723 catch(...) {
2726 return SUCCEEDED(InitResult);
2729 bool WasapiBackendFactory::querySupport(BackendType type)
2730 { return type == BackendType::Playback || type == BackendType::Capture; }
2732 auto WasapiBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
2734 std::vector<std::string> outnames;
2736 auto devlock = DeviceListLock{gDeviceList};
2737 switch(type)
2739 case BackendType::Playback:
2741 auto defaultId = devlock.getPlaybackDefaultId();
2742 for(const DevMap &entry : devlock.getPlaybackList())
2744 if(entry.devid != defaultId)
2746 outnames.emplace_back(entry.name);
2747 continue;
2749 /* Default device goes first. */
2750 outnames.emplace(outnames.cbegin(), entry.name);
2753 break;
2755 case BackendType::Capture:
2757 auto defaultId = devlock.getCaptureDefaultId();
2758 for(const DevMap &entry : devlock.getCaptureList())
2760 if(entry.devid != defaultId)
2762 outnames.emplace_back(entry.name);
2763 continue;
2765 outnames.emplace(outnames.cbegin(), entry.name);
2768 break;
2771 return outnames;
2774 BackendPtr WasapiBackendFactory::createBackend(DeviceBase *device, BackendType type)
2776 if(type == BackendType::Playback)
2777 return BackendPtr{new WasapiPlayback{device}};
2778 if(type == BackendType::Capture)
2779 return BackendPtr{new WasapiCapture{device}};
2780 return nullptr;
2783 BackendFactory &WasapiBackendFactory::getFactory()
2785 static WasapiBackendFactory factory{};
2786 return factory;
2789 alc::EventSupport WasapiBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
2791 switch(eventType)
2793 case alc::EventType::DefaultDeviceChanged:
2794 return alc::EventSupport::FullSupport;
2796 case alc::EventType::DeviceAdded:
2797 case alc::EventType::DeviceRemoved:
2798 #if !ALSOFT_UWP
2799 return alc::EventSupport::FullSupport;
2800 #endif
2802 case alc::EventType::Count:
2803 break;
2805 return alc::EventSupport::NoSupport;