Avoid a stateful unique_ptr deleter
[openal-soft.git] / alc / backends / wasapi.cpp
blob063fca9897698ceabe85f1d5bb01a98c34e98f62
1 /**
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
21 #include "config.h"
23 #include "wasapi.h"
25 #define WIN32_LEAN_AND_MEAN
26 #include <windows.h>
28 #include <stdlib.h>
29 #include <stdio.h>
30 #include <memory.h>
32 #include <wtypes.h>
33 #include <mmdeviceapi.h>
34 #include <audioclient.h>
35 #include <cguid.h>
36 #include <devpropdef.h>
37 #include <mmreg.h>
38 #include <propsys.h>
39 #include <propkey.h>
40 #include <devpkey.h>
41 #ifndef _WAVEFORMATEXTENSIBLE_
42 #include <ks.h>
43 #include <ksmedia.h>
44 #endif
46 #include <algorithm>
47 #include <atomic>
48 #include <chrono>
49 #include <condition_variable>
50 #include <cstring>
51 #include <deque>
52 #include <functional>
53 #include <future>
54 #include <mutex>
55 #include <string>
56 #include <thread>
57 #include <vector>
59 #include "albit.h"
60 #include "alnumeric.h"
61 #include "comptr.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"
67 #include "strutils.h"
68 #include "threads.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);
77 #endif
78 #ifndef KSDATAFORMAT_SUBTYPE_IEEE_FLOAT
79 DEFINE_GUID(KSDATAFORMAT_SUBTYPE_IEEE_FLOAT, 0x00000003, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71);
80 #endif
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 );
87 namespace {
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
108 b |= b>>1;
109 b |= b>>2;
110 b |= b>>4;
111 b |= b>>8;
112 b |= b>>16;
113 return b;
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()));
135 class GuidPrinter {
136 char mMsg[64];
138 public:
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; }
148 struct PropVariant {
149 PROPVARIANT mProp;
151 public:
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; }
166 struct DevMap {
167 std::string name;
168 std::string endpoint_guid; // obtained from PKEY_AudioEndpoint_GUID , set to "Unknown device GUID" if absent.
169 std::wstring devid;
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());
199 if(FAILED(hr))
201 WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
202 return std::make_pair(UnknownName, UnknownGuid);
205 PropVariant pvprop;
206 hr = ps->GetValue(reinterpret_cast<const PROPERTYKEY&>(DEVPKEY_Device_FriendlyName), pvprop.get());
207 if(FAILED(hr))
209 WARN("GetValue Device_FriendlyName failed: 0x%08lx\n", hr);
210 name += UnknownName;
212 else if(pvprop->vt == VT_LPWSTR)
213 name += wstr_to_utf8(pvprop->pwszVal);
214 else
216 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop->vt);
217 name += UnknownName;
220 pvprop.clear();
221 hr = ps->GetValue(reinterpret_cast<const PROPERTYKEY&>(PKEY_AudioEndpoint_GUID), pvprop.get());
222 if(FAILED(hr))
224 WARN("GetValue AudioEndpoint_GUID failed: 0x%08lx\n", hr);
225 guid = UnknownGuid;
227 else if(pvprop->vt == VT_LPWSTR)
228 guid = wstr_to_utf8(pvprop->pwszVal);
229 else
231 WARN("Unexpected PROPVARIANT type: 0x%04x\n", pvprop->vt);
232 guid = UnknownGuid;
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())};
242 if(FAILED(hr))
244 WARN("OpenPropertyStore failed: 0x%08lx\n", hr);
245 return UnknownFormFactor;
248 EndpointFormFactor formfactor{UnknownFormFactor};
249 PropVariant pvform;
250 hr = ps->GetValue(PKEY_AudioEndpoint_FormFactor, pvform.get());
251 if(FAILED(hr))
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);
257 return formfactor;
261 void add_device(IMMDevice *device, const WCHAR *devid, al::vector<DevMap> &list)
263 for(auto &entry : list)
265 if(entry.devid == devid)
266 return;
269 auto name_guid = get_device_name_and_guid(device);
271 int count{1};
272 std::string newname{name_guid.first};
273 while(checkName(list, newname))
275 newname = name_guid.first;
276 newname += " #";
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)
288 WCHAR *devid;
290 const HRESULT hr{device->GetId(&devid)};
291 if(FAILED(hr))
293 ERR("Failed to get device id: %lx\n", hr);
294 return nullptr;
297 return devid;
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())};
306 if(FAILED(hr))
308 ERR("Failed to enumerate audio endpoints: 0x%08lx\n", hr);
309 return;
312 UINT count{0};
313 hr = coll->GetCount(&count);
314 if(SUCCEEDED(hr) && count > 0)
315 list.reserve(count);
317 ComPtr<IMMDevice> device;
318 hr = devenum->GetDefaultAudioEndpoint(flowdir, eMultimedia, device.getPtr());
319 if(SUCCEEDED(hr))
321 if(WCHAR *devid{get_device_id(device.get())})
323 add_device(device.get(), devid, list);
324 CoTaskMemFree(devid);
326 device = nullptr;
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);
339 device = nullptr;
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)
354 out->Format = *in;
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;
361 else
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)
367 out->Format = *in;
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;
374 else
375 ERR("Unhandled IEEE float channel count: %d\n", out->Format.nChannels);
376 out->SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
378 else
380 ERR("Unhandled format tag: 0x%04x\n", in->wFormatTag);
381 return false;
383 return true;
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)};
393 TRACE("%s:\n"
394 " FormatTag = 0x%04x\n"
395 " Channels = %d\n"
396 " SamplesPerSec = %lu\n"
397 " AvgBytesPerSec = %lu\n"
398 " BlockAlign = %d\n"
399 " BitsPerSample = %d\n"
400 " Size = %d\n"
401 " Samples = %d\n"
402 " ChannelMask = 0x%lx\n"
403 " SubFormat = %s\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());
409 else
410 TRACE("%s:\n"
411 " FormatTag = 0x%04x\n"
412 " Channels = %d\n"
413 " SamplesPerSec = %lu\n"
414 " AvgBytesPerSec = %lu\n"
415 " BlockAlign = %d\n"
416 " BitsPerSample = %d\n"
417 " Size = %d\n",
418 msg, format->wFormatTag, format->nChannels, format->nSamplesPerSec,
419 format->nAvgBytesPerSec, format->nBlockAlign, format->wBitsPerSample, format->cbSize);
423 enum class MsgType {
424 OpenDevice,
425 ReopenDevice,
426 ResetDevice,
427 StartDevice,
428 StopDevice,
429 CloseDevice,
430 EnumeratePlayback,
431 EnumerateCapture,
433 Count,
434 QuitThread = Count
437 constexpr char MessageStr[static_cast<size_t>(MsgType::Count)][20]{
438 "Open Device",
439 "Reopen Device",
440 "Reset Device",
441 "Start Device",
442 "Stop Device",
443 "Close Device",
444 "Enumerate Playback",
445 "Enumerate Capture"
449 /* Proxy interface used by the message handler. */
450 struct WasapiProxy {
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;
460 struct Msg {
461 MsgType mType;
462 WasapiProxy *mProxy;
463 const char *mParam;
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();
481 return future;
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();
493 return future;
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();
502 return msg;
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)};
516 if(FAILED(cohr))
518 WARN("Failed to initialize COM: 0x%08lx\n", cohr);
519 promise->set_value(cohr);
520 return 0;
523 void *ptr{};
524 HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
525 IID_IMMDeviceEnumerator, &ptr)};
526 if(FAILED(hr))
528 WARN("Failed to create IMMDeviceEnumerator instance: 0x%08lx\n", hr);
529 promise->set_value(hr);
530 CoUninitialize();
531 return 0;
533 static_cast<IMMDeviceEnumerator*>(ptr)->Release();
534 CoUninitialize();
536 TRACE("Message thread initialization complete\n");
537 promise->set_value(S_OK);
538 promise = nullptr;
540 TRACE("Starting message loop\n");
541 uint deviceCount{0};
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));
548 switch(msg.mType)
550 case MsgType::OpenDevice:
551 hr = cohr = S_OK;
552 if(++deviceCount == 1)
553 hr = cohr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
554 if(SUCCEEDED(hr))
555 hr = msg.mProxy->openProxy(msg.mParam);
556 msg.mPromise.set_value(hr);
558 if(FAILED(hr))
560 if(--deviceCount == 0 && SUCCEEDED(cohr))
561 CoUninitialize();
563 continue;
565 case MsgType::ReopenDevice:
566 hr = msg.mProxy->openProxy(msg.mParam);
567 msg.mPromise.set_value(hr);
568 continue;
570 case MsgType::ResetDevice:
571 hr = msg.mProxy->resetProxy();
572 msg.mPromise.set_value(hr);
573 continue;
575 case MsgType::StartDevice:
576 hr = msg.mProxy->startProxy();
577 msg.mPromise.set_value(hr);
578 continue;
580 case MsgType::StopDevice:
581 msg.mProxy->stopProxy();
582 msg.mPromise.set_value(S_OK);
583 continue;
585 case MsgType::CloseDevice:
586 msg.mProxy->closeProxy();
587 msg.mPromise.set_value(S_OK);
589 if(--deviceCount == 0)
590 CoUninitialize();
591 continue;
593 case MsgType::EnumeratePlayback:
594 case MsgType::EnumerateCapture:
595 hr = cohr = S_OK;
596 if(++deviceCount == 1)
597 hr = cohr = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
598 if(SUCCEEDED(hr))
599 hr = CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
600 IID_IMMDeviceEnumerator, &ptr);
601 if(FAILED(hr))
602 msg.mPromise.set_value(hr);
603 else
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))
615 CoUninitialize();
616 continue;
618 case MsgType::QuitThread:
619 break;
621 ERR("Unexpected message: %u\n", static_cast<uint>(msg.mType));
622 msg.mPromise.set_value(E_FAIL);
624 TRACE("Message loop finished\n");
626 return 0;
630 struct WasapiPlayback final : public BackendBase, WasapiProxy {
631 WasapiPlayback(DeviceBase *device) noexcept : BackendBase{device} { }
632 ~WasapiPlayback() override;
634 int mixerProc();
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};
658 std::mutex mMutex;
660 std::atomic<bool> mKillNow{true};
661 std::thread mThread;
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)};
681 if(FAILED(hr))
683 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr);
684 mDevice->handleDisconnect("COM init failed: 0x%08lx", hr);
685 return 1;
688 SetRTPriority();
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))
695 UINT32 written;
696 hr = mClient->GetCurrentPadding(&written);
697 if(FAILED(hr))
699 ERR("Failed to get padding: 0x%08lx\n", hr);
700 mDevice->handleDisconnect("Failed to retrieve buffer padding: 0x%08lx", hr);
701 break;
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);
711 continue;
714 BYTE *buffer;
715 hr = mRender->GetBuffer(len, &buffer);
716 if(SUCCEEDED(hr))
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);
725 if(FAILED(hr))
727 ERR("Failed to buffer data: 0x%08lx\n", hr);
728 mDevice->handleDisconnect("Failed to send playback samples: 0x%08lx", hr);
729 break;
732 mPadding.store(0u, std::memory_order_release);
734 CoUninitialize();
735 return 0;
739 void WasapiPlayback::open(const char *name)
741 HRESULT hr{S_OK};
743 if(!mNotifyEvent)
745 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
746 if(mNotifyEvent == nullptr)
748 ERR("Failed to create notify events: %lu\n", GetLastError());
749 hr = E_FAIL;
753 if(SUCCEEDED(hr))
755 if(name)
757 if(PlaybackDevices.empty())
758 pushMessage(MsgType::EnumeratePlayback);
759 if(std::strncmp(name, DevNameHead, DevNameHeadLen) == 0)
761 name += DevNameHeadLen;
762 if(*name == '\0')
763 name = nullptr;
767 if(SUCCEEDED(mOpenStatus))
768 hr = pushMessage(MsgType::ReopenDevice, name).get();
769 else
771 hr = pushMessage(MsgType::OpenDevice, name).get();
772 mOpenStatus = hr;
776 if(FAILED(hr))
777 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
778 hr};
781 HRESULT WasapiPlayback::openProxy(const char *name)
783 const wchar_t *devid{nullptr};
784 if(name)
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);
799 return E_FAIL;
801 name = iter->name.c_str();
802 devid = iter->devid.c_str();
805 void *ptr;
806 ComPtr<IMMDevice> mmdev;
807 HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
808 IID_IMMDeviceEnumerator, &ptr)};
809 if(SUCCEEDED(hr))
811 ComPtr<IMMDeviceEnumerator> enumerator{static_cast<IMMDeviceEnumerator*>(ptr)};
812 if(!devid)
813 hr = enumerator->GetDefaultAudioEndpoint(eRender, eMultimedia, mmdev.getPtr());
814 else
815 hr = enumerator->GetDevice(devid, mmdev.getPtr());
817 if(FAILED(hr))
819 WARN("Failed to open device \"%s\"\n", name?name:"(default)");
820 return hr;
823 mClient = nullptr;
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;
828 return hr;
831 void WasapiPlayback::closeProxy()
833 mClient = nullptr;
834 mMMDev = nullptr;
838 bool WasapiPlayback::reset()
840 HRESULT hr{pushMessage(MsgType::ResetDevice).get()};
841 if(FAILED(hr))
842 throw al::backend_exception{al::backend_error::DeviceError, "0x%08lx", hr};
843 return true;
846 HRESULT WasapiPlayback::resetProxy()
848 mClient = nullptr;
850 void *ptr;
851 HRESULT hr{mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr)};
852 if(FAILED(hr))
854 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
855 return hr;
857 mClient = ComPtr<IAudioClient>{static_cast<IAudioClient*>(ptr)};
859 WAVEFORMATEX *wfx;
860 hr = mClient->GetMixFormat(&wfx);
861 if(FAILED(hr))
863 ERR("Failed to get mix format: 0x%08lx\n", hr);
864 return hr;
867 WAVEFORMATEXTENSIBLE OutputType;
868 if(!MakeExtensible(&OutputType, wfx))
870 CoTaskMemFree(wfx);
871 return E_FAIL;
873 CoTaskMemFree(wfx);
874 wfx = nullptr;
876 const ReferenceTime per_time{ReferenceTime{seconds{mDevice->UpdateSize}} / mDevice->Frequency};
877 const ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
879 if(!mDevice->Flags.test(FrequencyRequest))
880 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
881 if(!mDevice->Flags.test(ChannelsRequest))
883 const uint32_t chancount{OutputType.Format.nChannels};
884 const DWORD chanmask{OutputType.dwChannelMask};
885 if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
886 mDevice->FmtChans = DevFmtX71;
887 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
888 mDevice->FmtChans = DevFmtX61;
889 else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
890 || (chanmask&X51RearMask) == X5DOT1REAR))
891 mDevice->FmtChans = DevFmtX51;
892 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
893 mDevice->FmtChans = DevFmtQuad;
894 else if(chancount >= 2 && (chanmask&StereoMask) == STEREO)
895 mDevice->FmtChans = DevFmtStereo;
896 else if(chancount >= 1 && (chanmask&MonoMask) == MONO)
897 mDevice->FmtChans = DevFmtMono;
898 else
899 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask);
902 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
903 switch(mDevice->FmtChans)
905 case DevFmtMono:
906 OutputType.Format.nChannels = 1;
907 OutputType.dwChannelMask = MONO;
908 break;
909 case DevFmtAmbi3D:
910 mDevice->FmtChans = DevFmtStereo;
911 /*fall-through*/
912 case DevFmtStereo:
913 OutputType.Format.nChannels = 2;
914 OutputType.dwChannelMask = STEREO;
915 break;
916 case DevFmtQuad:
917 OutputType.Format.nChannels = 4;
918 OutputType.dwChannelMask = QUAD;
919 break;
920 case DevFmtX51:
921 OutputType.Format.nChannels = 6;
922 OutputType.dwChannelMask = X5DOT1;
923 break;
924 case DevFmtX61:
925 OutputType.Format.nChannels = 7;
926 OutputType.dwChannelMask = X6DOT1;
927 break;
928 case DevFmtX71:
929 OutputType.Format.nChannels = 8;
930 OutputType.dwChannelMask = X7DOT1;
931 break;
933 switch(mDevice->FmtType)
935 case DevFmtByte:
936 mDevice->FmtType = DevFmtUByte;
937 /* fall-through */
938 case DevFmtUByte:
939 OutputType.Format.wBitsPerSample = 8;
940 OutputType.Samples.wValidBitsPerSample = 8;
941 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
942 break;
943 case DevFmtUShort:
944 mDevice->FmtType = DevFmtShort;
945 /* fall-through */
946 case DevFmtShort:
947 OutputType.Format.wBitsPerSample = 16;
948 OutputType.Samples.wValidBitsPerSample = 16;
949 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
950 break;
951 case DevFmtUInt:
952 mDevice->FmtType = DevFmtInt;
953 /* fall-through */
954 case DevFmtInt:
955 OutputType.Format.wBitsPerSample = 32;
956 OutputType.Samples.wValidBitsPerSample = 32;
957 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
958 break;
959 case DevFmtFloat:
960 OutputType.Format.wBitsPerSample = 32;
961 OutputType.Samples.wValidBitsPerSample = 32;
962 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
963 break;
965 OutputType.Format.nSamplesPerSec = mDevice->Frequency;
967 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
968 OutputType.Format.wBitsPerSample / 8);
969 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
970 OutputType.Format.nBlockAlign;
972 TraceFormat("Requesting playback format", &OutputType.Format);
973 hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
974 if(FAILED(hr))
976 ERR("Failed to check format support: 0x%08lx\n", hr);
977 hr = mClient->GetMixFormat(&wfx);
979 if(FAILED(hr))
981 ERR("Failed to find a supported format: 0x%08lx\n", hr);
982 return hr;
985 if(wfx != nullptr)
987 TraceFormat("Got playback format", wfx);
988 if(!MakeExtensible(&OutputType, wfx))
990 CoTaskMemFree(wfx);
991 return E_FAIL;
993 CoTaskMemFree(wfx);
994 wfx = nullptr;
996 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
997 const uint32_t chancount{OutputType.Format.nChannels};
998 const DWORD chanmask{OutputType.dwChannelMask};
999 /* Don't update the channel format if the requested format fits what's
1000 * supported.
1002 bool chansok{false};
1003 if(mDevice->Flags.test(ChannelsRequest))
1005 switch(mDevice->FmtChans)
1007 case DevFmtMono:
1008 chansok = (chancount >= 1 && (chanmask&MonoMask) == MONO);
1009 break;
1010 case DevFmtStereo:
1011 chansok = (chancount >= 2 && (chanmask&StereoMask) == STEREO);
1012 break;
1013 case DevFmtQuad:
1014 chansok = (chancount >= 4 && (chanmask&QuadMask) == QUAD);
1015 break;
1016 case DevFmtX51:
1017 chansok = (chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1018 || (chanmask&X51RearMask) == X5DOT1REAR));
1019 break;
1020 case DevFmtX61:
1021 chansok = (chancount >= 7 && (chanmask&X61Mask) == X6DOT1);
1022 break;
1023 case DevFmtX71:
1024 chansok = (chancount >= 8 && (chanmask&X71Mask) == X7DOT1);
1025 break;
1026 case DevFmtAmbi3D:
1027 break;
1030 if(!chansok)
1032 if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1033 mDevice->FmtChans = DevFmtX71;
1034 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1035 mDevice->FmtChans = DevFmtX61;
1036 else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1037 || (chanmask&X51RearMask) == X5DOT1REAR))
1038 mDevice->FmtChans = DevFmtX51;
1039 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1040 mDevice->FmtChans = DevFmtQuad;
1041 else if(chancount >= 2 && (chanmask&StereoMask) == STEREO)
1042 mDevice->FmtChans = DevFmtStereo;
1043 else if(chancount >= 1 && (chanmask&MonoMask) == MONO)
1044 mDevice->FmtChans = DevFmtMono;
1045 else
1047 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1048 OutputType.dwChannelMask);
1049 mDevice->FmtChans = DevFmtStereo;
1050 OutputType.Format.nChannels = 2;
1051 OutputType.dwChannelMask = STEREO;
1055 if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
1057 if(OutputType.Format.wBitsPerSample == 8)
1058 mDevice->FmtType = DevFmtUByte;
1059 else if(OutputType.Format.wBitsPerSample == 16)
1060 mDevice->FmtType = DevFmtShort;
1061 else if(OutputType.Format.wBitsPerSample == 32)
1062 mDevice->FmtType = DevFmtInt;
1063 else
1065 mDevice->FmtType = DevFmtShort;
1066 OutputType.Format.wBitsPerSample = 16;
1069 else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1071 mDevice->FmtType = DevFmtFloat;
1072 OutputType.Format.wBitsPerSample = 32;
1074 else
1076 ERR("Unhandled format sub-type: %s\n", GuidPrinter{OutputType.SubFormat}.c_str());
1077 mDevice->FmtType = DevFmtShort;
1078 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
1079 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
1080 OutputType.Format.wBitsPerSample = 16;
1081 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1083 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1085 mFrameStep = OutputType.Format.nChannels;
1087 const EndpointFormFactor formfactor{get_device_formfactor(mMMDev.get())};
1088 mDevice->Flags.set(DirectEar, (formfactor == Headphones || formfactor == Headset));
1090 setChannelOrderFromWFXMask(OutputType.dwChannelMask);
1092 hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
1093 buf_time.count(), 0, &OutputType.Format, nullptr);
1094 if(FAILED(hr))
1096 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
1097 return hr;
1100 UINT32 buffer_len{};
1101 ReferenceTime min_per{};
1102 hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
1103 if(SUCCEEDED(hr))
1104 hr = mClient->GetBufferSize(&buffer_len);
1105 if(FAILED(hr))
1107 ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
1108 return hr;
1111 /* Find the nearest multiple of the period size to the update size */
1112 if(min_per < per_time)
1113 min_per *= maxi64((per_time + min_per/2) / min_per, 1);
1114 mDevice->UpdateSize = minu(RefTime2Samples(min_per, mDevice->Frequency), buffer_len/2);
1115 mDevice->BufferSize = buffer_len;
1117 hr = mClient->SetEventHandle(mNotifyEvent);
1118 if(FAILED(hr))
1120 ERR("Failed to set event handle: 0x%08lx\n", hr);
1121 return hr;
1124 return hr;
1128 void WasapiPlayback::start()
1130 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
1131 if(FAILED(hr))
1132 throw al::backend_exception{al::backend_error::DeviceError,
1133 "Failed to start playback: 0x%lx", hr};
1136 HRESULT WasapiPlayback::startProxy()
1138 ResetEvent(mNotifyEvent);
1140 HRESULT hr{mClient->Start()};
1141 if(FAILED(hr))
1143 ERR("Failed to start audio client: 0x%08lx\n", hr);
1144 return hr;
1147 void *ptr;
1148 hr = mClient->GetService(IID_IAudioRenderClient, &ptr);
1149 if(SUCCEEDED(hr))
1151 mRender = ComPtr<IAudioRenderClient>{static_cast<IAudioRenderClient*>(ptr)};
1152 try {
1153 mKillNow.store(false, std::memory_order_release);
1154 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerProc), this};
1156 catch(...) {
1157 mRender = nullptr;
1158 ERR("Failed to start thread\n");
1159 hr = E_FAIL;
1163 if(FAILED(hr))
1164 mClient->Stop();
1166 return hr;
1170 void WasapiPlayback::stop()
1171 { pushMessage(MsgType::StopDevice).wait(); }
1173 void WasapiPlayback::stopProxy()
1175 if(!mRender || !mThread.joinable())
1176 return;
1178 mKillNow.store(true, std::memory_order_release);
1179 mThread.join();
1181 mRender = nullptr;
1182 mClient->Stop();
1186 ClockLatency WasapiPlayback::getClockLatency()
1188 ClockLatency ret;
1190 std::lock_guard<std::mutex> _{mMutex};
1191 ret.ClockTime = GetDeviceClockTime(mDevice);
1192 ret.Latency = std::chrono::seconds{mPadding.load(std::memory_order_relaxed)};
1193 ret.Latency /= mDevice->Frequency;
1195 return ret;
1199 struct WasapiCapture final : public BackendBase, WasapiProxy {
1200 WasapiCapture(DeviceBase *device) noexcept : BackendBase{device} { }
1201 ~WasapiCapture() override;
1203 int recordProc();
1205 void open(const char *name) override;
1206 HRESULT openProxy(const char *name) override;
1207 void closeProxy() override;
1209 HRESULT resetProxy() override;
1210 void start() override;
1211 HRESULT startProxy() override;
1212 void stop() override;
1213 void stopProxy() override;
1215 void captureSamples(al::byte *buffer, uint samples) override;
1216 uint availableSamples() override;
1218 HRESULT mOpenStatus{E_FAIL};
1219 ComPtr<IMMDevice> mMMDev{nullptr};
1220 ComPtr<IAudioClient> mClient{nullptr};
1221 ComPtr<IAudioCaptureClient> mCapture{nullptr};
1222 HANDLE mNotifyEvent{nullptr};
1224 ChannelConverter mChannelConv{};
1225 SampleConverterPtr mSampleConv;
1226 RingBufferPtr mRing;
1228 std::atomic<bool> mKillNow{true};
1229 std::thread mThread;
1231 DEF_NEWDEL(WasapiCapture)
1234 WasapiCapture::~WasapiCapture()
1236 if(SUCCEEDED(mOpenStatus))
1237 pushMessage(MsgType::CloseDevice).wait();
1238 mOpenStatus = E_FAIL;
1240 if(mNotifyEvent != nullptr)
1241 CloseHandle(mNotifyEvent);
1242 mNotifyEvent = nullptr;
1246 FORCE_ALIGN int WasapiCapture::recordProc()
1248 HRESULT hr{CoInitializeEx(nullptr, COINIT_MULTITHREADED)};
1249 if(FAILED(hr))
1251 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr);
1252 mDevice->handleDisconnect("COM init failed: 0x%08lx", hr);
1253 return 1;
1256 althrd_setname(RECORD_THREAD_NAME);
1258 al::vector<float> samples;
1259 while(!mKillNow.load(std::memory_order_relaxed))
1261 UINT32 avail;
1262 hr = mCapture->GetNextPacketSize(&avail);
1263 if(FAILED(hr))
1264 ERR("Failed to get next packet size: 0x%08lx\n", hr);
1265 else if(avail > 0)
1267 UINT32 numsamples;
1268 DWORD flags;
1269 BYTE *rdata;
1271 hr = mCapture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
1272 if(FAILED(hr))
1273 ERR("Failed to get capture buffer: 0x%08lx\n", hr);
1274 else
1276 if(mChannelConv.is_active())
1278 samples.resize(numsamples*2);
1279 mChannelConv.convert(rdata, samples.data(), numsamples);
1280 rdata = reinterpret_cast<BYTE*>(samples.data());
1283 auto data = mRing->getWriteVector();
1285 size_t dstframes;
1286 if(mSampleConv)
1288 const void *srcdata{rdata};
1289 uint srcframes{numsamples};
1291 dstframes = mSampleConv->convert(&srcdata, &srcframes, data.first.buf,
1292 static_cast<uint>(minz(data.first.len, INT_MAX)));
1293 if(srcframes > 0 && dstframes == data.first.len && data.second.len > 0)
1295 /* If some source samples remain, all of the first dest
1296 * block was filled, and there's space in the second
1297 * dest block, do another run for the second block.
1299 dstframes += mSampleConv->convert(&srcdata, &srcframes, data.second.buf,
1300 static_cast<uint>(minz(data.second.len, INT_MAX)));
1303 else
1305 const uint framesize{mDevice->frameSizeFromFmt()};
1306 size_t len1{minz(data.first.len, numsamples)};
1307 size_t len2{minz(data.second.len, numsamples-len1)};
1309 memcpy(data.first.buf, rdata, len1*framesize);
1310 if(len2 > 0)
1311 memcpy(data.second.buf, rdata+len1*framesize, len2*framesize);
1312 dstframes = len1 + len2;
1315 mRing->writeAdvance(dstframes);
1317 hr = mCapture->ReleaseBuffer(numsamples);
1318 if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
1322 if(FAILED(hr))
1324 mDevice->handleDisconnect("Failed to capture samples: 0x%08lx", hr);
1325 break;
1328 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
1329 if(res != WAIT_OBJECT_0)
1330 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1333 CoUninitialize();
1334 return 0;
1338 void WasapiCapture::open(const char *name)
1340 HRESULT hr{S_OK};
1342 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1343 if(mNotifyEvent == nullptr)
1345 ERR("Failed to create notify event: %lu\n", GetLastError());
1346 hr = E_FAIL;
1349 if(SUCCEEDED(hr))
1351 if(name)
1353 if(CaptureDevices.empty())
1354 pushMessage(MsgType::EnumerateCapture);
1355 if(std::strncmp(name, DevNameHead, DevNameHeadLen) == 0)
1357 name += DevNameHeadLen;
1358 if(*name == '\0')
1359 name = nullptr;
1362 hr = pushMessage(MsgType::OpenDevice, name).get();
1364 mOpenStatus = hr;
1366 if(FAILED(hr))
1367 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
1368 hr};
1370 hr = pushMessage(MsgType::ResetDevice).get();
1371 if(FAILED(hr))
1373 if(hr == E_OUTOFMEMORY)
1374 throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"};
1375 throw al::backend_exception{al::backend_error::DeviceError, "Device reset failed"};
1379 HRESULT WasapiCapture::openProxy(const char *name)
1381 const wchar_t *devid{nullptr};
1382 if(name)
1384 auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
1385 [name](const DevMap &entry) -> bool
1386 { return entry.name == name || entry.endpoint_guid == name; });
1387 if(iter == CaptureDevices.cend())
1389 const std::wstring wname{utf8_to_wstr(name)};
1390 iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
1391 [&wname](const DevMap &entry) -> bool
1392 { return entry.devid == wname; });
1394 if(iter == CaptureDevices.cend())
1396 WARN("Failed to find device name matching \"%s\"\n", name);
1397 return E_FAIL;
1399 name = iter->name.c_str();
1400 devid = iter->devid.c_str();
1403 void *ptr;
1404 HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
1405 IID_IMMDeviceEnumerator, &ptr)};
1406 if(SUCCEEDED(hr))
1408 ComPtr<IMMDeviceEnumerator> enumerator{static_cast<IMMDeviceEnumerator*>(ptr)};
1409 if(!devid)
1410 hr = enumerator->GetDefaultAudioEndpoint(eCapture, eMultimedia, mMMDev.getPtr());
1411 else
1412 hr = enumerator->GetDevice(devid, mMMDev.getPtr());
1414 if(FAILED(hr))
1416 WARN("Failed to open device \"%s\"\n", name?name:"(default)");
1417 return hr;
1420 mClient = nullptr;
1421 if(name) mDevice->DeviceName = std::string{DevNameHead} + name;
1422 else mDevice->DeviceName = DevNameHead + get_device_name_and_guid(mMMDev.get()).first;
1424 return hr;
1427 void WasapiCapture::closeProxy()
1429 mClient = nullptr;
1430 mMMDev = nullptr;
1433 HRESULT WasapiCapture::resetProxy()
1435 mClient = nullptr;
1437 void *ptr;
1438 HRESULT hr{mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr)};
1439 if(FAILED(hr))
1441 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
1442 return hr;
1444 mClient = ComPtr<IAudioClient>{static_cast<IAudioClient*>(ptr)};
1446 // Make sure buffer is at least 100ms in size
1447 ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
1448 buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}});
1450 WAVEFORMATEXTENSIBLE InputType{};
1451 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1452 switch(mDevice->FmtChans)
1454 case DevFmtMono:
1455 InputType.Format.nChannels = 1;
1456 InputType.dwChannelMask = MONO;
1457 break;
1458 case DevFmtStereo:
1459 InputType.Format.nChannels = 2;
1460 InputType.dwChannelMask = STEREO;
1461 break;
1462 case DevFmtQuad:
1463 InputType.Format.nChannels = 4;
1464 InputType.dwChannelMask = QUAD;
1465 break;
1466 case DevFmtX51:
1467 InputType.Format.nChannels = 6;
1468 InputType.dwChannelMask = X5DOT1;
1469 break;
1470 case DevFmtX61:
1471 InputType.Format.nChannels = 7;
1472 InputType.dwChannelMask = X6DOT1;
1473 break;
1474 case DevFmtX71:
1475 InputType.Format.nChannels = 8;
1476 InputType.dwChannelMask = X7DOT1;
1477 break;
1479 case DevFmtAmbi3D:
1480 return E_FAIL;
1482 switch(mDevice->FmtType)
1484 /* NOTE: Signedness doesn't matter, the converter will handle it. */
1485 case DevFmtByte:
1486 case DevFmtUByte:
1487 InputType.Format.wBitsPerSample = 8;
1488 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1489 break;
1490 case DevFmtShort:
1491 case DevFmtUShort:
1492 InputType.Format.wBitsPerSample = 16;
1493 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1494 break;
1495 case DevFmtInt:
1496 case DevFmtUInt:
1497 InputType.Format.wBitsPerSample = 32;
1498 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1499 break;
1500 case DevFmtFloat:
1501 InputType.Format.wBitsPerSample = 32;
1502 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1503 break;
1505 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
1506 InputType.Format.nSamplesPerSec = mDevice->Frequency;
1508 InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
1509 InputType.Format.wBitsPerSample / 8);
1510 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
1511 InputType.Format.nBlockAlign;
1512 InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format);
1514 TraceFormat("Requesting capture format", &InputType.Format);
1515 WAVEFORMATEX *wfx;
1516 hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, &wfx);
1517 if(FAILED(hr))
1519 ERR("Failed to check format support: 0x%08lx\n", hr);
1520 return hr;
1523 mSampleConv = nullptr;
1524 mChannelConv = {};
1526 if(wfx != nullptr)
1528 TraceFormat("Got capture format", wfx);
1529 if(!MakeExtensible(&InputType, wfx))
1531 CoTaskMemFree(wfx);
1532 return E_FAIL;
1534 CoTaskMemFree(wfx);
1535 wfx = nullptr;
1537 auto validate_fmt = [](DeviceBase *device, uint32_t chancount, DWORD chanmask) noexcept
1538 -> bool
1540 switch(device->FmtChans)
1542 /* If the device wants mono, we can handle any input. */
1543 case DevFmtMono:
1544 return true;
1545 /* If the device wants stereo, we can handle mono or stereo input. */
1546 case DevFmtStereo:
1547 return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO))
1548 || (chancount == 1 && (chanmask&MonoMask) == MONO);
1549 /* Otherwise, the device must match the input type. */
1550 case DevFmtQuad:
1551 return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD));
1552 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
1553 case DevFmtX51:
1554 return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1
1555 || (chanmask&X51RearMask) == X5DOT1REAR));
1556 case DevFmtX61:
1557 return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1));
1558 case DevFmtX71:
1559 return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1));
1560 case DevFmtAmbi3D:
1561 return (chanmask == 0 && chancount == device->channelsFromFmt());
1563 return false;
1565 if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask))
1567 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
1568 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1569 mDevice->Frequency, InputType.dwChannelMask, InputType.Format.nChannels,
1570 (InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample,
1571 InputType.Format.nSamplesPerSec);
1572 return E_FAIL;
1576 DevFmtType srcType{};
1577 if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
1579 if(InputType.Format.wBitsPerSample == 8)
1580 srcType = DevFmtUByte;
1581 else if(InputType.Format.wBitsPerSample == 16)
1582 srcType = DevFmtShort;
1583 else if(InputType.Format.wBitsPerSample == 32)
1584 srcType = DevFmtInt;
1585 else
1587 ERR("Unhandled integer bit depth: %d\n", InputType.Format.wBitsPerSample);
1588 return E_FAIL;
1591 else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1593 if(InputType.Format.wBitsPerSample == 32)
1594 srcType = DevFmtFloat;
1595 else
1597 ERR("Unhandled float bit depth: %d\n", InputType.Format.wBitsPerSample);
1598 return E_FAIL;
1601 else
1603 ERR("Unhandled format sub-type: %s\n", GuidPrinter{InputType.SubFormat}.c_str());
1604 return E_FAIL;
1607 if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1)
1609 uint chanmask{(1u<<InputType.Format.nChannels) - 1u};
1610 /* Exclude LFE from the downmix. */
1611 if((InputType.dwChannelMask&SPEAKER_LOW_FREQUENCY))
1613 constexpr auto lfemask = MaskFromTopBits(SPEAKER_LOW_FREQUENCY);
1614 const int lfeidx{al::popcount(InputType.dwChannelMask&lfemask) - 1};
1615 chanmask &= ~(1u << lfeidx);
1618 mChannelConv = ChannelConverter{srcType, InputType.Format.nChannels, chanmask,
1619 mDevice->FmtChans};
1620 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType));
1621 /* The channel converter always outputs float, so change the input type
1622 * for the resampler/type-converter.
1624 srcType = DevFmtFloat;
1626 else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1)
1628 mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans};
1629 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
1630 srcType = DevFmtFloat;
1633 if(mDevice->Frequency != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType)
1635 mSampleConv = CreateSampleConverter(srcType, mDevice->FmtType, mDevice->channelsFromFmt(),
1636 InputType.Format.nSamplesPerSec, mDevice->Frequency, Resampler::FastBSinc24);
1637 if(!mSampleConv)
1639 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1640 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1641 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
1642 return E_FAIL;
1644 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1645 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1646 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
1649 hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
1650 buf_time.count(), 0, &InputType.Format, nullptr);
1651 if(FAILED(hr))
1653 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
1654 return hr;
1657 UINT32 buffer_len{};
1658 ReferenceTime min_per{};
1659 hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
1660 if(SUCCEEDED(hr))
1661 hr = mClient->GetBufferSize(&buffer_len);
1662 if(FAILED(hr))
1664 ERR("Failed to get buffer size: 0x%08lx\n", hr);
1665 return hr;
1667 mDevice->UpdateSize = RefTime2Samples(min_per, mDevice->Frequency);
1668 mDevice->BufferSize = buffer_len;
1670 mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false);
1672 hr = mClient->SetEventHandle(mNotifyEvent);
1673 if(FAILED(hr))
1675 ERR("Failed to set event handle: 0x%08lx\n", hr);
1676 return hr;
1679 return hr;
1683 void WasapiCapture::start()
1685 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
1686 if(FAILED(hr))
1687 throw al::backend_exception{al::backend_error::DeviceError,
1688 "Failed to start recording: 0x%lx", hr};
1691 HRESULT WasapiCapture::startProxy()
1693 ResetEvent(mNotifyEvent);
1695 HRESULT hr{mClient->Start()};
1696 if(FAILED(hr))
1698 ERR("Failed to start audio client: 0x%08lx\n", hr);
1699 return hr;
1702 void *ptr;
1703 hr = mClient->GetService(IID_IAudioCaptureClient, &ptr);
1704 if(SUCCEEDED(hr))
1706 mCapture = ComPtr<IAudioCaptureClient>{static_cast<IAudioCaptureClient*>(ptr)};
1707 try {
1708 mKillNow.store(false, std::memory_order_release);
1709 mThread = std::thread{std::mem_fn(&WasapiCapture::recordProc), this};
1711 catch(...) {
1712 mCapture = nullptr;
1713 ERR("Failed to start thread\n");
1714 hr = E_FAIL;
1718 if(FAILED(hr))
1720 mClient->Stop();
1721 mClient->Reset();
1724 return hr;
1728 void WasapiCapture::stop()
1729 { pushMessage(MsgType::StopDevice).wait(); }
1731 void WasapiCapture::stopProxy()
1733 if(!mCapture || !mThread.joinable())
1734 return;
1736 mKillNow.store(true, std::memory_order_release);
1737 mThread.join();
1739 mCapture = nullptr;
1740 mClient->Stop();
1741 mClient->Reset();
1745 void WasapiCapture::captureSamples(al::byte *buffer, uint samples)
1746 { mRing->read(buffer, samples); }
1748 uint WasapiCapture::availableSamples()
1749 { return static_cast<uint>(mRing->readSpace()); }
1751 } // namespace
1754 bool WasapiBackendFactory::init()
1756 static HRESULT InitResult{E_FAIL};
1758 if(FAILED(InitResult)) try
1760 std::promise<HRESULT> promise;
1761 auto future = promise.get_future();
1763 std::thread{&WasapiProxy::messageHandler, &promise}.detach();
1764 InitResult = future.get();
1766 catch(...) {
1769 return SUCCEEDED(InitResult);
1772 bool WasapiBackendFactory::querySupport(BackendType type)
1773 { return type == BackendType::Playback || type == BackendType::Capture; }
1775 std::string WasapiBackendFactory::probe(BackendType type)
1777 std::string outnames;
1778 switch(type)
1780 case BackendType::Playback:
1781 WasapiProxy::pushMessageStatic(MsgType::EnumeratePlayback).wait();
1782 for(const DevMap &entry : PlaybackDevices)
1784 /* +1 to also append the null char (to ensure a null-separated list
1785 * and double-null terminated list).
1787 outnames.append(DevNameHead).append(entry.name.c_str(), entry.name.length()+1);
1789 break;
1791 case BackendType::Capture:
1792 WasapiProxy::pushMessageStatic(MsgType::EnumerateCapture).wait();
1793 for(const DevMap &entry : CaptureDevices)
1794 outnames.append(DevNameHead).append(entry.name.c_str(), entry.name.length()+1);
1795 break;
1798 return outnames;
1801 BackendPtr WasapiBackendFactory::createBackend(DeviceBase *device, BackendType type)
1803 if(type == BackendType::Playback)
1804 return BackendPtr{new WasapiPlayback{device}};
1805 if(type == BackendType::Capture)
1806 return BackendPtr{new WasapiCapture{device}};
1807 return nullptr;
1810 BackendFactory &WasapiBackendFactory::getFactory()
1812 static WasapiBackendFactory factory{};
1813 return factory;