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
33 #include <mmdeviceapi.h>
34 #include <audioclient.h>
36 #include <devpropdef.h>
41 #ifndef _WAVEFORMATEXTENSIBLE_
49 #include <condition_variable>
60 #include "alnumeric.h"
62 #include "core/converter.h"
63 #include "core/device.h"
64 #include "core/helpers.h"
65 #include "core/logging.h"
66 #include "ringbuffer.h"
71 /* Some headers seem to define these as macros for __uuidof, which is annoying
72 * since some headers don't declare them at all. Hopefully the ifdef is enough
73 * to tell if they need to be declared.
75 #ifndef KSDATAFORMAT_SUBTYPE_PCM
76 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM
, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
78 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
79 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
82 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName
, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
83 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor
, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
84 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID
, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
89 using std::chrono::milliseconds
;
90 using std::chrono::seconds
;
92 using ReferenceTime
= std::chrono::duration
<REFERENCE_TIME
,std::ratio
<1,10000000>>;
94 inline constexpr ReferenceTime
operator "" _reftime(unsigned long long int n
) noexcept
95 { return ReferenceTime
{static_cast<REFERENCE_TIME
>(n
)}; }
98 #define MONO SPEAKER_FRONT_CENTER
99 #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
100 #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
101 #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
102 #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
103 #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
104 #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)
106 constexpr inline DWORD
MaskFromTopBits(DWORD b
) noexcept
115 constexpr DWORD MonoMask
{MaskFromTopBits(MONO
)};
116 constexpr DWORD StereoMask
{MaskFromTopBits(STEREO
)};
117 constexpr DWORD QuadMask
{MaskFromTopBits(QUAD
)};
118 constexpr DWORD X51Mask
{MaskFromTopBits(X5DOT1
)};
119 constexpr DWORD X51RearMask
{MaskFromTopBits(X5DOT1REAR
)};
120 constexpr DWORD X61Mask
{MaskFromTopBits(X6DOT1
)};
121 constexpr DWORD X71Mask
{MaskFromTopBits(X7DOT1
)};
123 constexpr char DevNameHead
[] = "OpenAL Soft on ";
124 constexpr size_t DevNameHeadLen
{al::size(DevNameHead
) - 1};
127 /* Scales the given reftime value, rounding the result. */
128 inline uint
RefTime2Samples(const ReferenceTime
&val
, uint srate
)
130 const auto retval
= (val
*srate
+ ReferenceTime
{seconds
{1}}/2) / seconds
{1};
131 return static_cast<uint
>(mini64(retval
, std::numeric_limits
<uint
>::max()));
139 GuidPrinter(const GUID
&guid
)
141 std::snprintf(mMsg
, al::size(mMsg
), "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
142 DWORD
{guid
.Data1
}, guid
.Data2
, guid
.Data3
, guid
.Data4
[0], guid
.Data4
[1], guid
.Data4
[2],
143 guid
.Data4
[3], guid
.Data4
[4], guid
.Data4
[5], guid
.Data4
[6], guid
.Data4
[7]);
145 const char *c_str() const { return mMsg
; }
152 PropVariant() { PropVariantInit(&mProp
); }
153 ~PropVariant() { clear(); }
155 void clear() { PropVariantClear(&mProp
); }
157 PROPVARIANT
* get() noexcept
{ return &mProp
; }
159 PROPVARIANT
& operator*() noexcept
{ return mProp
; }
160 const PROPVARIANT
& operator*() const noexcept
{ return mProp
; }
162 PROPVARIANT
* operator->() noexcept
{ return &mProp
; }
163 const PROPVARIANT
* operator->() const noexcept
{ return &mProp
; }
168 std::string endpoint_guid
; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
171 template<typename T0
, typename T1
, typename T2
>
172 DevMap(T0
&& name_
, T1
&& guid_
, T2
&& devid_
)
173 : name
{std::forward
<T0
>(name_
)}
174 , endpoint_guid
{std::forward
<T1
>(guid_
)}
175 , devid
{std::forward
<T2
>(devid_
)}
179 bool checkName(const al::vector
<DevMap
> &list
, const std::string
&name
)
181 auto match_name
= [&name
](const DevMap
&entry
) -> bool
182 { return entry
.name
== name
; };
183 return std::find_if(list
.cbegin(), list
.cend(), match_name
) != list
.cend();
186 al::vector
<DevMap
> PlaybackDevices
;
187 al::vector
<DevMap
> CaptureDevices
;
190 using NameGUIDPair
= std::pair
<std::string
,std::string
>;
191 NameGUIDPair
get_device_name_and_guid(IMMDevice
*device
)
193 static constexpr char UnknownName
[]{"Unknown Device Name"};
194 static constexpr char UnknownGuid
[]{"Unknown Device GUID"};
195 std::string name
, guid
;
197 ComPtr
<IPropertyStore
> ps
;
198 HRESULT hr
= device
->OpenPropertyStore(STGM_READ
, ps
.getPtr());
201 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
202 return std::make_pair(UnknownName
, UnknownGuid
);
206 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(DEVPKEY_Device_FriendlyName
), pvprop
.get());
209 WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr
);
212 else if(pvprop
->vt
== VT_LPWSTR
)
213 name
+= wstr_to_utf8(pvprop
->pwszVal
);
216 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop
->vt
);
221 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(PKEY_AudioEndpoint_GUID
), pvprop
.get());
224 WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr
);
227 else if(pvprop
->vt
== VT_LPWSTR
)
228 guid
= wstr_to_utf8(pvprop
->pwszVal
);
231 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop
->vt
);
235 return std::make_pair(std::move(name
), std::move(guid
));
238 EndpointFormFactor
get_device_formfactor(IMMDevice
*device
)
240 ComPtr
<IPropertyStore
> ps
;
241 HRESULT hr
{device
->OpenPropertyStore(STGM_READ
, ps
.getPtr())};
244 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
245 return UnknownFormFactor
;
248 EndpointFormFactor formfactor
{UnknownFormFactor
};
250 hr
= ps
->GetValue(PKEY_AudioEndpoint_FormFactor
, pvform
.get());
252 WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr
);
253 else if(pvform
->vt
== VT_UI4
)
254 formfactor
= static_cast<EndpointFormFactor
>(pvform
->ulVal
);
255 else if(pvform
->vt
!= VT_EMPTY
)
256 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform
->vt
);
261 void add_device(IMMDevice
*device
, const WCHAR
*devid
, al::vector
<DevMap
> &list
)
263 for(auto &entry
: list
)
265 if(entry
.devid
== devid
)
269 auto name_guid
= get_device_name_and_guid(device
);
272 std::string newname
{name_guid
.first
};
273 while(checkName(list
, newname
))
275 newname
= name_guid
.first
;
277 newname
+= std::to_string(++count
);
279 list
.emplace_back(std::move(newname
), std::move(name_guid
.second
), devid
);
280 const DevMap
&newentry
= list
.back();
282 TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry
.name
.c_str(),
283 newentry
.endpoint_guid
.c_str(), newentry
.devid
.c_str());
286 WCHAR
*get_device_id(IMMDevice
*device
)
290 const HRESULT hr
{device
->GetId(&devid
)};
293 ERR("Failed to get device id: %lx\n", hr
);
300 void probe_devices(IMMDeviceEnumerator
*devenum
, EDataFlow flowdir
, al::vector
<DevMap
> &list
)
302 al::vector
<DevMap
>{}.swap(list
);
304 ComPtr
<IMMDeviceCollection
> coll
;
305 HRESULT hr
{devenum
->EnumAudioEndpoints(flowdir
, DEVICE_STATE_ACTIVE
, coll
.getPtr())};
308 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr
);
313 hr
= coll
->GetCount(&count
);
314 if(SUCCEEDED(hr
) && count
> 0)
317 ComPtr
<IMMDevice
> device
;
318 hr
= devenum
->GetDefaultAudioEndpoint(flowdir
, eMultimedia
, device
.getPtr());
321 if(WCHAR
*devid
{get_device_id(device
.get())})
323 add_device(device
.get(), devid
, list
);
324 CoTaskMemFree(devid
);
329 for(UINT i
{0};i
< count
;++i
)
331 hr
= coll
->Item(i
, device
.getPtr());
332 if(FAILED(hr
)) continue;
334 if(WCHAR
*devid
{get_device_id(device
.get())})
336 add_device(device
.get(), devid
, list
);
337 CoTaskMemFree(devid
);
344 bool MakeExtensible(WAVEFORMATEXTENSIBLE
*out
, const WAVEFORMATEX
*in
)
346 *out
= WAVEFORMATEXTENSIBLE
{};
347 if(in
->wFormatTag
== WAVE_FORMAT_EXTENSIBLE
)
349 *out
= *CONTAINING_RECORD(in
, const WAVEFORMATEXTENSIBLE
, Format
);
350 out
->Format
.cbSize
= sizeof(*out
) - sizeof(out
->Format
);
352 else if(in
->wFormatTag
== WAVE_FORMAT_PCM
)
355 out
->Format
.cbSize
= 0;
356 out
->Samples
.wValidBitsPerSample
= out
->Format
.wBitsPerSample
;
357 if(out
->Format
.nChannels
== 1)
358 out
->dwChannelMask
= MONO
;
359 else if(out
->Format
.nChannels
== 2)
360 out
->dwChannelMask
= STEREO
;
362 ERR("Unhandled PCM channel count: %d\n", out
->Format
.nChannels
);
363 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
365 else if(in
->wFormatTag
== WAVE_FORMAT_IEEE_FLOAT
)
368 out
->Format
.cbSize
= 0;
369 out
->Samples
.wValidBitsPerSample
= out
->Format
.wBitsPerSample
;
370 if(out
->Format
.nChannels
== 1)
371 out
->dwChannelMask
= MONO
;
372 else if(out
->Format
.nChannels
== 2)
373 out
->dwChannelMask
= STEREO
;
375 ERR("Unhandled IEEE float channel count: %d\n", out
->Format
.nChannels
);
376 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
380 ERR("Unhandled format tag: 0x%04x\n", in
->wFormatTag
);
386 void TraceFormat(const char *msg
, const WAVEFORMATEX
*format
)
388 constexpr size_t fmtex_extra_size
{sizeof(WAVEFORMATEXTENSIBLE
)-sizeof(WAVEFORMATEX
)};
389 if(format
->wFormatTag
== WAVE_FORMAT_EXTENSIBLE
&& format
->cbSize
>= fmtex_extra_size
)
391 const WAVEFORMATEXTENSIBLE
*fmtex
{
392 CONTAINING_RECORD(format
, const WAVEFORMATEXTENSIBLE
, Format
)};
394 " FormatTag = 0x%04x\n"
396 " SamplesPerSec = %lu\n"
397 " AvgBytesPerSec = %lu\n"
399 " BitsPerSample = %d\n"
402 " ChannelMask = 0x%lx\n"
404 msg
, fmtex
->Format
.wFormatTag
, fmtex
->Format
.nChannels
, fmtex
->Format
.nSamplesPerSec
,
405 fmtex
->Format
.nAvgBytesPerSec
, fmtex
->Format
.nBlockAlign
, fmtex
->Format
.wBitsPerSample
,
406 fmtex
->Format
.cbSize
, fmtex
->Samples
.wReserved
, fmtex
->dwChannelMask
,
407 GuidPrinter
{fmtex
->SubFormat
}.c_str());
411 " FormatTag = 0x%04x\n"
413 " SamplesPerSec = %lu\n"
414 " AvgBytesPerSec = %lu\n"
416 " BitsPerSample = %d\n"
418 msg
, format
->wFormatTag
, format
->nChannels
, format
->nSamplesPerSec
,
419 format
->nAvgBytesPerSec
, format
->nBlockAlign
, format
->wBitsPerSample
, format
->cbSize
);
437 constexpr char MessageStr
[static_cast<size_t>(MsgType::Count
)][20]{
444 "Enumerate Playback",
449 /* Proxy interface used by the message handler. */
451 virtual ~WasapiProxy() = default;
453 virtual HRESULT
openProxy(const char *name
) = 0;
454 virtual void closeProxy() = 0;
456 virtual HRESULT
resetProxy() = 0;
457 virtual HRESULT
startProxy() = 0;
458 virtual void stopProxy() = 0;
464 std::promise
<HRESULT
> mPromise
;
466 explicit operator bool() const noexcept
{ return mType
!= MsgType::QuitThread
; }
468 static std::deque
<Msg
> mMsgQueue
;
469 static std::mutex mMsgQueueLock
;
470 static std::condition_variable mMsgQueueCond
;
472 std::future
<HRESULT
> pushMessage(MsgType type
, const char *param
=nullptr)
474 std::promise
<HRESULT
> promise
;
475 std::future
<HRESULT
> future
{promise
.get_future()};
477 std::lock_guard
<std::mutex
> _
{mMsgQueueLock
};
478 mMsgQueue
.emplace_back(Msg
{type
, this, param
, std::move(promise
)});
480 mMsgQueueCond
.notify_one();
484 static std::future
<HRESULT
> pushMessageStatic(MsgType type
)
486 std::promise
<HRESULT
> promise
;
487 std::future
<HRESULT
> future
{promise
.get_future()};
489 std::lock_guard
<std::mutex
> _
{mMsgQueueLock
};
490 mMsgQueue
.emplace_back(Msg
{type
, nullptr, nullptr, std::move(promise
)});
492 mMsgQueueCond
.notify_one();
496 static Msg
popMessage()
498 std::unique_lock
<std::mutex
> lock
{mMsgQueueLock
};
499 mMsgQueueCond
.wait(lock
, []{return !mMsgQueue
.empty();});
500 Msg msg
{std::move(mMsgQueue
.front())};
501 mMsgQueue
.pop_front();
505 static int messageHandler(std::promise
<HRESULT
> *promise
);
507 std::deque
<WasapiProxy::Msg
> WasapiProxy::mMsgQueue
;
508 std::mutex
WasapiProxy::mMsgQueueLock
;
509 std::condition_variable
WasapiProxy::mMsgQueueCond
;
511 int WasapiProxy::messageHandler(std::promise
<HRESULT
> *promise
)
513 TRACE("Starting message thread\n");
515 HRESULT cohr
{CoInitializeEx(nullptr, COINIT_MULTITHREADED
)};
518 WARN("Failed to initialize COM: 0x%08lx\n", cohr
);
519 promise
->set_value(cohr
);
524 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
525 IID_IMMDeviceEnumerator
, &ptr
)};
528 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr
);
529 promise
->set_value(hr
);
533 static_cast<IMMDeviceEnumerator
*>(ptr
)->Release();
536 TRACE("Message thread initialization complete\n");
537 promise
->set_value(S_OK
);
540 TRACE("Starting message loop\n");
542 while(Msg msg
{popMessage()})
544 TRACE("Got message \"%s\" (0x%04x, this=%p, param=%p)\n",
545 MessageStr
[static_cast<size_t>(msg
.mType
)], static_cast<uint
>(msg
.mType
),
546 static_cast<void*>(msg
.mProxy
), static_cast<const void*>(msg
.mParam
));
550 case MsgType::OpenDevice
:
552 if(++deviceCount
== 1)
553 hr
= cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
555 hr
= msg
.mProxy
->openProxy(msg
.mParam
);
556 msg
.mPromise
.set_value(hr
);
560 if(--deviceCount
== 0 && SUCCEEDED(cohr
))
565 case MsgType::ReopenDevice
:
566 hr
= msg
.mProxy
->openProxy(msg
.mParam
);
567 msg
.mPromise
.set_value(hr
);
570 case MsgType::ResetDevice
:
571 hr
= msg
.mProxy
->resetProxy();
572 msg
.mPromise
.set_value(hr
);
575 case MsgType::StartDevice
:
576 hr
= msg
.mProxy
->startProxy();
577 msg
.mPromise
.set_value(hr
);
580 case MsgType::StopDevice
:
581 msg
.mProxy
->stopProxy();
582 msg
.mPromise
.set_value(S_OK
);
585 case MsgType::CloseDevice
:
586 msg
.mProxy
->closeProxy();
587 msg
.mPromise
.set_value(S_OK
);
589 if(--deviceCount
== 0)
593 case MsgType::EnumeratePlayback
:
594 case MsgType::EnumerateCapture
:
596 if(++deviceCount
== 1)
597 hr
= cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
599 hr
= CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
600 IID_IMMDeviceEnumerator
, &ptr
);
602 msg
.mPromise
.set_value(hr
);
605 ComPtr
<IMMDeviceEnumerator
> enumerator
{static_cast<IMMDeviceEnumerator
*>(ptr
)};
607 if(msg
.mType
== MsgType::EnumeratePlayback
)
608 probe_devices(enumerator
.get(), eRender
, PlaybackDevices
);
609 else if(msg
.mType
== MsgType::EnumerateCapture
)
610 probe_devices(enumerator
.get(), eCapture
, CaptureDevices
);
611 msg
.mPromise
.set_value(S_OK
);
614 if(--deviceCount
== 0 && SUCCEEDED(cohr
))
618 case MsgType::QuitThread
:
621 ERR("Unexpected message: %u\n", static_cast<uint
>(msg
.mType
));
622 msg
.mPromise
.set_value(E_FAIL
);
624 TRACE("Message loop finished\n");
630 struct WasapiPlayback final
: public BackendBase
, WasapiProxy
{
631 WasapiPlayback(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
632 ~WasapiPlayback() override
;
636 void open(const char *name
) override
;
637 HRESULT
openProxy(const char *name
) override
;
638 void closeProxy() override
;
640 bool reset() override
;
641 HRESULT
resetProxy() override
;
642 void start() override
;
643 HRESULT
startProxy() override
;
644 void stop() override
;
645 void stopProxy() override
;
647 ClockLatency
getClockLatency() override
;
649 HRESULT mOpenStatus
{E_FAIL
};
650 ComPtr
<IMMDevice
> mMMDev
{nullptr};
651 ComPtr
<IAudioClient
> mClient
{nullptr};
652 ComPtr
<IAudioRenderClient
> mRender
{nullptr};
653 HANDLE mNotifyEvent
{nullptr};
655 UINT32 mFrameStep
{0u};
656 std::atomic
<UINT32
> mPadding
{0u};
660 std::atomic
<bool> mKillNow
{true};
663 DEF_NEWDEL(WasapiPlayback
)
666 WasapiPlayback::~WasapiPlayback()
668 if(SUCCEEDED(mOpenStatus
))
669 pushMessage(MsgType::CloseDevice
).wait();
670 mOpenStatus
= E_FAIL
;
672 if(mNotifyEvent
!= nullptr)
673 CloseHandle(mNotifyEvent
);
674 mNotifyEvent
= nullptr;
678 FORCE_ALIGN
int WasapiPlayback::mixerProc()
680 HRESULT hr
{CoInitializeEx(nullptr, COINIT_MULTITHREADED
)};
683 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr
);
684 mDevice
->handleDisconnect("COM init failed: 0x%08lx", hr
);
689 althrd_setname(MIXER_THREAD_NAME
);
691 const uint update_size
{mDevice
->UpdateSize
};
692 const UINT32 buffer_len
{mDevice
->BufferSize
};
693 while(!mKillNow
.load(std::memory_order_relaxed
))
696 hr
= mClient
->GetCurrentPadding(&written
);
699 ERR("Failed to get padding: 0x%08lx\n", hr
);
700 mDevice
->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr
);
703 mPadding
.store(written
, std::memory_order_relaxed
);
705 uint len
{buffer_len
- written
};
706 if(len
< update_size
)
708 DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
)};
709 if(res
!= WAIT_OBJECT_0
)
710 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
715 hr
= mRender
->GetBuffer(len
, &buffer
);
719 std::lock_guard
<std::mutex
> _
{mMutex
};
720 mDevice
->renderSamples(buffer
, len
, mFrameStep
);
721 mPadding
.store(written
+ len
, std::memory_order_relaxed
);
723 hr
= mRender
->ReleaseBuffer(len
, 0);
727 ERR("Failed to buffer data: 0x%08lx\n", hr
);
728 mDevice
->handleDisconnect("Failed to send playback samples: 0x%08lx", hr
);
732 mPadding
.store(0u, std::memory_order_release
);
739 void WasapiPlayback::open(const char *name
)
745 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
746 if(mNotifyEvent
== nullptr)
748 ERR("Failed to create notify events: %lu\n", GetLastError());
757 if(PlaybackDevices
.empty())
758 pushMessage(MsgType::EnumeratePlayback
);
759 if(std::strncmp(name
, DevNameHead
, DevNameHeadLen
) == 0)
761 name
+= DevNameHeadLen
;
767 if(SUCCEEDED(mOpenStatus
))
768 hr
= pushMessage(MsgType::ReopenDevice
, name
).get();
771 hr
= pushMessage(MsgType::OpenDevice
, name
).get();
777 throw al::backend_exception
{al::backend_error::DeviceError
, "Device init failed: 0x%08lx",
781 HRESULT
WasapiPlayback::openProxy(const char *name
)
783 const wchar_t *devid
{nullptr};
786 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
787 [name
](const DevMap
&entry
) -> bool
788 { return entry
.name
== name
|| entry
.endpoint_guid
== name
; });
789 if(iter
== PlaybackDevices
.cend())
791 const std::wstring wname
{utf8_to_wstr(name
)};
792 iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
793 [&wname
](const DevMap
&entry
) -> bool
794 { return entry
.devid
== wname
; });
796 if(iter
== PlaybackDevices
.cend())
798 WARN("Failed to find device name matching \"%s\"\n", name
);
801 name
= iter
->name
.c_str();
802 devid
= iter
->devid
.c_str();
806 ComPtr
<IMMDevice
> mmdev
;
807 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
808 IID_IMMDeviceEnumerator
, &ptr
)};
811 ComPtr
<IMMDeviceEnumerator
> enumerator
{static_cast<IMMDeviceEnumerator
*>(ptr
)};
813 hr
= enumerator
->GetDefaultAudioEndpoint(eRender
, eMultimedia
, mmdev
.getPtr());
815 hr
= enumerator
->GetDevice(devid
, mmdev
.getPtr());
819 WARN("Failed to open device \"%s\"\n", name
?name
:"(default)");
824 mMMDev
= std::move(mmdev
);
825 if(name
) mDevice
->DeviceName
= std::string
{DevNameHead
} + name
;
826 else mDevice
->DeviceName
= DevNameHead
+ get_device_name_and_guid(mMMDev
.get()).first
;
831 void WasapiPlayback::closeProxy()
838 bool WasapiPlayback::reset()
840 HRESULT hr
{pushMessage(MsgType::ResetDevice
).get()};
842 throw al::backend_exception
{al::backend_error::DeviceError
, "0x%08lx", hr
};
846 HRESULT
WasapiPlayback::resetProxy()
851 HRESULT hr
{mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
)};
854 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
857 mClient
= ComPtr
<IAudioClient
>{static_cast<IAudioClient
*>(ptr
)};
860 hr
= mClient
->GetMixFormat(&wfx
);
863 ERR("Failed to get mix format: 0x%08lx\n", hr
);
867 WAVEFORMATEXTENSIBLE OutputType
;
868 if(!MakeExtensible(&OutputType
, wfx
))
876 const ReferenceTime per_time
{ReferenceTime
{seconds
{mDevice
->UpdateSize
}} / mDevice
->Frequency
};
877 const ReferenceTime buf_time
{ReferenceTime
{seconds
{mDevice
->BufferSize
}} / mDevice
->Frequency
};
879 if(!mDevice
->Flags
.test(FrequencyRequest
))
880 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
881 if(!mDevice
->Flags
.test(ChannelsRequest
))
883 const uint32_t chancount
{OutputType
.Format
.nChannels
};
884 const DWORD chanmask
{OutputType
.dwChannelMask
};
885 if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
886 mDevice
->FmtChans
= DevFmtX71
;
887 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
888 mDevice
->FmtChans
= DevFmtX61
;
889 else if(chancount
>= 6 && ((chanmask
&X51Mask
) == X5DOT1
890 || (chanmask
&X51RearMask
) == X5DOT1REAR
))
891 mDevice
->FmtChans
= DevFmtX51
;
892 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
893 mDevice
->FmtChans
= DevFmtQuad
;
894 else if(chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
)
895 mDevice
->FmtChans
= DevFmtStereo
;
896 else if(chancount
>= 1 && (chanmask
&MonoMask
) == MONO
)
897 mDevice
->FmtChans
= DevFmtMono
;
899 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount
, chanmask
);
902 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
903 switch(mDevice
->FmtChans
)
906 OutputType
.Format
.nChannels
= 1;
907 OutputType
.dwChannelMask
= MONO
;
910 mDevice
->FmtChans
= DevFmtStereo
;
913 OutputType
.Format
.nChannels
= 2;
914 OutputType
.dwChannelMask
= STEREO
;
917 OutputType
.Format
.nChannels
= 4;
918 OutputType
.dwChannelMask
= QUAD
;
921 OutputType
.Format
.nChannels
= 6;
922 OutputType
.dwChannelMask
= X5DOT1
;
925 OutputType
.Format
.nChannels
= 7;
926 OutputType
.dwChannelMask
= X6DOT1
;
929 OutputType
.Format
.nChannels
= 8;
930 OutputType
.dwChannelMask
= X7DOT1
;
933 switch(mDevice
->FmtType
)
936 mDevice
->FmtType
= DevFmtUByte
;
939 OutputType
.Format
.wBitsPerSample
= 8;
940 OutputType
.Samples
.wValidBitsPerSample
= 8;
941 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
944 mDevice
->FmtType
= DevFmtShort
;
947 OutputType
.Format
.wBitsPerSample
= 16;
948 OutputType
.Samples
.wValidBitsPerSample
= 16;
949 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
952 mDevice
->FmtType
= DevFmtInt
;
955 OutputType
.Format
.wBitsPerSample
= 32;
956 OutputType
.Samples
.wValidBitsPerSample
= 32;
957 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
960 OutputType
.Format
.wBitsPerSample
= 32;
961 OutputType
.Samples
.wValidBitsPerSample
= 32;
962 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
965 OutputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
967 OutputType
.Format
.nBlockAlign
= static_cast<WORD
>(OutputType
.Format
.nChannels
*
968 OutputType
.Format
.wBitsPerSample
/ 8);
969 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
970 OutputType
.Format
.nBlockAlign
;
972 TraceFormat("Requesting playback format", &OutputType
.Format
);
973 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &OutputType
.Format
, &wfx
);
976 ERR("Failed to check format support: 0x%08lx\n", hr
);
977 hr
= mClient
->GetMixFormat(&wfx
);
981 ERR("Failed to find a supported format: 0x%08lx\n", hr
);
987 TraceFormat("Got playback format", wfx
);
988 if(!MakeExtensible(&OutputType
, wfx
))
996 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
997 const uint32_t chancount
{OutputType
.Format
.nChannels
};
998 const DWORD chanmask
{OutputType
.dwChannelMask
};
999 /* Don't update the channel format if the requested format fits what's
1002 bool chansok
{false};
1003 if(mDevice
->Flags
.test(ChannelsRequest
))
1005 switch(mDevice
->FmtChans
)
1008 chansok
= (chancount
>= 1 && (chanmask
&MonoMask
) == MONO
);
1011 chansok
= (chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
);
1014 chansok
= (chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
);
1017 chansok
= (chancount
>= 6 && ((chanmask
&X51Mask
) == X5DOT1
1018 || (chanmask
&X51RearMask
) == X5DOT1REAR
));
1021 chansok
= (chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
);
1024 chansok
= (chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
);
1032 if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
1033 mDevice
->FmtChans
= DevFmtX71
;
1034 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
1035 mDevice
->FmtChans
= DevFmtX61
;
1036 else if(chancount
>= 6 && ((chanmask
&X51Mask
) == X5DOT1
1037 || (chanmask
&X51RearMask
) == X5DOT1REAR
))
1038 mDevice
->FmtChans
= DevFmtX51
;
1039 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
1040 mDevice
->FmtChans
= DevFmtQuad
;
1041 else if(chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
)
1042 mDevice
->FmtChans
= DevFmtStereo
;
1043 else if(chancount
>= 1 && (chanmask
&MonoMask
) == MONO
)
1044 mDevice
->FmtChans
= DevFmtMono
;
1047 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType
.Format
.nChannels
,
1048 OutputType
.dwChannelMask
);
1049 mDevice
->FmtChans
= DevFmtStereo
;
1050 OutputType
.Format
.nChannels
= 2;
1051 OutputType
.dwChannelMask
= STEREO
;
1055 if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1057 if(OutputType
.Format
.wBitsPerSample
== 8)
1058 mDevice
->FmtType
= DevFmtUByte
;
1059 else if(OutputType
.Format
.wBitsPerSample
== 16)
1060 mDevice
->FmtType
= DevFmtShort
;
1061 else if(OutputType
.Format
.wBitsPerSample
== 32)
1062 mDevice
->FmtType
= DevFmtInt
;
1065 mDevice
->FmtType
= DevFmtShort
;
1066 OutputType
.Format
.wBitsPerSample
= 16;
1069 else if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1071 mDevice
->FmtType
= DevFmtFloat
;
1072 OutputType
.Format
.wBitsPerSample
= 32;
1076 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{OutputType
.SubFormat
}.c_str());
1077 mDevice
->FmtType
= DevFmtShort
;
1078 if(OutputType
.Format
.wFormatTag
!= WAVE_FORMAT_EXTENSIBLE
)
1079 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_PCM
;
1080 OutputType
.Format
.wBitsPerSample
= 16;
1081 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1083 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1085 mFrameStep
= OutputType
.Format
.nChannels
;
1087 const EndpointFormFactor formfactor
{get_device_formfactor(mMMDev
.get())};
1088 mDevice
->Flags
.set(DirectEar
, (formfactor
== Headphones
|| formfactor
== Headset
));
1090 setChannelOrderFromWFXMask(OutputType
.dwChannelMask
);
1092 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1093 buf_time
.count(), 0, &OutputType
.Format
, nullptr);
1096 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1100 UINT32 buffer_len
{};
1101 ReferenceTime min_per
{};
1102 hr
= mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
1104 hr
= mClient
->GetBufferSize(&buffer_len
);
1107 ERR("Failed to get audio buffer info: 0x%08lx\n", hr
);
1111 /* Find the nearest multiple of the period size to the update size */
1112 if(min_per
< per_time
)
1113 min_per
*= maxi64((per_time
+ min_per
/2) / min_per
, 1);
1114 mDevice
->UpdateSize
= minu(RefTime2Samples(min_per
, mDevice
->Frequency
), buffer_len
/2);
1115 mDevice
->BufferSize
= buffer_len
;
1117 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1120 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1128 void WasapiPlayback::start()
1130 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
1132 throw al::backend_exception
{al::backend_error::DeviceError
,
1133 "Failed to start playback: 0x%lx", hr
};
1136 HRESULT
WasapiPlayback::startProxy()
1138 ResetEvent(mNotifyEvent
);
1140 HRESULT hr
{mClient
->Start()};
1143 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1148 hr
= mClient
->GetService(IID_IAudioRenderClient
, &ptr
);
1151 mRender
= ComPtr
<IAudioRenderClient
>{static_cast<IAudioRenderClient
*>(ptr
)};
1153 mKillNow
.store(false, std::memory_order_release
);
1154 mThread
= std::thread
{std::mem_fn(&WasapiPlayback::mixerProc
), this};
1158 ERR("Failed to start thread\n");
1170 void WasapiPlayback::stop()
1171 { pushMessage(MsgType::StopDevice
).wait(); }
1173 void WasapiPlayback::stopProxy()
1175 if(!mRender
|| !mThread
.joinable())
1178 mKillNow
.store(true, std::memory_order_release
);
1186 ClockLatency
WasapiPlayback::getClockLatency()
1190 std::lock_guard
<std::mutex
> _
{mMutex
};
1191 ret
.ClockTime
= GetDeviceClockTime(mDevice
);
1192 ret
.Latency
= std::chrono::seconds
{mPadding
.load(std::memory_order_relaxed
)};
1193 ret
.Latency
/= mDevice
->Frequency
;
1199 struct WasapiCapture final
: public BackendBase
, WasapiProxy
{
1200 WasapiCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
1201 ~WasapiCapture() override
;
1205 void open(const char *name
) override
;
1206 HRESULT
openProxy(const char *name
) override
;
1207 void closeProxy() override
;
1209 HRESULT
resetProxy() override
;
1210 void start() override
;
1211 HRESULT
startProxy() override
;
1212 void stop() override
;
1213 void stopProxy() override
;
1215 void captureSamples(al::byte
*buffer
, uint samples
) override
;
1216 uint
availableSamples() override
;
1218 HRESULT mOpenStatus
{E_FAIL
};
1219 ComPtr
<IMMDevice
> mMMDev
{nullptr};
1220 ComPtr
<IAudioClient
> mClient
{nullptr};
1221 ComPtr
<IAudioCaptureClient
> mCapture
{nullptr};
1222 HANDLE mNotifyEvent
{nullptr};
1224 ChannelConverter mChannelConv
{};
1225 SampleConverterPtr mSampleConv
;
1226 RingBufferPtr mRing
;
1228 std::atomic
<bool> mKillNow
{true};
1229 std::thread mThread
;
1231 DEF_NEWDEL(WasapiCapture
)
1234 WasapiCapture::~WasapiCapture()
1236 if(SUCCEEDED(mOpenStatus
))
1237 pushMessage(MsgType::CloseDevice
).wait();
1238 mOpenStatus
= E_FAIL
;
1240 if(mNotifyEvent
!= nullptr)
1241 CloseHandle(mNotifyEvent
);
1242 mNotifyEvent
= nullptr;
1246 FORCE_ALIGN
int WasapiCapture::recordProc()
1248 HRESULT hr
{CoInitializeEx(nullptr, COINIT_MULTITHREADED
)};
1251 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr
);
1252 mDevice
->handleDisconnect("COM init failed: 0x%08lx", hr
);
1256 althrd_setname(RECORD_THREAD_NAME
);
1258 al::vector
<float> samples
;
1259 while(!mKillNow
.load(std::memory_order_relaxed
))
1262 hr
= mCapture
->GetNextPacketSize(&avail
);
1264 ERR("Failed to get next packet size: 0x%08lx\n", hr
);
1271 hr
= mCapture
->GetBuffer(&rdata
, &numsamples
, &flags
, nullptr, nullptr);
1273 ERR("Failed to get capture buffer: 0x%08lx\n", hr
);
1276 if(mChannelConv
.is_active())
1278 samples
.resize(numsamples
*2);
1279 mChannelConv
.convert(rdata
, samples
.data(), numsamples
);
1280 rdata
= reinterpret_cast<BYTE
*>(samples
.data());
1283 auto data
= mRing
->getWriteVector();
1288 const void *srcdata
{rdata
};
1289 uint srcframes
{numsamples
};
1291 dstframes
= mSampleConv
->convert(&srcdata
, &srcframes
, data
.first
.buf
,
1292 static_cast<uint
>(minz(data
.first
.len
, INT_MAX
)));
1293 if(srcframes
> 0 && dstframes
== data
.first
.len
&& data
.second
.len
> 0)
1295 /* If some source samples remain, all of the first dest
1296 * block was filled, and there's space in the second
1297 * dest block, do another run for the second block.
1299 dstframes
+= mSampleConv
->convert(&srcdata
, &srcframes
, data
.second
.buf
,
1300 static_cast<uint
>(minz(data
.second
.len
, INT_MAX
)));
1305 const uint framesize
{mDevice
->frameSizeFromFmt()};
1306 size_t len1
{minz(data
.first
.len
, numsamples
)};
1307 size_t len2
{minz(data
.second
.len
, numsamples
-len1
)};
1309 memcpy(data
.first
.buf
, rdata
, len1
*framesize
);
1311 memcpy(data
.second
.buf
, rdata
+len1
*framesize
, len2
*framesize
);
1312 dstframes
= len1
+ len2
;
1315 mRing
->writeAdvance(dstframes
);
1317 hr
= mCapture
->ReleaseBuffer(numsamples
);
1318 if(FAILED(hr
)) ERR("Failed to release capture buffer: 0x%08lx\n", hr
);
1324 mDevice
->handleDisconnect("Failed to capture samples: 0x%08lx", hr
);
1328 DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
)};
1329 if(res
!= WAIT_OBJECT_0
)
1330 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
1338 void WasapiCapture::open(const char *name
)
1342 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1343 if(mNotifyEvent
== nullptr)
1345 ERR("Failed to create notify event: %lu\n", GetLastError());
1353 if(CaptureDevices
.empty())
1354 pushMessage(MsgType::EnumerateCapture
);
1355 if(std::strncmp(name
, DevNameHead
, DevNameHeadLen
) == 0)
1357 name
+= DevNameHeadLen
;
1362 hr
= pushMessage(MsgType::OpenDevice
, name
).get();
1367 throw al::backend_exception
{al::backend_error::DeviceError
, "Device init failed: 0x%08lx",
1370 hr
= pushMessage(MsgType::ResetDevice
).get();
1373 if(hr
== E_OUTOFMEMORY
)
1374 throw al::backend_exception
{al::backend_error::OutOfMemory
, "Out of memory"};
1375 throw al::backend_exception
{al::backend_error::DeviceError
, "Device reset failed"};
1379 HRESULT
WasapiCapture::openProxy(const char *name
)
1381 const wchar_t *devid
{nullptr};
1384 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1385 [name
](const DevMap
&entry
) -> bool
1386 { return entry
.name
== name
|| entry
.endpoint_guid
== name
; });
1387 if(iter
== CaptureDevices
.cend())
1389 const std::wstring wname
{utf8_to_wstr(name
)};
1390 iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1391 [&wname
](const DevMap
&entry
) -> bool
1392 { return entry
.devid
== wname
; });
1394 if(iter
== CaptureDevices
.cend())
1396 WARN("Failed to find device name matching \"%s\"\n", name
);
1399 name
= iter
->name
.c_str();
1400 devid
= iter
->devid
.c_str();
1404 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
1405 IID_IMMDeviceEnumerator
, &ptr
)};
1408 ComPtr
<IMMDeviceEnumerator
> enumerator
{static_cast<IMMDeviceEnumerator
*>(ptr
)};
1410 hr
= enumerator
->GetDefaultAudioEndpoint(eCapture
, eMultimedia
, mMMDev
.getPtr());
1412 hr
= enumerator
->GetDevice(devid
, mMMDev
.getPtr());
1416 WARN("Failed to open device \"%s\"\n", name
?name
:"(default)");
1421 if(name
) mDevice
->DeviceName
= std::string
{DevNameHead
} + name
;
1422 else mDevice
->DeviceName
= DevNameHead
+ get_device_name_and_guid(mMMDev
.get()).first
;
1427 void WasapiCapture::closeProxy()
1433 HRESULT
WasapiCapture::resetProxy()
1438 HRESULT hr
{mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
)};
1441 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
1444 mClient
= ComPtr
<IAudioClient
>{static_cast<IAudioClient
*>(ptr
)};
1446 // Make sure buffer is at least 100ms in size
1447 ReferenceTime buf_time
{ReferenceTime
{seconds
{mDevice
->BufferSize
}} / mDevice
->Frequency
};
1448 buf_time
= std::max(buf_time
, ReferenceTime
{milliseconds
{100}});
1450 WAVEFORMATEXTENSIBLE InputType
{};
1451 InputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
1452 switch(mDevice
->FmtChans
)
1455 InputType
.Format
.nChannels
= 1;
1456 InputType
.dwChannelMask
= MONO
;
1459 InputType
.Format
.nChannels
= 2;
1460 InputType
.dwChannelMask
= STEREO
;
1463 InputType
.Format
.nChannels
= 4;
1464 InputType
.dwChannelMask
= QUAD
;
1467 InputType
.Format
.nChannels
= 6;
1468 InputType
.dwChannelMask
= X5DOT1
;
1471 InputType
.Format
.nChannels
= 7;
1472 InputType
.dwChannelMask
= X6DOT1
;
1475 InputType
.Format
.nChannels
= 8;
1476 InputType
.dwChannelMask
= X7DOT1
;
1482 switch(mDevice
->FmtType
)
1484 /* NOTE: Signedness doesn't matter, the converter will handle it. */
1487 InputType
.Format
.wBitsPerSample
= 8;
1488 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1492 InputType
.Format
.wBitsPerSample
= 16;
1493 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1497 InputType
.Format
.wBitsPerSample
= 32;
1498 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1501 InputType
.Format
.wBitsPerSample
= 32;
1502 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
1505 InputType
.Samples
.wValidBitsPerSample
= InputType
.Format
.wBitsPerSample
;
1506 InputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
1508 InputType
.Format
.nBlockAlign
= static_cast<WORD
>(InputType
.Format
.nChannels
*
1509 InputType
.Format
.wBitsPerSample
/ 8);
1510 InputType
.Format
.nAvgBytesPerSec
= InputType
.Format
.nSamplesPerSec
*
1511 InputType
.Format
.nBlockAlign
;
1512 InputType
.Format
.cbSize
= sizeof(InputType
) - sizeof(InputType
.Format
);
1514 TraceFormat("Requesting capture format", &InputType
.Format
);
1516 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &InputType
.Format
, &wfx
);
1519 ERR("Failed to check format support: 0x%08lx\n", hr
);
1523 mSampleConv
= nullptr;
1528 TraceFormat("Got capture format", wfx
);
1529 if(!MakeExtensible(&InputType
, wfx
))
1537 auto validate_fmt
= [](DeviceBase
*device
, uint32_t chancount
, DWORD chanmask
) noexcept
1540 switch(device
->FmtChans
)
1542 /* If the device wants mono, we can handle any input. */
1545 /* If the device wants stereo, we can handle mono or stereo input. */
1547 return (chancount
== 2 && (chanmask
== 0 || (chanmask
&StereoMask
) == STEREO
))
1548 || (chancount
== 1 && (chanmask
&MonoMask
) == MONO
);
1549 /* Otherwise, the device must match the input type. */
1551 return (chancount
== 4 && (chanmask
== 0 || (chanmask
&QuadMask
) == QUAD
));
1552 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
1554 return (chancount
== 6 && (chanmask
== 0 || (chanmask
&X51Mask
) == X5DOT1
1555 || (chanmask
&X51RearMask
) == X5DOT1REAR
));
1557 return (chancount
== 7 && (chanmask
== 0 || (chanmask
&X61Mask
) == X6DOT1
));
1559 return (chancount
== 8 && (chanmask
== 0 || (chanmask
&X71Mask
) == X7DOT1
));
1561 return (chanmask
== 0 && chancount
== device
->channelsFromFmt());
1565 if(!validate_fmt(mDevice
, InputType
.Format
.nChannels
, InputType
.dwChannelMask
))
1567 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
1568 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1569 mDevice
->Frequency
, InputType
.dwChannelMask
, InputType
.Format
.nChannels
,
1570 (InputType
.Format
.nChannels
==1)?"":"s", InputType
.Format
.wBitsPerSample
,
1571 InputType
.Format
.nSamplesPerSec
);
1576 DevFmtType srcType
{};
1577 if(IsEqualGUID(InputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1579 if(InputType
.Format
.wBitsPerSample
== 8)
1580 srcType
= DevFmtUByte
;
1581 else if(InputType
.Format
.wBitsPerSample
== 16)
1582 srcType
= DevFmtShort
;
1583 else if(InputType
.Format
.wBitsPerSample
== 32)
1584 srcType
= DevFmtInt
;
1587 ERR("Unhandled integer bit depth: %d\n", InputType
.Format
.wBitsPerSample
);
1591 else if(IsEqualGUID(InputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1593 if(InputType
.Format
.wBitsPerSample
== 32)
1594 srcType
= DevFmtFloat
;
1597 ERR("Unhandled float bit depth: %d\n", InputType
.Format
.wBitsPerSample
);
1603 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{InputType
.SubFormat
}.c_str());
1607 if(mDevice
->FmtChans
== DevFmtMono
&& InputType
.Format
.nChannels
!= 1)
1609 uint chanmask
{(1u<<InputType
.Format
.nChannels
) - 1u};
1610 /* Exclude LFE from the downmix. */
1611 if((InputType
.dwChannelMask
&SPEAKER_LOW_FREQUENCY
))
1613 constexpr auto lfemask
= MaskFromTopBits(SPEAKER_LOW_FREQUENCY
);
1614 const int lfeidx
{al::popcount(InputType
.dwChannelMask
&lfemask
) - 1};
1615 chanmask
&= ~(1u << lfeidx
);
1618 mChannelConv
= ChannelConverter
{srcType
, InputType
.Format
.nChannels
, chanmask
,
1620 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType
));
1621 /* The channel converter always outputs float, so change the input type
1622 * for the resampler/type-converter.
1624 srcType
= DevFmtFloat
;
1626 else if(mDevice
->FmtChans
== DevFmtStereo
&& InputType
.Format
.nChannels
== 1)
1628 mChannelConv
= ChannelConverter
{srcType
, 1, 0x1, mDevice
->FmtChans
};
1629 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType
));
1630 srcType
= DevFmtFloat
;
1633 if(mDevice
->Frequency
!= InputType
.Format
.nSamplesPerSec
|| mDevice
->FmtType
!= srcType
)
1635 mSampleConv
= CreateSampleConverter(srcType
, mDevice
->FmtType
, mDevice
->channelsFromFmt(),
1636 InputType
.Format
.nSamplesPerSec
, mDevice
->Frequency
, Resampler::FastBSinc24
);
1639 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1640 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1641 mDevice
->Frequency
, DevFmtTypeString(srcType
), InputType
.Format
.nSamplesPerSec
);
1644 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1645 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1646 mDevice
->Frequency
, DevFmtTypeString(srcType
), InputType
.Format
.nSamplesPerSec
);
1649 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1650 buf_time
.count(), 0, &InputType
.Format
, nullptr);
1653 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1657 UINT32 buffer_len
{};
1658 ReferenceTime min_per
{};
1659 hr
= mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
1661 hr
= mClient
->GetBufferSize(&buffer_len
);
1664 ERR("Failed to get buffer size: 0x%08lx\n", hr
);
1667 mDevice
->UpdateSize
= RefTime2Samples(min_per
, mDevice
->Frequency
);
1668 mDevice
->BufferSize
= buffer_len
;
1670 mRing
= RingBuffer::Create(buffer_len
, mDevice
->frameSizeFromFmt(), false);
1672 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1675 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1683 void WasapiCapture::start()
1685 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
1687 throw al::backend_exception
{al::backend_error::DeviceError
,
1688 "Failed to start recording: 0x%lx", hr
};
1691 HRESULT
WasapiCapture::startProxy()
1693 ResetEvent(mNotifyEvent
);
1695 HRESULT hr
{mClient
->Start()};
1698 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1703 hr
= mClient
->GetService(IID_IAudioCaptureClient
, &ptr
);
1706 mCapture
= ComPtr
<IAudioCaptureClient
>{static_cast<IAudioCaptureClient
*>(ptr
)};
1708 mKillNow
.store(false, std::memory_order_release
);
1709 mThread
= std::thread
{std::mem_fn(&WasapiCapture::recordProc
), this};
1713 ERR("Failed to start thread\n");
1728 void WasapiCapture::stop()
1729 { pushMessage(MsgType::StopDevice
).wait(); }
1731 void WasapiCapture::stopProxy()
1733 if(!mCapture
|| !mThread
.joinable())
1736 mKillNow
.store(true, std::memory_order_release
);
1745 void WasapiCapture::captureSamples(al::byte
*buffer
, uint samples
)
1746 { mRing
->read(buffer
, samples
); }
1748 uint
WasapiCapture::availableSamples()
1749 { return static_cast<uint
>(mRing
->readSpace()); }
1754 bool WasapiBackendFactory::init()
1756 static HRESULT InitResult
{E_FAIL
};
1758 if(FAILED(InitResult
)) try
1760 std::promise
<HRESULT
> promise
;
1761 auto future
= promise
.get_future();
1763 std::thread
{&WasapiProxy::messageHandler
, &promise
}.detach();
1764 InitResult
= future
.get();
1769 return SUCCEEDED(InitResult
);
1772 bool WasapiBackendFactory::querySupport(BackendType type
)
1773 { return type
== BackendType::Playback
|| type
== BackendType::Capture
; }
1775 std::string
WasapiBackendFactory::probe(BackendType type
)
1777 std::string outnames
;
1780 case BackendType::Playback
:
1781 WasapiProxy::pushMessageStatic(MsgType::EnumeratePlayback
).wait();
1782 for(const DevMap
&entry
: PlaybackDevices
)
1784 /* +1 to also append the null char (to ensure a null-separated list
1785 * and double-null terminated list).
1787 outnames
.append(DevNameHead
).append(entry
.name
.c_str(), entry
.name
.length()+1);
1791 case BackendType::Capture
:
1792 WasapiProxy::pushMessageStatic(MsgType::EnumerateCapture
).wait();
1793 for(const DevMap
&entry
: CaptureDevices
)
1794 outnames
.append(DevNameHead
).append(entry
.name
.c_str(), entry
.name
.length()+1);
1801 BackendPtr
WasapiBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
1803 if(type
== BackendType::Playback
)
1804 return BackendPtr
{new WasapiPlayback
{device
}};
1805 if(type
== BackendType::Capture
)
1806 return BackendPtr
{new WasapiCapture
{device
}};
1810 BackendFactory
&WasapiBackendFactory::getFactory()
1812 static WasapiBackendFactory factory
{};