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
23 #include "backends/wasapi.h"
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>
62 #include "converter.h"
64 #include "ringbuffer.h"
69 /* Some headers seem to define these as macros for __uuidof, which is annoying
70 * since some headers don't declare them at all. Hopefully the ifdef is enough
71 * to tell if they need to be declared.
73 #ifndef KSDATAFORMAT_SUBTYPE_PCM
74 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM
, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
76 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
77 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
80 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName
, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
81 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor
, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
82 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID
, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
87 using std::chrono::milliseconds
;
88 using std::chrono::seconds
;
90 using ReferenceTime
= std::chrono::duration
<REFERENCE_TIME
,std::ratio
<1,10000000>>;
92 inline constexpr ReferenceTime
operator "" _reftime(unsigned long long int n
) noexcept
93 { return ReferenceTime
{static_cast<REFERENCE_TIME
>(n
)}; }
96 #define MONO SPEAKER_FRONT_CENTER
97 #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
98 #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
99 #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
100 #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
101 #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
102 #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)
104 constexpr inline DWORD
MaskFromTopBits(DWORD b
) noexcept
113 constexpr DWORD MonoMask
{MaskFromTopBits(MONO
)};
114 constexpr DWORD StereoMask
{MaskFromTopBits(STEREO
)};
115 constexpr DWORD QuadMask
{MaskFromTopBits(QUAD
)};
116 constexpr DWORD X51Mask
{MaskFromTopBits(X5DOT1
)};
117 constexpr DWORD X51RearMask
{MaskFromTopBits(X5DOT1REAR
)};
118 constexpr DWORD X61Mask
{MaskFromTopBits(X6DOT1
)};
119 constexpr DWORD X71Mask
{MaskFromTopBits(X7DOT1
)};
121 #define DEVNAME_HEAD "OpenAL Soft on "
124 /* Scales the given reftime value, ceiling the result. */
125 inline ALuint
RefTime2Samples(const ReferenceTime
&val
, ALuint srate
)
127 const auto retval
= (val
*srate
+ (seconds
{1}-1_reftime
)) / seconds
{1};
128 return static_cast<ALuint
>(retval
);
136 GuidPrinter(const GUID
&guid
)
138 std::snprintf(mMsg
, al::size(mMsg
), "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}",
139 DWORD
{guid
.Data1
}, guid
.Data2
, guid
.Data3
, guid
.Data4
[0], guid
.Data4
[1], guid
.Data4
[2],
140 guid
.Data4
[3], guid
.Data4
[4], guid
.Data4
[5], guid
.Data4
[6], guid
.Data4
[7]);
142 const char *c_str() const { return mMsg
; }
149 PropVariant() { PropVariantInit(&mProp
); }
150 ~PropVariant() { clear(); }
152 void clear() { PropVariantClear(&mProp
); }
154 PROPVARIANT
* get() noexcept
{ return &mProp
; }
156 PROPVARIANT
& operator*() noexcept
{ return mProp
; }
157 const PROPVARIANT
& operator*() const noexcept
{ return mProp
; }
159 PROPVARIANT
* operator->() noexcept
{ return &mProp
; }
160 const PROPVARIANT
* operator->() const noexcept
{ return &mProp
; }
165 std::string endpoint_guid
; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
168 template<typename T0
, typename T1
, typename T2
>
169 DevMap(T0
&& name_
, T1
&& guid_
, T2
&& devid_
)
170 : name
{std::forward
<T0
>(name_
)}
171 , endpoint_guid
{std::forward
<T1
>(guid_
)}
172 , devid
{std::forward
<T2
>(devid_
)}
176 bool checkName(const al::vector
<DevMap
> &list
, const std::string
&name
)
178 return std::find_if(list
.cbegin(), list
.cend(),
179 [&name
](const DevMap
&entry
) -> bool
180 { return entry
.name
== name
; }
184 al::vector
<DevMap
> PlaybackDevices
;
185 al::vector
<DevMap
> CaptureDevices
;
188 using NameGUIDPair
= std::pair
<std::string
,std::string
>;
189 NameGUIDPair
get_device_name_and_guid(IMMDevice
*device
)
191 std::string name
{DEVNAME_HEAD
};
195 HRESULT hr
= device
->OpenPropertyStore(STGM_READ
, &ps
);
198 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
199 return { name
+"Unknown Device Name", "Unknown Device GUID" };
203 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(DEVPKEY_Device_FriendlyName
), pvprop
.get());
206 WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr
);
207 name
+= "Unknown Device Name";
209 else if(pvprop
->vt
== VT_LPWSTR
)
210 name
+= wstr_to_utf8(pvprop
->pwszVal
);
213 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop
->vt
);
214 name
+= "Unknown Device Name";
218 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(PKEY_AudioEndpoint_GUID
), pvprop
.get());
221 WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr
);
222 guid
= "Unknown Device GUID";
224 else if(pvprop
->vt
== VT_LPWSTR
)
225 guid
= wstr_to_utf8(pvprop
->pwszVal
);
228 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop
->vt
);
229 guid
= "Unknown Device GUID";
237 void get_device_formfactor(IMMDevice
*device
, EndpointFormFactor
*formfactor
)
240 HRESULT hr
= device
->OpenPropertyStore(STGM_READ
, &ps
);
243 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
248 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(PKEY_AudioEndpoint_FormFactor
), pvform
.get());
250 WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr
);
251 else if(pvform
->vt
== VT_UI4
)
252 *formfactor
= static_cast<EndpointFormFactor
>(pvform
->ulVal
);
253 else if(pvform
->vt
== VT_EMPTY
)
254 *formfactor
= UnknownFormFactor
;
256 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform
->vt
);
262 void add_device(IMMDevice
*device
, const WCHAR
*devid
, al::vector
<DevMap
> &list
)
264 std::string basename
, guidstr
;
265 std::tie(basename
, guidstr
) = get_device_name_and_guid(device
);
268 std::string newname
{basename
};
269 while(checkName(list
, newname
))
273 newname
+= std::to_string(++count
);
275 list
.emplace_back(std::move(newname
), std::move(guidstr
), devid
);
276 const DevMap
&newentry
= list
.back();
278 TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry
.name
.c_str(),
279 newentry
.endpoint_guid
.c_str(), newentry
.devid
.c_str());
282 WCHAR
*get_device_id(IMMDevice
*device
)
286 HRESULT hr
= device
->GetId(&devid
);
289 ERR("Failed to get device id: %lx\n", hr
);
296 void probe_devices(IMMDeviceEnumerator
*devenum
, EDataFlow flowdir
, al::vector
<DevMap
> &list
)
298 al::vector
<DevMap
>{}.swap(list
);
300 IMMDeviceCollection
*coll
;
301 HRESULT hr
{devenum
->EnumAudioEndpoints(flowdir
, DEVICE_STATE_ACTIVE
, &coll
)};
304 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr
);
308 IMMDevice
*defdev
{nullptr};
309 WCHAR
*defdevid
{nullptr};
311 hr
= coll
->GetCount(&count
);
312 if(SUCCEEDED(hr
) && count
> 0)
316 hr
= devenum
->GetDefaultAudioEndpoint(flowdir
, eMultimedia
, &defdev
);
318 if(SUCCEEDED(hr
) && defdev
!= nullptr)
320 defdevid
= get_device_id(defdev
);
322 add_device(defdev
, defdevid
, list
);
325 for(UINT i
{0};i
< count
;++i
)
328 hr
= coll
->Item(i
, &device
);
329 if(FAILED(hr
)) continue;
331 WCHAR
*devid
{get_device_id(device
)};
334 if(!defdevid
|| wcscmp(devid
, defdevid
) != 0)
335 add_device(device
, devid
, list
);
336 CoTaskMemFree(devid
);
341 if(defdev
) defdev
->Release();
342 if(defdevid
) CoTaskMemFree(defdevid
);
347 bool MakeExtensible(WAVEFORMATEXTENSIBLE
*out
, const WAVEFORMATEX
*in
)
349 *out
= WAVEFORMATEXTENSIBLE
{};
350 if(in
->wFormatTag
== WAVE_FORMAT_EXTENSIBLE
)
352 *out
= *CONTAINING_RECORD(in
, const WAVEFORMATEXTENSIBLE
, Format
);
353 out
->Format
.cbSize
= sizeof(*out
) - sizeof(out
->Format
);
355 else if(in
->wFormatTag
== WAVE_FORMAT_PCM
)
358 out
->Format
.cbSize
= 0;
359 out
->Samples
.wValidBitsPerSample
= out
->Format
.wBitsPerSample
;
360 if(out
->Format
.nChannels
== 1)
361 out
->dwChannelMask
= MONO
;
362 else if(out
->Format
.nChannels
== 2)
363 out
->dwChannelMask
= STEREO
;
365 ERR("Unhandled PCM channel count: %d\n", out
->Format
.nChannels
);
366 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
368 else if(in
->wFormatTag
== WAVE_FORMAT_IEEE_FLOAT
)
371 out
->Format
.cbSize
= 0;
372 out
->Samples
.wValidBitsPerSample
= out
->Format
.wBitsPerSample
;
373 if(out
->Format
.nChannels
== 1)
374 out
->dwChannelMask
= MONO
;
375 else if(out
->Format
.nChannels
== 2)
376 out
->dwChannelMask
= STEREO
;
378 ERR("Unhandled IEEE float channel count: %d\n", out
->Format
.nChannels
);
379 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
383 ERR("Unhandled format tag: 0x%04x\n", in
->wFormatTag
);
389 void TraceFormat(const char *msg
, const WAVEFORMATEX
*format
)
391 constexpr size_t fmtex_extra_size
{sizeof(WAVEFORMATEXTENSIBLE
)-sizeof(WAVEFORMATEX
)};
392 if(format
->wFormatTag
== WAVE_FORMAT_EXTENSIBLE
&& format
->cbSize
>= fmtex_extra_size
)
394 const WAVEFORMATEXTENSIBLE
*fmtex
{
395 CONTAINING_RECORD(format
, const WAVEFORMATEXTENSIBLE
, Format
)};
397 " FormatTag = 0x%04x\n"
399 " SamplesPerSec = %lu\n"
400 " AvgBytesPerSec = %lu\n"
402 " BitsPerSample = %d\n"
405 " ChannelMask = 0x%lx\n"
407 msg
, fmtex
->Format
.wFormatTag
, fmtex
->Format
.nChannels
, fmtex
->Format
.nSamplesPerSec
,
408 fmtex
->Format
.nAvgBytesPerSec
, fmtex
->Format
.nBlockAlign
, fmtex
->Format
.wBitsPerSample
,
409 fmtex
->Format
.cbSize
, fmtex
->Samples
.wReserved
, fmtex
->dwChannelMask
,
410 GuidPrinter
{fmtex
->SubFormat
}.c_str());
414 " FormatTag = 0x%04x\n"
416 " SamplesPerSec = %lu\n"
417 " AvgBytesPerSec = %lu\n"
419 " BitsPerSample = %d\n"
421 msg
, format
->wFormatTag
, format
->nChannels
, format
->nSamplesPerSec
,
422 format
->nAvgBytesPerSec
, format
->nBlockAlign
, format
->wBitsPerSample
, format
->cbSize
);
439 constexpr char MessageStr
[static_cast<size_t>(MsgType::Count
)][20]{
445 "Enumerate Playback",
451 /* Proxy interface used by the message handler. */
453 virtual ~WasapiProxy() = default;
455 virtual HRESULT
openProxy() = 0;
456 virtual void closeProxy() = 0;
458 virtual HRESULT
resetProxy() = 0;
459 virtual HRESULT
startProxy() = 0;
460 virtual void stopProxy() = 0;
465 std::promise
<HRESULT
> mPromise
;
467 static std::deque
<Msg
> mMsgQueue
;
468 static std::mutex mMsgQueueLock
;
469 static std::condition_variable mMsgQueueCond
;
471 std::future
<HRESULT
> pushMessage(MsgType type
)
473 std::promise
<HRESULT
> promise
;
474 std::future
<HRESULT
> future
{promise
.get_future()};
476 std::lock_guard
<std::mutex
> _
{mMsgQueueLock
};
477 mMsgQueue
.emplace_back(Msg
{type
, this, std::move(promise
)});
479 mMsgQueueCond
.notify_one();
483 static std::future
<HRESULT
> pushMessageStatic(MsgType type
)
485 std::promise
<HRESULT
> promise
;
486 std::future
<HRESULT
> future
{promise
.get_future()};
488 std::lock_guard
<std::mutex
> _
{mMsgQueueLock
};
489 mMsgQueue
.emplace_back(Msg
{type
, nullptr, std::move(promise
)});
491 mMsgQueueCond
.notify_one();
495 static bool popMessage(Msg
&msg
)
497 std::unique_lock
<std::mutex
> lock
{mMsgQueueLock
};
498 mMsgQueueCond
.wait(lock
, []{return !mMsgQueue
.empty();});
499 msg
= std::move(mMsgQueue
.front());
500 mMsgQueue
.pop_front();
501 return msg
.mType
!= MsgType::QuitThread
;
504 static int messageHandler(std::promise
<HRESULT
> *promise
);
506 std::deque
<WasapiProxy::Msg
> WasapiProxy::mMsgQueue
;
507 std::mutex
WasapiProxy::mMsgQueueLock
;
508 std::condition_variable
WasapiProxy::mMsgQueueCond
;
510 int WasapiProxy::messageHandler(std::promise
<HRESULT
> *promise
)
512 TRACE("Starting message thread\n");
514 HRESULT cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
517 WARN("Failed to initialize COM: 0x%08lx\n", cohr
);
518 promise
->set_value(cohr
);
523 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
524 IID_IMMDeviceEnumerator
, &ptr
)};
527 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr
);
528 promise
->set_value(hr
);
532 auto Enumerator
= static_cast<IMMDeviceEnumerator
*>(ptr
);
533 Enumerator
->Release();
534 Enumerator
= nullptr;
537 TRACE("Message thread initialization complete\n");
538 promise
->set_value(S_OK
);
541 TRACE("Starting message loop\n");
542 ALuint deviceCount
{0};
544 while(popMessage(msg
))
546 TRACE("Got message \"%s\" (0x%04x, this=%p)\n",
547 MessageStr
[static_cast<size_t>(msg
.mType
)], static_cast<int>(msg
.mType
),
548 decltype(std::declval
<void*>()){msg
.mProxy
});
552 case MsgType::OpenDevice
:
554 if(++deviceCount
== 1)
555 hr
= cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
557 hr
= msg
.mProxy
->openProxy();
558 msg
.mPromise
.set_value(hr
);
562 if(--deviceCount
== 0 && SUCCEEDED(cohr
))
567 case MsgType::ResetDevice
:
568 hr
= msg
.mProxy
->resetProxy();
569 msg
.mPromise
.set_value(hr
);
572 case MsgType::StartDevice
:
573 hr
= msg
.mProxy
->startProxy();
574 msg
.mPromise
.set_value(hr
);
577 case MsgType::StopDevice
:
578 msg
.mProxy
->stopProxy();
579 msg
.mPromise
.set_value(S_OK
);
582 case MsgType::CloseDevice
:
583 msg
.mProxy
->closeProxy();
584 msg
.mPromise
.set_value(S_OK
);
586 if(--deviceCount
== 0)
590 case MsgType::EnumeratePlayback
:
591 case MsgType::EnumerateCapture
:
593 if(++deviceCount
== 1)
594 hr
= cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
596 hr
= CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
, IID_IMMDeviceEnumerator
, &ptr
);
598 msg
.mPromise
.set_value(hr
);
601 Enumerator
= static_cast<IMMDeviceEnumerator
*>(ptr
);
603 if(msg
.mType
== MsgType::EnumeratePlayback
)
604 probe_devices(Enumerator
, eRender
, PlaybackDevices
);
605 else if(msg
.mType
== MsgType::EnumerateCapture
)
606 probe_devices(Enumerator
, eCapture
, CaptureDevices
);
607 msg
.mPromise
.set_value(S_OK
);
609 Enumerator
->Release();
610 Enumerator
= nullptr;
613 if(--deviceCount
== 0 && SUCCEEDED(cohr
))
618 ERR("Unexpected message: %u\n", static_cast<unsigned int>(msg
.mType
));
619 msg
.mPromise
.set_value(E_FAIL
);
623 TRACE("Message loop finished\n");
629 struct WasapiPlayback final
: public BackendBase
, WasapiProxy
{
630 WasapiPlayback(ALCdevice
*device
) noexcept
: BackendBase
{device
} { }
631 ~WasapiPlayback() override
;
635 void open(const ALCchar
*name
) override
;
636 HRESULT
openProxy() override
;
637 void closeProxy() override
;
639 bool reset() override
;
640 HRESULT
resetProxy() override
;
641 void start() override
;
642 HRESULT
startProxy() override
;
643 void stop() override
;
644 void stopProxy() override
;
646 ClockLatency
getClockLatency() override
;
650 HRESULT mOpenStatus
{E_FAIL
};
651 IMMDevice
*mMMDev
{nullptr};
652 IAudioClient
*mClient
{nullptr};
653 IAudioRenderClient
*mRender
{nullptr};
654 HANDLE mNotifyEvent
{nullptr};
656 UINT32 mFrameStep
{0u};
657 std::atomic
<UINT32
> mPadding
{0u};
661 std::atomic
<bool> mKillNow
{true};
664 DEF_NEWDEL(WasapiPlayback
)
667 WasapiPlayback::~WasapiPlayback()
669 if(SUCCEEDED(mOpenStatus
))
670 pushMessage(MsgType::CloseDevice
).wait();
671 mOpenStatus
= E_FAIL
;
673 if(mNotifyEvent
!= nullptr)
674 CloseHandle(mNotifyEvent
);
675 mNotifyEvent
= nullptr;
679 FORCE_ALIGN
int WasapiPlayback::mixerProc()
681 HRESULT hr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
684 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr
);
685 mDevice
->handleDisconnect("COM init failed: 0x%08lx", hr
);
690 althrd_setname(MIXER_THREAD_NAME
);
692 const ALuint update_size
{mDevice
->UpdateSize
};
693 const UINT32 buffer_len
{mDevice
->BufferSize
};
694 while(!mKillNow
.load(std::memory_order_relaxed
))
697 hr
= mClient
->GetCurrentPadding(&written
);
700 ERR("Failed to get padding: 0x%08lx\n", hr
);
701 mDevice
->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr
);
704 mPadding
.store(written
, std::memory_order_relaxed
);
706 ALuint len
{buffer_len
- written
};
707 if(len
< update_size
)
709 DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
)};
710 if(res
!= WAIT_OBJECT_0
)
711 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
716 hr
= mRender
->GetBuffer(len
, &buffer
);
720 std::lock_guard
<std::mutex
> _
{mMutex
};
721 mDevice
->renderSamples(buffer
, len
, mFrameStep
);
722 mPadding
.store(written
+ len
, std::memory_order_relaxed
);
724 hr
= mRender
->ReleaseBuffer(len
, 0);
728 ERR("Failed to buffer data: 0x%08lx\n", hr
);
729 mDevice
->handleDisconnect("Failed to send playback samples: 0x%08lx", hr
);
733 mPadding
.store(0u, std::memory_order_release
);
740 void WasapiPlayback::open(const ALCchar
*name
)
744 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
745 if(mNotifyEvent
== nullptr)
747 ERR("Failed to create notify events: %lu\n", GetLastError());
755 if(PlaybackDevices
.empty())
756 pushMessage(MsgType::EnumeratePlayback
).wait();
759 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
760 [name
](const DevMap
&entry
) -> bool
761 { return entry
.name
== name
|| entry
.endpoint_guid
== name
; }
763 if(iter
== PlaybackDevices
.cend())
765 std::wstring wname
{utf8_to_wstr(name
)};
766 iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
767 [&wname
](const DevMap
&entry
) -> bool
768 { return entry
.devid
== wname
; }
771 if(iter
== PlaybackDevices
.cend())
772 WARN("Failed to find device name matching \"%s\"\n", name
);
775 mDevId
= iter
->devid
;
776 mDevice
->DeviceName
= iter
->name
;
783 hr
= pushMessage(MsgType::OpenDevice
).get();
788 if(mNotifyEvent
!= nullptr)
789 CloseHandle(mNotifyEvent
);
790 mNotifyEvent
= nullptr;
794 throw al::backend_exception
{ALC_INVALID_VALUE
, "Device init failed: 0x%08lx", hr
};
798 HRESULT
WasapiPlayback::openProxy()
801 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
, IID_IMMDeviceEnumerator
, &ptr
)};
804 auto Enumerator
= static_cast<IMMDeviceEnumerator
*>(ptr
);
806 hr
= Enumerator
->GetDefaultAudioEndpoint(eRender
, eMultimedia
, &mMMDev
);
808 hr
= Enumerator
->GetDevice(mDevId
.c_str(), &mMMDev
);
809 Enumerator
->Release();
812 hr
= mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
);
815 mClient
= static_cast<IAudioClient
*>(ptr
);
816 if(mDevice
->DeviceName
.empty())
817 mDevice
->DeviceName
= get_device_name_and_guid(mMMDev
).first
;
830 void WasapiPlayback::closeProxy()
842 bool WasapiPlayback::reset()
844 HRESULT hr
{pushMessage(MsgType::ResetDevice
).get()};
846 throw al::backend_exception
{ALC_INVALID_VALUE
, "0x%08lx", hr
};
850 HRESULT
WasapiPlayback::resetProxy()
857 HRESULT hr
= mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
);
860 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
863 mClient
= static_cast<IAudioClient
*>(ptr
);
866 hr
= mClient
->GetMixFormat(&wfx
);
869 ERR("Failed to get mix format: 0x%08lx\n", hr
);
873 WAVEFORMATEXTENSIBLE OutputType
;
874 if(!MakeExtensible(&OutputType
, wfx
))
882 const ReferenceTime per_time
{ReferenceTime
{seconds
{mDevice
->UpdateSize
}} / mDevice
->Frequency
};
883 const ReferenceTime buf_time
{ReferenceTime
{seconds
{mDevice
->BufferSize
}} / mDevice
->Frequency
};
885 if(!mDevice
->Flags
.get
<FrequencyRequest
>())
886 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
887 if(!mDevice
->Flags
.get
<ChannelsRequest
>())
889 const uint32_t chancount
{OutputType
.Format
.nChannels
};
890 const DWORD chanmask
{OutputType
.dwChannelMask
};
891 if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
892 mDevice
->FmtChans
= DevFmtX71
;
893 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
894 mDevice
->FmtChans
= DevFmtX61
;
895 else if(chancount
>= 6 && (chanmask
&X51Mask
) == X5DOT1
)
896 mDevice
->FmtChans
= DevFmtX51
;
897 else if(chancount
>= 6 && (chanmask
&X51RearMask
) == X5DOT1REAR
)
898 mDevice
->FmtChans
= DevFmtX51Rear
;
899 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
900 mDevice
->FmtChans
= DevFmtQuad
;
901 else if(chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
)
902 mDevice
->FmtChans
= DevFmtStereo
;
903 else if(chancount
>= 1 && (chanmask
&MonoMask
) == MONO
)
904 mDevice
->FmtChans
= DevFmtMono
;
906 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount
, chanmask
);
909 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
910 switch(mDevice
->FmtChans
)
913 OutputType
.Format
.nChannels
= 1;
914 OutputType
.dwChannelMask
= MONO
;
917 mDevice
->FmtChans
= DevFmtStereo
;
920 OutputType
.Format
.nChannels
= 2;
921 OutputType
.dwChannelMask
= STEREO
;
924 OutputType
.Format
.nChannels
= 4;
925 OutputType
.dwChannelMask
= QUAD
;
928 OutputType
.Format
.nChannels
= 6;
929 OutputType
.dwChannelMask
= X5DOT1
;
932 OutputType
.Format
.nChannels
= 6;
933 OutputType
.dwChannelMask
= X5DOT1REAR
;
936 OutputType
.Format
.nChannels
= 7;
937 OutputType
.dwChannelMask
= X6DOT1
;
940 OutputType
.Format
.nChannels
= 8;
941 OutputType
.dwChannelMask
= X7DOT1
;
944 switch(mDevice
->FmtType
)
947 mDevice
->FmtType
= DevFmtUByte
;
950 OutputType
.Format
.wBitsPerSample
= 8;
951 OutputType
.Samples
.wValidBitsPerSample
= 8;
952 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
955 mDevice
->FmtType
= DevFmtShort
;
958 OutputType
.Format
.wBitsPerSample
= 16;
959 OutputType
.Samples
.wValidBitsPerSample
= 16;
960 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
963 mDevice
->FmtType
= DevFmtInt
;
966 OutputType
.Format
.wBitsPerSample
= 32;
967 OutputType
.Samples
.wValidBitsPerSample
= 32;
968 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
971 OutputType
.Format
.wBitsPerSample
= 32;
972 OutputType
.Samples
.wValidBitsPerSample
= 32;
973 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
976 OutputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
978 OutputType
.Format
.nBlockAlign
= static_cast<WORD
>(OutputType
.Format
.nChannels
*
979 OutputType
.Format
.wBitsPerSample
/ 8);
980 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
981 OutputType
.Format
.nBlockAlign
;
983 TraceFormat("Requesting playback format", &OutputType
.Format
);
984 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &OutputType
.Format
, &wfx
);
987 ERR("Failed to check format support: 0x%08lx\n", hr
);
988 hr
= mClient
->GetMixFormat(&wfx
);
992 ERR("Failed to find a supported format: 0x%08lx\n", hr
);
998 TraceFormat("Got playback format", wfx
);
999 if(!MakeExtensible(&OutputType
, wfx
))
1007 mDevice
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
1008 const uint32_t chancount
{OutputType
.Format
.nChannels
};
1009 const DWORD chanmask
{OutputType
.dwChannelMask
};
1010 if(chancount
>= 8 && (chanmask
&X71Mask
) == X7DOT1
)
1011 mDevice
->FmtChans
= DevFmtX71
;
1012 else if(chancount
>= 7 && (chanmask
&X61Mask
) == X6DOT1
)
1013 mDevice
->FmtChans
= DevFmtX61
;
1014 else if(chancount
>= 6 && (chanmask
&X51Mask
) == X5DOT1
)
1015 mDevice
->FmtChans
= DevFmtX51
;
1016 else if(chancount
>= 6 && (chanmask
&X51RearMask
) == X5DOT1REAR
)
1017 mDevice
->FmtChans
= DevFmtX51Rear
;
1018 else if(chancount
>= 4 && (chanmask
&QuadMask
) == QUAD
)
1019 mDevice
->FmtChans
= DevFmtQuad
;
1020 else if(chancount
>= 2 && (chanmask
&StereoMask
) == STEREO
)
1021 mDevice
->FmtChans
= DevFmtStereo
;
1022 else if(chancount
>= 1 && (chanmask
&MonoMask
) == MONO
)
1023 mDevice
->FmtChans
= DevFmtMono
;
1026 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType
.Format
.nChannels
,
1027 OutputType
.dwChannelMask
);
1028 mDevice
->FmtChans
= DevFmtStereo
;
1029 OutputType
.Format
.nChannels
= 2;
1030 OutputType
.dwChannelMask
= STEREO
;
1033 if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1035 if(OutputType
.Format
.wBitsPerSample
== 8)
1036 mDevice
->FmtType
= DevFmtUByte
;
1037 else if(OutputType
.Format
.wBitsPerSample
== 16)
1038 mDevice
->FmtType
= DevFmtShort
;
1039 else if(OutputType
.Format
.wBitsPerSample
== 32)
1040 mDevice
->FmtType
= DevFmtInt
;
1043 mDevice
->FmtType
= DevFmtShort
;
1044 OutputType
.Format
.wBitsPerSample
= 16;
1047 else if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1049 mDevice
->FmtType
= DevFmtFloat
;
1050 OutputType
.Format
.wBitsPerSample
= 32;
1054 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{OutputType
.SubFormat
}.c_str());
1055 mDevice
->FmtType
= DevFmtShort
;
1056 if(OutputType
.Format
.wFormatTag
!= WAVE_FORMAT_EXTENSIBLE
)
1057 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_PCM
;
1058 OutputType
.Format
.wBitsPerSample
= 16;
1059 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1061 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1063 mFrameStep
= OutputType
.Format
.nChannels
;
1065 EndpointFormFactor formfactor
{UnknownFormFactor
};
1066 get_device_formfactor(mMMDev
, &formfactor
);
1067 mDevice
->IsHeadphones
= (mDevice
->FmtChans
== DevFmtStereo
1068 && (formfactor
== Headphones
|| formfactor
== Headset
));
1070 setChannelOrderFromWFXMask(OutputType
.dwChannelMask
);
1072 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1073 buf_time
.count(), 0, &OutputType
.Format
, nullptr);
1076 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1080 UINT32 buffer_len
{};
1081 ReferenceTime min_per
{};
1082 hr
= mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
1084 hr
= mClient
->GetBufferSize(&buffer_len
);
1087 ERR("Failed to get audio buffer info: 0x%08lx\n", hr
);
1091 /* Find the nearest multiple of the period size to the update size */
1092 if(min_per
< per_time
)
1093 min_per
*= maxi64((per_time
+ min_per
/2) / min_per
, 1);
1094 mDevice
->UpdateSize
= minu(RefTime2Samples(min_per
, mDevice
->Frequency
), buffer_len
/2);
1095 mDevice
->BufferSize
= buffer_len
;
1097 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1100 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1108 void WasapiPlayback::start()
1110 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
1112 throw al::backend_exception
{ALC_INVALID_DEVICE
, "Failed to start playback: 0x%lx", hr
};
1115 HRESULT
WasapiPlayback::startProxy()
1117 ResetEvent(mNotifyEvent
);
1119 HRESULT hr
= mClient
->Start();
1122 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1127 hr
= mClient
->GetService(IID_IAudioRenderClient
, &ptr
);
1130 mRender
= static_cast<IAudioRenderClient
*>(ptr
);
1132 mKillNow
.store(false, std::memory_order_release
);
1133 mThread
= std::thread
{std::mem_fn(&WasapiPlayback::mixerProc
), this};
1138 ERR("Failed to start thread\n");
1150 void WasapiPlayback::stop()
1151 { pushMessage(MsgType::StopDevice
).wait(); }
1153 void WasapiPlayback::stopProxy()
1155 if(!mRender
|| !mThread
.joinable())
1158 mKillNow
.store(true, std::memory_order_release
);
1167 ClockLatency
WasapiPlayback::getClockLatency()
1171 std::lock_guard
<std::mutex
> _
{mMutex
};
1172 ret
.ClockTime
= GetDeviceClockTime(mDevice
);
1173 ret
.Latency
= std::chrono::seconds
{mPadding
.load(std::memory_order_relaxed
)};
1174 ret
.Latency
/= mDevice
->Frequency
;
1180 struct WasapiCapture final
: public BackendBase
, WasapiProxy
{
1181 WasapiCapture(ALCdevice
*device
) noexcept
: BackendBase
{device
} { }
1182 ~WasapiCapture() override
;
1186 void open(const ALCchar
*name
) override
;
1187 HRESULT
openProxy() override
;
1188 void closeProxy() override
;
1190 HRESULT
resetProxy() override
;
1191 void start() override
;
1192 HRESULT
startProxy() override
;
1193 void stop() override
;
1194 void stopProxy() override
;
1196 ALCenum
captureSamples(al::byte
*buffer
, ALCuint samples
) override
;
1197 ALCuint
availableSamples() override
;
1199 std::wstring mDevId
;
1201 HRESULT mOpenStatus
{E_FAIL
};
1202 IMMDevice
*mMMDev
{nullptr};
1203 IAudioClient
*mClient
{nullptr};
1204 IAudioCaptureClient
*mCapture
{nullptr};
1205 HANDLE mNotifyEvent
{nullptr};
1207 ChannelConverter mChannelConv
{};
1208 SampleConverterPtr mSampleConv
;
1209 RingBufferPtr mRing
;
1211 std::atomic
<bool> mKillNow
{true};
1212 std::thread mThread
;
1214 DEF_NEWDEL(WasapiCapture
)
1217 WasapiCapture::~WasapiCapture()
1219 if(SUCCEEDED(mOpenStatus
))
1220 pushMessage(MsgType::CloseDevice
).wait();
1221 mOpenStatus
= E_FAIL
;
1223 if(mNotifyEvent
!= nullptr)
1224 CloseHandle(mNotifyEvent
);
1225 mNotifyEvent
= nullptr;
1229 FORCE_ALIGN
int WasapiCapture::recordProc()
1231 HRESULT hr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
1234 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr
);
1235 mDevice
->handleDisconnect("COM init failed: 0x%08lx", hr
);
1239 althrd_setname(RECORD_THREAD_NAME
);
1241 al::vector
<float> samples
;
1242 while(!mKillNow
.load(std::memory_order_relaxed
))
1245 hr
= mCapture
->GetNextPacketSize(&avail
);
1247 ERR("Failed to get next packet size: 0x%08lx\n", hr
);
1254 hr
= mCapture
->GetBuffer(&rdata
, &numsamples
, &flags
, nullptr, nullptr);
1256 ERR("Failed to get capture buffer: 0x%08lx\n", hr
);
1259 if(mChannelConv
.is_active())
1261 samples
.resize(numsamples
*2);
1262 mChannelConv
.convert(rdata
, samples
.data(), numsamples
);
1263 rdata
= reinterpret_cast<BYTE
*>(samples
.data());
1266 auto data
= mRing
->getWriteVector();
1271 const void *srcdata
{rdata
};
1272 ALuint srcframes
{numsamples
};
1274 dstframes
= mSampleConv
->convert(&srcdata
, &srcframes
, data
.first
.buf
,
1275 static_cast<ALuint
>(minz(data
.first
.len
, INT_MAX
)));
1276 if(srcframes
> 0 && dstframes
== data
.first
.len
&& data
.second
.len
> 0)
1278 /* If some source samples remain, all of the first dest
1279 * block was filled, and there's space in the second
1280 * dest block, do another run for the second block.
1282 dstframes
+= mSampleConv
->convert(&srcdata
, &srcframes
, data
.second
.buf
,
1283 static_cast<ALuint
>(minz(data
.second
.len
, INT_MAX
)));
1288 const auto framesize
= static_cast<ALuint
>(mDevice
->frameSizeFromFmt());
1289 size_t len1
{minz(data
.first
.len
, numsamples
)};
1290 size_t len2
{minz(data
.second
.len
, numsamples
-len1
)};
1292 memcpy(data
.first
.buf
, rdata
, len1
*framesize
);
1294 memcpy(data
.second
.buf
, rdata
+len1
*framesize
, len2
*framesize
);
1295 dstframes
= len1
+ len2
;
1298 mRing
->writeAdvance(dstframes
);
1300 hr
= mCapture
->ReleaseBuffer(numsamples
);
1301 if(FAILED(hr
)) ERR("Failed to release capture buffer: 0x%08lx\n", hr
);
1307 mDevice
->handleDisconnect("Failed to capture samples: 0x%08lx", hr
);
1311 DWORD res
{WaitForSingleObjectEx(mNotifyEvent
, 2000, FALSE
)};
1312 if(res
!= WAIT_OBJECT_0
)
1313 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
1321 void WasapiCapture::open(const ALCchar
*name
)
1325 mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1326 if(mNotifyEvent
== nullptr)
1328 ERR("Failed to create notify event: %lu\n", GetLastError());
1336 if(CaptureDevices
.empty())
1337 pushMessage(MsgType::EnumerateCapture
).wait();
1340 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1341 [name
](const DevMap
&entry
) -> bool
1342 { return entry
.name
== name
|| entry
.endpoint_guid
== name
; }
1344 if(iter
== CaptureDevices
.cend())
1346 std::wstring wname
{utf8_to_wstr(name
)};
1347 iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1348 [&wname
](const DevMap
&entry
) -> bool
1349 { return entry
.devid
== wname
; }
1352 if(iter
== CaptureDevices
.cend())
1353 WARN("Failed to find device name matching \"%s\"\n", name
);
1356 mDevId
= iter
->devid
;
1357 mDevice
->DeviceName
= iter
->name
;
1364 hr
= pushMessage(MsgType::OpenDevice
).get();
1369 if(mNotifyEvent
!= nullptr)
1370 CloseHandle(mNotifyEvent
);
1371 mNotifyEvent
= nullptr;
1375 throw al::backend_exception
{ALC_INVALID_VALUE
, "Device init failed: 0x%08lx", hr
};
1378 hr
= pushMessage(MsgType::ResetDevice
).get();
1381 if(hr
== E_OUTOFMEMORY
)
1382 throw al::backend_exception
{ALC_OUT_OF_MEMORY
, "Out of memory"};
1383 throw al::backend_exception
{ALC_INVALID_VALUE
, "Device reset failed"};
1387 HRESULT
WasapiCapture::openProxy()
1390 HRESULT hr
{CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
1391 IID_IMMDeviceEnumerator
, &ptr
)};
1394 auto Enumerator
= static_cast<IMMDeviceEnumerator
*>(ptr
);
1396 hr
= Enumerator
->GetDefaultAudioEndpoint(eCapture
, eMultimedia
, &mMMDev
);
1398 hr
= Enumerator
->GetDevice(mDevId
.c_str(), &mMMDev
);
1399 Enumerator
->Release();
1402 hr
= mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
);
1405 mClient
= static_cast<IAudioClient
*>(ptr
);
1406 if(mDevice
->DeviceName
.empty())
1407 mDevice
->DeviceName
= get_device_name_and_guid(mMMDev
).first
;
1420 void WasapiCapture::closeProxy()
1431 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
= 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 OutputType
{};
1451 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
1452 switch(mDevice
->FmtChans
)
1455 OutputType
.Format
.nChannels
= 1;
1456 OutputType
.dwChannelMask
= MONO
;
1459 OutputType
.Format
.nChannels
= 2;
1460 OutputType
.dwChannelMask
= STEREO
;
1463 OutputType
.Format
.nChannels
= 4;
1464 OutputType
.dwChannelMask
= QUAD
;
1467 OutputType
.Format
.nChannels
= 6;
1468 OutputType
.dwChannelMask
= X5DOT1
;
1471 OutputType
.Format
.nChannels
= 6;
1472 OutputType
.dwChannelMask
= X5DOT1REAR
;
1475 OutputType
.Format
.nChannels
= 7;
1476 OutputType
.dwChannelMask
= X6DOT1
;
1479 OutputType
.Format
.nChannels
= 8;
1480 OutputType
.dwChannelMask
= X7DOT1
;
1486 switch(mDevice
->FmtType
)
1488 /* NOTE: Signedness doesn't matter, the converter will handle it. */
1491 OutputType
.Format
.wBitsPerSample
= 8;
1492 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1496 OutputType
.Format
.wBitsPerSample
= 16;
1497 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1501 OutputType
.Format
.wBitsPerSample
= 32;
1502 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1505 OutputType
.Format
.wBitsPerSample
= 32;
1506 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
1509 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1510 OutputType
.Format
.nSamplesPerSec
= mDevice
->Frequency
;
1512 OutputType
.Format
.nBlockAlign
= static_cast<WORD
>(OutputType
.Format
.nChannels
*
1513 OutputType
.Format
.wBitsPerSample
/ 8);
1514 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
1515 OutputType
.Format
.nBlockAlign
;
1516 OutputType
.Format
.cbSize
= sizeof(OutputType
) - sizeof(OutputType
.Format
);
1518 TraceFormat("Requesting capture format", &OutputType
.Format
);
1520 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &OutputType
.Format
, &wfx
);
1523 ERR("Failed to check format support: 0x%08lx\n", hr
);
1527 mSampleConv
= nullptr;
1532 TraceFormat("Got capture format", wfx
);
1533 if(!(wfx
->nChannels
== OutputType
.Format
.nChannels
||
1534 (wfx
->nChannels
== 1 && OutputType
.Format
.nChannels
== 2) ||
1535 (wfx
->nChannels
== 2 && OutputType
.Format
.nChannels
== 1)))
1537 ERR("Failed to get matching format, wanted: %s %s %uhz, got: %d channel%s %d-bit %luhz\n",
1538 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1539 mDevice
->Frequency
, wfx
->nChannels
, (wfx
->nChannels
==1)?"":"s", wfx
->wBitsPerSample
,
1540 wfx
->nSamplesPerSec
);
1545 if(!MakeExtensible(&OutputType
, wfx
))
1555 if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1557 if(OutputType
.Format
.wBitsPerSample
== 8)
1558 srcType
= DevFmtUByte
;
1559 else if(OutputType
.Format
.wBitsPerSample
== 16)
1560 srcType
= DevFmtShort
;
1561 else if(OutputType
.Format
.wBitsPerSample
== 32)
1562 srcType
= DevFmtInt
;
1565 ERR("Unhandled integer bit depth: %d\n", OutputType
.Format
.wBitsPerSample
);
1569 else if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1571 if(OutputType
.Format
.wBitsPerSample
== 32)
1572 srcType
= DevFmtFloat
;
1575 ERR("Unhandled float bit depth: %d\n", OutputType
.Format
.wBitsPerSample
);
1581 ERR("Unhandled format sub-type: %s\n", GuidPrinter
{OutputType
.SubFormat
}.c_str());
1585 if(mDevice
->FmtChans
== DevFmtMono
&& OutputType
.Format
.nChannels
== 2)
1587 mChannelConv
= ChannelConverter
{srcType
, DevFmtStereo
, mDevice
->FmtChans
};
1588 TRACE("Created %s stereo-to-mono converter\n", DevFmtTypeString(srcType
));
1589 /* The channel converter always outputs float, so change the input type
1590 * for the resampler/type-converter.
1592 srcType
= DevFmtFloat
;
1594 else if(mDevice
->FmtChans
== DevFmtStereo
&& OutputType
.Format
.nChannels
== 1)
1596 mChannelConv
= ChannelConverter
{srcType
, DevFmtMono
, mDevice
->FmtChans
};
1597 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType
));
1598 srcType
= DevFmtFloat
;
1601 if(mDevice
->Frequency
!= OutputType
.Format
.nSamplesPerSec
|| mDevice
->FmtType
!= srcType
)
1603 mSampleConv
= CreateSampleConverter(srcType
, mDevice
->FmtType
, mDevice
->channelsFromFmt(),
1604 OutputType
.Format
.nSamplesPerSec
, mDevice
->Frequency
, Resampler::FastBSinc24
);
1607 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1608 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1609 mDevice
->Frequency
, DevFmtTypeString(srcType
), OutputType
.Format
.nSamplesPerSec
);
1612 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1613 DevFmtChannelsString(mDevice
->FmtChans
), DevFmtTypeString(mDevice
->FmtType
),
1614 mDevice
->Frequency
, DevFmtTypeString(srcType
), OutputType
.Format
.nSamplesPerSec
);
1617 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1618 buf_time
.count(), 0, &OutputType
.Format
, nullptr);
1621 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1625 UINT32 buffer_len
{};
1626 ReferenceTime min_per
{};
1627 hr
= mClient
->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME
&>(min_per
), nullptr);
1629 hr
= mClient
->GetBufferSize(&buffer_len
);
1632 ERR("Failed to get buffer size: 0x%08lx\n", hr
);
1635 mDevice
->UpdateSize
= RefTime2Samples(min_per
, mDevice
->Frequency
);
1636 mDevice
->BufferSize
= buffer_len
;
1638 mRing
= RingBuffer::Create(buffer_len
, mDevice
->frameSizeFromFmt(), false);
1640 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1643 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1651 void WasapiCapture::start()
1653 const HRESULT hr
{pushMessage(MsgType::StartDevice
).get()};
1655 throw al::backend_exception
{ALC_INVALID_DEVICE
, "Failed to start recording: 0x%lx", hr
};
1658 HRESULT
WasapiCapture::startProxy()
1660 ResetEvent(mNotifyEvent
);
1662 HRESULT hr
{mClient
->Start()};
1665 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1670 hr
= mClient
->GetService(IID_IAudioCaptureClient
, &ptr
);
1673 mCapture
= static_cast<IAudioCaptureClient
*>(ptr
);
1675 mKillNow
.store(false, std::memory_order_release
);
1676 mThread
= std::thread
{std::mem_fn(&WasapiCapture::recordProc
), this};
1679 mCapture
->Release();
1681 ERR("Failed to start thread\n");
1696 void WasapiCapture::stop()
1697 { pushMessage(MsgType::StopDevice
).wait(); }
1699 void WasapiCapture::stopProxy()
1701 if(!mCapture
|| !mThread
.joinable())
1704 mKillNow
.store(true, std::memory_order_release
);
1707 mCapture
->Release();
1714 ALCuint
WasapiCapture::availableSamples()
1715 { return static_cast<ALCuint
>(mRing
->readSpace()); }
1717 ALCenum
WasapiCapture::captureSamples(al::byte
*buffer
, ALCuint samples
)
1719 mRing
->read(buffer
, samples
);
1720 return ALC_NO_ERROR
;
1726 bool WasapiBackendFactory::init()
1728 static HRESULT InitResult
{E_FAIL
};
1730 if(FAILED(InitResult
)) try
1732 std::promise
<HRESULT
> promise
;
1733 auto future
= promise
.get_future();
1735 std::thread
{&WasapiProxy::messageHandler
, &promise
}.detach();
1736 InitResult
= future
.get();
1741 return SUCCEEDED(InitResult
) ? ALC_TRUE
: ALC_FALSE
;
1744 bool WasapiBackendFactory::querySupport(BackendType type
)
1745 { return type
== BackendType::Playback
|| type
== BackendType::Capture
; }
1747 std::string
WasapiBackendFactory::probe(BackendType type
)
1749 std::string outnames
;
1750 auto add_device
= [&outnames
](const DevMap
&entry
) -> void
1752 /* +1 to also append the null char (to ensure a null-separated list and
1753 * double-null terminated list).
1755 outnames
.append(entry
.name
.c_str(), entry
.name
.length()+1);
1760 case BackendType::Playback
:
1761 WasapiProxy::pushMessageStatic(MsgType::EnumeratePlayback
).wait();
1762 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
1765 case BackendType::Capture
:
1766 WasapiProxy::pushMessageStatic(MsgType::EnumerateCapture
).wait();
1767 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
1774 BackendPtr
WasapiBackendFactory::createBackend(ALCdevice
*device
, BackendType type
)
1776 if(type
== BackendType::Playback
)
1777 return BackendPtr
{new WasapiPlayback
{device
}};
1778 if(type
== BackendType::Capture
)
1779 return BackendPtr
{new WasapiCapture
{device
}};
1783 BackendFactory
&WasapiBackendFactory::getFactory()
1785 static WasapiBackendFactory factory
{};