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
25 #define WIN32_LEAN_AND_MEAN
34 #include <mmdeviceapi.h>
35 #include <audiosessiontypes.h>
36 #include <audioclient.h>
37 #include <spatialaudioclient.h>
39 #include <devpropdef.h>
44 #ifndef _WAVEFORMATEXTENSIBLE_
52 #include <condition_variable>
59 #include <string_view>
64 #include "alc/alconfig.h"
65 #include "alnumeric.h"
68 #include "althrd_setname.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"
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
;
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);
100 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
101 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
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 );
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
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
)};
148 constexpr AudioObjectType
operator|(AudioObjectType lhs
, AudioObjectType rhs
) noexcept
149 { return static_cast<AudioObjectType
>(lhs
| al::to_underlying(rhs
)); }
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
...>;
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. */
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()));
205 std::array
<char,64> mMsg
{};
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(); }
221 PropVariant() { PropVariantInit(&mProp
); }
222 PropVariant(const PropVariant
&rhs
) : PropVariant
{} { PropVariantCopy(&mProp
, &rhs
.mProp
); }
223 ~PropVariant() { clear(); }
225 auto operator=(const PropVariant
&rhs
) -> PropVariant
&
228 PropVariantCopy(&mProp
, &rhs
.mProp
);
232 void clear() { PropVariantClear(&mProp
); }
234 PROPVARIANT
* get() noexcept
{ return &mProp
; }
236 /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
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());
261 mProp
.blob
.cbSize
= static_cast<ULONG
>(data
.size());
262 mProp
.blob
.pBlobData
= data
.data();
264 /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
269 std::string endpoint_guid
; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
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. */
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();
291 auto lock() noexcept(noexcept(mMutex
.lock())) { return mMutex
.lock(); }
292 auto unlock() noexcept(noexcept(mMutex
.unlock())) { return mMutex
.unlock(); }
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
;
319 struct AvrtHandleCloser
{
320 void operator()(HANDLE handle
) { AvRevertMmThreadCharacteristics(handle
); }
322 using AvrtHandlePtr
= std::unique_ptr
<std::remove_pointer_t
<HANDLE
>,AvrtHandleCloser
>;
325 #if defined(ALSOFT_UWP)
328 eCapture
= (eRender
+ 1),
329 eAll
= (eCapture
+ 1),
330 EDataFlow_enum_count
= (eAll
+ 1)
334 #if defined(ALSOFT_UWP)
335 using DeviceHandle
= Windows::Devices::Enumeration::DeviceInformation
;
336 using EventRegistrationToken
= winrt::event_token
;
338 using DeviceHandle
= ComPtr
<IMMDevice
>;
342 struct NameGUIDPair
{ std::string mName
; std::string mGuid
; };
343 auto GetDeviceNameAndGuid(const DeviceHandle
&device
) -> NameGUIDPair
345 constexpr auto UnknownName
= "Unknown Device Name"sv
;
346 constexpr auto UnknownGuid
= "Unknown Device GUID"sv
;
348 #if !defined(ALSOFT_UWP)
349 std::string name
, guid
;
351 ComPtr
<IPropertyStore
> ps
;
352 HRESULT hr
{device
->OpenPropertyStore(STGM_READ
, al::out_ptr(ps
))};
355 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
356 return {std::string
{UnknownName
}, std::string
{UnknownGuid
}};
360 hr
= ps
->GetValue(al::bit_cast
<PROPERTYKEY
>(DEVPKEY_Device_FriendlyName
), pvprop
.get());
362 WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr
);
363 else if(pvprop
.type() == VT_LPWSTR
)
364 name
= wstr_to_utf8(pvprop
.value
<std::wstring_view
>());
366 WARN("Unexpected Device_FriendlyName PROPVARIANT type: 0x%04x\n", pvprop
.type());
369 hr
= ps
->GetValue(al::bit_cast
<PROPERTYKEY
>(PKEY_AudioEndpoint_GUID
), pvprop
.get());
371 WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr
);
372 else if(pvprop
.type() == VT_LPWSTR
)
373 guid
= wstr_to_utf8(pvprop
.value
<std::wstring_view
>());
375 WARN("Unexpected AudioEndpoint_GUID PROPVARIANT type: 0x%04x\n", pvprop
.type());
377 std::string name
{wstr_to_utf8(device
.Name())};
379 // device->Id is DeviceInterfacePath: \\?\SWD#MMDEVAPI#{0.0.0.00000000}.{a21c17a0-fc1d-405e-ab5a-b513422b57d1}#{e6327cad-dcec-4949-ae8a-991e976a79d2}
380 auto devIfPath
= device
.Id();
381 if(auto devIdStart
= wcsstr(devIfPath
.data(), L
"}."))
383 devIdStart
+= 2; // L"}."
384 if(auto devIdStartEnd
= wcschr(devIdStart
, L
'#'))
386 std::wstring wDevId
{devIdStart
, static_cast<size_t>(devIdStartEnd
- devIdStart
)};
387 guid
= wstr_to_utf8(wDevId
.c_str());
388 std::transform(guid
.begin(), guid
.end(), guid
.begin(),
389 [](char ch
) { return static_cast<char>(std::toupper(ch
)); });
393 if(name
.empty()) name
= UnknownName
;
394 if(guid
.empty()) guid
= UnknownGuid
;
395 return {std::move(name
), std::move(guid
)};
397 #if !defined(ALSOFT_UWP)
398 EndpointFormFactor
GetDeviceFormfactor(IMMDevice
*device
)
400 ComPtr
<IPropertyStore
> ps
;
401 HRESULT hr
{device
->OpenPropertyStore(STGM_READ
, al::out_ptr(ps
))};
404 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
405 return UnknownFormFactor
;
408 EndpointFormFactor formfactor
{UnknownFormFactor
};
410 hr
= ps
->GetValue(PKEY_AudioEndpoint_FormFactor
, pvform
.get());
412 WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr
);
413 else if(pvform
.type() == VT_UI4
)
414 formfactor
= static_cast<EndpointFormFactor
>(pvform
.value
<uint
>());
415 else if(pvform
.type() != VT_EMPTY
)
416 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform
.type());
422 #if defined(ALSOFT_UWP)
423 struct DeviceHelper final
: public IActivateAudioInterfaceCompletionHandler
425 struct DeviceHelper final
: private IMMNotificationClient
428 #if defined(ALSOFT_UWP)
431 /* TODO: UWP also needs to watch for device added/removed events and
432 * dynamically add/remove devices from the lists.
434 mActiveClientEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
436 mRenderDeviceChangedToken
= MediaDevice::DefaultAudioRenderDeviceChanged([this](const IInspectable
& /*sender*/, const DefaultAudioRenderDeviceChangedEventArgs
& args
) {
437 if (args
.Role() == AudioDeviceRole::Default
)
439 const std::string msg
{ "Default playback device changed: " +
440 wstr_to_utf8(args
.Id())};
441 alc::Event(alc::EventType::DefaultDeviceChanged
, alc::DeviceType::Playback
,
446 mCaptureDeviceChangedToken
= MediaDevice::DefaultAudioCaptureDeviceChanged([this](const IInspectable
& /*sender*/, const DefaultAudioCaptureDeviceChangedEventArgs
& args
) {
447 if (args
.Role() == AudioDeviceRole::Default
)
449 const std::string msg
{ "Default capture device changed: " +
450 wstr_to_utf8(args
.Id()) };
451 alc::Event(alc::EventType::DefaultDeviceChanged
, alc::DeviceType::Capture
,
457 DeviceHelper() = default;
461 #if defined(ALSOFT_UWP)
462 MediaDevice::DefaultAudioRenderDeviceChanged(mRenderDeviceChangedToken
);
463 MediaDevice::DefaultAudioCaptureDeviceChanged(mCaptureDeviceChangedToken
);
465 if(mActiveClientEvent
!= nullptr)
466 CloseHandle(mActiveClientEvent
);
467 mActiveClientEvent
= nullptr;
470 mEnumerator
->UnregisterEndpointNotificationCallback(this);
471 mEnumerator
= nullptr;
476 auto as() noexcept
-> T
{ return T
{this}; }
478 /** -------------------------- IUnknown ----------------------------- */
479 std::atomic
<ULONG
> mRefCount
{1};
480 STDMETHODIMP_(ULONG
) AddRef() noexcept override
{ return mRefCount
.fetch_add(1u) + 1u; }
481 STDMETHODIMP_(ULONG
) Release() noexcept override
{ return mRefCount
.fetch_sub(1u) - 1u; }
483 STDMETHODIMP
QueryInterface(const IID
& IId
, void **UnknownPtrPtr
) noexcept override
485 // Three rules of QueryInterface:
486 // https://docs.microsoft.com/en-us/windows/win32/com/rules-for-implementing-queryinterface
487 // 1. Objects must have identity.
488 // 2. The set of interfaces on an object instance must be static.
489 // 3. It must be possible to query successfully for any interface on an object from any other interface.
491 // If ppvObject(the address) is nullptr, then this method returns E_POINTER.
495 // https://docs.microsoft.com/en-us/windows/win32/com/implementing-reference-counting
496 // Whenever a client calls a method(or API function), such as QueryInterface, that returns a new interface
497 // pointer, the method being called is responsible for incrementing the reference count through the returned
498 // pointer. For example, when a client first creates an object, it receives an interface pointer to an object
499 // that, from the client's point of view, has a reference count of one. If the client then calls AddRef on the
500 // interface pointer, the reference count becomes two. The client must call Release twice on the interface
501 // pointer to drop all of its references to the object.
502 #if defined(ALSOFT_UWP)
503 if(IId
== __uuidof(IActivateAudioInterfaceCompletionHandler
))
505 *UnknownPtrPtr
= as
<IActivateAudioInterfaceCompletionHandler
*>();
510 if(IId
== __uuidof(IMMNotificationClient
))
512 *UnknownPtrPtr
= as
<IMMNotificationClient
*>();
517 else if(IId
== __uuidof(IAgileObject
) || IId
== __uuidof(IUnknown
))
519 *UnknownPtrPtr
= as
<IUnknown
*>();
524 // This method returns S_OK if the interface is supported, and E_NOINTERFACE otherwise.
525 *UnknownPtrPtr
= nullptr;
526 return E_NOINTERFACE
;
529 #if defined(ALSOFT_UWP)
530 /** ----------------------- IActivateAudioInterfaceCompletionHandler ------------ */
531 HRESULT
ActivateCompleted(IActivateAudioInterfaceAsyncOperation
*) override
533 SetEvent(mActiveClientEvent
);
535 // Need to return S_OK
539 /** ----------------------- IMMNotificationClient ------------ */
540 STDMETHODIMP
OnDeviceStateChanged(LPCWSTR
/*pwstrDeviceId*/, DWORD
/*dwNewState*/) noexcept override
{ return S_OK
; }
542 STDMETHODIMP
OnDeviceAdded(LPCWSTR pwstrDeviceId
) noexcept override
544 ComPtr
<IMMDevice
> device
;
545 HRESULT hr
{mEnumerator
->GetDevice(pwstrDeviceId
, al::out_ptr(device
))};
548 ERR("Failed to get device: 0x%08lx\n", hr
);
552 ComPtr
<IMMEndpoint
> endpoint
;
553 hr
= device
->QueryInterface(__uuidof(IMMEndpoint
), al::out_ptr(endpoint
));
556 ERR("Failed to get device endpoint: 0x%08lx\n", hr
);
561 hr
= endpoint
->GetDataFlow(&flowdir
);
564 ERR("Failed to get endpoint data flow: 0x%08lx\n", hr
);
568 auto devlock
= DeviceListLock
{gDeviceList
};
569 auto &list
= (flowdir
==eRender
) ? devlock
.getPlaybackList() : devlock
.getCaptureList();
571 if(AddDevice(device
, pwstrDeviceId
, list
))
573 const auto devtype
= (flowdir
==eRender
) ? alc::DeviceType::Playback
574 : alc::DeviceType::Capture
;
575 const std::string msg
{"Device added: "+list
.back().name
};
576 alc::Event(alc::EventType::DeviceAdded
, devtype
, msg
);
582 STDMETHODIMP
OnDeviceRemoved(LPCWSTR pwstrDeviceId
) noexcept override
584 auto devlock
= DeviceListLock
{gDeviceList
};
585 for(auto flowdir
: std::array
{eRender
, eCapture
})
587 auto &list
= (flowdir
==eRender
) ? devlock
.getPlaybackList() : devlock
.getCaptureList();
588 auto devtype
= (flowdir
==eRender
)?alc::DeviceType::Playback
: alc::DeviceType::Capture
;
590 /* Find the ID in the list to remove. */
591 auto iter
= std::find_if(list
.begin(), list
.end(),
592 [pwstrDeviceId
](const DevMap
&entry
) noexcept
593 { return pwstrDeviceId
== entry
.devid
; });
594 if(iter
== list
.end()) continue;
596 TRACE("Removing device \"%s\", \"%s\", \"%ls\"\n", iter
->name
.c_str(),
597 iter
->endpoint_guid
.c_str(), iter
->devid
.c_str());
599 std::string msg
{"Device removed: "+std::move(iter
->name
)};
602 alc::Event(alc::EventType::DeviceRemoved
, devtype
, msg
);
607 /* NOLINTNEXTLINE(clazy-function-args-by-ref) */
608 STDMETHODIMP
OnPropertyValueChanged(LPCWSTR
/*pwstrDeviceId*/, const PROPERTYKEY
/*key*/) noexcept override
{ return S_OK
; }
610 STDMETHODIMP
OnDefaultDeviceChanged(EDataFlow flow
, ERole role
, LPCWSTR pwstrDefaultDeviceId
) noexcept override
612 if(role
!= eMultimedia
)
615 const std::wstring_view devid
{pwstrDefaultDeviceId
? pwstrDefaultDeviceId
616 : std::wstring_view
{}};
619 DeviceListLock
{gDeviceList
}.setPlaybackDefaultId(devid
);
620 const std::string msg
{"Default playback device changed: " + wstr_to_utf8(devid
)};
621 alc::Event(alc::EventType::DefaultDeviceChanged
, alc::DeviceType::Playback
, msg
);
623 else if(flow
== eCapture
)
625 DeviceListLock
{gDeviceList
}.setCaptureDefaultId(devid
);
626 const std::string msg
{"Default capture device changed: " + wstr_to_utf8(devid
)};
627 alc::Event(alc::EventType::DefaultDeviceChanged
, alc::DeviceType::Capture
, msg
);
633 /** -------------------------- DeviceHelper ----------------------------- */
636 #if !defined(ALSOFT_UWP)
637 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
638 __uuidof(IMMDeviceEnumerator
), al::out_ptr(mEnumerator
))};
640 mEnumerator
->RegisterEndpointNotificationCallback(this);
642 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr
);
649 HRESULT
openDevice(std::wstring_view devid
, EDataFlow flow
, DeviceHandle
& device
)
651 #if !defined(ALSOFT_UWP)
656 hr
= mEnumerator
->GetDefaultAudioEndpoint(flow
, eMultimedia
, al::out_ptr(device
));
658 hr
= mEnumerator
->GetDevice(devid
.data(), al::out_ptr(device
));
662 const auto deviceRole
= Windows::Media::Devices::AudioDeviceRole::Default
;
664 devid
.empty() ? (flow
== eRender
? MediaDevice::GetDefaultAudioRenderId(deviceRole
) : MediaDevice::GetDefaultAudioCaptureId(deviceRole
))
665 : winrt::hstring(devid
.data());
666 if (devIfPath
.empty())
669 auto&& deviceInfo
= DeviceInformation::CreateFromIdAsync(devIfPath
, nullptr, DeviceInformationKind::DeviceInterface
).get();
671 return E_NOINTERFACE
;
677 #if !defined(ALSOFT_UWP)
678 static HRESULT
activateAudioClient(_In_ DeviceHandle
&device
, REFIID iid
, void **ppv
)
679 { return device
->Activate(iid
, CLSCTX_INPROC_SERVER
, nullptr, ppv
); }
681 HRESULT
activateAudioClient(_In_ DeviceHandle
&device
, _In_ REFIID iid
, void **ppv
)
683 ComPtr
<IActivateAudioInterfaceAsyncOperation
> asyncOp
;
684 HRESULT hr
{ActivateAudioInterfaceAsync(device
.Id().data(), iid
, nullptr, this,
685 al::out_ptr(asyncOp
))};
689 /* I don't like waiting for INFINITE time, but the activate operation
690 * can take an indefinite amount of time since it can require user
693 DWORD res
{WaitForSingleObjectEx(mActiveClientEvent
, INFINITE
, FALSE
)};
694 if(res
!= WAIT_OBJECT_0
)
696 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
700 HRESULT hrActivateRes
{E_FAIL
};
701 ComPtr
<IUnknown
> punkAudioIface
;
702 hr
= asyncOp
->GetActivateResult(&hrActivateRes
, al::out_ptr(punkAudioIface
));
703 if(SUCCEEDED(hr
)) hr
= hrActivateRes
;
704 if(FAILED(hr
)) return hr
;
706 return punkAudioIface
->QueryInterface(iid
, ppv
);
710 std::wstring
probeDevices(EDataFlow flowdir
, std::vector
<DevMap
> &list
)
712 std::wstring defaultId
;
713 std::vector
<DevMap
>{}.swap(list
);
715 #if !defined(ALSOFT_UWP)
716 ComPtr
<IMMDeviceCollection
> coll
;
717 HRESULT hr
{mEnumerator
->EnumAudioEndpoints(flowdir
, DEVICE_STATE_ACTIVE
,
721 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr
);
726 hr
= coll
->GetCount(&count
);
727 if(SUCCEEDED(hr
) && count
> 0)
730 ComPtr
<IMMDevice
> device
;
731 hr
= mEnumerator
->GetDefaultAudioEndpoint(flowdir
, eMultimedia
, al::out_ptr(device
));
734 if(WCHAR
*devid
{GetDeviceId(device
.get())})
737 CoTaskMemFree(devid
);
742 for(UINT i
{0};i
< count
;++i
)
744 hr
= coll
->Item(i
, al::out_ptr(device
));
748 if(WCHAR
*devid
{GetDeviceId(device
.get())})
750 std::ignore
= AddDevice(device
, devid
, list
);
751 CoTaskMemFree(devid
);
756 const auto deviceRole
= Windows::Media::Devices::AudioDeviceRole::Default
;
757 auto DefaultAudioId
= flowdir
== eRender
? MediaDevice::GetDefaultAudioRenderId(deviceRole
)
758 : MediaDevice::GetDefaultAudioCaptureId(deviceRole
);
759 if(!DefaultAudioId
.empty())
761 auto deviceInfo
= DeviceInformation::CreateFromIdAsync(DefaultAudioId
, nullptr,
762 DeviceInformationKind::DeviceInterface
).get();
764 defaultId
= deviceInfo
.Id().data();
767 // Get the string identifier of the audio renderer
768 auto AudioSelector
= flowdir
== eRender
? MediaDevice::GetAudioRenderSelector() : MediaDevice::GetAudioCaptureSelector();
770 // Setup the asynchronous callback
771 auto&& DeviceInfoCollection
= DeviceInformation::FindAllAsync(AudioSelector
, /*PropertyList*/nullptr, DeviceInformationKind::DeviceInterface
).get();
772 if(DeviceInfoCollection
)
775 auto deviceCount
= DeviceInfoCollection
.Size();
776 for(unsigned int i
{0};i
< deviceCount
;++i
)
778 auto deviceInfo
= DeviceInfoCollection
.GetAt(i
);
780 std::ignore
= AddDevice(deviceInfo
, deviceInfo
.Id().data(), list
);
783 catch (const winrt::hresult_error
& /*ex*/) {
792 static bool AddDevice(const DeviceHandle
&device
, const WCHAR
*devid
, std::vector
<DevMap
> &list
)
794 for(auto &entry
: list
)
796 if(entry
.devid
== devid
)
800 auto name_guid
= GetDeviceNameAndGuid(device
);
802 std::string newname
{name_guid
.mName
};
803 while(checkName(list
, newname
))
805 newname
= name_guid
.mName
;
807 newname
+= std::to_string(++count
);
809 list
.emplace_back(std::move(newname
), std::move(name_guid
.mGuid
), devid
);
810 const DevMap
&newentry
= list
.back();
812 TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry
.name
.c_str(),
813 newentry
.endpoint_guid
.c_str(), newentry
.devid
.c_str());
817 #if !defined(ALSOFT_UWP)
818 static WCHAR
*GetDeviceId(IMMDevice
*device
)
822 const HRESULT hr
{device
->GetId(&devid
)};
825 ERR("Failed to get device id: %lx\n", hr
);
831 ComPtr
<IMMDeviceEnumerator
> mEnumerator
{nullptr};
835 HANDLE mActiveClientEvent
{nullptr};
837 EventRegistrationToken mRenderDeviceChangedToken
;
838 EventRegistrationToken mCaptureDeviceChangedToken
;
842 bool MakeExtensible(WAVEFORMATEXTENSIBLE
*out
, const WAVEFORMATEX
*in
)
844 *out
= WAVEFORMATEXTENSIBLE
{};
845 if(in
->wFormatTag
== WAVE_FORMAT_EXTENSIBLE
)
847 *out
= *CONTAINING_RECORD(in
, const WAVEFORMATEXTENSIBLE
, Format
);
848 out
->Format
.cbSize
= sizeof(*out
) - sizeof(out
->Format
);
850 else if(in
->wFormatTag
== WAVE_FORMAT_PCM
)
853 out
->Format
.cbSize
= 0;
854 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
855 out
->Samples
.wValidBitsPerSample
= out
->Format
.wBitsPerSample
;
856 if(out
->Format
.nChannels
== 1)
857 out
->dwChannelMask
= MONO
;
858 else if(out
->Format
.nChannels
== 2)
859 out
->dwChannelMask
= STEREO
;
861 ERR("Unhandled PCM channel count: %d\n", out
->Format
.nChannels
);
862 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
864 else if(in
->wFormatTag
== WAVE_FORMAT_IEEE_FLOAT
)
867 out
->Format
.cbSize
= 0;
868 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
869 out
->Samples
.wValidBitsPerSample
= out
->Format
.wBitsPerSample
;
870 if(out
->Format
.nChannels
== 1)
871 out
->dwChannelMask
= MONO
;
872 else if(out
->Format
.nChannels
== 2)
873 out
->dwChannelMask
= STEREO
;
875 ERR("Unhandled IEEE float channel count: %d\n", out
->Format
.nChannels
);
876 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
880 ERR("Unhandled format tag: 0x%04x\n", in
->wFormatTag
);
886 void TraceFormat(const char *msg
, const WAVEFORMATEX
*format
)
888 constexpr size_t fmtex_extra_size
{sizeof(WAVEFORMATEXTENSIBLE
)-sizeof(WAVEFORMATEX
)};
889 if(format
->wFormatTag
== WAVE_FORMAT_EXTENSIBLE
&& format
->cbSize
>= fmtex_extra_size
)
891 const WAVEFORMATEXTENSIBLE
*fmtex
{
892 CONTAINING_RECORD(format
, const WAVEFORMATEXTENSIBLE
, Format
)};
893 /* NOLINTBEGIN(cppcoreguidelines-pro-type-union-access) */
895 " FormatTag = 0x%04x\n"
897 " SamplesPerSec = %lu\n"
898 " AvgBytesPerSec = %lu\n"
900 " BitsPerSample = %d\n"
903 " ChannelMask = 0x%lx\n"
905 msg
, fmtex
->Format
.wFormatTag
, fmtex
->Format
.nChannels
, fmtex
->Format
.nSamplesPerSec
,
906 fmtex
->Format
.nAvgBytesPerSec
, fmtex
->Format
.nBlockAlign
, fmtex
->Format
.wBitsPerSample
,
907 fmtex
->Format
.cbSize
, fmtex
->Samples
.wReserved
, fmtex
->dwChannelMask
,
908 GuidPrinter
{fmtex
->SubFormat
}.c_str());
909 /* NOLINTEND(cppcoreguidelines-pro-type-union-access) */
913 " FormatTag = 0x%04x\n"
915 " SamplesPerSec = %lu\n"
916 " AvgBytesPerSec = %lu\n"
918 " BitsPerSample = %d\n"
920 msg
, format
->wFormatTag
, format
->nChannels
, format
->nSamplesPerSec
,
921 format
->nAvgBytesPerSec
, format
->nBlockAlign
, format
->wBitsPerSample
, format
->cbSize
);
935 constexpr const char *GetMessageTypeName(MsgType type
) noexcept
939 case MsgType::OpenDevice
: return "Open Device";
940 case MsgType::ResetDevice
: return "Reset Device";
941 case MsgType::StartDevice
: return "Start Device";
942 case MsgType::StopDevice
: return "Stop Device";
943 case MsgType::CloseDevice
: return "Close Device";
944 case MsgType::QuitThread
: break;
950 /* Proxy interface used by the message handler. */
952 WasapiProxy() = default;
953 WasapiProxy(const WasapiProxy
&) = delete;
954 WasapiProxy(WasapiProxy
&&) = delete;
955 virtual ~WasapiProxy() = default;
957 void operator=(const WasapiProxy
&) = delete;
958 void operator=(WasapiProxy
&&) = delete;
960 virtual HRESULT
openProxy(std::string_view name
) = 0;
961 virtual void closeProxy() = 0;
963 virtual HRESULT
resetProxy() = 0;
964 virtual HRESULT
startProxy() = 0;
965 virtual void stopProxy() = 0;
970 std::string_view mParam
;
971 std::promise
<HRESULT
> mPromise
;
973 explicit operator bool() const noexcept
{ return mType
!= MsgType::QuitThread
; }
975 static inline std::deque
<Msg
> mMsgQueue
;
976 static inline std::mutex mMsgQueueLock
;
977 static inline std::condition_variable mMsgQueueCond
;
978 static inline DWORD sAvIndex
{};
980 static inline std::optional
<DeviceHelper
> sDeviceHelper
;
982 std::future
<HRESULT
> pushMessage(MsgType type
, std::string_view param
={})
984 std::promise
<HRESULT
> promise
;
985 std::future
<HRESULT
> future
{promise
.get_future()};
987 std::lock_guard
<std::mutex
> msglock
{mMsgQueueLock
};
988 mMsgQueue
.emplace_back(Msg
{type
, this, param
, std::move(promise
)});
990 mMsgQueueCond
.notify_one();
994 static std::future
<HRESULT
> pushMessageStatic(MsgType type
)
996 std::promise
<HRESULT
> promise
;
997 std::future
<HRESULT
> future
{promise
.get_future()};
999 std::lock_guard
<std::mutex
> msglock
{mMsgQueueLock
};
1000 mMsgQueue
.emplace_back(Msg
{type
, nullptr, {}, std::move(promise
)});
1002 mMsgQueueCond
.notify_one();
1006 static Msg
popMessage()
1008 std::unique_lock
<std::mutex
> lock
{mMsgQueueLock
};
1009 mMsgQueueCond
.wait(lock
, []{return !mMsgQueue
.empty();});
1010 Msg msg
{std::move(mMsgQueue
.front())};
1011 mMsgQueue
.pop_front();
1015 static int messageHandler(std::promise
<HRESULT
> *promise
);
1018 int WasapiProxy::messageHandler(std::promise
<HRESULT
> *promise
)
1020 TRACE("Starting message thread\n");
1022 ComWrapper com
{COINIT_MULTITHREADED
};
1025 WARN("Failed to initialize COM: 0x%08lx\n", com
.status());
1026 promise
->set_value(com
.status());
1030 struct HelperResetter
{
1031 HelperResetter() = default;
1032 HelperResetter(const HelperResetter
&) = delete;
1033 auto operator=(const HelperResetter
&) -> HelperResetter
& = delete;
1034 ~HelperResetter() { sDeviceHelper
.reset(); }
1036 HelperResetter scoped_watcher
;
1038 HRESULT hr
{sDeviceHelper
.emplace().init()};
1039 promise
->set_value(hr
);
1045 auto devlock
= DeviceListLock
{gDeviceList
};
1046 auto defaultId
= sDeviceHelper
->probeDevices(eRender
, devlock
.getPlaybackList());
1047 if(!defaultId
.empty()) devlock
.setPlaybackDefaultId(defaultId
);
1048 defaultId
= sDeviceHelper
->probeDevices(eCapture
, devlock
.getCaptureList());
1049 if(!defaultId
.empty()) devlock
.setCaptureDefaultId(defaultId
);
1052 TRACE("Starting message loop\n");
1053 while(Msg msg
{popMessage()})
1055 TRACE("Got message \"%s\" (0x%04x, this=%p, param=\"%.*s\")\n",
1056 GetMessageTypeName(msg
.mType
), static_cast<uint
>(msg
.mType
),
1057 static_cast<void*>(msg
.mProxy
), al::sizei(msg
.mParam
), msg
.mParam
.data());
1061 case MsgType::OpenDevice
:
1062 hr
= msg
.mProxy
->openProxy(msg
.mParam
);
1063 msg
.mPromise
.set_value(hr
);
1066 case MsgType::ResetDevice
:
1067 hr
= msg
.mProxy
->resetProxy();
1068 msg
.mPromise
.set_value(hr
);
1071 case MsgType::StartDevice
:
1072 hr
= msg
.mProxy
->startProxy();
1073 msg
.mPromise
.set_value(hr
);
1076 case MsgType::StopDevice
:
1077 msg
.mProxy
->stopProxy();
1078 msg
.mPromise
.set_value(S_OK
);
1081 case MsgType::CloseDevice
:
1082 msg
.mProxy
->closeProxy();
1083 msg
.mPromise
.set_value(S_OK
);
1086 case MsgType::QuitThread
:
1089 ERR("Unexpected message: %u\n", static_cast<uint
>(msg
.mType
));
1090 msg
.mPromise
.set_value(E_FAIL
);
1092 TRACE("Message loop finished\n");
1097 struct WasapiPlayback final
: public BackendBase
, WasapiProxy
{
1098 WasapiPlayback(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
1099 ~WasapiPlayback() override
;
1102 int mixerSpatialProc();
1104 void open(std::string_view name
) override
;
1105 HRESULT
openProxy(std::string_view name
) override
;
1106 void closeProxy() override
;
1108 bool reset() override
;
1109 HRESULT
resetProxy() override
;
1110 void start() override
;
1111 HRESULT
startProxy() override
;
1112 void stop() override
;
1113 void stopProxy() override
;
1115 ClockLatency
getClockLatency() override
;
1117 void prepareFormat(WAVEFORMATEXTENSIBLE
&OutputType
);
1118 void finalizeFormat(WAVEFORMATEXTENSIBLE
&OutputType
);
1120 auto initSpatial() -> bool;
1122 HRESULT mOpenStatus
{E_FAIL
};
1123 DeviceHandle mMMDev
{nullptr};
1125 struct PlainDevice
{
1126 ComPtr
<IAudioClient
> mClient
{nullptr};
1127 ComPtr
<IAudioRenderClient
> mRender
{nullptr};
1129 struct SpatialDevice
{
1130 ComPtr
<ISpatialAudioClient
> mClient
{nullptr};
1131 ComPtr
<ISpatialAudioObjectRenderStream
> mRender
{nullptr};
1132 AudioObjectType mStaticMask
{};
1134 std::variant
<PlainDevice
,SpatialDevice
> mAudio
{std::in_place_index_t
<0>{}};
1135 HANDLE mNotifyEvent
{nullptr};
1137 UINT32 mOutBufferSize
{}, mOutUpdateSize
{};
1138 std::vector
<char> mResampleBuffer
{};
1139 uint mBufferFilled
{0};
1140 SampleConverterPtr mResampler
;
1142 WAVEFORMATEXTENSIBLE mFormat
{};
1143 std::atomic
<UINT32
> mPadding
{0u};
1147 std::atomic
<bool> mKillNow
{true};
1148 std::thread mThread
;
1151 WasapiPlayback::~WasapiPlayback()
1153 if(SUCCEEDED(mOpenStatus
))
1154 pushMessage(MsgType::CloseDevice
).wait();
1155 mOpenStatus
= E_FAIL
;
1157 if(mNotifyEvent
!= nullptr)
1158 CloseHandle(mNotifyEvent
);
1159 mNotifyEvent
= nullptr;
1163 FORCE_ALIGN
int WasapiPlayback::mixerProc()
1165 ComWrapper com
{COINIT_MULTITHREADED
};
1168 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com
.status());
1169 mDevice
->handleDisconnect("COM init failed: 0x%08lx", com
.status());
1173 auto &audio
= std::get
<PlainDevice
>(mAudio
);
1176 althrd_setname(GetMixerThreadName());
1178 const uint frame_size
{mFormat
.Format
.nChannels
* mFormat
.Format
.wBitsPerSample
/ 8u};
1179 const uint update_size
{mOutUpdateSize
};
1180 const UINT32 buffer_len
{mOutBufferSize
};
1181 const void *resbufferptr
{};
1184 /* TODO: "Audio" or "Pro Audio"? The suggestion is to use "Pro Audio" for
1185 * device periods less than 10ms, and "Audio" for greater than or equal to
1188 auto taskname
= (update_size
< mFormat
.Format
.nSamplesPerSec
/100) ? L
"Pro Audio" : L
"Audio";
1189 auto avhandle
= AvrtHandlePtr
{AvSetMmThreadCharacteristicsW(taskname
, &sAvIndex
)};
1193 while(!mKillNow
.load(std::memory_order_relaxed
))
1196 HRESULT hr
{audio
.mClient
->GetCurrentPadding(&written
)};
1199 ERR("Failed to get padding: 0x%08lx\n", hr
);
1200 mDevice
->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr
);
1203 mPadding
.store(written
, std::memory_order_relaxed
);
1205 uint len
{buffer_len
- written
};
1206 if(len
< update_size
)
1208 DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
)};
1209 if(res
!= WAIT_OBJECT_0
)
1210 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
1215 hr
= audio
.mRender
->GetBuffer(len
, &buffer
);
1220 std::lock_guard
<std::mutex
> dlock
{mMutex
};
1221 auto dst
= al::span
{buffer
, size_t{len
}*frame_size
};
1222 for(UINT32 done
{0};done
< len
;)
1224 if(mBufferFilled
== 0)
1226 mDevice
->renderSamples(mResampleBuffer
.data(), mDevice
->UpdateSize
,
1227 mFormat
.Format
.nChannels
);
1228 resbufferptr
= mResampleBuffer
.data();
1229 mBufferFilled
= mDevice
->UpdateSize
;
1232 uint got
{mResampler
->convert(&resbufferptr
, &mBufferFilled
, dst
.data(),
1234 dst
= dst
.subspan(size_t{got
}*frame_size
);
1237 mPadding
.store(written
+ done
, std::memory_order_relaxed
);
1242 std::lock_guard
<std::mutex
> dlock
{mMutex
};
1243 mDevice
->renderSamples(buffer
, len
, mFormat
.Format
.nChannels
);
1244 mPadding
.store(written
+ len
, std::memory_order_relaxed
);
1246 hr
= audio
.mRender
->ReleaseBuffer(len
, 0);
1250 ERR("Failed to buffer data: 0x%08lx\n", hr
);
1251 mDevice
->handleDisconnect("Failed to send playback samples: 0x%08lx", hr
);
1255 mPadding
.store(0u, std::memory_order_release
);
1260 FORCE_ALIGN
int WasapiPlayback::mixerSpatialProc()
1262 ComWrapper com
{COINIT_MULTITHREADED
};
1265 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com
.status());
1266 mDevice
->handleDisconnect("COM init failed: 0x%08lx", com
.status());
1270 auto &audio
= std::get
<SpatialDevice
>(mAudio
);
1273 althrd_setname(GetMixerThreadName());
1275 std::vector
<ComPtr
<ISpatialAudioObject
>> channels
;
1276 std::vector
<void*> buffers
;
1277 std::vector
<void*> resbuffers
;
1278 std::vector
<const void*> tmpbuffers
;
1281 auto taskname
= (mOutUpdateSize
< mFormat
.Format
.nSamplesPerSec
/100) ? L
"Pro Audio" : L
"Audio";
1282 auto avhandle
= AvrtHandlePtr
{AvSetMmThreadCharacteristicsW(taskname
, &sAvIndex
)};
1285 /* TODO: Set mPadding appropriately. There doesn't seem to be a way to
1286 * update it dynamically based on the stream, so a fixed size may be the
1289 mPadding
.store(mOutBufferSize
-mOutUpdateSize
, std::memory_order_release
);
1292 while(!mKillNow
.load(std::memory_order_relaxed
))
1294 if(DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 1000, FALSE
)}; res
!= WAIT_OBJECT_0
)
1296 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
1298 HRESULT hr
{audio
.mRender
->Reset()};
1301 ERR("ISpatialAudioObjectRenderStream::Reset failed: 0x%08lx\n", hr
);
1302 mDevice
->handleDisconnect("Device lost: 0x%08lx", hr
);
1307 UINT32 dynamicCount
{}, framesToDo
{};
1308 HRESULT hr
{audio
.mRender
->BeginUpdatingAudioObjects(&dynamicCount
, &framesToDo
)};
1311 if(channels
.empty()) UNLIKELY
1313 auto flags
= as_unsigned(audio
.mStaticMask
);
1314 channels
.reserve(as_unsigned(al::popcount(flags
)));
1317 auto id
= decltype(flags
){1} << al::countr_zero(flags
);
1320 channels
.emplace_back();
1321 audio
.mRender
->ActivateSpatialAudioObject(static_cast<AudioObjectType
>(id
),
1322 al::out_ptr(channels
.back()));
1324 buffers
.resize(channels
.size());
1327 tmpbuffers
.resize(buffers
.size());
1328 resbuffers
.resize(buffers
.size());
1329 auto bufptr
= mResampleBuffer
.begin();
1330 for(size_t i
{0};i
< tmpbuffers
.size();++i
)
1332 resbuffers
[i
] = al::to_address(bufptr
);
1333 bufptr
+= ptrdiff_t(mDevice
->UpdateSize
*sizeof(float));
1338 /* We have to call to get each channel's buffer individually every
1339 * update, unfortunately.
1341 std::transform(channels
.cbegin(), channels
.cend(), buffers
.begin(),
1342 [](const ComPtr
<ISpatialAudioObject
> &obj
) -> void*
1344 auto buffer
= LPBYTE
{};
1345 auto size
= UINT32
{};
1346 obj
->GetBuffer(&buffer
, &size
);
1351 mDevice
->renderSamples(buffers
, framesToDo
);
1354 std::lock_guard
<std::mutex
> dlock
{mMutex
};
1355 for(UINT32 pos
{0};pos
< framesToDo
;)
1357 if(mBufferFilled
== 0)
1359 mDevice
->renderSamples(resbuffers
, mDevice
->UpdateSize
);
1360 std::copy(resbuffers
.cbegin(), resbuffers
.cend(), tmpbuffers
.begin());
1361 mBufferFilled
= mDevice
->UpdateSize
;
1364 const uint got
{mResampler
->convertPlanar(tmpbuffers
.data(), &mBufferFilled
,
1365 buffers
.data(), framesToDo
-pos
)};
1366 for(auto &buf
: buffers
)
1367 buf
= static_cast<float*>(buf
) + got
; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
1372 hr
= audio
.mRender
->EndUpdatingAudioObjects();
1376 ERR("Failed to update playback objects: 0x%08lx\n", hr
);
1378 mPadding
.store(0u, std::memory_order_release
);
1384 void WasapiPlayback::open(std::string_view name
)
1386 if(SUCCEEDED(mOpenStatus
))
1387 throw al::backend_exception
{al::backend_error::DeviceError
,
1388 "Unexpected duplicate open call"};
1390 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1391 if(mNotifyEvent
== nullptr)
1393 ERR("Failed to create notify events: %lu\n", GetLastError());
1394 throw al::backend_exception
{al::backend_error::DeviceError
,
1395 "Failed to create notify events"};
1398 mOpenStatus
= pushMessage(MsgType::OpenDevice
, name
).get();
1399 if(FAILED(mOpenStatus
))
1400 throw al::backend_exception
{al::backend_error::DeviceError
, "Device init failed: 0x%08lx",
1404 HRESULT
WasapiPlayback::openProxy(std::string_view name
)
1406 std::string devname
;
1410 auto devlock
= DeviceListLock
{gDeviceList
};
1411 auto list
= al::span
{devlock
.getPlaybackList()};
1412 auto iter
= std::find_if(list
.cbegin(), list
.cend(),
1413 [name
](const DevMap
&entry
) -> bool
1414 { return entry
.name
== name
|| entry
.endpoint_guid
== name
; });
1415 if(iter
== list
.cend())
1417 const std::wstring wname
{utf8_to_wstr(name
)};
1418 iter
= std::find_if(list
.cbegin(), list
.cend(),
1419 [&wname
](const DevMap
&entry
) -> bool
1420 { return entry
.devid
== wname
; });
1422 if(iter
== list
.cend())
1424 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name
), name
.data());
1427 devname
= iter
->name
;
1428 devid
= iter
->devid
;
1431 HRESULT hr
{sDeviceHelper
->openDevice(devid
, eRender
, mMMDev
)};
1434 WARN("Failed to open device \"%s\"\n", devname
.empty() ? "(default)" : devname
.c_str());
1437 if(!devname
.empty())
1438 mDeviceName
= std::move(devname
);
1440 mDeviceName
= GetDeviceNameAndGuid(mMMDev
).mName
;
1445 void WasapiPlayback::closeProxy()
1447 mAudio
.emplace
<PlainDevice
>();
1452 void WasapiPlayback::prepareFormat(WAVEFORMATEXTENSIBLE
&OutputType
)
1454 bool isRear51
{false};
1456 if(!mDevice
->Flags
.test(FrequencyRequest
))
1457 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
1458 if(!mDevice
->Flags
.test(ChannelsRequest
))
1460 /* If not requesting a channel configuration, auto-select given what
1461 * fits the mask's lsb (to ensure no gaps in the output channels). If
1462 * there's no mask, we can only assume mono or stereo.
1464 const uint32_t chancount
{OutputType
.Format
.nChannels
};
1465 const DWORD chanmask
{OutputType
.dwChannelMask
};
1466 if(chancount
>= 12 && (chanmask
&X714Mask
) == X7DOT1DOT4
)
1467 mDevice
->FmtChans
= DevFmtX714
;
1468 else if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
1469 mDevice
->FmtChans
= DevFmtX71
;
1470 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
1471 mDevice
->FmtChans
= DevFmtX61
;
1472 else if(chancount
>= 6 && (chanmask
&X51Mask
) == X5DOT1
)
1473 mDevice
->FmtChans
= DevFmtX51
;
1474 else if(chancount
>= 6 && (chanmask
&X51RearMask
) == X5DOT1REAR
)
1476 mDevice
->FmtChans
= DevFmtX51
;
1479 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
1480 mDevice
->FmtChans
= DevFmtQuad
;
1481 else if(chancount
>= 2 && ((chanmask
&StereoMask
) == STEREO
|| !chanmask
))
1482 mDevice
->FmtChans
= DevFmtStereo
;
1483 else if(chancount
>= 1 && ((chanmask
&MonoMask
) == MONO
|| !chanmask
))
1484 mDevice
->FmtChans
= DevFmtMono
;
1486 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount
, chanmask
);
1490 const uint32_t chancount
{OutputType
.Format
.nChannels
};
1491 const DWORD chanmask
{OutputType
.dwChannelMask
};
1492 isRear51
= (chancount
== 6 && (chanmask
&X51RearMask
) == X5DOT1REAR
);
1495 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
1496 switch(mDevice
->FmtChans
)
1499 OutputType
.Format
.nChannels
= 1;
1500 OutputType
.dwChannelMask
= MONO
;
1503 mDevice
->FmtChans
= DevFmtStereo
;
1506 OutputType
.Format
.nChannels
= 2;
1507 OutputType
.dwChannelMask
= STEREO
;
1510 OutputType
.Format
.nChannels
= 4;
1511 OutputType
.dwChannelMask
= QUAD
;
1514 OutputType
.Format
.nChannels
= 6;
1515 OutputType
.dwChannelMask
= isRear51
? X5DOT1REAR
: X5DOT1
;
1518 OutputType
.Format
.nChannels
= 7;
1519 OutputType
.dwChannelMask
= X6DOT1
;
1523 OutputType
.Format
.nChannels
= 8;
1524 OutputType
.dwChannelMask
= X7DOT1
;
1527 mDevice
->FmtChans
= DevFmtX714
;
1530 OutputType
.Format
.nChannels
= 12;
1531 OutputType
.dwChannelMask
= X7DOT1DOT4
;
1534 switch(mDevice
->FmtType
)
1537 mDevice
->FmtType
= DevFmtUByte
;
1540 OutputType
.Format
.wBitsPerSample
= 8;
1541 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1544 mDevice
->FmtType
= DevFmtShort
;
1547 OutputType
.Format
.wBitsPerSample
= 16;
1548 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1551 mDevice
->FmtType
= DevFmtInt
;
1554 OutputType
.Format
.wBitsPerSample
= 32;
1555 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1558 OutputType
.Format
.wBitsPerSample
= 32;
1559 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
1562 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1563 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1564 OutputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
1566 OutputType
.Format
.nBlockAlign
= static_cast<WORD
>(OutputType
.Format
.nChannels
*
1567 OutputType
.Format
.wBitsPerSample
/ 8);
1568 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
1569 OutputType
.Format
.nBlockAlign
;
1572 void WasapiPlayback::finalizeFormat(WAVEFORMATEXTENSIBLE
&OutputType
)
1574 if(!GetConfigValueBool(mDevice
->mDeviceName
, "wasapi", "allow-resampler", true))
1575 mDevice
->Frequency
= uint(OutputType
.Format
.nSamplesPerSec
);
1577 mDevice
->Frequency
= std::min(mDevice
->Frequency
, uint(OutputType
.Format
.nSamplesPerSec
));
1579 const uint32_t chancount
{OutputType
.Format
.nChannels
};
1580 const DWORD chanmask
{OutputType
.dwChannelMask
};
1581 /* Don't update the channel format if the requested format fits what's
1584 bool chansok
{false};
1585 if(mDevice
->Flags
.test(ChannelsRequest
))
1587 /* When requesting a channel configuration, make sure it fits the
1588 * mask's lsb (to ensure no gaps in the output channels). If there's no
1589 * mask, assume the request fits with enough channels.
1591 switch(mDevice
->FmtChans
)
1594 chansok
= (chancount
>= 1 && ((chanmask
&MonoMask
) == MONO
|| !chanmask
));
1597 chansok
= (chancount
>= 2 && ((chanmask
&StereoMask
) == STEREO
|| !chanmask
));
1600 chansok
= (chancount
>= 4 && ((chanmask
&QuadMask
) == QUAD
|| !chanmask
));
1603 chansok
= (chancount
>= 6 && ((chanmask
&X51Mask
) == X5DOT1
1604 || (chanmask
&X51RearMask
) == X5DOT1REAR
|| !chanmask
));
1607 chansok
= (chancount
>= 7 && ((chanmask
&X61Mask
) == X6DOT1
|| !chanmask
));
1611 chansok
= (chancount
>= 8 && ((chanmask
&X71Mask
) == X7DOT1
|| !chanmask
));
1614 chansok
= (chancount
>= 12 && ((chanmask
&X714Mask
) == X7DOT1DOT4
|| !chanmask
));
1622 if(chancount
>= 12 && (chanmask
&X714Mask
) == X7DOT1DOT4
)
1623 mDevice
->FmtChans
= DevFmtX714
;
1624 else if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
1625 mDevice
->FmtChans
= DevFmtX71
;
1626 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
1627 mDevice
->FmtChans
= DevFmtX61
;
1628 else if(chancount
>= 6 && ((chanmask
&X51Mask
) == X5DOT1
1629 || (chanmask
&X51RearMask
) == X5DOT1REAR
))
1630 mDevice
->FmtChans
= DevFmtX51
;
1631 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
1632 mDevice
->FmtChans
= DevFmtQuad
;
1633 else if(chancount
>= 2 && ((chanmask
&StereoMask
) == STEREO
|| !chanmask
))
1634 mDevice
->FmtChans
= DevFmtStereo
;
1635 else if(chancount
>= 1 && ((chanmask
&MonoMask
) == MONO
|| !chanmask
))
1636 mDevice
->FmtChans
= DevFmtMono
;
1639 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType
.Format
.nChannels
,
1640 OutputType
.dwChannelMask
);
1641 mDevice
->FmtChans
= DevFmtStereo
;
1642 OutputType
.Format
.nChannels
= 2;
1643 OutputType
.dwChannelMask
= STEREO
;
1647 if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1649 if(OutputType
.Format
.wBitsPerSample
== 8)
1650 mDevice
->FmtType
= DevFmtUByte
;
1651 else if(OutputType
.Format
.wBitsPerSample
== 16)
1652 mDevice
->FmtType
= DevFmtShort
;
1653 else if(OutputType
.Format
.wBitsPerSample
== 32)
1654 mDevice
->FmtType
= DevFmtInt
;
1657 mDevice
->FmtType
= DevFmtShort
;
1658 OutputType
.Format
.wBitsPerSample
= 16;
1661 else if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1663 mDevice
->FmtType
= DevFmtFloat
;
1664 OutputType
.Format
.wBitsPerSample
= 32;
1668 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{OutputType
.SubFormat
}.c_str());
1669 mDevice
->FmtType
= DevFmtShort
;
1670 if(OutputType
.Format
.wFormatTag
!= WAVE_FORMAT_EXTENSIBLE
)
1671 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_PCM
;
1672 OutputType
.Format
.wBitsPerSample
= 16;
1673 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1675 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1676 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1680 auto WasapiPlayback::initSpatial() -> bool
1682 auto &audio
= mAudio
.emplace
<SpatialDevice
>();
1683 HRESULT hr
{sDeviceHelper
->activateAudioClient(mMMDev
, __uuidof(ISpatialAudioClient
),
1684 al::out_ptr(audio
.mClient
))};
1687 ERR("Failed to activate spatial audio client: 0x%08lx\n", hr
);
1691 ComPtr
<IAudioFormatEnumerator
> fmtenum
;
1692 hr
= audio
.mClient
->GetSupportedAudioObjectFormatEnumerator(al::out_ptr(fmtenum
));
1695 ERR("Failed to get format enumerator: 0x%08lx\n", hr
);
1700 hr
= fmtenum
->GetCount(&fmtcount
);
1701 if(FAILED(hr
) || fmtcount
== 0)
1703 ERR("Failed to get format count: 0x%08lx\n", hr
);
1707 WAVEFORMATEX
*preferredFormat
{};
1708 hr
= fmtenum
->GetFormat(0, &preferredFormat
);
1711 ERR("Failed to get preferred format: 0x%08lx\n", hr
);
1714 TraceFormat("Preferred mix format", preferredFormat
);
1717 hr
= audio
.mClient
->GetMaxFrameCount(preferredFormat
, &maxFrames
);
1719 ERR("Failed to get max frames: 0x%08lx\n", hr
);
1721 TRACE("Max sample frames: %u\n", maxFrames
);
1722 for(UINT32 i
{1};i
< fmtcount
;++i
)
1724 WAVEFORMATEX
*otherFormat
{};
1725 hr
= fmtenum
->GetFormat(i
, &otherFormat
);
1727 ERR("Failed to format %u: 0x%08lx\n", i
+1, hr
);
1730 TraceFormat("Other mix format", otherFormat
);
1731 UINT32 otherMaxFrames
{};
1732 hr
= audio
.mClient
->GetMaxFrameCount(otherFormat
, &otherMaxFrames
);
1734 ERR("Failed to get max frames: 0x%08lx\n", hr
);
1736 TRACE("Max sample frames: %u\n", otherMaxFrames
);
1740 WAVEFORMATEXTENSIBLE OutputType
;
1741 if(!MakeExtensible(&OutputType
, preferredFormat
))
1744 /* This seems to be the format of each "object", which should be mono. */
1745 if(!(OutputType
.Format
.nChannels
== 1
1746 && (OutputType
.dwChannelMask
== MONO
|| !OutputType
.dwChannelMask
)))
1747 ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType
.Format
.nChannels
,
1748 OutputType
.dwChannelMask
);
1750 /* Force 32-bit float. This is currently required for planar output. */
1751 if(OutputType
.Format
.wFormatTag
!= WAVE_FORMAT_EXTENSIBLE
1752 && OutputType
.Format
.wFormatTag
!= WAVE_FORMAT_IEEE_FLOAT
)
1754 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_IEEE_FLOAT
;
1755 OutputType
.Format
.cbSize
= 0;
1757 if(OutputType
.Format
.wBitsPerSample
!= 32)
1759 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nAvgBytesPerSec
* 32u
1760 / OutputType
.Format
.wBitsPerSample
;
1761 OutputType
.Format
.nBlockAlign
= static_cast<WORD
>(OutputType
.Format
.nBlockAlign
* 32
1762 / OutputType
.Format
.wBitsPerSample
);
1763 OutputType
.Format
.wBitsPerSample
= 32;
1765 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
1766 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1767 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
1769 /* Match the output rate if not requesting anything specific. */
1770 if(!mDevice
->Flags
.test(FrequencyRequest
))
1771 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
1773 auto getTypeMask
= [](DevFmtChannels chans
) noexcept
1777 case DevFmtMono
: return ChannelMask_Mono
;
1778 case DevFmtStereo
: return ChannelMask_Stereo
;
1779 case DevFmtQuad
: return ChannelMask_Quad
;
1780 case DevFmtX51
: return ChannelMask_X51
;
1781 case DevFmtX61
: return ChannelMask_X61
;
1782 case DevFmtX3D71
: [[fallthrough
]];
1783 case DevFmtX71
: return ChannelMask_X71
;
1784 case DevFmtX714
: return ChannelMask_X714
;
1785 case DevFmtX7144
: return ChannelMask_X7144
;
1789 return ChannelMask_Stereo
;
1792 SpatialAudioObjectRenderStreamActivationParams streamParams
{};
1793 streamParams
.ObjectFormat
= &OutputType
.Format
;
1794 streamParams
.StaticObjectTypeMask
= getTypeMask(mDevice
->FmtChans
);
1795 streamParams
.Category
= AudioCategory_Media
;
1796 streamParams
.EventHandle
= mNotifyEvent
;
1798 PropVariant paramProp
{};
1799 paramProp
.setBlob({reinterpret_cast<BYTE
*>(&streamParams
), sizeof(streamParams
)});
1801 hr
= audio
.mClient
->ActivateSpatialAudioStream(paramProp
.get(),
1802 __uuidof(ISpatialAudioObjectRenderStream
), al::out_ptr(audio
.mRender
));
1805 ERR("Failed to activate spatial audio stream: 0x%08lx\n", hr
);
1809 audio
.mStaticMask
= streamParams
.StaticObjectTypeMask
;
1810 mFormat
= OutputType
;
1812 mDevice
->FmtType
= DevFmtFloat
;
1813 mDevice
->Flags
.reset(DirectEar
).set(Virtualization
);
1814 if(streamParams
.StaticObjectTypeMask
== ChannelMask_Stereo
)
1815 mDevice
->FmtChans
= DevFmtStereo
;
1816 if(!GetConfigValueBool(mDevice
->mDeviceName
, "wasapi", "allow-resampler", true))
1817 mDevice
->Frequency
= uint(OutputType
.Format
.nSamplesPerSec
);
1819 mDevice
->Frequency
= std::min(mDevice
->Frequency
,
1820 uint(OutputType
.Format
.nSamplesPerSec
));
1822 setDefaultWFXChannelOrder();
1824 /* FIXME: Get the real update and buffer size. Presumably the actual device
1825 * is configured once ActivateSpatialAudioStream succeeds, and an
1826 * IAudioClient from the same IMMDevice accesses the same device
1827 * configuration. This isn't obviously correct, but for now assume
1828 * IAudioClient::GetDevicePeriod returns the current device period time
1829 * that ISpatialAudioObjectRenderStream will try to wake up at.
1831 * Unfortunately this won't get the buffer size of the
1832 * ISpatialAudioObjectRenderStream, so we only assume there's two periods.
1834 mOutUpdateSize
= mDevice
->UpdateSize
;
1835 mOutBufferSize
= mOutUpdateSize
*2;
1836 ReferenceTime per_time
{ReferenceTime
{seconds
{mDevice
->UpdateSize
}} / mDevice
->Frequency
};
1838 ComPtr
<IAudioClient
> tmpClient
;
1839 hr
= sDeviceHelper
->activateAudioClient(mMMDev
, __uuidof(IAudioClient
),
1840 al::out_ptr(tmpClient
));
1842 ERR("Failed to activate audio client: 0x%08lx\n", hr
);
1845 hr
= tmpClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(per_time
), nullptr);
1847 ERR("Failed to get device period: 0x%08lx\n", hr
);
1850 mOutUpdateSize
= RefTime2Samples(per_time
, mFormat
.Format
.nSamplesPerSec
);
1851 mOutBufferSize
= mOutUpdateSize
*2;
1854 tmpClient
= nullptr;
1856 mDevice
->UpdateSize
= RefTime2Samples(per_time
, mDevice
->Frequency
);
1857 mDevice
->BufferSize
= mDevice
->UpdateSize
*2;
1859 mResampler
= nullptr;
1860 mResampleBuffer
.clear();
1861 mResampleBuffer
.shrink_to_fit();
1863 if(mDevice
->Frequency
!= mFormat
.Format
.nSamplesPerSec
)
1865 const auto flags
= as_unsigned(streamParams
.StaticObjectTypeMask
);
1866 const auto channelCount
= as_unsigned(al::popcount(flags
));
1867 mResampler
= SampleConverter::Create(mDevice
->FmtType
, mDevice
->FmtType
, channelCount
,
1868 mDevice
->Frequency
, mFormat
.Format
.nSamplesPerSec
, Resampler::FastBSinc24
);
1869 mResampleBuffer
.resize(size_t{mDevice
->UpdateSize
} * channelCount
*
1870 mFormat
.Format
.wBitsPerSample
/ 8);
1872 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
1873 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1874 mFormat
.Format
.nSamplesPerSec
, mOutUpdateSize
, mDevice
->Frequency
,
1875 mDevice
->UpdateSize
);
1881 bool WasapiPlayback::reset()
1883 HRESULT hr
{pushMessage(MsgType::ResetDevice
).get()};
1885 throw al::backend_exception
{al::backend_error::DeviceError
, "0x%08lx", hr
};
1889 HRESULT
WasapiPlayback::resetProxy()
1891 if(GetConfigValueBool(mDevice
->mDeviceName
, "wasapi", "spatial-api", false))
1897 mDevice
->Flags
.reset(Virtualization
);
1899 auto &audio
= mAudio
.emplace
<PlainDevice
>();
1900 HRESULT hr
{sDeviceHelper
->activateAudioClient(mMMDev
, __uuidof(IAudioClient
),
1901 al::out_ptr(audio
.mClient
))};
1904 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
1909 hr
= audio
.mClient
->GetMixFormat(&wfx
);
1912 ERR("Failed to get mix format: 0x%08lx\n", hr
);
1915 TraceFormat("Device mix format", wfx
);
1917 WAVEFORMATEXTENSIBLE OutputType
;
1918 if(!MakeExtensible(&OutputType
, wfx
))
1926 const ReferenceTime per_time
{ReferenceTime
{seconds
{mDevice
->UpdateSize
}} / mDevice
->Frequency
};
1927 const ReferenceTime buf_time
{ReferenceTime
{seconds
{mDevice
->BufferSize
}} / mDevice
->Frequency
};
1929 prepareFormat(OutputType
);
1931 TraceFormat("Requesting playback format", &OutputType
.Format
);
1932 hr
= audio
.mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &OutputType
.Format
, &wfx
);
1935 WARN("Failed to check format support: 0x%08lx\n", hr
);
1936 hr
= audio
.mClient
->GetMixFormat(&wfx
);
1940 ERR("Failed to find a supported format: 0x%08lx\n", hr
);
1946 TraceFormat("Got playback format", wfx
);
1947 if(!MakeExtensible(&OutputType
, wfx
))
1955 finalizeFormat(OutputType
);
1957 mFormat
= OutputType
;
1959 #if !defined(ALSOFT_UWP)
1960 const EndpointFormFactor formfactor
{GetDeviceFormfactor(mMMDev
.get())};
1961 mDevice
->Flags
.set(DirectEar
, (formfactor
== Headphones
|| formfactor
== Headset
));
1963 mDevice
->Flags
.set(DirectEar
, false);
1965 setDefaultWFXChannelOrder();
1967 hr
= audio
.mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1968 buf_time
.count(), 0, &OutputType
.Format
, nullptr);
1971 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1975 UINT32 buffer_len
{};
1976 ReferenceTime min_per
{};
1977 hr
= audio
.mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
1979 hr
= audio
.mClient
->GetBufferSize(&buffer_len
);
1982 ERR("Failed to get audio buffer info: 0x%08lx\n", hr
);
1986 hr
= audio
.mClient
->SetEventHandle(mNotifyEvent
);
1989 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1993 hr
= audio
.mClient
->GetService(__uuidof(IAudioRenderClient
), al::out_ptr(audio
.mRender
));
1996 ERR("Failed to get IAudioRenderClient: 0x%08lx\n", hr
);
2000 /* Find the nearest multiple of the period size to the update size */
2001 if(min_per
< per_time
)
2002 min_per
*= std::max
<int64_t>((per_time
+ min_per
/2) / min_per
, 1_i64
);
2004 mOutBufferSize
= buffer_len
;
2005 mOutUpdateSize
= std::min(RefTime2Samples(min_per
, mFormat
.Format
.nSamplesPerSec
),
2008 mDevice
->BufferSize
= static_cast<uint
>(uint64_t{buffer_len
} * mDevice
->Frequency
/
2009 mFormat
.Format
.nSamplesPerSec
);
2010 mDevice
->UpdateSize
= std::min(RefTime2Samples(min_per
, mDevice
->Frequency
),
2011 mDevice
->BufferSize
/2u);
2013 mResampler
= nullptr;
2014 mResampleBuffer
.clear();
2015 mResampleBuffer
.shrink_to_fit();
2017 if(mDevice
->Frequency
!= mFormat
.Format
.nSamplesPerSec
)
2019 mResampler
= SampleConverter::Create(mDevice
->FmtType
, mDevice
->FmtType
,
2020 mFormat
.Format
.nChannels
, mDevice
->Frequency
, mFormat
.Format
.nSamplesPerSec
,
2021 Resampler::FastBSinc24
);
2022 mResampleBuffer
.resize(size_t{mDevice
->UpdateSize
} * mFormat
.Format
.nChannels
*
2023 mFormat
.Format
.wBitsPerSample
/ 8);
2025 TRACE("Created converter for %s/%s format, dst: %luhz (%u), src: %uhz (%u)\n",
2026 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
2027 mFormat
.Format
.nSamplesPerSec
, mOutUpdateSize
, mDevice
->Frequency
,
2028 mDevice
->UpdateSize
);
2035 void WasapiPlayback::start()
2037 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
2039 throw al::backend_exception
{al::backend_error::DeviceError
,
2040 "Failed to start playback: 0x%lx", hr
};
2043 HRESULT
WasapiPlayback::startProxy()
2045 ResetEvent(mNotifyEvent
);
2047 auto start_plain
= [&](PlainDevice
&audio
) -> HRESULT
2049 HRESULT hr
{audio
.mClient
->Start()};
2052 ERR("Failed to start audio client: 0x%08lx\n", hr
);
2057 mKillNow
.store(false, std::memory_order_release
);
2058 mThread
= std::thread
{std::mem_fn(&WasapiPlayback::mixerProc
), this};
2061 ERR("Failed to start thread\n");
2062 audio
.mClient
->Stop();
2067 auto start_spatial
= [&](SpatialDevice
&audio
) -> HRESULT
2069 HRESULT hr
{audio
.mRender
->Start()};
2072 ERR("Failed to start spatial audio stream: 0x%08lx\n", hr
);
2077 mKillNow
.store(false, std::memory_order_release
);
2078 mThread
= std::thread
{std::mem_fn(&WasapiPlayback::mixerSpatialProc
), this};
2081 ERR("Failed to start thread\n");
2087 audio
.mRender
->Stop();
2088 audio
.mRender
->Reset();
2093 return std::visit(overloaded
{start_plain
, start_spatial
}, mAudio
);
2097 void WasapiPlayback::stop()
2098 { pushMessage(MsgType::StopDevice
).wait(); }
2100 void WasapiPlayback::stopProxy()
2102 if(!mThread
.joinable())
2105 mKillNow
.store(true, std::memory_order_release
);
2108 auto stop_plain
= [](PlainDevice
&audio
) -> void
2109 { audio
.mClient
->Stop(); };
2110 auto stop_spatial
= [](SpatialDevice
&audio
) -> void
2112 audio
.mRender
->Stop();
2113 audio
.mRender
->Reset();
2115 std::visit(overloaded
{stop_plain
, stop_spatial
}, mAudio
);
2119 ClockLatency
WasapiPlayback::getClockLatency()
2121 std::lock_guard
<std::mutex
> dlock
{mMutex
};
2123 ret
.ClockTime
= mDevice
->getClockTime();
2124 ret
.Latency
= seconds
{mPadding
.load(std::memory_order_relaxed
)};
2125 ret
.Latency
/= mFormat
.Format
.nSamplesPerSec
;
2128 auto extra
= mResampler
->currentInputDelay();
2129 ret
.Latency
+= std::chrono::duration_cast
<nanoseconds
>(extra
) / mDevice
->Frequency
;
2130 ret
.Latency
+= nanoseconds
{seconds
{mBufferFilled
}} / mDevice
->Frequency
;
2137 struct WasapiCapture final
: public BackendBase
, WasapiProxy
{
2138 WasapiCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
2139 ~WasapiCapture() override
;
2143 void open(std::string_view name
) override
;
2144 HRESULT
openProxy(std::string_view name
) override
;
2145 void closeProxy() override
;
2147 HRESULT
resetProxy() override
;
2148 void start() override
;
2149 HRESULT
startProxy() override
;
2150 void stop() override
;
2151 void stopProxy() override
;
2153 void captureSamples(std::byte
*buffer
, uint samples
) override
;
2154 uint
availableSamples() override
;
2156 HRESULT mOpenStatus
{E_FAIL
};
2157 DeviceHandle mMMDev
{nullptr};
2158 ComPtr
<IAudioClient
> mClient
{nullptr};
2159 ComPtr
<IAudioCaptureClient
> mCapture
{nullptr};
2160 HANDLE mNotifyEvent
{nullptr};
2162 ChannelConverter mChannelConv
{};
2163 SampleConverterPtr mSampleConv
;
2164 RingBufferPtr mRing
;
2166 std::atomic
<bool> mKillNow
{true};
2167 std::thread mThread
;
2170 WasapiCapture::~WasapiCapture()
2172 if(SUCCEEDED(mOpenStatus
))
2173 pushMessage(MsgType::CloseDevice
).wait();
2174 mOpenStatus
= E_FAIL
;
2176 if(mNotifyEvent
!= nullptr)
2177 CloseHandle(mNotifyEvent
);
2178 mNotifyEvent
= nullptr;
2182 FORCE_ALIGN
int WasapiCapture::recordProc()
2184 ComWrapper com
{COINIT_MULTITHREADED
};
2187 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", com
.status());
2188 mDevice
->handleDisconnect("COM init failed: 0x%08lx", com
.status());
2192 althrd_setname(GetRecordThreadName());
2194 std::vector
<float> samples
;
2195 while(!mKillNow
.load(std::memory_order_relaxed
))
2198 HRESULT hr
{mCapture
->GetNextPacketSize(&avail
)};
2200 ERR("Failed to get next packet size: 0x%08lx\n", hr
);
2207 hr
= mCapture
->GetBuffer(&rdata
, &numsamples
, &flags
, nullptr, nullptr);
2209 ERR("Failed to get capture buffer: 0x%08lx\n", hr
);
2212 if(mChannelConv
.is_active())
2214 samples
.resize(numsamples
*2_uz
);
2215 mChannelConv
.convert(rdata
, samples
.data(), numsamples
);
2216 rdata
= reinterpret_cast<BYTE
*>(samples
.data());
2219 auto data
= mRing
->getWriteVector();
2224 static constexpr auto lenlimit
= size_t{std::numeric_limits
<int>::max()};
2225 const void *srcdata
{rdata
};
2226 uint srcframes
{numsamples
};
2228 dstframes
= mSampleConv
->convert(&srcdata
, &srcframes
, data
[0].buf
,
2229 static_cast<uint
>(std::min(data
[0].len
, lenlimit
)));
2230 if(srcframes
> 0 && dstframes
== data
[0].len
&& data
[1].len
> 0)
2232 /* If some source samples remain, all of the first dest
2233 * block was filled, and there's space in the second
2234 * dest block, do another run for the second block.
2236 dstframes
+= mSampleConv
->convert(&srcdata
, &srcframes
, data
[1].buf
,
2237 static_cast<uint
>(std::min(data
[1].len
, lenlimit
)));
2242 const uint framesize
{mDevice
->frameSizeFromFmt()};
2243 auto dst
= al::span
{rdata
, size_t{numsamples
}*framesize
};
2244 size_t len1
{std::min(data
[0].len
, size_t{numsamples
})};
2245 size_t len2
{std::min(data
[1].len
, numsamples
-len1
)};
2247 memcpy(data
[0].buf
, dst
.data(), len1
*framesize
);
2250 dst
= dst
.subspan(len1
*framesize
);
2251 memcpy(data
[1].buf
, dst
.data(), len2
*framesize
);
2253 dstframes
= len1
+ len2
;
2256 mRing
->writeAdvance(dstframes
);
2258 hr
= mCapture
->ReleaseBuffer(numsamples
);
2259 if(FAILED(hr
)) ERR("Failed to release capture buffer: 0x%08lx\n", hr
);
2265 mDevice
->handleDisconnect("Failed to capture samples: 0x%08lx", hr
);
2269 DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
)};
2270 if(res
!= WAIT_OBJECT_0
)
2271 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
2278 void WasapiCapture::open(std::string_view name
)
2280 if(SUCCEEDED(mOpenStatus
))
2281 throw al::backend_exception
{al::backend_error::DeviceError
,
2282 "Unexpected duplicate open call"};
2284 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
2285 if(mNotifyEvent
== nullptr)
2287 ERR("Failed to create notify events: %lu\n", GetLastError());
2288 throw al::backend_exception
{al::backend_error::DeviceError
,
2289 "Failed to create notify events"};
2292 mOpenStatus
= pushMessage(MsgType::OpenDevice
, name
).get();
2293 if(FAILED(mOpenStatus
))
2294 throw al::backend_exception
{al::backend_error::DeviceError
, "Device init failed: 0x%08lx",
2297 HRESULT hr
{pushMessage(MsgType::ResetDevice
).get()};
2300 if(hr
== E_OUTOFMEMORY
)
2301 throw al::backend_exception
{al::backend_error::OutOfMemory
, "Out of memory"};
2302 throw al::backend_exception
{al::backend_error::DeviceError
, "Device reset failed"};
2306 HRESULT
WasapiCapture::openProxy(std::string_view name
)
2308 std::string devname
;
2312 auto devlock
= DeviceListLock
{gDeviceList
};
2313 auto devlist
= al::span
{devlock
.getCaptureList()};
2314 auto iter
= std::find_if(devlist
.cbegin(), devlist
.cend(),
2315 [name
](const DevMap
&entry
) -> bool
2316 { return entry
.name
== name
|| entry
.endpoint_guid
== name
; });
2317 if(iter
== devlist
.cend())
2319 const std::wstring wname
{utf8_to_wstr(name
)};
2320 iter
= std::find_if(devlist
.cbegin(), devlist
.cend(),
2321 [&wname
](const DevMap
&entry
) -> bool
2322 { return entry
.devid
== wname
; });
2324 if(iter
== devlist
.cend())
2326 WARN("Failed to find device name matching \"%.*s\"\n", al::sizei(name
), name
.data());
2329 devname
= iter
->name
;
2330 devid
= iter
->devid
;
2333 HRESULT hr
{sDeviceHelper
->openDevice(devid
, eCapture
, mMMDev
)};
2336 WARN("Failed to open device \"%s\"\n", devname
.empty() ? "(default)" : devname
.c_str());
2340 if(!devname
.empty())
2341 mDeviceName
= std::move(devname
);
2343 mDeviceName
= GetDeviceNameAndGuid(mMMDev
).mName
;
2348 void WasapiCapture::closeProxy()
2355 HRESULT
WasapiCapture::resetProxy()
2360 HRESULT hr
{sDeviceHelper
->activateAudioClient(mMMDev
, __uuidof(IAudioClient
),
2361 al::out_ptr(mClient
))};
2364 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
2369 hr
= mClient
->GetMixFormat(&wfx
);
2372 ERR("Failed to get capture format: 0x%08lx\n", hr
);
2375 TraceFormat("Device capture format", wfx
);
2377 WAVEFORMATEXTENSIBLE InputType
{};
2378 if(!MakeExtensible(&InputType
, wfx
))
2386 const bool isRear51
{InputType
.Format
.nChannels
== 6
2387 && (InputType
.dwChannelMask
&X51RearMask
) == X5DOT1REAR
};
2389 // Make sure buffer is at least 100ms in size
2390 ReferenceTime buf_time
{ReferenceTime
{seconds
{mDevice
->BufferSize
}} / mDevice
->Frequency
};
2391 buf_time
= std::max(buf_time
, ReferenceTime
{milliseconds
{100}});
2394 InputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
2395 switch(mDevice
->FmtChans
)
2398 InputType
.Format
.nChannels
= 1;
2399 InputType
.dwChannelMask
= MONO
;
2402 InputType
.Format
.nChannels
= 2;
2403 InputType
.dwChannelMask
= STEREO
;
2406 InputType
.Format
.nChannels
= 4;
2407 InputType
.dwChannelMask
= QUAD
;
2410 InputType
.Format
.nChannels
= 6;
2411 InputType
.dwChannelMask
= isRear51
? X5DOT1REAR
: X5DOT1
;
2414 InputType
.Format
.nChannels
= 7;
2415 InputType
.dwChannelMask
= X6DOT1
;
2418 InputType
.Format
.nChannels
= 8;
2419 InputType
.dwChannelMask
= X7DOT1
;
2422 InputType
.Format
.nChannels
= 12;
2423 InputType
.dwChannelMask
= X7DOT1DOT4
;
2431 switch(mDevice
->FmtType
)
2433 /* NOTE: Signedness doesn't matter, the converter will handle it. */
2436 InputType
.Format
.wBitsPerSample
= 8;
2437 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
2441 InputType
.Format
.wBitsPerSample
= 16;
2442 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
2446 InputType
.Format
.wBitsPerSample
= 32;
2447 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
2450 InputType
.Format
.wBitsPerSample
= 32;
2451 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
2454 /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-union-access) */
2455 InputType
.Samples
.wValidBitsPerSample
= InputType
.Format
.wBitsPerSample
;
2456 InputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
2458 InputType
.Format
.nBlockAlign
= static_cast<WORD
>(InputType
.Format
.nChannels
*
2459 InputType
.Format
.wBitsPerSample
/ 8);
2460 InputType
.Format
.nAvgBytesPerSec
= InputType
.Format
.nSamplesPerSec
*
2461 InputType
.Format
.nBlockAlign
;
2462 InputType
.Format
.cbSize
= sizeof(InputType
) - sizeof(InputType
.Format
);
2464 TraceFormat("Requesting capture format", &InputType
.Format
);
2465 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &InputType
.Format
, &wfx
);
2468 WARN("Failed to check capture format support: 0x%08lx\n", hr
);
2469 hr
= mClient
->GetMixFormat(&wfx
);
2473 ERR("Failed to find a supported capture format: 0x%08lx\n", hr
);
2477 mSampleConv
= nullptr;
2482 TraceFormat("Got capture format", wfx
);
2483 if(!MakeExtensible(&InputType
, wfx
))
2491 auto validate_fmt
= [](DeviceBase
*device
, uint32_t chancount
, DWORD chanmask
) noexcept
2494 switch(device
->FmtChans
)
2496 /* If the device wants mono, we can handle any input. */
2499 /* If the device wants stereo, we can handle mono or stereo input. */
2501 return (chancount
== 2 && (chanmask
== 0 || (chanmask
&StereoMask
) == STEREO
))
2502 || (chancount
== 1 && (chanmask
&MonoMask
) == MONO
);
2503 /* Otherwise, the device must match the input type. */
2505 return (chancount
== 4 && (chanmask
== 0 || (chanmask
&QuadMask
) == QUAD
));
2506 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
2508 return (chancount
== 6 && (chanmask
== 0 || (chanmask
&X51Mask
) == X5DOT1
2509 || (chanmask
&X51RearMask
) == X5DOT1REAR
));
2511 return (chancount
== 7 && (chanmask
== 0 || (chanmask
&X61Mask
) == X6DOT1
));
2514 return (chancount
== 8 && (chanmask
== 0 || (chanmask
&X71Mask
) == X7DOT1
));
2516 return (chancount
== 12 && (chanmask
== 0 || (chanmask
&X714Mask
) == X7DOT1DOT4
));
2518 return (chancount
== 16 && chanmask
== 0);
2520 return (chanmask
== 0 && chancount
== device
->channelsFromFmt());
2524 if(!validate_fmt(mDevice
, InputType
.Format
.nChannels
, InputType
.dwChannelMask
))
2526 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
2527 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
2528 mDevice
->Frequency
, InputType
.dwChannelMask
, InputType
.Format
.nChannels
,
2529 (InputType
.Format
.nChannels
==1)?"":"s", InputType
.Format
.wBitsPerSample
,
2530 InputType
.Format
.nSamplesPerSec
);
2535 DevFmtType srcType
{};
2536 if(IsEqualGUID(InputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
2538 if(InputType
.Format
.wBitsPerSample
== 8)
2539 srcType
= DevFmtUByte
;
2540 else if(InputType
.Format
.wBitsPerSample
== 16)
2541 srcType
= DevFmtShort
;
2542 else if(InputType
.Format
.wBitsPerSample
== 32)
2543 srcType
= DevFmtInt
;
2546 ERR("Unhandled integer bit depth: %d\n", InputType
.Format
.wBitsPerSample
);
2550 else if(IsEqualGUID(InputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
2552 if(InputType
.Format
.wBitsPerSample
== 32)
2553 srcType
= DevFmtFloat
;
2556 ERR("Unhandled float bit depth: %d\n", InputType
.Format
.wBitsPerSample
);
2562 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{InputType
.SubFormat
}.c_str());
2566 if(mDevice
->FmtChans
== DevFmtMono
&& InputType
.Format
.nChannels
!= 1)
2568 uint chanmask
{(1u<<InputType
.Format
.nChannels
) - 1u};
2569 /* Exclude LFE from the downmix. */
2570 if((InputType
.dwChannelMask
&SPEAKER_LOW_FREQUENCY
))
2572 constexpr auto lfemask
= MaskFromTopBits(SPEAKER_LOW_FREQUENCY
);
2573 const int lfeidx
{al::popcount(InputType
.dwChannelMask
&lfemask
) - 1};
2574 chanmask
&= ~(1u << lfeidx
);
2577 mChannelConv
= ChannelConverter
{srcType
, InputType
.Format
.nChannels
, chanmask
,
2579 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType
));
2580 /* The channel converter always outputs float, so change the input type
2581 * for the resampler/type-converter.
2583 srcType
= DevFmtFloat
;
2585 else if(mDevice
->FmtChans
== DevFmtStereo
&& InputType
.Format
.nChannels
== 1)
2587 mChannelConv
= ChannelConverter
{srcType
, 1, 0x1, mDevice
->FmtChans
};
2588 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType
));
2589 srcType
= DevFmtFloat
;
2592 if(mDevice
->Frequency
!= InputType
.Format
.nSamplesPerSec
|| mDevice
->FmtType
!= srcType
)
2594 mSampleConv
= SampleConverter::Create(srcType
, mDevice
->FmtType
,
2595 mDevice
->channelsFromFmt(), InputType
.Format
.nSamplesPerSec
, mDevice
->Frequency
,
2596 Resampler::FastBSinc24
);
2599 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2600 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
2601 mDevice
->Frequency
, DevFmtTypeString(srcType
), InputType
.Format
.nSamplesPerSec
);
2604 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
2605 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
2606 mDevice
->Frequency
, DevFmtTypeString(srcType
), InputType
.Format
.nSamplesPerSec
);
2609 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
2610 buf_time
.count(), 0, &InputType
.Format
, nullptr);
2613 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
2617 hr
= mClient
->GetService(__uuidof(IAudioCaptureClient
), al::out_ptr(mCapture
));
2620 ERR("Failed to get IAudioCaptureClient: 0x%08lx\n", hr
);
2624 UINT32 buffer_len
{};
2625 ReferenceTime min_per
{};
2626 hr
= mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
2628 hr
= mClient
->GetBufferSize(&buffer_len
);
2631 ERR("Failed to get buffer size: 0x%08lx\n", hr
);
2634 mDevice
->UpdateSize
= RefTime2Samples(min_per
, mDevice
->Frequency
);
2635 mDevice
->BufferSize
= buffer_len
;
2637 mRing
= RingBuffer::Create(buffer_len
, mDevice
->frameSizeFromFmt(), false);
2639 hr
= mClient
->SetEventHandle(mNotifyEvent
);
2642 ERR("Failed to set event handle: 0x%08lx\n", hr
);
2650 void WasapiCapture::start()
2652 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
2654 throw al::backend_exception
{al::backend_error::DeviceError
,
2655 "Failed to start recording: 0x%lx", hr
};
2658 HRESULT
WasapiCapture::startProxy()
2660 ResetEvent(mNotifyEvent
);
2662 HRESULT hr
{mClient
->Start()};
2665 ERR("Failed to start audio client: 0x%08lx\n", hr
);
2670 mKillNow
.store(false, std::memory_order_release
);
2671 mThread
= std::thread
{std::mem_fn(&WasapiCapture::recordProc
), this};
2674 ERR("Failed to start thread\n");
2684 void WasapiCapture::stop()
2685 { pushMessage(MsgType::StopDevice
).wait(); }
2687 void WasapiCapture::stopProxy()
2689 if(!mThread
.joinable())
2692 mKillNow
.store(true, std::memory_order_release
);
2700 void WasapiCapture::captureSamples(std::byte
*buffer
, uint samples
)
2701 { std::ignore
= mRing
->read(buffer
, samples
); }
2703 uint
WasapiCapture::availableSamples()
2704 { return static_cast<uint
>(mRing
->readSpace()); }
2709 bool WasapiBackendFactory::init()
2711 static HRESULT InitResult
{E_FAIL
};
2712 if(FAILED(InitResult
)) try
2714 std::promise
<HRESULT
> promise
;
2715 auto future
= promise
.get_future();
2717 std::thread
{&WasapiProxy::messageHandler
, &promise
}.detach();
2718 InitResult
= future
.get();
2723 return SUCCEEDED(InitResult
);
2726 bool WasapiBackendFactory::querySupport(BackendType type
)
2727 { return type
== BackendType::Playback
|| type
== BackendType::Capture
; }
2729 auto WasapiBackendFactory::enumerate(BackendType type
) -> std::vector
<std::string
>
2731 std::vector
<std::string
> outnames
;
2733 auto devlock
= DeviceListLock
{gDeviceList
};
2736 case BackendType::Playback
:
2738 auto defaultId
= devlock
.getPlaybackDefaultId();
2739 for(const DevMap
&entry
: devlock
.getPlaybackList())
2741 if(entry
.devid
!= defaultId
)
2743 outnames
.emplace_back(entry
.name
);
2746 /* Default device goes first. */
2747 outnames
.emplace(outnames
.cbegin(), entry
.name
);
2752 case BackendType::Capture
:
2754 auto defaultId
= devlock
.getCaptureDefaultId();
2755 for(const DevMap
&entry
: devlock
.getCaptureList())
2757 if(entry
.devid
!= defaultId
)
2759 outnames
.emplace_back(entry
.name
);
2762 outnames
.emplace(outnames
.cbegin(), entry
.name
);
2771 BackendPtr
WasapiBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
2773 if(type
== BackendType::Playback
)
2774 return BackendPtr
{new WasapiPlayback
{device
}};
2775 if(type
== BackendType::Capture
)
2776 return BackendPtr
{new WasapiCapture
{device
}};
2780 BackendFactory
&WasapiBackendFactory::getFactory()
2782 static WasapiBackendFactory factory
{};
2786 alc::EventSupport
WasapiBackendFactory::queryEventSupport(alc::EventType eventType
, BackendType
)
2790 case alc::EventType::DefaultDeviceChanged
:
2791 return alc::EventSupport::FullSupport
;
2793 case alc::EventType::DeviceAdded
:
2794 case alc::EventType::DeviceRemoved
:
2795 #if !defined(ALSOFT_UWP)
2796 return alc::EventSupport::FullSupport
;
2799 case alc::EventType::Count
:
2802 return alc::EventSupport::NoSupport
;