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"
30 #include <mmdeviceapi.h>
31 #include <audioclient.h>
33 #include <devpropdef.h>
38 #ifndef _WAVEFORMATEXTENSIBLE_
51 #include "ringbuffer.h"
53 #include "converter.h"
56 /* Some headers seem to define these as macros for __uuidof, which is annoying
57 * since some headers don't declare them at all. Hopefully the ifdef is enough
58 * to tell if they need to be declared.
60 #ifndef KSDATAFORMAT_SUBTYPE_PCM
61 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_PCM
, 0x00000001, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
63 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
64 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
67 DEFINE_DEVPROPKEY(DEVPKEY_Device_FriendlyName
, 0xa45c254e, 0xdf1c, 0x4efd, 0x80,0x20, 0x67,0xd1,0x46,0xa8,0x50,0xe0, 14);
68 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_FormFactor
, 0x1da5d803, 0xd492, 0x4edd, 0x8c,0x23, 0xe0,0xc0,0xff,0xee,0x7f,0x0e, 0);
69 DEFINE_PROPERTYKEY(PKEY_AudioEndpoint_GUID
, 0x1da5d803, 0xd492, 0x4edd, 0x8c, 0x23,0xe0, 0xc0,0xff,0xee,0x7f,0x0e, 4 );
74 #define MONO SPEAKER_FRONT_CENTER
75 #define STEREO (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT)
76 #define QUAD (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
77 #define X5DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
78 #define X5DOT1REAR (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT)
79 #define X6DOT1 (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_CENTER|SPEAKER_SIDE_LEFT|SPEAKER_SIDE_RIGHT)
80 #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)
81 #define X7DOT1_WIDE (SPEAKER_FRONT_LEFT|SPEAKER_FRONT_RIGHT|SPEAKER_FRONT_CENTER|SPEAKER_LOW_FREQUENCY|SPEAKER_BACK_LEFT|SPEAKER_BACK_RIGHT|SPEAKER_FRONT_LEFT_OF_CENTER|SPEAKER_FRONT_RIGHT_OF_CENTER)
83 #define REFTIME_PER_SEC ((REFERENCE_TIME)10000000)
85 #define DEVNAME_HEAD "OpenAL Soft on "
88 /* Scales the given value using 64-bit integer math, ceiling the result. */
89 inline ALint64
ScaleCeil(ALint64 val
, ALint64 new_scale
, ALint64 old_scale
)
91 return (val
*new_scale
+ old_scale
-1) / old_scale
;
99 PropVariant() { PropVariantInit(&mProp
); }
100 ~PropVariant() { clear(); }
102 void clear() { PropVariantClear(&mProp
); }
104 PROPVARIANT
* get() noexcept
{ return &mProp
; }
106 PROPVARIANT
& operator*() noexcept
{ return mProp
; }
107 const PROPVARIANT
& operator*() const noexcept
{ return mProp
; }
109 PROPVARIANT
* operator->() noexcept
{ return &mProp
; }
110 const PROPVARIANT
* operator->() const noexcept
{ return &mProp
; }
115 std::string endpoint_guid
; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
118 template<typename T0
, typename T1
, typename T2
>
119 DevMap(T0
&& name_
, T1
&& guid_
, T2
&& devid_
)
120 : name
{std::forward
<T0
>(name_
)}
121 , endpoint_guid
{std::forward
<T1
>(guid_
)}
122 , devid
{std::forward
<T2
>(devid_
)}
126 bool checkName(const al::vector
<DevMap
> &list
, const std::string
&name
)
128 return std::find_if(list
.cbegin(), list
.cend(),
129 [&name
](const DevMap
&entry
) -> bool
130 { return entry
.name
== name
; }
134 al::vector
<DevMap
> PlaybackDevices
;
135 al::vector
<DevMap
> CaptureDevices
;
141 struct ThreadRequest
{
147 #define WM_USER_First (WM_USER+0)
148 #define WM_USER_OpenDevice (WM_USER+0)
149 #define WM_USER_ResetDevice (WM_USER+1)
150 #define WM_USER_StartDevice (WM_USER+2)
151 #define WM_USER_StopDevice (WM_USER+3)
152 #define WM_USER_CloseDevice (WM_USER+4)
153 #define WM_USER_Enumerate (WM_USER+5)
154 #define WM_USER_Last (WM_USER+5)
156 constexpr char MessageStr
[WM_USER_Last
+1-WM_USER
][20] = {
165 inline void ReturnMsgResponse(ThreadRequest
*req
, HRESULT res
)
168 SetEvent(req
->FinishedEvt
);
171 HRESULT
WaitForResponse(ThreadRequest
*req
)
173 if(WaitForSingleObject(req
->FinishedEvt
, INFINITE
) == WAIT_OBJECT_0
)
175 ERR("Message response error: %lu\n", GetLastError());
180 using NameGUIDPair
= std::pair
<std::string
,std::string
>;
181 NameGUIDPair
get_device_name_and_guid(IMMDevice
*device
)
183 std::string name
{DEVNAME_HEAD
};
187 HRESULT hr
= device
->OpenPropertyStore(STGM_READ
, &ps
);
190 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
191 return { name
+"Unknown Device Name", "Unknown Device GUID" };
195 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(DEVPKEY_Device_FriendlyName
), pvprop
.get());
198 WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr
);
199 name
+= "Unknown Device Name";
201 else if(pvprop
->vt
== VT_LPWSTR
)
202 name
+= wstr_to_utf8(pvprop
->pwszVal
);
205 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop
->vt
);
206 name
+= "Unknown Device Name";
210 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(PKEY_AudioEndpoint_GUID
), pvprop
.get());
213 WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr
);
214 guid
= "Unknown Device GUID";
216 else if(pvprop
->vt
== VT_LPWSTR
)
217 guid
= wstr_to_utf8(pvprop
->pwszVal
);
220 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop
->vt
);
221 guid
= "Unknown Device GUID";
229 void get_device_formfactor(IMMDevice
*device
, EndpointFormFactor
*formfactor
)
232 HRESULT hr
= device
->OpenPropertyStore(STGM_READ
, &ps
);
235 WARN("OpenPropertyStore failed: 0x%08lx\n", hr
);
240 hr
= ps
->GetValue(reinterpret_cast<const PROPERTYKEY
&>(PKEY_AudioEndpoint_FormFactor
), pvform
.get());
242 WARN("GetValue AudioEndpoint_FormFactor failed: 0x%08lx\n", hr
);
243 else if(pvform
->vt
== VT_UI4
)
244 *formfactor
= static_cast<EndpointFormFactor
>(pvform
->ulVal
);
245 else if(pvform
->vt
== VT_EMPTY
)
246 *formfactor
= UnknownFormFactor
;
248 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvform
->vt
);
254 void add_device(IMMDevice
*device
, const WCHAR
*devid
, al::vector
<DevMap
> &list
)
256 std::string basename
, guidstr
;
257 std::tie(basename
, guidstr
) = get_device_name_and_guid(device
);
260 std::string newname
{basename
};
261 while(checkName(list
, newname
))
265 newname
+= std::to_string(++count
);
267 list
.emplace_back(std::move(newname
), std::move(guidstr
), devid
);
268 const DevMap
&newentry
= list
.back();
270 TRACE("Got device \"%s\", \"%s\", \"%ls\"\n", newentry
.name
.c_str(),
271 newentry
.endpoint_guid
.c_str(), newentry
.devid
.c_str());
274 WCHAR
*get_device_id(IMMDevice
*device
)
278 HRESULT hr
= device
->GetId(&devid
);
281 ERR("Failed to get device id: %lx\n", hr
);
288 HRESULT
probe_devices(IMMDeviceEnumerator
*devenum
, EDataFlow flowdir
, al::vector
<DevMap
> &list
)
290 IMMDeviceCollection
*coll
;
291 HRESULT hr
= devenum
->EnumAudioEndpoints(flowdir
, DEVICE_STATE_ACTIVE
, &coll
);
294 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr
);
298 IMMDevice
*defdev
{nullptr};
299 WCHAR
*defdevid
{nullptr};
301 hr
= coll
->GetCount(&count
);
302 if(SUCCEEDED(hr
) && count
> 0)
307 hr
= devenum
->GetDefaultAudioEndpoint(flowdir
, eMultimedia
, &defdev
);
309 if(SUCCEEDED(hr
) && defdev
!= nullptr)
311 defdevid
= get_device_id(defdev
);
313 add_device(defdev
, defdevid
, list
);
316 for(UINT i
{0};i
< count
;++i
)
319 hr
= coll
->Item(i
, &device
);
320 if(FAILED(hr
)) continue;
322 WCHAR
*devid
= get_device_id(device
);
325 if(wcscmp(devid
, defdevid
) != 0)
326 add_device(device
, devid
, list
);
327 CoTaskMemFree(devid
);
332 if(defdev
) defdev
->Release();
333 if(defdevid
) CoTaskMemFree(defdevid
);
340 /* Proxy interface used by the message handler. */
342 virtual HRESULT
openProxy() = 0;
343 virtual void closeProxy() = 0;
345 virtual HRESULT
resetProxy() = 0;
346 virtual HRESULT
startProxy() = 0;
347 virtual void stopProxy() = 0;
350 DWORD CALLBACK
WasapiProxy_messageHandler(void *ptr
)
352 auto req
= reinterpret_cast<ThreadRequest
*>(ptr
);
354 TRACE("Starting message thread\n");
356 HRESULT cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
359 WARN("Failed to initialize COM: 0x%08lx\n", cohr
);
360 ReturnMsgResponse(req
, cohr
);
364 HRESULT hr
= CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
365 IID_IMMDeviceEnumerator
, &ptr
);
368 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr
);
370 ReturnMsgResponse(req
, hr
);
373 auto Enumerator
= reinterpret_cast<IMMDeviceEnumerator
*>(ptr
);
374 Enumerator
->Release();
375 Enumerator
= nullptr;
379 /* HACK: Force Windows to create a message queue for this thread before
380 * returning success, otherwise PostThreadMessage may fail if it gets
381 * called before GetMessage.
384 PeekMessage(&msg
, nullptr, WM_USER
, WM_USER
, PM_NOREMOVE
);
386 TRACE("Message thread initialization complete\n");
387 ReturnMsgResponse(req
, S_OK
);
389 TRACE("Starting message loop\n");
390 ALuint deviceCount
{0};
391 while(GetMessage(&msg
, nullptr, WM_USER_First
, WM_USER_Last
))
393 TRACE("Got message \"%s\" (0x%04x, lparam=%p, wparam=%p)\n",
394 (msg
.message
>= WM_USER
&& msg
.message
<= WM_USER_Last
) ?
395 MessageStr
[msg
.message
-WM_USER
] : "Unknown",
396 msg
.message
, (void*)msg
.lParam
, (void*)msg
.wParam
399 WasapiProxy
*proxy
{nullptr};
402 case WM_USER_OpenDevice
:
403 req
= reinterpret_cast<ThreadRequest
*>(msg
.wParam
);
404 proxy
= reinterpret_cast<WasapiProxy
*>(msg
.lParam
);
407 if(++deviceCount
== 1)
408 hr
= cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
410 hr
= proxy
->openProxy();
413 if(--deviceCount
== 0 && SUCCEEDED(cohr
))
417 ReturnMsgResponse(req
, hr
);
420 case WM_USER_ResetDevice
:
421 req
= reinterpret_cast<ThreadRequest
*>(msg
.wParam
);
422 proxy
= reinterpret_cast<WasapiProxy
*>(msg
.lParam
);
424 hr
= proxy
->resetProxy();
425 ReturnMsgResponse(req
, hr
);
428 case WM_USER_StartDevice
:
429 req
= reinterpret_cast<ThreadRequest
*>(msg
.wParam
);
430 proxy
= reinterpret_cast<WasapiProxy
*>(msg
.lParam
);
432 hr
= proxy
->startProxy();
433 ReturnMsgResponse(req
, hr
);
436 case WM_USER_StopDevice
:
437 req
= reinterpret_cast<ThreadRequest
*>(msg
.wParam
);
438 proxy
= reinterpret_cast<WasapiProxy
*>(msg
.lParam
);
441 ReturnMsgResponse(req
, S_OK
);
444 case WM_USER_CloseDevice
:
445 req
= reinterpret_cast<ThreadRequest
*>(msg
.wParam
);
446 proxy
= reinterpret_cast<WasapiProxy
*>(msg
.lParam
);
449 if(--deviceCount
== 0)
452 ReturnMsgResponse(req
, S_OK
);
455 case WM_USER_Enumerate
:
456 req
= reinterpret_cast<ThreadRequest
*>(msg
.wParam
);
459 if(++deviceCount
== 1)
460 hr
= cohr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
462 hr
= CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
, IID_IMMDeviceEnumerator
, &ptr
);
465 Enumerator
= reinterpret_cast<IMMDeviceEnumerator
*>(ptr
);
467 if(msg
.lParam
== ALL_DEVICE_PROBE
)
468 hr
= probe_devices(Enumerator
, eRender
, PlaybackDevices
);
469 else if(msg
.lParam
== CAPTURE_DEVICE_PROBE
)
470 hr
= probe_devices(Enumerator
, eCapture
, CaptureDevices
);
472 Enumerator
->Release();
473 Enumerator
= nullptr;
476 if(--deviceCount
== 0 && SUCCEEDED(cohr
))
479 ReturnMsgResponse(req
, hr
);
483 ERR("Unexpected message: %u\n", msg
.message
);
487 TRACE("Message loop finished\n");
493 struct ALCwasapiPlayback final
: public ALCbackend
, WasapiProxy
{
494 HRESULT
openProxy() override
;
495 void closeProxy() override
;
497 HRESULT
resetProxy() override
;
498 HRESULT
startProxy() override
;
499 void stopProxy() override
;
503 IMMDevice
*mMMDev
{nullptr};
504 IAudioClient
*mClient
{nullptr};
505 IAudioRenderClient
*mRender
{nullptr};
506 HANDLE mNotifyEvent
{nullptr};
508 HANDLE mMsgEvent
{nullptr};
510 std::atomic
<UINT32
> mPadding
{0u};
512 std::atomic
<ALenum
> mKillNow
{AL_TRUE
};
516 int ALCwasapiPlayback_mixerProc(ALCwasapiPlayback
*self
);
518 void ALCwasapiPlayback_Construct(ALCwasapiPlayback
*self
, ALCdevice
*device
);
519 void ALCwasapiPlayback_Destruct(ALCwasapiPlayback
*self
);
520 ALCenum
ALCwasapiPlayback_open(ALCwasapiPlayback
*self
, const ALCchar
*name
);
521 ALCboolean
ALCwasapiPlayback_reset(ALCwasapiPlayback
*self
);
522 ALCboolean
ALCwasapiPlayback_start(ALCwasapiPlayback
*self
);
523 void ALCwasapiPlayback_stop(ALCwasapiPlayback
*self
);
524 DECLARE_FORWARD2(ALCwasapiPlayback
, ALCbackend
, ALCenum
, captureSamples
, ALCvoid
*, ALCuint
)
525 DECLARE_FORWARD(ALCwasapiPlayback
, ALCbackend
, ALCuint
, availableSamples
)
526 ClockLatency
ALCwasapiPlayback_getClockLatency(ALCwasapiPlayback
*self
);
527 DECLARE_FORWARD(ALCwasapiPlayback
, ALCbackend
, void, lock
)
528 DECLARE_FORWARD(ALCwasapiPlayback
, ALCbackend
, void, unlock
)
529 DECLARE_DEFAULT_ALLOCATORS(ALCwasapiPlayback
)
531 DEFINE_ALCBACKEND_VTABLE(ALCwasapiPlayback
);
534 void ALCwasapiPlayback_Construct(ALCwasapiPlayback
*self
, ALCdevice
*device
)
536 new (self
) ALCwasapiPlayback
{};
537 SET_VTABLE2(ALCwasapiPlayback
, ALCbackend
, self
);
538 ALCbackend_Construct(STATIC_CAST(ALCbackend
, self
), device
);
541 void ALCwasapiPlayback_Destruct(ALCwasapiPlayback
*self
)
545 ThreadRequest req
= { self
->mMsgEvent
, 0 };
546 auto proxy
= static_cast<WasapiProxy
*>(self
);
547 if(PostThreadMessage(ThreadID
, WM_USER_CloseDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
548 (void)WaitForResponse(&req
);
550 CloseHandle(self
->mMsgEvent
);
551 self
->mMsgEvent
= nullptr;
554 if(self
->mNotifyEvent
!= nullptr)
555 CloseHandle(self
->mNotifyEvent
);
556 self
->mNotifyEvent
= nullptr;
557 if(self
->mMsgEvent
!= nullptr)
558 CloseHandle(self
->mMsgEvent
);
559 self
->mMsgEvent
= nullptr;
561 ALCbackend_Destruct(STATIC_CAST(ALCbackend
, self
));
562 self
->~ALCwasapiPlayback();
566 FORCE_ALIGN
int ALCwasapiPlayback_mixerProc(ALCwasapiPlayback
*self
)
568 ALCdevice
*device
{STATIC_CAST(ALCbackend
, self
)->mDevice
};
569 IAudioClient
*client
{self
->mClient
};
570 IAudioRenderClient
*render
{self
->mRender
};
572 HRESULT hr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
575 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr
);
576 ALCwasapiPlayback_lock(self
);
577 aluHandleDisconnect(device
, "COM init failed: 0x%08lx", hr
);
578 ALCwasapiPlayback_unlock(self
);
583 althrd_setname(MIXER_THREAD_NAME
);
585 ALuint update_size
{device
->UpdateSize
};
586 UINT32 buffer_len
{update_size
* device
->NumUpdates
};
587 while(!self
->mKillNow
.load(std::memory_order_relaxed
))
590 hr
= client
->GetCurrentPadding(&written
);
593 ERR("Failed to get padding: 0x%08lx\n", hr
);
594 ALCwasapiPlayback_lock(self
);
595 aluHandleDisconnect(device
, "Failed to retrieve buffer padding: 0x%08lx", hr
);
596 ALCwasapiPlayback_unlock(self
);
599 self
->mPadding
.store(written
, std::memory_order_relaxed
);
601 ALuint len
{buffer_len
- written
};
602 if(len
< update_size
)
605 res
= WaitForSingleObjectEx(self
->mNotifyEvent
, 2000, FALSE
);
606 if(res
!= WAIT_OBJECT_0
)
607 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
610 len
-= len
%update_size
;
613 hr
= render
->GetBuffer(len
, &buffer
);
616 ALCwasapiPlayback_lock(self
);
617 aluMixData(device
, buffer
, len
);
618 self
->mPadding
.store(written
+ len
, std::memory_order_relaxed
);
619 ALCwasapiPlayback_unlock(self
);
620 hr
= render
->ReleaseBuffer(len
, 0);
624 ERR("Failed to buffer data: 0x%08lx\n", hr
);
625 ALCwasapiPlayback_lock(self
);
626 aluHandleDisconnect(device
, "Failed to send playback samples: 0x%08lx", hr
);
627 ALCwasapiPlayback_unlock(self
);
631 self
->mPadding
.store(0u, std::memory_order_release
);
638 ALCboolean
MakeExtensible(WAVEFORMATEXTENSIBLE
*out
, const WAVEFORMATEX
*in
)
640 memset(out
, 0, sizeof(*out
));
641 if(in
->wFormatTag
== WAVE_FORMAT_EXTENSIBLE
)
642 *out
= *(const WAVEFORMATEXTENSIBLE
*)in
;
643 else if(in
->wFormatTag
== WAVE_FORMAT_PCM
)
646 out
->Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
647 out
->Format
.cbSize
= sizeof(*out
) - sizeof(*in
);
648 if(out
->Format
.nChannels
== 1)
649 out
->dwChannelMask
= MONO
;
650 else if(out
->Format
.nChannels
== 2)
651 out
->dwChannelMask
= STEREO
;
653 ERR("Unhandled PCM channel count: %d\n", out
->Format
.nChannels
);
654 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
656 else if(in
->wFormatTag
== WAVE_FORMAT_IEEE_FLOAT
)
659 out
->Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
660 out
->Format
.cbSize
= sizeof(*out
) - sizeof(*in
);
661 if(out
->Format
.nChannels
== 1)
662 out
->dwChannelMask
= MONO
;
663 else if(out
->Format
.nChannels
== 2)
664 out
->dwChannelMask
= STEREO
;
666 ERR("Unhandled IEEE float channel count: %d\n", out
->Format
.nChannels
);
667 out
->SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
671 ERR("Unhandled format tag: 0x%04x\n", in
->wFormatTag
);
677 ALCenum
ALCwasapiPlayback_open(ALCwasapiPlayback
*self
, const ALCchar
*deviceName
)
681 self
->mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
682 self
->mMsgEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
683 if(self
->mNotifyEvent
== nullptr || self
->mMsgEvent
== nullptr)
685 ERR("Failed to create message events: %lu\n", GetLastError());
693 if(PlaybackDevices
.empty())
695 ThreadRequest req
= { self
->mMsgEvent
, 0 };
696 if(PostThreadMessage(ThreadID
, WM_USER_Enumerate
, (WPARAM
)&req
, ALL_DEVICE_PROBE
))
697 (void)WaitForResponse(&req
);
701 auto iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
702 [deviceName
](const DevMap
&entry
) -> bool
703 { return entry
.name
== deviceName
|| entry
.endpoint_guid
== deviceName
; }
705 if(iter
== PlaybackDevices
.cend())
707 std::wstring wname
{utf8_to_wstr(deviceName
)};
708 iter
= std::find_if(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(),
709 [&wname
](const DevMap
&entry
) -> bool
710 { return entry
.devid
== wname
; }
713 if(iter
== PlaybackDevices
.cend())
714 WARN("Failed to find device name matching \"%s\"\n", deviceName
);
717 ALCdevice
*device
= STATIC_CAST(ALCbackend
,self
)->mDevice
;
718 self
->mDevId
= iter
->devid
;
719 device
->DeviceName
= iter
->name
;
727 ThreadRequest req
{ self
->mMsgEvent
, 0 };
728 auto proxy
= static_cast<WasapiProxy
*>(self
);
731 if(PostThreadMessage(ThreadID
, WM_USER_OpenDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
732 hr
= WaitForResponse(&req
);
734 ERR("Failed to post thread message: %lu\n", GetLastError());
739 if(self
->mNotifyEvent
!= nullptr)
740 CloseHandle(self
->mNotifyEvent
);
741 self
->mNotifyEvent
= nullptr;
742 if(self
->mMsgEvent
!= nullptr)
743 CloseHandle(self
->mMsgEvent
);
744 self
->mMsgEvent
= nullptr;
746 self
->mDevId
.clear();
748 ERR("Device init failed: 0x%08lx\n", hr
);
749 return ALC_INVALID_VALUE
;
755 HRESULT
ALCwasapiPlayback::openProxy()
757 ALCdevice
*device
= STATIC_CAST(ALCbackend
, this)->mDevice
;
760 HRESULT hr
= CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
, IID_IMMDeviceEnumerator
, &ptr
);
763 auto Enumerator
= reinterpret_cast<IMMDeviceEnumerator
*>(ptr
);
765 hr
= Enumerator
->GetDefaultAudioEndpoint(eRender
, eMultimedia
, &mMMDev
);
767 hr
= Enumerator
->GetDevice(mDevId
.c_str(), &mMMDev
);
768 Enumerator
->Release();
771 hr
= mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
);
774 mClient
= reinterpret_cast<IAudioClient
*>(ptr
);
775 if(device
->DeviceName
.empty())
776 device
->DeviceName
= get_device_name_and_guid(mMMDev
).first
;
789 void ALCwasapiPlayback::closeProxy()
801 ALCboolean
ALCwasapiPlayback_reset(ALCwasapiPlayback
*self
)
803 ThreadRequest req
{ self
->mMsgEvent
, 0 };
806 auto proxy
= static_cast<WasapiProxy
*>(self
);
807 if(PostThreadMessage(ThreadID
, WM_USER_ResetDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
808 hr
= WaitForResponse(&req
);
810 return SUCCEEDED(hr
) ? ALC_TRUE
: ALC_FALSE
;
813 HRESULT
ALCwasapiPlayback::resetProxy()
815 ALCdevice
*device
{STATIC_CAST(ALCbackend
, this)->mDevice
};
822 HRESULT hr
= mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
);
825 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
828 mClient
= reinterpret_cast<IAudioClient
*>(ptr
);
831 hr
= mClient
->GetMixFormat(&wfx
);
834 ERR("Failed to get mix format: 0x%08lx\n", hr
);
838 WAVEFORMATEXTENSIBLE OutputType
;
839 if(!MakeExtensible(&OutputType
, wfx
))
847 REFERENCE_TIME buf_time
{ScaleCeil(device
->UpdateSize
*device
->NumUpdates
, REFTIME_PER_SEC
,
850 if(!(device
->Flags
&DEVICE_FREQUENCY_REQUEST
))
851 device
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
852 if(!(device
->Flags
&DEVICE_CHANNELS_REQUEST
))
854 if(OutputType
.Format
.nChannels
== 1 && OutputType
.dwChannelMask
== MONO
)
855 device
->FmtChans
= DevFmtMono
;
856 else if(OutputType
.Format
.nChannels
== 2 && OutputType
.dwChannelMask
== STEREO
)
857 device
->FmtChans
= DevFmtStereo
;
858 else if(OutputType
.Format
.nChannels
== 4 && OutputType
.dwChannelMask
== QUAD
)
859 device
->FmtChans
= DevFmtQuad
;
860 else if(OutputType
.Format
.nChannels
== 6 && OutputType
.dwChannelMask
== X5DOT1
)
861 device
->FmtChans
= DevFmtX51
;
862 else if(OutputType
.Format
.nChannels
== 6 && OutputType
.dwChannelMask
== X5DOT1REAR
)
863 device
->FmtChans
= DevFmtX51Rear
;
864 else if(OutputType
.Format
.nChannels
== 7 && OutputType
.dwChannelMask
== X6DOT1
)
865 device
->FmtChans
= DevFmtX61
;
866 else if(OutputType
.Format
.nChannels
== 8 && (OutputType
.dwChannelMask
== X7DOT1
|| OutputType
.dwChannelMask
== X7DOT1_WIDE
))
867 device
->FmtChans
= DevFmtX71
;
869 ERR("Unhandled channel config: %d -- 0x%08lx\n", OutputType
.Format
.nChannels
, OutputType
.dwChannelMask
);
872 switch(device
->FmtChans
)
875 OutputType
.Format
.nChannels
= 1;
876 OutputType
.dwChannelMask
= MONO
;
879 device
->FmtChans
= DevFmtStereo
;
882 OutputType
.Format
.nChannels
= 2;
883 OutputType
.dwChannelMask
= STEREO
;
886 OutputType
.Format
.nChannels
= 4;
887 OutputType
.dwChannelMask
= QUAD
;
890 OutputType
.Format
.nChannels
= 6;
891 OutputType
.dwChannelMask
= X5DOT1
;
894 OutputType
.Format
.nChannels
= 6;
895 OutputType
.dwChannelMask
= X5DOT1REAR
;
898 OutputType
.Format
.nChannels
= 7;
899 OutputType
.dwChannelMask
= X6DOT1
;
902 OutputType
.Format
.nChannels
= 8;
903 OutputType
.dwChannelMask
= X7DOT1
;
906 switch(device
->FmtType
)
909 device
->FmtType
= DevFmtUByte
;
912 OutputType
.Format
.wBitsPerSample
= 8;
913 OutputType
.Samples
.wValidBitsPerSample
= 8;
914 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
917 device
->FmtType
= DevFmtShort
;
920 OutputType
.Format
.wBitsPerSample
= 16;
921 OutputType
.Samples
.wValidBitsPerSample
= 16;
922 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
925 device
->FmtType
= DevFmtInt
;
928 OutputType
.Format
.wBitsPerSample
= 32;
929 OutputType
.Samples
.wValidBitsPerSample
= 32;
930 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
933 OutputType
.Format
.wBitsPerSample
= 32;
934 OutputType
.Samples
.wValidBitsPerSample
= 32;
935 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
938 OutputType
.Format
.nSamplesPerSec
= device
->Frequency
;
940 OutputType
.Format
.nBlockAlign
= OutputType
.Format
.nChannels
*
941 OutputType
.Format
.wBitsPerSample
/ 8;
942 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
943 OutputType
.Format
.nBlockAlign
;
945 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &OutputType
.Format
, &wfx
);
948 ERR("Failed to check format support: 0x%08lx\n", hr
);
949 hr
= mClient
->GetMixFormat(&wfx
);
953 ERR("Failed to find a supported format: 0x%08lx\n", hr
);
959 if(!MakeExtensible(&OutputType
, wfx
))
967 device
->Frequency
= OutputType
.Format
.nSamplesPerSec
;
968 if(OutputType
.Format
.nChannels
== 1 && OutputType
.dwChannelMask
== MONO
)
969 device
->FmtChans
= DevFmtMono
;
970 else if(OutputType
.Format
.nChannels
== 2 && OutputType
.dwChannelMask
== STEREO
)
971 device
->FmtChans
= DevFmtStereo
;
972 else if(OutputType
.Format
.nChannels
== 4 && OutputType
.dwChannelMask
== QUAD
)
973 device
->FmtChans
= DevFmtQuad
;
974 else if(OutputType
.Format
.nChannels
== 6 && OutputType
.dwChannelMask
== X5DOT1
)
975 device
->FmtChans
= DevFmtX51
;
976 else if(OutputType
.Format
.nChannels
== 6 && OutputType
.dwChannelMask
== X5DOT1REAR
)
977 device
->FmtChans
= DevFmtX51Rear
;
978 else if(OutputType
.Format
.nChannels
== 7 && OutputType
.dwChannelMask
== X6DOT1
)
979 device
->FmtChans
= DevFmtX61
;
980 else if(OutputType
.Format
.nChannels
== 8 && (OutputType
.dwChannelMask
== X7DOT1
|| OutputType
.dwChannelMask
== X7DOT1_WIDE
))
981 device
->FmtChans
= DevFmtX71
;
984 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType
.Format
.nChannels
, OutputType
.dwChannelMask
);
985 device
->FmtChans
= DevFmtStereo
;
986 OutputType
.Format
.nChannels
= 2;
987 OutputType
.dwChannelMask
= STEREO
;
990 if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
992 if(OutputType
.Format
.wBitsPerSample
== 8)
993 device
->FmtType
= DevFmtUByte
;
994 else if(OutputType
.Format
.wBitsPerSample
== 16)
995 device
->FmtType
= DevFmtShort
;
996 else if(OutputType
.Format
.wBitsPerSample
== 32)
997 device
->FmtType
= DevFmtInt
;
1000 device
->FmtType
= DevFmtShort
;
1001 OutputType
.Format
.wBitsPerSample
= 16;
1004 else if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1006 device
->FmtType
= DevFmtFloat
;
1007 OutputType
.Format
.wBitsPerSample
= 32;
1011 ERR("Unhandled format sub-type\n");
1012 device
->FmtType
= DevFmtShort
;
1013 OutputType
.Format
.wBitsPerSample
= 16;
1014 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1016 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1019 EndpointFormFactor formfactor
= UnknownFormFactor
;
1020 get_device_formfactor(mMMDev
, &formfactor
);
1021 device
->IsHeadphones
= (device
->FmtChans
== DevFmtStereo
&&
1022 (formfactor
== Headphones
|| formfactor
== Headset
)
1025 SetDefaultWFXChannelOrder(device
);
1027 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1028 buf_time
, 0, &OutputType
.Format
, nullptr);
1031 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1035 UINT32 buffer_len
, min_len
;
1036 REFERENCE_TIME min_per
;
1037 hr
= mClient
->GetDevicePeriod(&min_per
, nullptr);
1040 min_len
= (UINT32
)ScaleCeil(min_per
, device
->Frequency
, REFTIME_PER_SEC
);
1041 /* Find the nearest multiple of the period size to the update size */
1042 if(min_len
< device
->UpdateSize
)
1043 min_len
*= maxu((device
->UpdateSize
+ min_len
/2) / min_len
, 1u);
1044 hr
= mClient
->GetBufferSize(&buffer_len
);
1048 ERR("Failed to get audio buffer info: 0x%08lx\n", hr
);
1052 device
->UpdateSize
= min_len
;
1053 device
->NumUpdates
= buffer_len
/ device
->UpdateSize
;
1054 if(device
->NumUpdates
<= 1)
1056 ERR("Audio client returned buffer_len < period*2; expect break up\n");
1057 device
->NumUpdates
= 2;
1058 device
->UpdateSize
= buffer_len
/ device
->NumUpdates
;
1061 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1064 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1072 ALCboolean
ALCwasapiPlayback_start(ALCwasapiPlayback
*self
)
1074 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1077 auto proxy
= static_cast<WasapiProxy
*>(self
);
1078 if(PostThreadMessage(ThreadID
, WM_USER_StartDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
1079 hr
= WaitForResponse(&req
);
1081 return SUCCEEDED(hr
) ? ALC_TRUE
: ALC_FALSE
;
1084 HRESULT
ALCwasapiPlayback::startProxy()
1086 ResetEvent(mNotifyEvent
);
1088 HRESULT hr
= mClient
->Start();
1091 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1096 hr
= mClient
->GetService(IID_IAudioRenderClient
, &ptr
);
1099 mRender
= reinterpret_cast<IAudioRenderClient
*>(ptr
);
1101 mKillNow
.store(AL_FALSE
, std::memory_order_release
);
1102 mThread
= std::thread(ALCwasapiPlayback_mixerProc
, this);
1107 ERR("Failed to start thread\n");
1119 void ALCwasapiPlayback_stop(ALCwasapiPlayback
*self
)
1121 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1122 auto proxy
= static_cast<WasapiProxy
*>(self
);
1123 if(PostThreadMessage(ThreadID
, WM_USER_StopDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
1124 (void)WaitForResponse(&req
);
1127 void ALCwasapiPlayback::stopProxy()
1129 if(!mRender
|| !mThread
.joinable())
1132 mKillNow
.store(AL_TRUE
);
1141 ClockLatency
ALCwasapiPlayback_getClockLatency(ALCwasapiPlayback
*self
)
1145 ALCwasapiPlayback_lock(self
);
1146 ALCdevice
*device
{STATIC_CAST(ALCbackend
, self
)->mDevice
};
1147 ret
.ClockTime
= GetDeviceClockTime(device
);
1148 ret
.Latency
= std::chrono::seconds
{self
->mPadding
.load(std::memory_order_relaxed
)};
1149 ret
.Latency
/= device
->Frequency
;
1150 ALCwasapiPlayback_unlock(self
);
1156 struct ALCwasapiCapture final
: public ALCbackend
, WasapiProxy
{
1157 HRESULT
openProxy() override
;
1158 void closeProxy() override
;
1160 HRESULT
resetProxy() override
;
1161 HRESULT
startProxy() override
;
1162 void stopProxy() override
;
1164 std::wstring mDevId
;
1166 IMMDevice
*mMMDev
{nullptr};
1167 IAudioClient
*mClient
{nullptr};
1168 IAudioCaptureClient
*mCapture
{nullptr};
1169 HANDLE mNotifyEvent
{nullptr};
1171 HANDLE mMsgEvent
{nullptr};
1173 ChannelConverter
*mChannelConv
{nullptr};
1174 SampleConverter
*mSampleConv
{nullptr};
1175 ll_ringbuffer_t
*mRing
{nullptr};
1177 std::atomic
<int> mKillNow
{AL_TRUE
};
1178 std::thread mThread
;
1181 int ALCwasapiCapture_recordProc(ALCwasapiCapture
*self
);
1183 void ALCwasapiCapture_Construct(ALCwasapiCapture
*self
, ALCdevice
*device
);
1184 void ALCwasapiCapture_Destruct(ALCwasapiCapture
*self
);
1185 ALCenum
ALCwasapiCapture_open(ALCwasapiCapture
*self
, const ALCchar
*name
);
1186 DECLARE_FORWARD(ALCwasapiCapture
, ALCbackend
, ALCboolean
, reset
)
1187 ALCboolean
ALCwasapiCapture_start(ALCwasapiCapture
*self
);
1188 void ALCwasapiCapture_stop(ALCwasapiCapture
*self
);
1189 ALCenum
ALCwasapiCapture_captureSamples(ALCwasapiCapture
*self
, ALCvoid
*buffer
, ALCuint samples
);
1190 ALuint
ALCwasapiCapture_availableSamples(ALCwasapiCapture
*self
);
1191 DECLARE_FORWARD(ALCwasapiCapture
, ALCbackend
, ClockLatency
, getClockLatency
)
1192 DECLARE_FORWARD(ALCwasapiCapture
, ALCbackend
, void, lock
)
1193 DECLARE_FORWARD(ALCwasapiCapture
, ALCbackend
, void, unlock
)
1194 DECLARE_DEFAULT_ALLOCATORS(ALCwasapiCapture
)
1196 DEFINE_ALCBACKEND_VTABLE(ALCwasapiCapture
);
1199 void ALCwasapiCapture_Construct(ALCwasapiCapture
*self
, ALCdevice
*device
)
1201 new (self
) ALCwasapiCapture
{};
1202 SET_VTABLE2(ALCwasapiCapture
, ALCbackend
, self
);
1203 ALCbackend_Construct(STATIC_CAST(ALCbackend
, self
), device
);
1206 void ALCwasapiCapture_Destruct(ALCwasapiCapture
*self
)
1210 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1211 auto proxy
= static_cast<WasapiProxy
*>(self
);
1212 if(PostThreadMessage(ThreadID
, WM_USER_CloseDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
1213 (void)WaitForResponse(&req
);
1215 CloseHandle(self
->mMsgEvent
);
1216 self
->mMsgEvent
= nullptr;
1219 if(self
->mNotifyEvent
!= nullptr)
1220 CloseHandle(self
->mNotifyEvent
);
1221 self
->mNotifyEvent
= nullptr;
1223 ll_ringbuffer_free(self
->mRing
);
1224 self
->mRing
= nullptr;
1226 DestroySampleConverter(&self
->mSampleConv
);
1227 DestroyChannelConverter(&self
->mChannelConv
);
1229 ALCbackend_Destruct(STATIC_CAST(ALCbackend
, self
));
1230 self
->~ALCwasapiCapture();
1234 FORCE_ALIGN
int ALCwasapiCapture_recordProc(ALCwasapiCapture
*self
)
1236 ALCdevice
*device
{STATIC_CAST(ALCbackend
, self
)->mDevice
};
1237 IAudioCaptureClient
*capture
{self
->mCapture
};
1239 HRESULT hr
= CoInitializeEx(nullptr, COINIT_MULTITHREADED
);
1242 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr
);
1243 ALCwasapiCapture_lock(self
);
1244 aluHandleDisconnect(device
, "COM init failed: 0x%08lx", hr
);
1245 ALCwasapiCapture_unlock(self
);
1249 althrd_setname(RECORD_THREAD_NAME
);
1251 al::vector
<float> samples
;
1252 while(!self
->mKillNow
.load(std::memory_order_relaxed
))
1257 hr
= capture
->GetNextPacketSize(&avail
);
1259 ERR("Failed to get next packet size: 0x%08lx\n", hr
);
1266 hr
= capture
->GetBuffer(&rdata
, &numsamples
, &flags
, nullptr, nullptr);
1268 ERR("Failed to get capture buffer: 0x%08lx\n", hr
);
1271 if(self
->mChannelConv
)
1273 samples
.resize(numsamples
*2);
1274 ChannelConverterInput(self
->mChannelConv
, rdata
, samples
.data(), numsamples
);
1275 rdata
= reinterpret_cast<BYTE
*>(samples
.data());
1278 auto data
= ll_ringbuffer_get_write_vector(self
->mRing
);
1281 if(self
->mSampleConv
)
1283 const ALvoid
*srcdata
= rdata
;
1284 ALsizei srcframes
= numsamples
;
1286 dstframes
= SampleConverterInput(self
->mSampleConv
,
1287 &srcdata
, &srcframes
, data
.first
.buf
,
1288 (ALsizei
)minz(data
.first
.len
, INT_MAX
)
1290 if(srcframes
> 0 && dstframes
== data
.first
.len
&& data
.second
.len
> 0)
1292 /* If some source samples remain, all of the first dest
1293 * block was filled, and there's space in the second
1294 * dest block, do another run for the second block.
1296 dstframes
+= SampleConverterInput(self
->mSampleConv
,
1297 &srcdata
, &srcframes
, data
.second
.buf
,
1298 (ALsizei
)minz(data
.second
.len
, INT_MAX
)
1304 ALuint framesize
= FrameSizeFromDevFmt(device
->FmtChans
, device
->FmtType
,
1305 device
->mAmbiOrder
);
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 ll_ringbuffer_write_advance(self
->mRing
, dstframes
);
1317 hr
= capture
->ReleaseBuffer(numsamples
);
1318 if(FAILED(hr
)) ERR("Failed to release capture buffer: 0x%08lx\n", hr
);
1324 ALCwasapiCapture_lock(self
);
1325 aluHandleDisconnect(device
, "Failed to capture samples: 0x%08lx", hr
);
1326 ALCwasapiCapture_unlock(self
);
1330 res
= WaitForSingleObjectEx(self
->mNotifyEvent
, 2000, FALSE
);
1331 if(res
!= WAIT_OBJECT_0
)
1332 ERR("WaitForSingleObjectEx error: 0x%lx\n", res
);
1340 ALCenum
ALCwasapiCapture_open(ALCwasapiCapture
*self
, const ALCchar
*deviceName
)
1344 self
->mNotifyEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1345 self
->mMsgEvent
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1346 if(self
->mNotifyEvent
== nullptr || self
->mMsgEvent
== nullptr)
1348 ERR("Failed to create message events: %lu\n", GetLastError());
1356 if(CaptureDevices
.empty())
1358 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1359 if(PostThreadMessage(ThreadID
, WM_USER_Enumerate
, (WPARAM
)&req
, CAPTURE_DEVICE_PROBE
))
1360 (void)WaitForResponse(&req
);
1364 auto iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1365 [deviceName
](const DevMap
&entry
) -> bool
1366 { return entry
.name
== deviceName
|| entry
.endpoint_guid
== deviceName
; }
1368 if(iter
== CaptureDevices
.cend())
1370 std::wstring wname
{utf8_to_wstr(deviceName
)};
1371 iter
= std::find_if(CaptureDevices
.cbegin(), CaptureDevices
.cend(),
1372 [&wname
](const DevMap
&entry
) -> bool
1373 { return entry
.devid
== wname
; }
1376 if(iter
== CaptureDevices
.cend())
1377 WARN("Failed to find device name matching \"%s\"\n", deviceName
);
1380 ALCdevice
*device
= STATIC_CAST(ALCbackend
,self
)->mDevice
;
1381 self
->mDevId
= iter
->devid
;
1382 device
->DeviceName
= iter
->name
;
1390 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1393 auto proxy
= static_cast<WasapiProxy
*>(self
);
1394 if(PostThreadMessage(ThreadID
, WM_USER_OpenDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
1395 hr
= WaitForResponse(&req
);
1397 ERR("Failed to post thread message: %lu\n", GetLastError());
1402 if(self
->mNotifyEvent
!= nullptr)
1403 CloseHandle(self
->mNotifyEvent
);
1404 self
->mNotifyEvent
= nullptr;
1405 if(self
->mMsgEvent
!= nullptr)
1406 CloseHandle(self
->mMsgEvent
);
1407 self
->mMsgEvent
= nullptr;
1409 self
->mDevId
.clear();
1411 ERR("Device init failed: 0x%08lx\n", hr
);
1412 return ALC_INVALID_VALUE
;
1416 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1419 auto proxy
= static_cast<WasapiProxy
*>(self
);
1420 if(PostThreadMessage(ThreadID
, WM_USER_ResetDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
1421 hr
= WaitForResponse(&req
);
1423 ERR("Failed to post thread message: %lu\n", GetLastError());
1427 if(hr
== E_OUTOFMEMORY
)
1428 return ALC_OUT_OF_MEMORY
;
1429 return ALC_INVALID_VALUE
;
1433 return ALC_NO_ERROR
;
1436 HRESULT
ALCwasapiCapture::openProxy()
1438 ALCdevice
*device
{STATIC_CAST(ALCbackend
, this)->mDevice
};
1441 HRESULT hr
= CoCreateInstance(CLSID_MMDeviceEnumerator
, nullptr, CLSCTX_INPROC_SERVER
,
1442 IID_IMMDeviceEnumerator
, &ptr
);
1445 auto Enumerator
= reinterpret_cast<IMMDeviceEnumerator
*>(ptr
);
1447 hr
= Enumerator
->GetDefaultAudioEndpoint(eCapture
, eMultimedia
, &mMMDev
);
1449 hr
= Enumerator
->GetDevice(mDevId
.c_str(), &mMMDev
);
1450 Enumerator
->Release();
1453 hr
= mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
);
1456 mClient
= reinterpret_cast<IAudioClient
*>(ptr
);
1457 if(device
->DeviceName
.empty())
1458 device
->DeviceName
= get_device_name_and_guid(mMMDev
).first
;
1471 void ALCwasapiCapture::closeProxy()
1482 HRESULT
ALCwasapiCapture::resetProxy()
1484 ALCdevice
*device
{STATIC_CAST(ALCbackend
, this)->mDevice
};
1491 HRESULT hr
{mMMDev
->Activate(IID_IAudioClient
, CLSCTX_INPROC_SERVER
, nullptr, &ptr
)};
1494 ERR("Failed to reactivate audio client: 0x%08lx\n", hr
);
1497 mClient
= reinterpret_cast<IAudioClient
*>(ptr
);
1499 REFERENCE_TIME buf_time
{ScaleCeil(device
->UpdateSize
*device
->NumUpdates
, REFTIME_PER_SEC
,
1500 device
->Frequency
)};
1501 // Make sure buffer is at least 100ms in size
1502 buf_time
= maxu64(buf_time
, REFTIME_PER_SEC
/10);
1503 device
->UpdateSize
= (ALuint
)ScaleCeil(buf_time
, device
->Frequency
, REFTIME_PER_SEC
) /
1506 WAVEFORMATEXTENSIBLE OutputType
;
1507 OutputType
.Format
.wFormatTag
= WAVE_FORMAT_EXTENSIBLE
;
1508 switch(device
->FmtChans
)
1511 OutputType
.Format
.nChannels
= 1;
1512 OutputType
.dwChannelMask
= MONO
;
1515 OutputType
.Format
.nChannels
= 2;
1516 OutputType
.dwChannelMask
= STEREO
;
1519 OutputType
.Format
.nChannels
= 4;
1520 OutputType
.dwChannelMask
= QUAD
;
1523 OutputType
.Format
.nChannels
= 6;
1524 OutputType
.dwChannelMask
= X5DOT1
;
1527 OutputType
.Format
.nChannels
= 6;
1528 OutputType
.dwChannelMask
= X5DOT1REAR
;
1531 OutputType
.Format
.nChannels
= 7;
1532 OutputType
.dwChannelMask
= X6DOT1
;
1535 OutputType
.Format
.nChannels
= 8;
1536 OutputType
.dwChannelMask
= X7DOT1
;
1542 switch(device
->FmtType
)
1544 /* NOTE: Signedness doesn't matter, the converter will handle it. */
1547 OutputType
.Format
.wBitsPerSample
= 8;
1548 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1552 OutputType
.Format
.wBitsPerSample
= 16;
1553 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1557 OutputType
.Format
.wBitsPerSample
= 32;
1558 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_PCM
;
1561 OutputType
.Format
.wBitsPerSample
= 32;
1562 OutputType
.SubFormat
= KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
;
1565 OutputType
.Samples
.wValidBitsPerSample
= OutputType
.Format
.wBitsPerSample
;
1566 OutputType
.Format
.nSamplesPerSec
= device
->Frequency
;
1568 OutputType
.Format
.nBlockAlign
= OutputType
.Format
.nChannels
*
1569 OutputType
.Format
.wBitsPerSample
/ 8;
1570 OutputType
.Format
.nAvgBytesPerSec
= OutputType
.Format
.nSamplesPerSec
*
1571 OutputType
.Format
.nBlockAlign
;
1572 OutputType
.Format
.cbSize
= sizeof(OutputType
) - sizeof(OutputType
.Format
);
1575 hr
= mClient
->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED
, &OutputType
.Format
, &wfx
);
1578 ERR("Failed to check format support: 0x%08lx\n", hr
);
1582 DestroySampleConverter(&mSampleConv
);
1583 DestroyChannelConverter(&mChannelConv
);
1587 if(!(wfx
->nChannels
== OutputType
.Format
.nChannels
||
1588 (wfx
->nChannels
== 1 && OutputType
.Format
.nChannels
== 2) ||
1589 (wfx
->nChannels
== 2 && OutputType
.Format
.nChannels
== 1)))
1591 ERR("Failed to get matching format, wanted: %s %s %uhz, got: %d channel%s %d-bit %luhz\n",
1592 DevFmtChannelsString(device
->FmtChans
), DevFmtTypeString(device
->FmtType
),
1593 device
->Frequency
, wfx
->nChannels
, (wfx
->nChannels
==1)?"":"s", wfx
->wBitsPerSample
,
1594 wfx
->nSamplesPerSec
);
1599 if(!MakeExtensible(&OutputType
, wfx
))
1608 enum DevFmtType srcType
;
1609 if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_PCM
))
1611 if(OutputType
.Format
.wBitsPerSample
== 8)
1612 srcType
= DevFmtUByte
;
1613 else if(OutputType
.Format
.wBitsPerSample
== 16)
1614 srcType
= DevFmtShort
;
1615 else if(OutputType
.Format
.wBitsPerSample
== 32)
1616 srcType
= DevFmtInt
;
1619 ERR("Unhandled integer bit depth: %d\n", OutputType
.Format
.wBitsPerSample
);
1623 else if(IsEqualGUID(OutputType
.SubFormat
, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
))
1625 if(OutputType
.Format
.wBitsPerSample
== 32)
1626 srcType
= DevFmtFloat
;
1629 ERR("Unhandled float bit depth: %d\n", OutputType
.Format
.wBitsPerSample
);
1635 ERR("Unhandled format sub-type\n");
1639 if(device
->FmtChans
== DevFmtMono
&& OutputType
.Format
.nChannels
== 2)
1641 mChannelConv
= CreateChannelConverter(srcType
, DevFmtStereo
, device
->FmtChans
);
1644 ERR("Failed to create %s stereo-to-mono converter\n", DevFmtTypeString(srcType
));
1647 TRACE("Created %s stereo-to-mono converter\n", DevFmtTypeString(srcType
));
1648 /* The channel converter always outputs float, so change the input type
1649 * for the resampler/type-converter.
1651 srcType
= DevFmtFloat
;
1653 else if(device
->FmtChans
== DevFmtStereo
&& OutputType
.Format
.nChannels
== 1)
1655 mChannelConv
= CreateChannelConverter(srcType
, DevFmtMono
, device
->FmtChans
);
1658 ERR("Failed to create %s mono-to-stereo converter\n", DevFmtTypeString(srcType
));
1661 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType
));
1662 srcType
= DevFmtFloat
;
1665 if(device
->Frequency
!= OutputType
.Format
.nSamplesPerSec
|| device
->FmtType
!= srcType
)
1667 mSampleConv
= CreateSampleConverter(
1668 srcType
, device
->FmtType
, ChannelsFromDevFmt(device
->FmtChans
, device
->mAmbiOrder
),
1669 OutputType
.Format
.nSamplesPerSec
, device
->Frequency
, BSinc24Resampler
1673 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1674 DevFmtChannelsString(device
->FmtChans
), DevFmtTypeString(device
->FmtType
),
1675 device
->Frequency
, DevFmtTypeString(srcType
), OutputType
.Format
.nSamplesPerSec
);
1678 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1679 DevFmtChannelsString(device
->FmtChans
), DevFmtTypeString(device
->FmtType
),
1680 device
->Frequency
, DevFmtTypeString(srcType
), OutputType
.Format
.nSamplesPerSec
);
1683 hr
= mClient
->Initialize(AUDCLNT_SHAREMODE_SHARED
, AUDCLNT_STREAMFLAGS_EVENTCALLBACK
,
1684 buf_time
, 0, &OutputType
.Format
, nullptr);
1687 ERR("Failed to initialize audio client: 0x%08lx\n", hr
);
1692 hr
= mClient
->GetBufferSize(&buffer_len
);
1695 ERR("Failed to get buffer size: 0x%08lx\n", hr
);
1699 buffer_len
= maxu(device
->UpdateSize
*device
->NumUpdates
, buffer_len
);
1700 ll_ringbuffer_free(mRing
);
1701 mRing
= ll_ringbuffer_create(buffer_len
,
1702 FrameSizeFromDevFmt(device
->FmtChans
, device
->FmtType
, device
->mAmbiOrder
),
1707 ERR("Failed to allocate capture ring buffer\n");
1708 return E_OUTOFMEMORY
;
1711 hr
= mClient
->SetEventHandle(mNotifyEvent
);
1714 ERR("Failed to set event handle: 0x%08lx\n", hr
);
1722 ALCboolean
ALCwasapiCapture_start(ALCwasapiCapture
*self
)
1724 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1727 auto proxy
= static_cast<WasapiProxy
*>(self
);
1728 if(PostThreadMessage(ThreadID
, WM_USER_StartDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
1729 hr
= WaitForResponse(&req
);
1731 return SUCCEEDED(hr
) ? ALC_TRUE
: ALC_FALSE
;
1734 HRESULT
ALCwasapiCapture::startProxy()
1736 ResetEvent(mNotifyEvent
);
1738 HRESULT hr
{mClient
->Start()};
1741 ERR("Failed to start audio client: 0x%08lx\n", hr
);
1746 hr
= mClient
->GetService(IID_IAudioCaptureClient
, &ptr
);
1749 mCapture
= reinterpret_cast<IAudioCaptureClient
*>(ptr
);
1751 mKillNow
.store(AL_FALSE
, std::memory_order_release
);
1752 mThread
= std::thread(ALCwasapiCapture_recordProc
, this);
1755 mCapture
->Release();
1757 ERR("Failed to start thread\n");
1772 void ALCwasapiCapture_stop(ALCwasapiCapture
*self
)
1774 ThreadRequest req
{ self
->mMsgEvent
, 0 };
1775 auto proxy
= static_cast<WasapiProxy
*>(self
);
1776 if(PostThreadMessage(ThreadID
, WM_USER_StopDevice
, (WPARAM
)&req
, (LPARAM
)proxy
))
1777 (void)WaitForResponse(&req
);
1780 void ALCwasapiCapture::stopProxy()
1782 if(!mCapture
|| !mThread
.joinable())
1785 mKillNow
.store(AL_TRUE
);
1788 mCapture
->Release();
1795 ALuint
ALCwasapiCapture_availableSamples(ALCwasapiCapture
*self
)
1797 return (ALuint
)ll_ringbuffer_read_space(self
->mRing
);
1800 ALCenum
ALCwasapiCapture_captureSamples(ALCwasapiCapture
*self
, ALCvoid
*buffer
, ALCuint samples
)
1802 if(ALCwasapiCapture_availableSamples(self
) < samples
)
1803 return ALC_INVALID_VALUE
;
1804 ll_ringbuffer_read(self
->mRing
, reinterpret_cast<char*>(buffer
), samples
);
1805 return ALC_NO_ERROR
;
1811 bool WasapiBackendFactory::init()
1813 static HRESULT InitResult
;
1818 InitResult
= E_FAIL
;
1820 req
.FinishedEvt
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1821 if(req
.FinishedEvt
== nullptr)
1822 ERR("Failed to create event: %lu\n", GetLastError());
1825 ThreadHdl
= CreateThread(nullptr, 0, WasapiProxy_messageHandler
, &req
, 0, &ThreadID
);
1826 if(ThreadHdl
!= nullptr)
1827 InitResult
= WaitForResponse(&req
);
1828 CloseHandle(req
.FinishedEvt
);
1832 return SUCCEEDED(InitResult
) ? ALC_TRUE
: ALC_FALSE
;
1835 void WasapiBackendFactory::deinit()
1837 PlaybackDevices
.clear();
1838 CaptureDevices
.clear();
1842 TRACE("Sending WM_QUIT to Thread %04lx\n", ThreadID
);
1843 PostThreadMessage(ThreadID
, WM_QUIT
, 0, 0);
1844 CloseHandle(ThreadHdl
);
1845 ThreadHdl
= nullptr;
1849 bool WasapiBackendFactory::querySupport(ALCbackend_Type type
)
1850 { return (type
== ALCbackend_Playback
|| type
== ALCbackend_Capture
); }
1852 void WasapiBackendFactory::probe(enum DevProbe type
, std::string
*outnames
)
1854 ThreadRequest req
{ nullptr, 0 };
1856 req
.FinishedEvt
= CreateEventW(nullptr, FALSE
, FALSE
, nullptr);
1857 if(req
.FinishedEvt
== nullptr)
1858 ERR("Failed to create event: %lu\n", GetLastError());
1861 auto add_device
= [outnames
](const DevMap
&entry
) -> void
1863 /* +1 to also append the null char (to ensure a null-separated list
1864 * and double-null terminated list).
1866 outnames
->append(entry
.name
.c_str(), entry
.name
.length()+1);
1868 HRESULT hr
= E_FAIL
;
1869 if(PostThreadMessage(ThreadID
, WM_USER_Enumerate
, (WPARAM
)&req
, type
))
1870 hr
= WaitForResponse(&req
);
1871 if(SUCCEEDED(hr
)) switch(type
)
1873 case ALL_DEVICE_PROBE
:
1874 std::for_each(PlaybackDevices
.cbegin(), PlaybackDevices
.cend(), add_device
);
1877 case CAPTURE_DEVICE_PROBE
:
1878 std::for_each(CaptureDevices
.cbegin(), CaptureDevices
.cend(), add_device
);
1881 CloseHandle(req
.FinishedEvt
);
1882 req
.FinishedEvt
= nullptr;
1886 ALCbackend
*WasapiBackendFactory::createBackend(ALCdevice
*device
, ALCbackend_Type type
)
1888 if(type
== ALCbackend_Playback
)
1890 ALCwasapiPlayback
*backend
;
1891 NEW_OBJ(backend
, ALCwasapiPlayback
)(device
);
1892 if(!backend
) return nullptr;
1893 return STATIC_CAST(ALCbackend
, backend
);
1895 if(type
== ALCbackend_Capture
)
1897 ALCwasapiCapture
*backend
;
1898 NEW_OBJ(backend
, ALCwasapiCapture
)(device
);
1899 if(!backend
) return nullptr;
1900 return STATIC_CAST(ALCbackend
, backend
);
1906 BackendFactory
&WasapiBackendFactory::getFactory()
1908 static WasapiBackendFactory factory
{};