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