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
};
878 bool isRear51
{false};
880 if(!mDevice
->Flags
.test(FrequencyRequest
))
881 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
882 if(!mDevice
->Flags
.test(ChannelsRequest
))
884 const uint32_t chancount
{OutputType
.Format
.nChannels
};
885 const DWORD chanmask
{OutputType
.dwChannelMask
};
886 if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
887 mDevice
->FmtChans
= DevFmtX71
;
888 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
889 mDevice
->FmtChans
= DevFmtX61
;
890 else if(chancount
>= 6 && (chanmask
&X51Mask
) == X5DOT1
)
891 mDevice
->FmtChans
= DevFmtX51
;
892 else if(chancount
>= 6 && (chanmask
&X51RearMask
) == X5DOT1REAR
)
894 mDevice
->FmtChans
= DevFmtX51
;
897 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
898 mDevice
->FmtChans
= DevFmtQuad
;
899 else if(chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
)
900 mDevice
->FmtChans
= DevFmtStereo
;
901 else if(chancount
>= 1 && (chanmask
&MonoMask
) == MONO
)
902 mDevice
->FmtChans
= DevFmtMono
;
904 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount
, chanmask
);
908 const uint32_t chancount
{OutputType
.Format
.nChannels
};
909 const DWORD chanmask
{OutputType
.dwChannelMask
};
910 isRear51
= (chancount
>= 6 && (chanmask
&X51RearMask
) == X5DOT1REAR
);
913 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
914 switch(mDevice
->FmtChans
)
917 OutputType
.Format
.nChannels
= 1;
918 OutputType
.dwChannelMask
= MONO
;
921 mDevice
->FmtChans
= DevFmtStereo
;
924 OutputType
.Format
.nChannels
= 2;
925 OutputType
.dwChannelMask
= STEREO
;
928 OutputType
.Format
.nChannels
= 4;
929 OutputType
.dwChannelMask
= QUAD
;
932 OutputType
.Format
.nChannels
= 6;
933 OutputType
.dwChannelMask
= isRear51
? X5DOT1REAR
: X5DOT1
;
936 OutputType
.Format
.nChannels
= 7;
937 OutputType
.dwChannelMask
= X6DOT1
;
941 OutputType
.Format
.nChannels
= 8;
942 OutputType
.dwChannelMask
= X7DOT1
;
945 switch(mDevice
->FmtType
)
948 mDevice
->FmtType
= DevFmtUByte
;
951 OutputType
.Format
.wBitsPerSample
= 8;
952 OutputType
.Samples
.wValidBitsPerSample
= 8;
953 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
956 mDevice
->FmtType
= DevFmtShort
;
959 OutputType
.Format
.wBitsPerSample
= 16;
960 OutputType
.Samples
.wValidBitsPerSample
= 16;
961 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
964 mDevice
->FmtType
= DevFmtInt
;
967 OutputType
.Format
.wBitsPerSample
= 32;
968 OutputType
.Samples
.wValidBitsPerSample
= 32;
969 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
972 OutputType
.Format
.wBitsPerSample
= 32;
973 OutputType
.Samples
.wValidBitsPerSample
= 32;
974 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
977 OutputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
979 OutputType
.Format
.nBlockAlign
= static_cast<WORD
>(OutputType
.Format
.nChannels
*
980 OutputType
.Format
.wBitsPerSample
/ 8);
981 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
982 OutputType
.Format
.nBlockAlign
;
984 TraceFormat("Requesting playback format", &OutputType
.Format
);
985 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &OutputType
.Format
, &wfx
);
988 ERR("Failed to check format support: 0x%08lx\n", hr
);
989 hr
= mClient
->GetMixFormat(&wfx
);
993 ERR("Failed to find a supported format: 0x%08lx\n", hr
);
999 TraceFormat("Got playback format", wfx
);
1000 if(!MakeExtensible(&OutputType
, wfx
))
1008 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
1009 const uint32_t chancount
{OutputType
.Format
.nChannels
};
1010 const DWORD chanmask
{OutputType
.dwChannelMask
};
1011 /* Don't update the channel format if the requested format fits what's
1014 bool chansok
{false};
1015 if(mDevice
->Flags
.test(ChannelsRequest
))
1017 switch(mDevice
->FmtChans
)
1020 chansok
= (chancount
>= 1 && (chanmask
&MonoMask
) == MONO
);
1023 chansok
= (chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
);
1026 chansok
= (chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
);
1029 chansok
= (chancount
>= 6 && ((chanmask
&X51Mask
) == X5DOT1
1030 || (chanmask
&X51RearMask
) == X5DOT1REAR
));
1033 chansok
= (chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
);
1037 chansok
= (chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
);
1045 if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
1046 mDevice
->FmtChans
= DevFmtX71
;
1047 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
1048 mDevice
->FmtChans
= DevFmtX61
;
1049 else if(chancount
>= 6 && ((chanmask
&X51Mask
) == X5DOT1
1050 || (chanmask
&X51RearMask
) == X5DOT1REAR
))
1051 mDevice
->FmtChans
= DevFmtX51
;
1052 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
1053 mDevice
->FmtChans
= DevFmtQuad
;
1054 else if(chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
)
1055 mDevice
->FmtChans
= DevFmtStereo
;
1056 else if(chancount
>= 1 && (chanmask
&MonoMask
) == MONO
)
1057 mDevice
->FmtChans
= DevFmtMono
;
1060 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType
.Format
.nChannels
,
1061 OutputType
.dwChannelMask
);
1062 mDevice
->FmtChans
= DevFmtStereo
;
1063 OutputType
.Format
.nChannels
= 2;
1064 OutputType
.dwChannelMask
= STEREO
;
1068 if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1070 if(OutputType
.Format
.wBitsPerSample
== 8)
1071 mDevice
->FmtType
= DevFmtUByte
;
1072 else if(OutputType
.Format
.wBitsPerSample
== 16)
1073 mDevice
->FmtType
= DevFmtShort
;
1074 else if(OutputType
.Format
.wBitsPerSample
== 32)
1075 mDevice
->FmtType
= DevFmtInt
;
1078 mDevice
->FmtType
= DevFmtShort
;
1079 OutputType
.Format
.wBitsPerSample
= 16;
1082 else if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1084 mDevice
->FmtType
= DevFmtFloat
;
1085 OutputType
.Format
.wBitsPerSample
= 32;
1089 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{OutputType
.SubFormat
}.c_str());
1090 mDevice
->FmtType
= DevFmtShort
;
1091 if(OutputType
.Format
.wFormatTag
!= WAVE_FORMAT_EXTENSIBLE
)
1092 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_PCM
;
1093 OutputType
.Format
.wBitsPerSample
= 16;
1094 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1096 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1098 mFrameStep
= OutputType
.Format
.nChannels
;
1100 const EndpointFormFactor formfactor
{get_device_formfactor(mMMDev
.get())};
1101 mDevice
->Flags
.set(DirectEar
, (formfactor
== Headphones
|| formfactor
== Headset
));
1103 setDefaultWFXChannelOrder();
1105 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1106 buf_time
.count(), 0, &OutputType
.Format
, nullptr);
1109 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1113 UINT32 buffer_len
{};
1114 ReferenceTime min_per
{};
1115 hr
= mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
1117 hr
= mClient
->GetBufferSize(&buffer_len
);
1120 ERR("Failed to get audio buffer info: 0x%08lx\n", hr
);
1124 /* Find the nearest multiple of the period size to the update size */
1125 if(min_per
< per_time
)
1126 min_per
*= maxi64((per_time
+ min_per
/2) / min_per
, 1);
1127 mDevice
->UpdateSize
= minu(RefTime2Samples(min_per
, mDevice
->Frequency
), buffer_len
/2);
1128 mDevice
->BufferSize
= buffer_len
;
1130 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1133 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1141 void WasapiPlayback::start()
1143 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
1145 throw al::backend_exception
{al::backend_error::DeviceError
,
1146 "Failed to start playback: 0x%lx", hr
};
1149 HRESULT
WasapiPlayback::startProxy()
1151 ResetEvent(mNotifyEvent
);
1153 HRESULT hr
{mClient
->Start()};
1156 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1161 hr
= mClient
->GetService(IID_IAudioRenderClient
, &ptr
);
1164 mRender
= ComPtr
<IAudioRenderClient
>{static_cast<IAudioRenderClient
*>(ptr
)};
1166 mKillNow
.store(false, std::memory_order_release
);
1167 mThread
= std::thread
{std::mem_fn(&WasapiPlayback::mixerProc
), this};
1171 ERR("Failed to start thread\n");
1183 void WasapiPlayback::stop()
1184 { pushMessage(MsgType::StopDevice
).wait(); }
1186 void WasapiPlayback::stopProxy()
1188 if(!mRender
|| !mThread
.joinable())
1191 mKillNow
.store(true, std::memory_order_release
);
1199 ClockLatency
WasapiPlayback::getClockLatency()
1203 std::lock_guard
<std::mutex
> _
{mMutex
};
1204 ret
.ClockTime
= GetDeviceClockTime(mDevice
);
1205 ret
.Latency
= std::chrono::seconds
{mPadding
.load(std::memory_order_relaxed
)};
1206 ret
.Latency
/= mDevice
->Frequency
;
1212 struct WasapiCapture final
: public BackendBase
, WasapiProxy
{
1213 WasapiCapture(DeviceBase
*device
) noexcept
: BackendBase
{device
} { }
1214 ~WasapiCapture() override
;
1218 void open(const char *name
) override
;
1219 HRESULT
openProxy(const char *name
) override
;
1220 void closeProxy() override
;
1222 HRESULT
resetProxy() override
;
1223 void start() override
;
1224 HRESULT
startProxy() override
;
1225 void stop() override
;
1226 void stopProxy() override
;
1228 void captureSamples(al::byte
*buffer
, uint samples
) override
;
1229 uint
availableSamples() override
;
1231 HRESULT mOpenStatus
{E_FAIL
};
1232 ComPtr
<IMMDevice
> mMMDev
{nullptr};
1233 ComPtr
<IAudioClient
> mClient
{nullptr};
1234 ComPtr
<IAudioCaptureClient
> mCapture
{nullptr};
1235 HANDLE mNotifyEvent
{nullptr};
1237 ChannelConverter mChannelConv
{};
1238 SampleConverterPtr mSampleConv
;
1239 RingBufferPtr mRing
;
1241 std::atomic
<bool> mKillNow
{true};
1242 std::thread mThread
;
1244 DEF_NEWDEL(WasapiCapture
)
1247 WasapiCapture::~WasapiCapture()
1249 if(SUCCEEDED(mOpenStatus
))
1250 pushMessage(MsgType::CloseDevice
).wait();
1251 mOpenStatus
= E_FAIL
;
1253 if(mNotifyEvent
!= nullptr)
1254 CloseHandle(mNotifyEvent
);
1255 mNotifyEvent
= nullptr;
1259 FORCE_ALIGN
int WasapiCapture::recordProc()
1261 HRESULT hr
{CoInitializeEx(nullptr, COINIT_MULTITHREADED
)};
1264 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr
);
1265 mDevice
->handleDisconnect("COM init failed: 0x%08lx", hr
);
1269 althrd_setname(RECORD_THREAD_NAME
);
1271 al::vector
<float> samples
;
1272 while(!mKillNow
.load(std::memory_order_relaxed
))
1275 hr
= mCapture
->GetNextPacketSize(&avail
);
1277 ERR("Failed to get next packet size: 0x%08lx\n", hr
);
1284 hr
= mCapture
->GetBuffer(&rdata
, &numsamples
, &flags
, nullptr, nullptr);
1286 ERR("Failed to get capture buffer: 0x%08lx\n", hr
);
1289 if(mChannelConv
.is_active())
1291 samples
.resize(numsamples
*2);
1292 mChannelConv
.convert(rdata
, samples
.data(), numsamples
);
1293 rdata
= reinterpret_cast<BYTE
*>(samples
.data());
1296 auto data
= mRing
->getWriteVector();
1301 const void *srcdata
{rdata
};
1302 uint srcframes
{numsamples
};
1304 dstframes
= mSampleConv
->convert(&srcdata
, &srcframes
, data
.first
.buf
,
1305 static_cast<uint
>(minz(data
.first
.len
, INT_MAX
)));
1306 if(srcframes
> 0 && dstframes
== data
.first
.len
&& data
.second
.len
> 0)
1308 /* If some source samples remain, all of the first dest
1309 * block was filled, and there's space in the second
1310 * dest block, do another run for the second block.
1312 dstframes
+= mSampleConv
->convert(&srcdata
, &srcframes
, data
.second
.buf
,
1313 static_cast<uint
>(minz(data
.second
.len
, INT_MAX
)));
1318 const uint framesize
{mDevice
->frameSizeFromFmt()};
1319 size_t len1
{minz(data
.first
.len
, numsamples
)};
1320 size_t len2
{minz(data
.second
.len
, numsamples
-len1
)};
1322 memcpy(data
.first
.buf
, rdata
, len1
*framesize
);
1324 memcpy(data
.second
.buf
, rdata
+len1
*framesize
, len2
*framesize
);
1325 dstframes
= len1
+ len2
;
1328 mRing
->writeAdvance(dstframes
);
1330 hr
= mCapture
->ReleaseBuffer(numsamples
);
1331 if(FAILED(hr
)) ERR("Failed to release capture buffer: 0x%08lx\n", hr
);
1337 mDevice
->handleDisconnect("Failed to capture samples: 0x%08lx", hr
);
1341 DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
)};
1342 if(res
!= WAIT_OBJECT_0
)
1343 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
1351 void WasapiCapture::open(const char *name
)
1355 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1356 if(mNotifyEvent
== nullptr)
1358 ERR("Failed to create notify event: %lu\n", GetLastError());
1366 if(CaptureDevices
.empty())
1367 pushMessage(MsgType::EnumerateCapture
);
1368 if(std::strncmp(name
, DevNameHead
, DevNameHeadLen
) == 0)
1370 name
+= DevNameHeadLen
;
1375 hr
= pushMessage(MsgType::OpenDevice
, name
).get();
1380 throw al::backend_exception
{al::backend_error::DeviceError
, "Device init failed: 0x%08lx",
1383 hr
= pushMessage(MsgType::ResetDevice
).get();
1386 if(hr
== E_OUTOFMEMORY
)
1387 throw al::backend_exception
{al::backend_error::OutOfMemory
, "Out of memory"};
1388 throw al::backend_exception
{al::backend_error::DeviceError
, "Device reset failed"};
1392 HRESULT
WasapiCapture::openProxy(const char *name
)
1394 const wchar_t *devid
{nullptr};
1397 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1398 [name
](const DevMap
&entry
) -> bool
1399 { return entry
.name
== name
|| entry
.endpoint_guid
== name
; });
1400 if(iter
== CaptureDevices
.cend())
1402 const std::wstring wname
{utf8_to_wstr(name
)};
1403 iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1404 [&wname
](const DevMap
&entry
) -> bool
1405 { return entry
.devid
== wname
; });
1407 if(iter
== CaptureDevices
.cend())
1409 WARN("Failed to find device name matching \"%s\"\n", name
);
1412 name
= iter
->name
.c_str();
1413 devid
= iter
->devid
.c_str();
1417 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
1418 IID_IMMDeviceEnumerator
, &ptr
)};
1421 ComPtr
<IMMDeviceEnumerator
> enumerator
{static_cast<IMMDeviceEnumerator
*>(ptr
)};
1423 hr
= enumerator
->GetDefaultAudioEndpoint(eCapture
, eMultimedia
, mMMDev
.getPtr());
1425 hr
= enumerator
->GetDevice(devid
, mMMDev
.getPtr());
1429 WARN("Failed to open device \"%s\"\n", name
?name
:"(default)");
1434 if(name
) mDevice
->DeviceName
= std::string
{DevNameHead
} + name
;
1435 else mDevice
->DeviceName
= DevNameHead
+ get_device_name_and_guid(mMMDev
.get()).first
;
1440 void WasapiCapture::closeProxy()
1446 HRESULT
WasapiCapture::resetProxy()
1451 HRESULT hr
{mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
)};
1454 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
1457 mClient
= ComPtr
<IAudioClient
>{static_cast<IAudioClient
*>(ptr
)};
1459 // Make sure buffer is at least 100ms in size
1460 ReferenceTime buf_time
{ReferenceTime
{seconds
{mDevice
->BufferSize
}} / mDevice
->Frequency
};
1461 buf_time
= std::max(buf_time
, ReferenceTime
{milliseconds
{100}});
1463 WAVEFORMATEXTENSIBLE InputType
{};
1464 InputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
1465 switch(mDevice
->FmtChans
)
1468 InputType
.Format
.nChannels
= 1;
1469 InputType
.dwChannelMask
= MONO
;
1472 InputType
.Format
.nChannels
= 2;
1473 InputType
.dwChannelMask
= STEREO
;
1476 InputType
.Format
.nChannels
= 4;
1477 InputType
.dwChannelMask
= QUAD
;
1480 InputType
.Format
.nChannels
= 6;
1481 InputType
.dwChannelMask
= X5DOT1
;
1484 InputType
.Format
.nChannels
= 7;
1485 InputType
.dwChannelMask
= X6DOT1
;
1488 InputType
.Format
.nChannels
= 8;
1489 InputType
.dwChannelMask
= X7DOT1
;
1496 switch(mDevice
->FmtType
)
1498 /* NOTE: Signedness doesn't matter, the converter will handle it. */
1501 InputType
.Format
.wBitsPerSample
= 8;
1502 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1506 InputType
.Format
.wBitsPerSample
= 16;
1507 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1511 InputType
.Format
.wBitsPerSample
= 32;
1512 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1515 InputType
.Format
.wBitsPerSample
= 32;
1516 InputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
1519 InputType
.Samples
.wValidBitsPerSample
= InputType
.Format
.wBitsPerSample
;
1520 InputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
1522 InputType
.Format
.nBlockAlign
= static_cast<WORD
>(InputType
.Format
.nChannels
*
1523 InputType
.Format
.wBitsPerSample
/ 8);
1524 InputType
.Format
.nAvgBytesPerSec
= InputType
.Format
.nSamplesPerSec
*
1525 InputType
.Format
.nBlockAlign
;
1526 InputType
.Format
.cbSize
= sizeof(InputType
) - sizeof(InputType
.Format
);
1528 TraceFormat("Requesting capture format", &InputType
.Format
);
1529 WAVEFORMATEX
*wfx
{};
1530 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &InputType
.Format
, &wfx
);
1533 WARN("Failed to check format support: 0x%08lx\n", hr
);
1534 hr
= mClient
->GetMixFormat(&wfx
);
1538 ERR("Failed to check format support: 0x%08lx\n", hr
);
1542 mSampleConv
= nullptr;
1547 TraceFormat("Got capture format", wfx
);
1548 if(!MakeExtensible(&InputType
, wfx
))
1556 auto validate_fmt
= [](DeviceBase
*device
, uint32_t chancount
, DWORD chanmask
) noexcept
1559 switch(device
->FmtChans
)
1561 /* If the device wants mono, we can handle any input. */
1564 /* If the device wants stereo, we can handle mono or stereo input. */
1566 return (chancount
== 2 && (chanmask
== 0 || (chanmask
&StereoMask
) == STEREO
))
1567 || (chancount
== 1 && (chanmask
&MonoMask
) == MONO
);
1568 /* Otherwise, the device must match the input type. */
1570 return (chancount
== 4 && (chanmask
== 0 || (chanmask
&QuadMask
) == QUAD
));
1571 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
1573 return (chancount
== 6 && (chanmask
== 0 || (chanmask
&X51Mask
) == X5DOT1
1574 || (chanmask
&X51RearMask
) == X5DOT1REAR
));
1576 return (chancount
== 7 && (chanmask
== 0 || (chanmask
&X61Mask
) == X6DOT1
));
1579 return (chancount
== 8 && (chanmask
== 0 || (chanmask
&X71Mask
) == X7DOT1
));
1581 return (chanmask
== 0 && chancount
== device
->channelsFromFmt());
1585 if(!validate_fmt(mDevice
, InputType
.Format
.nChannels
, InputType
.dwChannelMask
))
1587 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
1588 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1589 mDevice
->Frequency
, InputType
.dwChannelMask
, InputType
.Format
.nChannels
,
1590 (InputType
.Format
.nChannels
==1)?"":"s", InputType
.Format
.wBitsPerSample
,
1591 InputType
.Format
.nSamplesPerSec
);
1596 DevFmtType srcType
{};
1597 if(IsEqualGUID(InputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1599 if(InputType
.Format
.wBitsPerSample
== 8)
1600 srcType
= DevFmtUByte
;
1601 else if(InputType
.Format
.wBitsPerSample
== 16)
1602 srcType
= DevFmtShort
;
1603 else if(InputType
.Format
.wBitsPerSample
== 32)
1604 srcType
= DevFmtInt
;
1607 ERR("Unhandled integer bit depth: %d\n", InputType
.Format
.wBitsPerSample
);
1611 else if(IsEqualGUID(InputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1613 if(InputType
.Format
.wBitsPerSample
== 32)
1614 srcType
= DevFmtFloat
;
1617 ERR("Unhandled float bit depth: %d\n", InputType
.Format
.wBitsPerSample
);
1623 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{InputType
.SubFormat
}.c_str());
1627 if(mDevice
->FmtChans
== DevFmtMono
&& InputType
.Format
.nChannels
!= 1)
1629 uint chanmask
{(1u<<InputType
.Format
.nChannels
) - 1u};
1630 /* Exclude LFE from the downmix. */
1631 if((InputType
.dwChannelMask
&SPEAKER_LOW_FREQUENCY
))
1633 constexpr auto lfemask
= MaskFromTopBits(SPEAKER_LOW_FREQUENCY
);
1634 const int lfeidx
{al::popcount(InputType
.dwChannelMask
&lfemask
) - 1};
1635 chanmask
&= ~(1u << lfeidx
);
1638 mChannelConv
= ChannelConverter
{srcType
, InputType
.Format
.nChannels
, chanmask
,
1640 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType
));
1641 /* The channel converter always outputs float, so change the input type
1642 * for the resampler/type-converter.
1644 srcType
= DevFmtFloat
;
1646 else if(mDevice
->FmtChans
== DevFmtStereo
&& InputType
.Format
.nChannels
== 1)
1648 mChannelConv
= ChannelConverter
{srcType
, 1, 0x1, mDevice
->FmtChans
};
1649 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType
));
1650 srcType
= DevFmtFloat
;
1653 if(mDevice
->Frequency
!= InputType
.Format
.nSamplesPerSec
|| mDevice
->FmtType
!= srcType
)
1655 mSampleConv
= CreateSampleConverter(srcType
, mDevice
->FmtType
, mDevice
->channelsFromFmt(),
1656 InputType
.Format
.nSamplesPerSec
, mDevice
->Frequency
, Resampler::FastBSinc24
);
1659 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1660 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1661 mDevice
->Frequency
, DevFmtTypeString(srcType
), InputType
.Format
.nSamplesPerSec
);
1664 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1665 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1666 mDevice
->Frequency
, DevFmtTypeString(srcType
), InputType
.Format
.nSamplesPerSec
);
1669 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1670 buf_time
.count(), 0, &InputType
.Format
, nullptr);
1673 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1677 UINT32 buffer_len
{};
1678 ReferenceTime min_per
{};
1679 hr
= mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
1681 hr
= mClient
->GetBufferSize(&buffer_len
);
1684 ERR("Failed to get buffer size: 0x%08lx\n", hr
);
1687 mDevice
->UpdateSize
= RefTime2Samples(min_per
, mDevice
->Frequency
);
1688 mDevice
->BufferSize
= buffer_len
;
1690 mRing
= RingBuffer::Create(buffer_len
, mDevice
->frameSizeFromFmt(), false);
1692 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1695 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1703 void WasapiCapture::start()
1705 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
1707 throw al::backend_exception
{al::backend_error::DeviceError
,
1708 "Failed to start recording: 0x%lx", hr
};
1711 HRESULT
WasapiCapture::startProxy()
1713 ResetEvent(mNotifyEvent
);
1715 HRESULT hr
{mClient
->Start()};
1718 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1723 hr
= mClient
->GetService(IID_IAudioCaptureClient
, &ptr
);
1726 mCapture
= ComPtr
<IAudioCaptureClient
>{static_cast<IAudioCaptureClient
*>(ptr
)};
1728 mKillNow
.store(false, std::memory_order_release
);
1729 mThread
= std::thread
{std::mem_fn(&WasapiCapture::recordProc
), this};
1733 ERR("Failed to start thread\n");
1748 void WasapiCapture::stop()
1749 { pushMessage(MsgType::StopDevice
).wait(); }
1751 void WasapiCapture::stopProxy()
1753 if(!mCapture
|| !mThread
.joinable())
1756 mKillNow
.store(true, std::memory_order_release
);
1765 void WasapiCapture::captureSamples(al::byte
*buffer
, uint samples
)
1766 { mRing
->read(buffer
, samples
); }
1768 uint
WasapiCapture::availableSamples()
1769 { return static_cast<uint
>(mRing
->readSpace()); }
1774 bool WasapiBackendFactory::init()
1776 static HRESULT InitResult
{E_FAIL
};
1778 if(FAILED(InitResult
)) try
1780 std::promise
<HRESULT
> promise
;
1781 auto future
= promise
.get_future();
1783 std::thread
{&WasapiProxy::messageHandler
, &promise
}.detach();
1784 InitResult
= future
.get();
1789 return SUCCEEDED(InitResult
);
1792 bool WasapiBackendFactory::querySupport(BackendType type
)
1793 { return type
== BackendType::Playback
|| type
== BackendType::Capture
; }
1795 std::string
WasapiBackendFactory::probe(BackendType type
)
1797 std::string outnames
;
1800 case BackendType::Playback
:
1801 WasapiProxy::pushMessageStatic(MsgType::EnumeratePlayback
).wait();
1802 for(const DevMap
&entry
: PlaybackDevices
)
1804 /* +1 to also append the null char (to ensure a null-separated list
1805 * and double-null terminated list).
1807 outnames
.append(DevNameHead
).append(entry
.name
.c_str(), entry
.name
.length()+1);
1811 case BackendType::Capture
:
1812 WasapiProxy::pushMessageStatic(MsgType::EnumerateCapture
).wait();
1813 for(const DevMap
&entry
: CaptureDevices
)
1814 outnames
.append(DevNameHead
).append(entry
.name
.c_str(), entry
.name
.length()+1);
1821 BackendPtr
WasapiBackendFactory::createBackend(DeviceBase
*device
, BackendType type
)
1823 if(type
== BackendType::Playback
)
1824 return BackendPtr
{new WasapiPlayback
{device
}};
1825 if(type
== BackendType::Capture
)
1826 return BackendPtr
{new WasapiCapture
{device
}};
1830 BackendFactory
&WasapiBackendFactory::getFactory()
1832 static WasapiBackendFactory factory
{};