Track 5.1 Rear with WASAPI playback
[openal-soft.git] / alc / backends / wasapi.cpp
blob9a51485aae4797872501161c00c7a3cc7cd14b06
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};
878 bool isRear51{false};
880 if(!mDevice->Flags.test(FrequencyRequest))
881 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
882 if(!mDevice->Flags.test(ChannelsRequest))
884 const uint32_t chancount{OutputType.Format.nChannels};
885 const DWORD chanmask{OutputType.dwChannelMask};
886 if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
887 mDevice->FmtChans = DevFmtX71;
888 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
889 mDevice->FmtChans = DevFmtX61;
890 else if(chancount >= 6 && (chanmask&X51Mask) == X5DOT1)
891 mDevice->FmtChans = DevFmtX51;
892 else if(chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR)
894 mDevice->FmtChans = DevFmtX51;
895 isRear51 = true;
897 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
898 mDevice->FmtChans = DevFmtQuad;
899 else if(chancount >= 2 && (chanmask&StereoMask) == STEREO)
900 mDevice->FmtChans = DevFmtStereo;
901 else if(chancount >= 1 && (chanmask&MonoMask) == MONO)
902 mDevice->FmtChans = DevFmtMono;
903 else
904 ERR("Unhandled channel config: %d -- 0x%08lx\n", chancount, chanmask);
906 else
908 const uint32_t chancount{OutputType.Format.nChannels};
909 const DWORD chanmask{OutputType.dwChannelMask};
910 isRear51 = (chancount >= 6 && (chanmask&X51RearMask) == X5DOT1REAR);
913 OutputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
914 switch(mDevice->FmtChans)
916 case DevFmtMono:
917 OutputType.Format.nChannels = 1;
918 OutputType.dwChannelMask = MONO;
919 break;
920 case DevFmtAmbi3D:
921 mDevice->FmtChans = DevFmtStereo;
922 /*fall-through*/
923 case DevFmtStereo:
924 OutputType.Format.nChannels = 2;
925 OutputType.dwChannelMask = STEREO;
926 break;
927 case DevFmtQuad:
928 OutputType.Format.nChannels = 4;
929 OutputType.dwChannelMask = QUAD;
930 break;
931 case DevFmtX51:
932 OutputType.Format.nChannels = 6;
933 OutputType.dwChannelMask = isRear51 ? X5DOT1REAR : X5DOT1;
934 break;
935 case DevFmtX61:
936 OutputType.Format.nChannels = 7;
937 OutputType.dwChannelMask = X6DOT1;
938 break;
939 case DevFmtX71:
940 case DevFmtX3D71:
941 OutputType.Format.nChannels = 8;
942 OutputType.dwChannelMask = X7DOT1;
943 break;
945 switch(mDevice->FmtType)
947 case DevFmtByte:
948 mDevice->FmtType = DevFmtUByte;
949 /* fall-through */
950 case DevFmtUByte:
951 OutputType.Format.wBitsPerSample = 8;
952 OutputType.Samples.wValidBitsPerSample = 8;
953 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
954 break;
955 case DevFmtUShort:
956 mDevice->FmtType = DevFmtShort;
957 /* fall-through */
958 case DevFmtShort:
959 OutputType.Format.wBitsPerSample = 16;
960 OutputType.Samples.wValidBitsPerSample = 16;
961 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
962 break;
963 case DevFmtUInt:
964 mDevice->FmtType = DevFmtInt;
965 /* fall-through */
966 case DevFmtInt:
967 OutputType.Format.wBitsPerSample = 32;
968 OutputType.Samples.wValidBitsPerSample = 32;
969 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
970 break;
971 case DevFmtFloat:
972 OutputType.Format.wBitsPerSample = 32;
973 OutputType.Samples.wValidBitsPerSample = 32;
974 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
975 break;
977 OutputType.Format.nSamplesPerSec = mDevice->Frequency;
979 OutputType.Format.nBlockAlign = static_cast<WORD>(OutputType.Format.nChannels *
980 OutputType.Format.wBitsPerSample / 8);
981 OutputType.Format.nAvgBytesPerSec = OutputType.Format.nSamplesPerSec *
982 OutputType.Format.nBlockAlign;
984 TraceFormat("Requesting playback format", &OutputType.Format);
985 hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &OutputType.Format, &wfx);
986 if(FAILED(hr))
988 ERR("Failed to check format support: 0x%08lx\n", hr);
989 hr = mClient->GetMixFormat(&wfx);
991 if(FAILED(hr))
993 ERR("Failed to find a supported format: 0x%08lx\n", hr);
994 return hr;
997 if(wfx != nullptr)
999 TraceFormat("Got playback format", wfx);
1000 if(!MakeExtensible(&OutputType, wfx))
1002 CoTaskMemFree(wfx);
1003 return E_FAIL;
1005 CoTaskMemFree(wfx);
1006 wfx = nullptr;
1008 mDevice->Frequency = OutputType.Format.nSamplesPerSec;
1009 const uint32_t chancount{OutputType.Format.nChannels};
1010 const DWORD chanmask{OutputType.dwChannelMask};
1011 /* Don't update the channel format if the requested format fits what's
1012 * supported.
1014 bool chansok{false};
1015 if(mDevice->Flags.test(ChannelsRequest))
1017 switch(mDevice->FmtChans)
1019 case DevFmtMono:
1020 chansok = (chancount >= 1 && (chanmask&MonoMask) == MONO);
1021 break;
1022 case DevFmtStereo:
1023 chansok = (chancount >= 2 && (chanmask&StereoMask) == STEREO);
1024 break;
1025 case DevFmtQuad:
1026 chansok = (chancount >= 4 && (chanmask&QuadMask) == QUAD);
1027 break;
1028 case DevFmtX51:
1029 chansok = (chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1030 || (chanmask&X51RearMask) == X5DOT1REAR));
1031 break;
1032 case DevFmtX61:
1033 chansok = (chancount >= 7 && (chanmask&X61Mask) == X6DOT1);
1034 break;
1035 case DevFmtX71:
1036 case DevFmtX3D71:
1037 chansok = (chancount >= 8 && (chanmask&X71Mask) == X7DOT1);
1038 break;
1039 case DevFmtAmbi3D:
1040 break;
1043 if(!chansok)
1045 if(chancount >= 8 && (chanmask&X71Mask) == X7DOT1)
1046 mDevice->FmtChans = DevFmtX71;
1047 else if(chancount >= 7 && (chanmask&X61Mask) == X6DOT1)
1048 mDevice->FmtChans = DevFmtX61;
1049 else if(chancount >= 6 && ((chanmask&X51Mask) == X5DOT1
1050 || (chanmask&X51RearMask) == X5DOT1REAR))
1051 mDevice->FmtChans = DevFmtX51;
1052 else if(chancount >= 4 && (chanmask&QuadMask) == QUAD)
1053 mDevice->FmtChans = DevFmtQuad;
1054 else if(chancount >= 2 && (chanmask&StereoMask) == STEREO)
1055 mDevice->FmtChans = DevFmtStereo;
1056 else if(chancount >= 1 && (chanmask&MonoMask) == MONO)
1057 mDevice->FmtChans = DevFmtMono;
1058 else
1060 ERR("Unhandled extensible channels: %d -- 0x%08lx\n", OutputType.Format.nChannels,
1061 OutputType.dwChannelMask);
1062 mDevice->FmtChans = DevFmtStereo;
1063 OutputType.Format.nChannels = 2;
1064 OutputType.dwChannelMask = STEREO;
1068 if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
1070 if(OutputType.Format.wBitsPerSample == 8)
1071 mDevice->FmtType = DevFmtUByte;
1072 else if(OutputType.Format.wBitsPerSample == 16)
1073 mDevice->FmtType = DevFmtShort;
1074 else if(OutputType.Format.wBitsPerSample == 32)
1075 mDevice->FmtType = DevFmtInt;
1076 else
1078 mDevice->FmtType = DevFmtShort;
1079 OutputType.Format.wBitsPerSample = 16;
1082 else if(IsEqualGUID(OutputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1084 mDevice->FmtType = DevFmtFloat;
1085 OutputType.Format.wBitsPerSample = 32;
1087 else
1089 ERR("Unhandled format sub-type: %s\n", GuidPrinter{OutputType.SubFormat}.c_str());
1090 mDevice->FmtType = DevFmtShort;
1091 if(OutputType.Format.wFormatTag != WAVE_FORMAT_EXTENSIBLE)
1092 OutputType.Format.wFormatTag = WAVE_FORMAT_PCM;
1093 OutputType.Format.wBitsPerSample = 16;
1094 OutputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1096 OutputType.Samples.wValidBitsPerSample = OutputType.Format.wBitsPerSample;
1098 mFrameStep = OutputType.Format.nChannels;
1100 const EndpointFormFactor formfactor{get_device_formfactor(mMMDev.get())};
1101 mDevice->Flags.set(DirectEar, (formfactor == Headphones || formfactor == Headset));
1103 setDefaultWFXChannelOrder();
1105 hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
1106 buf_time.count(), 0, &OutputType.Format, nullptr);
1107 if(FAILED(hr))
1109 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
1110 return hr;
1113 UINT32 buffer_len{};
1114 ReferenceTime min_per{};
1115 hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
1116 if(SUCCEEDED(hr))
1117 hr = mClient->GetBufferSize(&buffer_len);
1118 if(FAILED(hr))
1120 ERR("Failed to get audio buffer info: 0x%08lx\n", hr);
1121 return hr;
1124 /* Find the nearest multiple of the period size to the update size */
1125 if(min_per < per_time)
1126 min_per *= maxi64((per_time + min_per/2) / min_per, 1);
1127 mDevice->UpdateSize = minu(RefTime2Samples(min_per, mDevice->Frequency), buffer_len/2);
1128 mDevice->BufferSize = buffer_len;
1130 hr = mClient->SetEventHandle(mNotifyEvent);
1131 if(FAILED(hr))
1133 ERR("Failed to set event handle: 0x%08lx\n", hr);
1134 return hr;
1137 return hr;
1141 void WasapiPlayback::start()
1143 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
1144 if(FAILED(hr))
1145 throw al::backend_exception{al::backend_error::DeviceError,
1146 "Failed to start playback: 0x%lx", hr};
1149 HRESULT WasapiPlayback::startProxy()
1151 ResetEvent(mNotifyEvent);
1153 HRESULT hr{mClient->Start()};
1154 if(FAILED(hr))
1156 ERR("Failed to start audio client: 0x%08lx\n", hr);
1157 return hr;
1160 void *ptr;
1161 hr = mClient->GetService(IID_IAudioRenderClient, &ptr);
1162 if(SUCCEEDED(hr))
1164 mRender = ComPtr<IAudioRenderClient>{static_cast<IAudioRenderClient*>(ptr)};
1165 try {
1166 mKillNow.store(false, std::memory_order_release);
1167 mThread = std::thread{std::mem_fn(&WasapiPlayback::mixerProc), this};
1169 catch(...) {
1170 mRender = nullptr;
1171 ERR("Failed to start thread\n");
1172 hr = E_FAIL;
1176 if(FAILED(hr))
1177 mClient->Stop();
1179 return hr;
1183 void WasapiPlayback::stop()
1184 { pushMessage(MsgType::StopDevice).wait(); }
1186 void WasapiPlayback::stopProxy()
1188 if(!mRender || !mThread.joinable())
1189 return;
1191 mKillNow.store(true, std::memory_order_release);
1192 mThread.join();
1194 mRender = nullptr;
1195 mClient->Stop();
1199 ClockLatency WasapiPlayback::getClockLatency()
1201 ClockLatency ret;
1203 std::lock_guard<std::mutex> _{mMutex};
1204 ret.ClockTime = GetDeviceClockTime(mDevice);
1205 ret.Latency = std::chrono::seconds{mPadding.load(std::memory_order_relaxed)};
1206 ret.Latency /= mDevice->Frequency;
1208 return ret;
1212 struct WasapiCapture final : public BackendBase, WasapiProxy {
1213 WasapiCapture(DeviceBase *device) noexcept : BackendBase{device} { }
1214 ~WasapiCapture() override;
1216 int recordProc();
1218 void open(const char *name) override;
1219 HRESULT openProxy(const char *name) override;
1220 void closeProxy() override;
1222 HRESULT resetProxy() override;
1223 void start() override;
1224 HRESULT startProxy() override;
1225 void stop() override;
1226 void stopProxy() override;
1228 void captureSamples(al::byte *buffer, uint samples) override;
1229 uint availableSamples() override;
1231 HRESULT mOpenStatus{E_FAIL};
1232 ComPtr<IMMDevice> mMMDev{nullptr};
1233 ComPtr<IAudioClient> mClient{nullptr};
1234 ComPtr<IAudioCaptureClient> mCapture{nullptr};
1235 HANDLE mNotifyEvent{nullptr};
1237 ChannelConverter mChannelConv{};
1238 SampleConverterPtr mSampleConv;
1239 RingBufferPtr mRing;
1241 std::atomic<bool> mKillNow{true};
1242 std::thread mThread;
1244 DEF_NEWDEL(WasapiCapture)
1247 WasapiCapture::~WasapiCapture()
1249 if(SUCCEEDED(mOpenStatus))
1250 pushMessage(MsgType::CloseDevice).wait();
1251 mOpenStatus = E_FAIL;
1253 if(mNotifyEvent != nullptr)
1254 CloseHandle(mNotifyEvent);
1255 mNotifyEvent = nullptr;
1259 FORCE_ALIGN int WasapiCapture::recordProc()
1261 HRESULT hr{CoInitializeEx(nullptr, COINIT_MULTITHREADED)};
1262 if(FAILED(hr))
1264 ERR("CoInitializeEx(nullptr, COINIT_MULTITHREADED) failed: 0x%08lx\n", hr);
1265 mDevice->handleDisconnect("COM init failed: 0x%08lx", hr);
1266 return 1;
1269 althrd_setname(RECORD_THREAD_NAME);
1271 al::vector<float> samples;
1272 while(!mKillNow.load(std::memory_order_relaxed))
1274 UINT32 avail;
1275 hr = mCapture->GetNextPacketSize(&avail);
1276 if(FAILED(hr))
1277 ERR("Failed to get next packet size: 0x%08lx\n", hr);
1278 else if(avail > 0)
1280 UINT32 numsamples;
1281 DWORD flags;
1282 BYTE *rdata;
1284 hr = mCapture->GetBuffer(&rdata, &numsamples, &flags, nullptr, nullptr);
1285 if(FAILED(hr))
1286 ERR("Failed to get capture buffer: 0x%08lx\n", hr);
1287 else
1289 if(mChannelConv.is_active())
1291 samples.resize(numsamples*2);
1292 mChannelConv.convert(rdata, samples.data(), numsamples);
1293 rdata = reinterpret_cast<BYTE*>(samples.data());
1296 auto data = mRing->getWriteVector();
1298 size_t dstframes;
1299 if(mSampleConv)
1301 const void *srcdata{rdata};
1302 uint srcframes{numsamples};
1304 dstframes = mSampleConv->convert(&srcdata, &srcframes, data.first.buf,
1305 static_cast<uint>(minz(data.first.len, INT_MAX)));
1306 if(srcframes > 0 && dstframes == data.first.len && data.second.len > 0)
1308 /* If some source samples remain, all of the first dest
1309 * block was filled, and there's space in the second
1310 * dest block, do another run for the second block.
1312 dstframes += mSampleConv->convert(&srcdata, &srcframes, data.second.buf,
1313 static_cast<uint>(minz(data.second.len, INT_MAX)));
1316 else
1318 const uint framesize{mDevice->frameSizeFromFmt()};
1319 size_t len1{minz(data.first.len, numsamples)};
1320 size_t len2{minz(data.second.len, numsamples-len1)};
1322 memcpy(data.first.buf, rdata, len1*framesize);
1323 if(len2 > 0)
1324 memcpy(data.second.buf, rdata+len1*framesize, len2*framesize);
1325 dstframes = len1 + len2;
1328 mRing->writeAdvance(dstframes);
1330 hr = mCapture->ReleaseBuffer(numsamples);
1331 if(FAILED(hr)) ERR("Failed to release capture buffer: 0x%08lx\n", hr);
1335 if(FAILED(hr))
1337 mDevice->handleDisconnect("Failed to capture samples: 0x%08lx", hr);
1338 break;
1341 DWORD res{WaitForSingleObjectEx(mNotifyEvent, 2000, FALSE)};
1342 if(res != WAIT_OBJECT_0)
1343 ERR("WaitForSingleObjectEx error: 0x%lx\n", res);
1346 CoUninitialize();
1347 return 0;
1351 void WasapiCapture::open(const char *name)
1353 HRESULT hr{S_OK};
1355 mNotifyEvent = CreateEventW(nullptr, FALSE, FALSE, nullptr);
1356 if(mNotifyEvent == nullptr)
1358 ERR("Failed to create notify event: %lu\n", GetLastError());
1359 hr = E_FAIL;
1362 if(SUCCEEDED(hr))
1364 if(name)
1366 if(CaptureDevices.empty())
1367 pushMessage(MsgType::EnumerateCapture);
1368 if(std::strncmp(name, DevNameHead, DevNameHeadLen) == 0)
1370 name += DevNameHeadLen;
1371 if(*name == '\0')
1372 name = nullptr;
1375 hr = pushMessage(MsgType::OpenDevice, name).get();
1377 mOpenStatus = hr;
1379 if(FAILED(hr))
1380 throw al::backend_exception{al::backend_error::DeviceError, "Device init failed: 0x%08lx",
1381 hr};
1383 hr = pushMessage(MsgType::ResetDevice).get();
1384 if(FAILED(hr))
1386 if(hr == E_OUTOFMEMORY)
1387 throw al::backend_exception{al::backend_error::OutOfMemory, "Out of memory"};
1388 throw al::backend_exception{al::backend_error::DeviceError, "Device reset failed"};
1392 HRESULT WasapiCapture::openProxy(const char *name)
1394 const wchar_t *devid{nullptr};
1395 if(name)
1397 auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
1398 [name](const DevMap &entry) -> bool
1399 { return entry.name == name || entry.endpoint_guid == name; });
1400 if(iter == CaptureDevices.cend())
1402 const std::wstring wname{utf8_to_wstr(name)};
1403 iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
1404 [&wname](const DevMap &entry) -> bool
1405 { return entry.devid == wname; });
1407 if(iter == CaptureDevices.cend())
1409 WARN("Failed to find device name matching \"%s\"\n", name);
1410 return E_FAIL;
1412 name = iter->name.c_str();
1413 devid = iter->devid.c_str();
1416 void *ptr;
1417 HRESULT hr{CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_INPROC_SERVER,
1418 IID_IMMDeviceEnumerator, &ptr)};
1419 if(SUCCEEDED(hr))
1421 ComPtr<IMMDeviceEnumerator> enumerator{static_cast<IMMDeviceEnumerator*>(ptr)};
1422 if(!devid)
1423 hr = enumerator->GetDefaultAudioEndpoint(eCapture, eMultimedia, mMMDev.getPtr());
1424 else
1425 hr = enumerator->GetDevice(devid, mMMDev.getPtr());
1427 if(FAILED(hr))
1429 WARN("Failed to open device \"%s\"\n", name?name:"(default)");
1430 return hr;
1433 mClient = nullptr;
1434 if(name) mDevice->DeviceName = std::string{DevNameHead} + name;
1435 else mDevice->DeviceName = DevNameHead + get_device_name_and_guid(mMMDev.get()).first;
1437 return hr;
1440 void WasapiCapture::closeProxy()
1442 mClient = nullptr;
1443 mMMDev = nullptr;
1446 HRESULT WasapiCapture::resetProxy()
1448 mClient = nullptr;
1450 void *ptr;
1451 HRESULT hr{mMMDev->Activate(IID_IAudioClient, CLSCTX_INPROC_SERVER, nullptr, &ptr)};
1452 if(FAILED(hr))
1454 ERR("Failed to reactivate audio client: 0x%08lx\n", hr);
1455 return hr;
1457 mClient = ComPtr<IAudioClient>{static_cast<IAudioClient*>(ptr)};
1459 // Make sure buffer is at least 100ms in size
1460 ReferenceTime buf_time{ReferenceTime{seconds{mDevice->BufferSize}} / mDevice->Frequency};
1461 buf_time = std::max(buf_time, ReferenceTime{milliseconds{100}});
1463 WAVEFORMATEXTENSIBLE InputType{};
1464 InputType.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
1465 switch(mDevice->FmtChans)
1467 case DevFmtMono:
1468 InputType.Format.nChannels = 1;
1469 InputType.dwChannelMask = MONO;
1470 break;
1471 case DevFmtStereo:
1472 InputType.Format.nChannels = 2;
1473 InputType.dwChannelMask = STEREO;
1474 break;
1475 case DevFmtQuad:
1476 InputType.Format.nChannels = 4;
1477 InputType.dwChannelMask = QUAD;
1478 break;
1479 case DevFmtX51:
1480 InputType.Format.nChannels = 6;
1481 InputType.dwChannelMask = X5DOT1;
1482 break;
1483 case DevFmtX61:
1484 InputType.Format.nChannels = 7;
1485 InputType.dwChannelMask = X6DOT1;
1486 break;
1487 case DevFmtX71:
1488 InputType.Format.nChannels = 8;
1489 InputType.dwChannelMask = X7DOT1;
1490 break;
1492 case DevFmtX3D71:
1493 case DevFmtAmbi3D:
1494 return E_FAIL;
1496 switch(mDevice->FmtType)
1498 /* NOTE: Signedness doesn't matter, the converter will handle it. */
1499 case DevFmtByte:
1500 case DevFmtUByte:
1501 InputType.Format.wBitsPerSample = 8;
1502 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1503 break;
1504 case DevFmtShort:
1505 case DevFmtUShort:
1506 InputType.Format.wBitsPerSample = 16;
1507 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1508 break;
1509 case DevFmtInt:
1510 case DevFmtUInt:
1511 InputType.Format.wBitsPerSample = 32;
1512 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
1513 break;
1514 case DevFmtFloat:
1515 InputType.Format.wBitsPerSample = 32;
1516 InputType.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
1517 break;
1519 InputType.Samples.wValidBitsPerSample = InputType.Format.wBitsPerSample;
1520 InputType.Format.nSamplesPerSec = mDevice->Frequency;
1522 InputType.Format.nBlockAlign = static_cast<WORD>(InputType.Format.nChannels *
1523 InputType.Format.wBitsPerSample / 8);
1524 InputType.Format.nAvgBytesPerSec = InputType.Format.nSamplesPerSec *
1525 InputType.Format.nBlockAlign;
1526 InputType.Format.cbSize = sizeof(InputType) - sizeof(InputType.Format);
1528 TraceFormat("Requesting capture format", &InputType.Format);
1529 WAVEFORMATEX *wfx{};
1530 hr = mClient->IsFormatSupported(AUDCLNT_SHAREMODE_SHARED, &InputType.Format, &wfx);
1531 if(FAILED(hr))
1533 WARN("Failed to check format support: 0x%08lx\n", hr);
1534 hr = mClient->GetMixFormat(&wfx);
1536 if(FAILED(hr))
1538 ERR("Failed to check format support: 0x%08lx\n", hr);
1539 return hr;
1542 mSampleConv = nullptr;
1543 mChannelConv = {};
1545 if(wfx != nullptr)
1547 TraceFormat("Got capture format", wfx);
1548 if(!MakeExtensible(&InputType, wfx))
1550 CoTaskMemFree(wfx);
1551 return E_FAIL;
1553 CoTaskMemFree(wfx);
1554 wfx = nullptr;
1556 auto validate_fmt = [](DeviceBase *device, uint32_t chancount, DWORD chanmask) noexcept
1557 -> bool
1559 switch(device->FmtChans)
1561 /* If the device wants mono, we can handle any input. */
1562 case DevFmtMono:
1563 return true;
1564 /* If the device wants stereo, we can handle mono or stereo input. */
1565 case DevFmtStereo:
1566 return (chancount == 2 && (chanmask == 0 || (chanmask&StereoMask) == STEREO))
1567 || (chancount == 1 && (chanmask&MonoMask) == MONO);
1568 /* Otherwise, the device must match the input type. */
1569 case DevFmtQuad:
1570 return (chancount == 4 && (chanmask == 0 || (chanmask&QuadMask) == QUAD));
1571 /* 5.1 (Side) and 5.1 (Rear) are interchangeable here. */
1572 case DevFmtX51:
1573 return (chancount == 6 && (chanmask == 0 || (chanmask&X51Mask) == X5DOT1
1574 || (chanmask&X51RearMask) == X5DOT1REAR));
1575 case DevFmtX61:
1576 return (chancount == 7 && (chanmask == 0 || (chanmask&X61Mask) == X6DOT1));
1577 case DevFmtX71:
1578 case DevFmtX3D71:
1579 return (chancount == 8 && (chanmask == 0 || (chanmask&X71Mask) == X7DOT1));
1580 case DevFmtAmbi3D:
1581 return (chanmask == 0 && chancount == device->channelsFromFmt());
1583 return false;
1585 if(!validate_fmt(mDevice, InputType.Format.nChannels, InputType.dwChannelMask))
1587 ERR("Failed to match format, wanted: %s %s %uhz, got: 0x%08lx mask %d channel%s %d-bit %luhz\n",
1588 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1589 mDevice->Frequency, InputType.dwChannelMask, InputType.Format.nChannels,
1590 (InputType.Format.nChannels==1)?"":"s", InputType.Format.wBitsPerSample,
1591 InputType.Format.nSamplesPerSec);
1592 return E_FAIL;
1596 DevFmtType srcType{};
1597 if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_PCM))
1599 if(InputType.Format.wBitsPerSample == 8)
1600 srcType = DevFmtUByte;
1601 else if(InputType.Format.wBitsPerSample == 16)
1602 srcType = DevFmtShort;
1603 else if(InputType.Format.wBitsPerSample == 32)
1604 srcType = DevFmtInt;
1605 else
1607 ERR("Unhandled integer bit depth: %d\n", InputType.Format.wBitsPerSample);
1608 return E_FAIL;
1611 else if(IsEqualGUID(InputType.SubFormat, KSDATAFORMAT_SUBTYPE_IEEE_FLOAT))
1613 if(InputType.Format.wBitsPerSample == 32)
1614 srcType = DevFmtFloat;
1615 else
1617 ERR("Unhandled float bit depth: %d\n", InputType.Format.wBitsPerSample);
1618 return E_FAIL;
1621 else
1623 ERR("Unhandled format sub-type: %s\n", GuidPrinter{InputType.SubFormat}.c_str());
1624 return E_FAIL;
1627 if(mDevice->FmtChans == DevFmtMono && InputType.Format.nChannels != 1)
1629 uint chanmask{(1u<<InputType.Format.nChannels) - 1u};
1630 /* Exclude LFE from the downmix. */
1631 if((InputType.dwChannelMask&SPEAKER_LOW_FREQUENCY))
1633 constexpr auto lfemask = MaskFromTopBits(SPEAKER_LOW_FREQUENCY);
1634 const int lfeidx{al::popcount(InputType.dwChannelMask&lfemask) - 1};
1635 chanmask &= ~(1u << lfeidx);
1638 mChannelConv = ChannelConverter{srcType, InputType.Format.nChannels, chanmask,
1639 mDevice->FmtChans};
1640 TRACE("Created %s multichannel-to-mono converter\n", DevFmtTypeString(srcType));
1641 /* The channel converter always outputs float, so change the input type
1642 * for the resampler/type-converter.
1644 srcType = DevFmtFloat;
1646 else if(mDevice->FmtChans == DevFmtStereo && InputType.Format.nChannels == 1)
1648 mChannelConv = ChannelConverter{srcType, 1, 0x1, mDevice->FmtChans};
1649 TRACE("Created %s mono-to-stereo converter\n", DevFmtTypeString(srcType));
1650 srcType = DevFmtFloat;
1653 if(mDevice->Frequency != InputType.Format.nSamplesPerSec || mDevice->FmtType != srcType)
1655 mSampleConv = CreateSampleConverter(srcType, mDevice->FmtType, mDevice->channelsFromFmt(),
1656 InputType.Format.nSamplesPerSec, mDevice->Frequency, Resampler::FastBSinc24);
1657 if(!mSampleConv)
1659 ERR("Failed to create converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1660 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1661 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
1662 return E_FAIL;
1664 TRACE("Created converter for %s format, dst: %s %uhz, src: %s %luhz\n",
1665 DevFmtChannelsString(mDevice->FmtChans), DevFmtTypeString(mDevice->FmtType),
1666 mDevice->Frequency, DevFmtTypeString(srcType), InputType.Format.nSamplesPerSec);
1669 hr = mClient->Initialize(AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
1670 buf_time.count(), 0, &InputType.Format, nullptr);
1671 if(FAILED(hr))
1673 ERR("Failed to initialize audio client: 0x%08lx\n", hr);
1674 return hr;
1677 UINT32 buffer_len{};
1678 ReferenceTime min_per{};
1679 hr = mClient->GetDevicePeriod(&reinterpret_cast<REFERENCE_TIME&>(min_per), nullptr);
1680 if(SUCCEEDED(hr))
1681 hr = mClient->GetBufferSize(&buffer_len);
1682 if(FAILED(hr))
1684 ERR("Failed to get buffer size: 0x%08lx\n", hr);
1685 return hr;
1687 mDevice->UpdateSize = RefTime2Samples(min_per, mDevice->Frequency);
1688 mDevice->BufferSize = buffer_len;
1690 mRing = RingBuffer::Create(buffer_len, mDevice->frameSizeFromFmt(), false);
1692 hr = mClient->SetEventHandle(mNotifyEvent);
1693 if(FAILED(hr))
1695 ERR("Failed to set event handle: 0x%08lx\n", hr);
1696 return hr;
1699 return hr;
1703 void WasapiCapture::start()
1705 const HRESULT hr{pushMessage(MsgType::StartDevice).get()};
1706 if(FAILED(hr))
1707 throw al::backend_exception{al::backend_error::DeviceError,
1708 "Failed to start recording: 0x%lx", hr};
1711 HRESULT WasapiCapture::startProxy()
1713 ResetEvent(mNotifyEvent);
1715 HRESULT hr{mClient->Start()};
1716 if(FAILED(hr))
1718 ERR("Failed to start audio client: 0x%08lx\n", hr);
1719 return hr;
1722 void *ptr;
1723 hr = mClient->GetService(IID_IAudioCaptureClient, &ptr);
1724 if(SUCCEEDED(hr))
1726 mCapture = ComPtr<IAudioCaptureClient>{static_cast<IAudioCaptureClient*>(ptr)};
1727 try {
1728 mKillNow.store(false, std::memory_order_release);
1729 mThread = std::thread{std::mem_fn(&WasapiCapture::recordProc), this};
1731 catch(...) {
1732 mCapture = nullptr;
1733 ERR("Failed to start thread\n");
1734 hr = E_FAIL;
1738 if(FAILED(hr))
1740 mClient->Stop();
1741 mClient->Reset();
1744 return hr;
1748 void WasapiCapture::stop()
1749 { pushMessage(MsgType::StopDevice).wait(); }
1751 void WasapiCapture::stopProxy()
1753 if(!mCapture || !mThread.joinable())
1754 return;
1756 mKillNow.store(true, std::memory_order_release);
1757 mThread.join();
1759 mCapture = nullptr;
1760 mClient->Stop();
1761 mClient->Reset();
1765 void WasapiCapture::captureSamples(al::byte *buffer, uint samples)
1766 { mRing->read(buffer, samples); }
1768 uint WasapiCapture::availableSamples()
1769 { return static_cast<uint>(mRing->readSpace()); }
1771 } // namespace
1774 bool WasapiBackendFactory::init()
1776 static HRESULT InitResult{E_FAIL};
1778 if(FAILED(InitResult)) try
1780 std::promise<HRESULT> promise;
1781 auto future = promise.get_future();
1783 std::thread{&WasapiProxy::messageHandler, &promise}.detach();
1784 InitResult = future.get();
1786 catch(...) {
1789 return SUCCEEDED(InitResult);
1792 bool WasapiBackendFactory::querySupport(BackendType type)
1793 { return type == BackendType::Playback || type == BackendType::Capture; }
1795 std::string WasapiBackendFactory::probe(BackendType type)
1797 std::string outnames;
1798 switch(type)
1800 case BackendType::Playback:
1801 WasapiProxy::pushMessageStatic(MsgType::EnumeratePlayback).wait();
1802 for(const DevMap &entry : PlaybackDevices)
1804 /* +1 to also append the null char (to ensure a null-separated list
1805 * and double-null terminated list).
1807 outnames.append(DevNameHead).append(entry.name.c_str(), entry.name.length()+1);
1809 break;
1811 case BackendType::Capture:
1812 WasapiProxy::pushMessageStatic(MsgType::EnumerateCapture).wait();
1813 for(const DevMap &entry : CaptureDevices)
1814 outnames.append(DevNameHead).append(entry.name.c_str(), entry.name.length()+1);
1815 break;
1818 return outnames;
1821 BackendPtr WasapiBackendFactory::createBackend(DeviceBase *device, BackendType type)
1823 if(type == BackendType::Playback)
1824 return BackendPtr{new WasapiPlayback{device}};
1825 if(type == BackendType::Capture)
1826 return BackendPtr{new WasapiCapture{device}};
1827 return nullptr;
1830 BackendFactory &WasapiBackendFactory::getFactory()
1832 static WasapiBackendFactory factory{};
1833 return factory;