Lower the priority of the JACK backend
[openal-soft.git] / alc / alc.cpp
blobfe304c3d342c2d98bedeace27abd8617ffd96918
1 /**
2 * OpenAL cross platform audio library
3 * Copyright (C) 1999-2007 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"
22 #include "config_backends.h"
23 #include "config_simd.h"
25 #include "version.h"
27 #ifdef _WIN32
28 #define WIN32_LEAN_AND_MEAN
29 #include <windows.h>
30 #endif
32 #include <algorithm>
33 #include <array>
34 #include <atomic>
35 #include <bitset>
36 #include <cassert>
37 #include <cctype>
38 #include <chrono>
39 #include <cinttypes>
40 #include <climits>
41 #include <cmath>
42 #include <csignal>
43 #include <cstddef>
44 #include <cstdio>
45 #include <cstdlib>
46 #include <cstring>
47 #include <exception>
48 #include <functional>
49 #include <iterator>
50 #include <limits>
51 #include <memory>
52 #include <mutex>
53 #include <new>
54 #include <optional>
55 #include <stdexcept>
56 #include <string>
57 #include <string_view>
58 #include <tuple>
59 #include <utility>
60 #include <vector>
62 #include "AL/al.h"
63 #include "AL/alc.h"
64 #include "AL/alext.h"
65 #include "AL/efx.h"
67 #include "al/auxeffectslot.h"
68 #include "al/buffer.h"
69 #include "al/debug.h"
70 #include "al/effect.h"
71 #include "al/filter.h"
72 #include "al/source.h"
73 #include "alc/events.h"
74 #include "albit.h"
75 #include "alconfig.h"
76 #include "almalloc.h"
77 #include "alnumbers.h"
78 #include "alnumeric.h"
79 #include "alspan.h"
80 #include "alstring.h"
81 #include "alu.h"
82 #include "atomic.h"
83 #include "context.h"
84 #include "core/ambidefs.h"
85 #include "core/bformatdec.h"
86 #include "core/bs2b.h"
87 #include "core/context.h"
88 #include "core/cpu_caps.h"
89 #include "core/devformat.h"
90 #include "core/device.h"
91 #include "core/effects/base.h"
92 #include "core/effectslot.h"
93 #include "core/filters/nfc.h"
94 #include "core/helpers.h"
95 #include "core/mastering.h"
96 #include "core/fpu_ctrl.h"
97 #include "core/logging.h"
98 #include "core/uhjfilter.h"
99 #include "core/voice.h"
100 #include "core/voice_change.h"
101 #include "device.h"
102 #include "effects/base.h"
103 #include "export_list.h"
104 #include "flexarray.h"
105 #include "inprogext.h"
106 #include "intrusive_ptr.h"
107 #include "opthelpers.h"
108 #include "strutils.h"
110 #include "backends/base.h"
111 #include "backends/null.h"
112 #include "backends/loopback.h"
113 #if HAVE_PIPEWIRE
114 #include "backends/pipewire.h"
115 #endif
116 #if HAVE_JACK
117 #include "backends/jack.h"
118 #endif
119 #if HAVE_PULSEAUDIO
120 #include "backends/pulseaudio.h"
121 #endif
122 #if HAVE_ALSA
123 #include "backends/alsa.h"
124 #endif
125 #if HAVE_WASAPI
126 #include "backends/wasapi.h"
127 #endif
128 #if HAVE_COREAUDIO
129 #include "backends/coreaudio.h"
130 #endif
131 #if HAVE_OPENSL
132 #include "backends/opensl.h"
133 #endif
134 #if HAVE_OBOE
135 #include "backends/oboe.h"
136 #endif
137 #if HAVE_SOLARIS
138 #include "backends/solaris.h"
139 #endif
140 #if HAVE_SNDIO
141 #include "backends/sndio.h"
142 #endif
143 #if HAVE_OSS
144 #include "backends/oss.h"
145 #endif
146 #if HAVE_DSOUND
147 #include "backends/dsound.h"
148 #endif
149 #if HAVE_WINMM
150 #include "backends/winmm.h"
151 #endif
152 #if HAVE_PORTAUDIO
153 #include "backends/portaudio.h"
154 #endif
155 #if HAVE_SDL2
156 #include "backends/sdl2.h"
157 #endif
158 #if HAVE_OTHERIO
159 #include "backends/otherio.h"
160 #endif
161 #if HAVE_WAVE
162 #include "backends/wave.h"
163 #endif
165 #if ALSOFT_EAX
166 #include "al/eax/api.h"
167 #include "al/eax/globals.h"
168 #endif
171 /************************************************
172 * Library initialization
173 ************************************************/
174 #if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC)
175 BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/)
177 switch(reason)
179 case DLL_PROCESS_ATTACH:
180 /* Pin the DLL so we won't get unloaded until the process terminates */
181 GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
182 reinterpret_cast<WCHAR*>(module), &module);
183 break;
185 return TRUE;
187 #endif
189 namespace {
191 using namespace std::string_view_literals;
192 using std::chrono::seconds;
193 using std::chrono::nanoseconds;
195 using voidp = void*;
196 using float2 = std::array<float,2>;
199 auto gProcessRunning = true;
200 struct ProcessWatcher {
201 ProcessWatcher() = default;
202 ProcessWatcher(const ProcessWatcher&) = delete;
203 ProcessWatcher& operator=(const ProcessWatcher&) = delete;
204 ~ProcessWatcher() { gProcessRunning = false; }
206 ProcessWatcher gProcessWatcher;
208 /************************************************
209 * Backends
210 ************************************************/
211 struct BackendInfo {
212 const char *name;
213 BackendFactory& (*getFactory)();
216 std::array BackendList{
217 #if HAVE_PIPEWIRE
218 BackendInfo{"pipewire", PipeWireBackendFactory::getFactory},
219 #endif
220 #if HAVE_PULSEAUDIO
221 BackendInfo{"pulse", PulseBackendFactory::getFactory},
222 #endif
223 #if HAVE_WASAPI
224 BackendInfo{"wasapi", WasapiBackendFactory::getFactory},
225 #endif
226 #if HAVE_COREAUDIO
227 BackendInfo{"core", CoreAudioBackendFactory::getFactory},
228 #endif
229 #if HAVE_OBOE
230 BackendInfo{"oboe", OboeBackendFactory::getFactory},
231 #endif
232 #if HAVE_OPENSL
233 BackendInfo{"opensl", OSLBackendFactory::getFactory},
234 #endif
235 #if HAVE_ALSA
236 BackendInfo{"alsa", AlsaBackendFactory::getFactory},
237 #endif
238 #if HAVE_SOLARIS
239 BackendInfo{"solaris", SolarisBackendFactory::getFactory},
240 #endif
241 #if HAVE_SNDIO
242 BackendInfo{"sndio", SndIOBackendFactory::getFactory},
243 #endif
244 #if HAVE_OSS
245 BackendInfo{"oss", OSSBackendFactory::getFactory},
246 #endif
247 #if HAVE_DSOUND
248 BackendInfo{"dsound", DSoundBackendFactory::getFactory},
249 #endif
250 #if HAVE_WINMM
251 BackendInfo{"winmm", WinMMBackendFactory::getFactory},
252 #endif
253 #if HAVE_PORTAUDIO
254 BackendInfo{"port", PortBackendFactory::getFactory},
255 #endif
256 #if HAVE_SDL2
257 BackendInfo{"sdl2", SDL2BackendFactory::getFactory},
258 #endif
259 #if HAVE_JACK
260 BackendInfo{"jack", JackBackendFactory::getFactory},
261 #endif
262 #if HAVE_OTHERIO
263 BackendInfo{"otherio", OtherIOBackendFactory::getFactory},
264 #endif
266 BackendInfo{"null", NullBackendFactory::getFactory},
267 #if HAVE_WAVE
268 BackendInfo{"wave", WaveBackendFactory::getFactory},
269 #endif
272 BackendFactory *PlaybackFactory{};
273 BackendFactory *CaptureFactory{};
276 [[nodiscard]] constexpr auto GetNoErrorString() noexcept { return "No Error"; }
277 [[nodiscard]] constexpr auto GetInvalidDeviceString() noexcept { return "Invalid Device"; }
278 [[nodiscard]] constexpr auto GetInvalidContextString() noexcept { return "Invalid Context"; }
279 [[nodiscard]] constexpr auto GetInvalidEnumString() noexcept { return "Invalid Enum"; }
280 [[nodiscard]] constexpr auto GetInvalidValueString() noexcept { return "Invalid Value"; }
281 [[nodiscard]] constexpr auto GetOutOfMemoryString() noexcept { return "Out of Memory"; }
283 [[nodiscard]] constexpr auto GetDefaultName() noexcept { return "OpenAL Soft\0"; }
285 #ifdef _WIN32
286 [[nodiscard]] constexpr auto GetDevicePrefix() noexcept { return "OpenAL Soft on "sv; }
287 #else
288 [[nodiscard]] constexpr auto GetDevicePrefix() noexcept { return std::string_view{}; }
289 #endif
291 /************************************************
292 * Global variables
293 ************************************************/
295 /* Enumerated device names */
296 std::vector<std::string> alcAllDevicesArray;
297 std::vector<std::string> alcCaptureDeviceArray;
298 std::string alcAllDevicesList;
299 std::string alcCaptureDeviceList;
301 /* Default is always the first in the list */
302 std::string alcDefaultAllDevicesSpecifier;
303 std::string alcCaptureDefaultDeviceSpecifier;
305 std::atomic<ALCenum> LastNullDeviceError{ALC_NO_ERROR};
307 /* Flag to trap ALC device errors */
308 bool TrapALCError{false};
310 /* One-time configuration init control */
311 std::once_flag alc_config_once{};
313 /* Flag to specify if alcSuspendContext/alcProcessContext should defer/process
314 * updates.
316 bool SuspendDefers{true};
318 /* Initial seed for dithering. */
319 constexpr uint DitherRNGSeed{22222u};
322 /************************************************
323 * ALC information
324 ************************************************/
325 [[nodiscard]] constexpr auto GetNoDeviceExtList() noexcept -> const char*
327 return "ALC_ENUMERATE_ALL_EXT "
328 "ALC_ENUMERATION_EXT "
329 "ALC_EXT_CAPTURE "
330 "ALC_EXT_direct_context "
331 "ALC_EXT_EFX "
332 "ALC_EXT_thread_local_context "
333 "ALC_SOFT_loopback "
334 "ALC_SOFT_loopback_bformat "
335 "ALC_SOFT_reopen_device "
336 "ALC_SOFT_system_events";
338 [[nodiscard]] constexpr auto GetExtensionList() noexcept -> const char*
340 return "ALC_ENUMERATE_ALL_EXT "
341 "ALC_ENUMERATION_EXT "
342 "ALC_EXT_CAPTURE "
343 "ALC_EXT_debug "
344 "ALC_EXT_DEDICATED "
345 "ALC_EXT_direct_context "
346 "ALC_EXT_disconnect "
347 "ALC_EXT_EFX "
348 "ALC_EXT_thread_local_context "
349 "ALC_SOFT_device_clock "
350 "ALC_SOFT_HRTF "
351 "ALC_SOFT_loopback "
352 "ALC_SOFT_loopback_bformat "
353 "ALC_SOFT_output_limiter "
354 "ALC_SOFT_output_mode "
355 "ALC_SOFT_pause_device "
356 "ALC_SOFT_reopen_device "
357 "ALC_SOFT_system_events";
360 constexpr int alcMajorVersion{1};
361 constexpr int alcMinorVersion{1};
363 constexpr int alcEFXMajorVersion{1};
364 constexpr int alcEFXMinorVersion{0};
367 using DeviceRef = al::intrusive_ptr<ALCdevice>;
370 /************************************************
371 * Device lists
372 ************************************************/
373 std::vector<ALCdevice*> DeviceList;
374 std::vector<ALCcontext*> ContextList;
376 std::recursive_mutex ListLock;
379 void alc_initconfig()
381 if(auto loglevel = al::getenv("ALSOFT_LOGLEVEL"))
383 long lvl = strtol(loglevel->c_str(), nullptr, 0);
384 if(lvl >= static_cast<long>(LogLevel::Trace))
385 gLogLevel = LogLevel::Trace;
386 else if(lvl <= static_cast<long>(LogLevel::Disable))
387 gLogLevel = LogLevel::Disable;
388 else
389 gLogLevel = static_cast<LogLevel>(lvl);
392 #ifdef _WIN32
393 if(const auto logfile = al::getenv(L"ALSOFT_LOGFILE"))
395 FILE *logf{_wfopen(logfile->c_str(), L"wt")};
396 if(logf) gLogFile = logf;
397 else
399 auto u8name = wstr_to_utf8(*logfile);
400 ERR("Failed to open log file '%s'\n", u8name.c_str());
403 #else
404 if(const auto logfile = al::getenv("ALSOFT_LOGFILE"))
406 FILE *logf{fopen(logfile->c_str(), "wt")};
407 if(logf) gLogFile = logf;
408 else ERR("Failed to open log file '%s'\n", logfile->c_str());
410 #endif
412 TRACE("Initializing library v%s-%s %s\n", ALSOFT_VERSION, ALSOFT_GIT_COMMIT_HASH,
413 ALSOFT_GIT_BRANCH);
415 std::string names;
416 if(std::size(BackendList) < 1)
417 names = "(none)";
418 else
420 const al::span<const BackendInfo> infos{BackendList};
421 names = infos[0].name;
422 for(const auto &backend : infos.subspan<1>())
424 names += ", ";
425 names += backend.name;
428 TRACE("Supported backends: %s\n", names.c_str());
430 ReadALConfig();
432 if(auto suspendmode = al::getenv("__ALSOFT_SUSPEND_CONTEXT"))
434 if(al::case_compare(*suspendmode, "ignore"sv) == 0)
436 SuspendDefers = false;
437 TRACE("Selected context suspend behavior, \"ignore\"\n");
439 else
440 ERR("Unhandled context suspend behavior setting: \"%s\"\n", suspendmode->c_str());
443 int capfilter{0};
444 #if HAVE_SSE4_1
445 capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
446 #elif HAVE_SSE3
447 capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
448 #elif HAVE_SSE2
449 capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2;
450 #elif HAVE_SSE
451 capfilter |= CPU_CAP_SSE;
452 #endif
453 #if HAVE_NEON
454 capfilter |= CPU_CAP_NEON;
455 #endif
456 if(auto cpuopt = ConfigValueStr({}, {}, "disable-cpu-exts"sv))
458 std::string_view cpulist{*cpuopt};
459 if(al::case_compare(cpulist, "all"sv) == 0)
460 capfilter = 0;
461 else while(!cpulist.empty())
463 auto nextpos = std::min(cpulist.find(','), cpulist.size());
464 auto entry = cpulist.substr(0, nextpos);
466 while(nextpos < cpulist.size() && cpulist[nextpos] == ',')
467 ++nextpos;
468 cpulist.remove_prefix(nextpos);
470 while(!entry.empty() && std::isspace(entry.front()))
471 entry.remove_prefix(1);
472 while(!entry.empty() && std::isspace(entry.back()))
473 entry.remove_suffix(1);
474 if(entry.empty())
475 continue;
477 if(al::case_compare(entry, "sse"sv) == 0)
478 capfilter &= ~CPU_CAP_SSE;
479 else if(al::case_compare(entry, "sse2"sv) == 0)
480 capfilter &= ~CPU_CAP_SSE2;
481 else if(al::case_compare(entry, "sse3"sv) == 0)
482 capfilter &= ~CPU_CAP_SSE3;
483 else if(al::case_compare(entry, "sse4.1"sv) == 0)
484 capfilter &= ~CPU_CAP_SSE4_1;
485 else if(al::case_compare(entry, "neon"sv) == 0)
486 capfilter &= ~CPU_CAP_NEON;
487 else
488 WARN("Invalid CPU extension \"%.*s\"\n", al::sizei(entry), entry.data());
491 if(auto cpuopt = GetCPUInfo())
493 if(!cpuopt->mVendor.empty() || !cpuopt->mName.empty())
495 TRACE("Vendor ID: \"%s\"\n", cpuopt->mVendor.c_str());
496 TRACE("Name: \"%s\"\n", cpuopt->mName.c_str());
498 const int caps{cpuopt->mCaps};
499 TRACE("Extensions:%s%s%s%s%s%s\n",
500 ((capfilter&CPU_CAP_SSE) ? ((caps&CPU_CAP_SSE) ? " +SSE" : " -SSE") : ""),
501 ((capfilter&CPU_CAP_SSE2) ? ((caps&CPU_CAP_SSE2) ? " +SSE2" : " -SSE2") : ""),
502 ((capfilter&CPU_CAP_SSE3) ? ((caps&CPU_CAP_SSE3) ? " +SSE3" : " -SSE3") : ""),
503 ((capfilter&CPU_CAP_SSE4_1) ? ((caps&CPU_CAP_SSE4_1) ? " +SSE4.1" : " -SSE4.1") : ""),
504 ((capfilter&CPU_CAP_NEON) ? ((caps&CPU_CAP_NEON) ? " +NEON" : " -NEON") : ""),
505 ((!capfilter) ? " -none-" : ""));
506 CPUCapFlags = caps & capfilter;
509 if(auto priopt = ConfigValueInt({}, {}, "rt-prio"sv))
510 RTPrioLevel = *priopt;
511 if(auto limopt = ConfigValueBool({}, {}, "rt-time-limit"sv))
512 AllowRTTimeLimit = *limopt;
515 CompatFlagBitset compatflags{};
516 auto checkflag = [](const char *envname, const std::string_view optname) -> bool
518 if(auto optval = al::getenv(envname))
520 return al::case_compare(*optval, "true"sv) == 0
521 || strtol(optval->c_str(), nullptr, 0) == 1;
523 return GetConfigValueBool({}, "game_compat", optname, false);
525 sBufferSubDataCompat = checkflag("__ALSOFT_ENABLE_SUB_DATA_EXT", "enable-sub-data-ext"sv);
526 compatflags.set(CompatFlags::ReverseX, checkflag("__ALSOFT_REVERSE_X", "reverse-x"sv));
527 compatflags.set(CompatFlags::ReverseY, checkflag("__ALSOFT_REVERSE_Y", "reverse-y"sv));
528 compatflags.set(CompatFlags::ReverseZ, checkflag("__ALSOFT_REVERSE_Z", "reverse-z"sv));
530 aluInit(compatflags, ConfigValueFloat({}, "game_compat"sv, "nfc-scale"sv).value_or(1.0f));
532 Voice::InitMixer(ConfigValueStr({}, {}, "resampler"sv));
534 if(auto uhjfiltopt = ConfigValueStr({}, "uhj"sv, "decode-filter"sv))
536 if(al::case_compare(*uhjfiltopt, "fir256"sv) == 0)
537 UhjDecodeQuality = UhjQualityType::FIR256;
538 else if(al::case_compare(*uhjfiltopt, "fir512"sv) == 0)
539 UhjDecodeQuality = UhjQualityType::FIR512;
540 else if(al::case_compare(*uhjfiltopt, "iir"sv) == 0)
541 UhjDecodeQuality = UhjQualityType::IIR;
542 else
543 WARN("Unsupported uhj/decode-filter: %s\n", uhjfiltopt->c_str());
545 if(auto uhjfiltopt = ConfigValueStr({}, "uhj"sv, "encode-filter"sv))
547 if(al::case_compare(*uhjfiltopt, "fir256"sv) == 0)
548 UhjEncodeQuality = UhjQualityType::FIR256;
549 else if(al::case_compare(*uhjfiltopt, "fir512"sv) == 0)
550 UhjEncodeQuality = UhjQualityType::FIR512;
551 else if(al::case_compare(*uhjfiltopt, "iir"sv) == 0)
552 UhjEncodeQuality = UhjQualityType::IIR;
553 else
554 WARN("Unsupported uhj/encode-filter: %s\n", uhjfiltopt->c_str());
557 if(auto traperr = al::getenv("ALSOFT_TRAP_ERROR"); traperr
558 && (al::case_compare(*traperr, "true"sv) == 0
559 || std::strtol(traperr->c_str(), nullptr, 0) == 1))
561 TrapALError = true;
562 TrapALCError = true;
564 else
566 traperr = al::getenv("ALSOFT_TRAP_AL_ERROR");
567 if(traperr)
568 TrapALError = al::case_compare(*traperr, "true"sv) == 0
569 || strtol(traperr->c_str(), nullptr, 0) == 1;
570 else
571 TrapALError = GetConfigValueBool({}, {}, "trap-al-error"sv, false);
573 traperr = al::getenv("ALSOFT_TRAP_ALC_ERROR");
574 if(traperr)
575 TrapALCError = al::case_compare(*traperr, "true"sv) == 0
576 || strtol(traperr->c_str(), nullptr, 0) == 1;
577 else
578 TrapALCError = GetConfigValueBool({}, {}, "trap-alc-error"sv, false);
581 if(auto boostopt = ConfigValueFloat({}, "reverb"sv, "boost"sv))
583 const float valf{std::isfinite(*boostopt) ? std::clamp(*boostopt, -24.0f, 24.0f) : 0.0f};
584 ReverbBoost *= std::pow(10.0f, valf / 20.0f);
587 auto BackendListEnd = BackendList.end();
588 auto devopt = al::getenv("ALSOFT_DRIVERS");
589 if(!devopt) devopt = ConfigValueStr({}, {}, "drivers"sv);
590 if(devopt)
592 auto backendlist_cur = BackendList.begin();
594 bool endlist{true};
595 std::string_view drvlist{*devopt};
596 while(!drvlist.empty())
598 auto nextpos = std::min(drvlist.find(','), drvlist.size());
599 auto entry = drvlist.substr(0, nextpos);
601 endlist = true;
602 if(nextpos < drvlist.size())
604 endlist = false;
605 while(nextpos < drvlist.size() && drvlist[nextpos] == ',')
606 ++nextpos;
608 drvlist.remove_prefix(nextpos);
610 while(!entry.empty() && std::isspace(entry.front()))
611 entry.remove_prefix(1);
612 const bool delitem{!entry.empty() && entry.front() == '-'};
613 if(delitem) entry.remove_prefix(1);
615 while(!entry.empty() && std::isspace(entry.back()))
616 entry.remove_suffix(1);
617 if(entry.empty())
618 continue;
620 #ifdef HAVE_WASAPI
621 /* HACK: For backwards compatibility, convert backend references of
622 * mmdevapi to wasapi. This should eventually be removed.
624 if(entry == "mmdevapi"sv)
625 entry = "wasapi"sv;
626 #endif
628 auto find_backend = [entry](const BackendInfo &backend) -> bool
629 { return entry == backend.name; };
630 auto this_backend = std::find_if(BackendList.begin(), BackendListEnd, find_backend);
632 if(this_backend == BackendListEnd)
633 continue;
635 if(delitem)
636 BackendListEnd = std::move(this_backend+1, BackendListEnd, this_backend);
637 else
638 backendlist_cur = std::rotate(backendlist_cur, this_backend, this_backend+1);
641 if(endlist)
642 BackendListEnd = backendlist_cur;
645 auto init_backend = [](BackendInfo &backend) -> void
647 if(PlaybackFactory && CaptureFactory)
648 return;
650 BackendFactory &factory = backend.getFactory();
651 if(!factory.init())
653 WARN("Failed to initialize backend \"%s\"\n", backend.name);
654 return;
657 TRACE("Initialized backend \"%s\"\n", backend.name);
658 if(!PlaybackFactory && factory.querySupport(BackendType::Playback))
660 PlaybackFactory = &factory;
661 TRACE("Added \"%s\" for playback\n", backend.name);
663 if(!CaptureFactory && factory.querySupport(BackendType::Capture))
665 CaptureFactory = &factory;
666 TRACE("Added \"%s\" for capture\n", backend.name);
669 std::for_each(BackendList.begin(), BackendListEnd, init_backend);
671 LoopbackBackendFactory::getFactory().init();
673 if(!PlaybackFactory)
674 WARN("No playback backend available!\n");
675 if(!CaptureFactory)
676 WARN("No capture backend available!\n");
678 if(auto exclopt = ConfigValueStr({}, {}, "excludefx"sv))
680 std::string_view exclude{*exclopt};
681 while(!exclude.empty())
683 const auto nextpos = exclude.find(',');
684 const auto entry = exclude.substr(0, nextpos);
685 exclude.remove_prefix((nextpos < exclude.size()) ? nextpos+1 : exclude.size());
687 std::for_each(gEffectList.cbegin(), gEffectList.cend(),
688 [entry](const EffectList &effectitem) noexcept
690 if(entry == std::data(effectitem.name))
691 DisabledEffects.set(effectitem.type);
696 InitEffect(&ALCcontext::sDefaultEffect);
697 auto defrevopt = al::getenv("ALSOFT_DEFAULT_REVERB");
698 if(!defrevopt) defrevopt = ConfigValueStr({}, {}, "default-reverb"sv);
699 if(defrevopt) LoadReverbPreset(*defrevopt, &ALCcontext::sDefaultEffect);
701 #if ALSOFT_EAX
703 if(const auto eax_enable_opt = ConfigValueBool({}, "eax", "enable"))
705 eax_g_is_enabled = *eax_enable_opt;
706 if(!eax_g_is_enabled)
707 TRACE("%s\n", "EAX disabled by a configuration.");
709 else
710 eax_g_is_enabled = true;
712 if((DisabledEffects.test(EAXREVERB_EFFECT) || DisabledEffects.test(CHORUS_EFFECT))
713 && eax_g_is_enabled)
715 eax_g_is_enabled = false;
716 TRACE("EAX disabled because %s disabled.\n",
717 (DisabledEffects.test(EAXREVERB_EFFECT) && DisabledEffects.test(CHORUS_EFFECT))
718 ? "EAXReverb and Chorus are" :
719 DisabledEffects.test(EAXREVERB_EFFECT) ? "EAXReverb is" :
720 DisabledEffects.test(CHORUS_EFFECT) ? "Chorus is" : "");
723 #endif // ALSOFT_EAX
725 inline void InitConfig()
726 { std::call_once(alc_config_once, [](){alc_initconfig();}); }
729 /************************************************
730 * Device enumeration
731 ************************************************/
732 void ProbeAllDevicesList()
734 InitConfig();
736 std::lock_guard<std::recursive_mutex> listlock{ListLock};
737 if(!PlaybackFactory)
739 decltype(alcAllDevicesArray){}.swap(alcAllDevicesArray);
740 decltype(alcAllDevicesList){}.swap(alcAllDevicesList);
742 else
744 alcAllDevicesArray = PlaybackFactory->enumerate(BackendType::Playback);
745 if(const auto prefix = GetDevicePrefix(); !prefix.empty())
746 std::for_each(alcAllDevicesArray.begin(), alcAllDevicesArray.end(),
747 [prefix](std::string &name) { name.insert(0, prefix); });
749 decltype(alcAllDevicesList){}.swap(alcAllDevicesList);
750 if(alcAllDevicesArray.empty())
751 alcAllDevicesList += '\0';
752 else for(auto &devname : alcAllDevicesArray)
753 alcAllDevicesList.append(devname) += '\0';
756 void ProbeCaptureDeviceList()
758 InitConfig();
760 std::lock_guard<std::recursive_mutex> listlock{ListLock};
761 if(!CaptureFactory)
763 decltype(alcCaptureDeviceArray){}.swap(alcCaptureDeviceArray);
764 decltype(alcCaptureDeviceList){}.swap(alcCaptureDeviceList);
766 else
768 alcCaptureDeviceArray = CaptureFactory->enumerate(BackendType::Capture);
769 if(const auto prefix = GetDevicePrefix(); !prefix.empty())
770 std::for_each(alcCaptureDeviceArray.begin(), alcCaptureDeviceArray.end(),
771 [prefix](std::string &name) { name.insert(0, prefix); });
773 decltype(alcCaptureDeviceList){}.swap(alcCaptureDeviceList);
774 if(alcCaptureDeviceArray.empty())
775 alcCaptureDeviceList += '\0';
776 else for(auto &devname : alcCaptureDeviceArray)
777 alcCaptureDeviceList.append(devname) += '\0';
782 al::span<const ALCint> SpanFromAttributeList(const ALCint *attribs) noexcept
784 al::span<const ALCint> attrSpan;
785 if(attribs)
787 const ALCint *attrEnd{attribs};
788 while(*attrEnd != 0)
789 attrEnd += 2; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
790 attrSpan = {attribs, attrEnd};
792 return attrSpan;
795 struct DevFmtPair { DevFmtChannels chans; DevFmtType type; };
796 std::optional<DevFmtPair> DecomposeDevFormat(ALenum format)
798 struct FormatType {
799 ALenum format;
800 DevFmtChannels channels;
801 DevFmtType type;
803 static constexpr std::array list{
804 FormatType{AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte},
805 FormatType{AL_FORMAT_MONO16, DevFmtMono, DevFmtShort},
806 FormatType{AL_FORMAT_MONO_I32, DevFmtMono, DevFmtInt},
807 FormatType{AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat},
809 FormatType{AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte},
810 FormatType{AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort},
811 FormatType{AL_FORMAT_STEREO_I32, DevFmtStereo, DevFmtInt},
812 FormatType{AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat},
814 FormatType{AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte},
815 FormatType{AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort},
816 FormatType{AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat},
817 FormatType{AL_FORMAT_QUAD_I32, DevFmtQuad, DevFmtInt},
818 FormatType{AL_FORMAT_QUAD_FLOAT32, DevFmtQuad, DevFmtFloat},
820 FormatType{AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte},
821 FormatType{AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort},
822 FormatType{AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat},
823 FormatType{AL_FORMAT_51CHN_I32, DevFmtX51, DevFmtInt},
824 FormatType{AL_FORMAT_51CHN_FLOAT32, DevFmtX51, DevFmtFloat},
826 FormatType{AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte},
827 FormatType{AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort},
828 FormatType{AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat},
829 FormatType{AL_FORMAT_61CHN_I32, DevFmtX61, DevFmtInt},
830 FormatType{AL_FORMAT_61CHN_FLOAT32, DevFmtX61, DevFmtFloat},
832 FormatType{AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte},
833 FormatType{AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort},
834 FormatType{AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat},
835 FormatType{AL_FORMAT_71CHN_I32, DevFmtX71, DevFmtInt},
836 FormatType{AL_FORMAT_71CHN_FLOAT32, DevFmtX71, DevFmtFloat},
839 for(const auto &item : list)
841 if(item.format == format)
842 return DevFmtPair{item.channels, item.type};
845 return std::nullopt;
848 std::optional<DevFmtType> DevFmtTypeFromEnum(ALCenum type)
850 switch(type)
852 case ALC_BYTE_SOFT: return DevFmtByte;
853 case ALC_UNSIGNED_BYTE_SOFT: return DevFmtUByte;
854 case ALC_SHORT_SOFT: return DevFmtShort;
855 case ALC_UNSIGNED_SHORT_SOFT: return DevFmtUShort;
856 case ALC_INT_SOFT: return DevFmtInt;
857 case ALC_UNSIGNED_INT_SOFT: return DevFmtUInt;
858 case ALC_FLOAT_SOFT: return DevFmtFloat;
860 WARN("Unsupported format type: 0x%04x\n", type);
861 return std::nullopt;
863 ALCenum EnumFromDevFmt(DevFmtType type)
865 switch(type)
867 case DevFmtByte: return ALC_BYTE_SOFT;
868 case DevFmtUByte: return ALC_UNSIGNED_BYTE_SOFT;
869 case DevFmtShort: return ALC_SHORT_SOFT;
870 case DevFmtUShort: return ALC_UNSIGNED_SHORT_SOFT;
871 case DevFmtInt: return ALC_INT_SOFT;
872 case DevFmtUInt: return ALC_UNSIGNED_INT_SOFT;
873 case DevFmtFloat: return ALC_FLOAT_SOFT;
875 throw std::runtime_error{"Invalid DevFmtType: "+std::to_string(int(type))};
878 std::optional<DevFmtChannels> DevFmtChannelsFromEnum(ALCenum channels)
880 switch(channels)
882 case ALC_MONO_SOFT: return DevFmtMono;
883 case ALC_STEREO_SOFT: return DevFmtStereo;
884 case ALC_QUAD_SOFT: return DevFmtQuad;
885 case ALC_5POINT1_SOFT: return DevFmtX51;
886 case ALC_6POINT1_SOFT: return DevFmtX61;
887 case ALC_7POINT1_SOFT: return DevFmtX71;
888 case ALC_BFORMAT3D_SOFT: return DevFmtAmbi3D;
890 WARN("Unsupported format channels: 0x%04x\n", channels);
891 return std::nullopt;
893 ALCenum EnumFromDevFmt(DevFmtChannels channels)
895 switch(channels)
897 case DevFmtMono: return ALC_MONO_SOFT;
898 case DevFmtStereo: return ALC_STEREO_SOFT;
899 case DevFmtQuad: return ALC_QUAD_SOFT;
900 case DevFmtX51: return ALC_5POINT1_SOFT;
901 case DevFmtX61: return ALC_6POINT1_SOFT;
902 case DevFmtX71: return ALC_7POINT1_SOFT;
903 case DevFmtAmbi3D: return ALC_BFORMAT3D_SOFT;
904 /* FIXME: Shouldn't happen. */
905 case DevFmtX714:
906 case DevFmtX7144:
907 case DevFmtX3D71: break;
909 throw std::runtime_error{"Invalid DevFmtChannels: "+std::to_string(int(channels))};
912 std::optional<DevAmbiLayout> DevAmbiLayoutFromEnum(ALCenum layout)
914 switch(layout)
916 case ALC_FUMA_SOFT: return DevAmbiLayout::FuMa;
917 case ALC_ACN_SOFT: return DevAmbiLayout::ACN;
919 WARN("Unsupported ambisonic layout: 0x%04x\n", layout);
920 return std::nullopt;
922 ALCenum EnumFromDevAmbi(DevAmbiLayout layout)
924 switch(layout)
926 case DevAmbiLayout::FuMa: return ALC_FUMA_SOFT;
927 case DevAmbiLayout::ACN: return ALC_ACN_SOFT;
929 throw std::runtime_error{"Invalid DevAmbiLayout: "+std::to_string(int(layout))};
932 std::optional<DevAmbiScaling> DevAmbiScalingFromEnum(ALCenum scaling)
934 switch(scaling)
936 case ALC_FUMA_SOFT: return DevAmbiScaling::FuMa;
937 case ALC_SN3D_SOFT: return DevAmbiScaling::SN3D;
938 case ALC_N3D_SOFT: return DevAmbiScaling::N3D;
940 WARN("Unsupported ambisonic scaling: 0x%04x\n", scaling);
941 return std::nullopt;
943 ALCenum EnumFromDevAmbi(DevAmbiScaling scaling)
945 switch(scaling)
947 case DevAmbiScaling::FuMa: return ALC_FUMA_SOFT;
948 case DevAmbiScaling::SN3D: return ALC_SN3D_SOFT;
949 case DevAmbiScaling::N3D: return ALC_N3D_SOFT;
951 throw std::runtime_error{"Invalid DevAmbiScaling: "+std::to_string(int(scaling))};
955 /* Downmixing channel arrays, to map a device format's missing channels to
956 * existing ones. Based on what PipeWire does, though simplified.
958 constexpr float inv_sqrt2f{static_cast<float>(1.0 / al::numbers::sqrt2)};
959 constexpr std::array FrontStereo3dB{
960 InputRemixMap::TargetMix{FrontLeft, inv_sqrt2f},
961 InputRemixMap::TargetMix{FrontRight, inv_sqrt2f}
963 constexpr std::array FrontStereo6dB{
964 InputRemixMap::TargetMix{FrontLeft, 0.5f},
965 InputRemixMap::TargetMix{FrontRight, 0.5f}
967 constexpr std::array SideStereo3dB{
968 InputRemixMap::TargetMix{SideLeft, inv_sqrt2f},
969 InputRemixMap::TargetMix{SideRight, inv_sqrt2f}
971 constexpr std::array BackStereo3dB{
972 InputRemixMap::TargetMix{BackLeft, inv_sqrt2f},
973 InputRemixMap::TargetMix{BackRight, inv_sqrt2f}
975 constexpr std::array FrontLeft3dB{InputRemixMap::TargetMix{FrontLeft, inv_sqrt2f}};
976 constexpr std::array FrontRight3dB{InputRemixMap::TargetMix{FrontRight, inv_sqrt2f}};
977 constexpr std::array SideLeft0dB{InputRemixMap::TargetMix{SideLeft, 1.0f}};
978 constexpr std::array SideRight0dB{InputRemixMap::TargetMix{SideRight, 1.0f}};
979 constexpr std::array BackLeft0dB{InputRemixMap::TargetMix{BackLeft, 1.0f}};
980 constexpr std::array BackRight0dB{InputRemixMap::TargetMix{BackRight, 1.0f}};
981 constexpr std::array BackCenter3dB{InputRemixMap::TargetMix{BackCenter, inv_sqrt2f}};
983 constexpr std::array StereoDownmix{
984 InputRemixMap{FrontCenter, FrontStereo3dB},
985 InputRemixMap{SideLeft, FrontLeft3dB},
986 InputRemixMap{SideRight, FrontRight3dB},
987 InputRemixMap{BackLeft, FrontLeft3dB},
988 InputRemixMap{BackRight, FrontRight3dB},
989 InputRemixMap{BackCenter, FrontStereo6dB},
991 constexpr std::array QuadDownmix{
992 InputRemixMap{FrontCenter, FrontStereo3dB},
993 InputRemixMap{SideLeft, BackLeft0dB},
994 InputRemixMap{SideRight, BackRight0dB},
995 InputRemixMap{BackCenter, BackStereo3dB},
997 constexpr std::array X51Downmix{
998 InputRemixMap{BackLeft, SideLeft0dB},
999 InputRemixMap{BackRight, SideRight0dB},
1000 InputRemixMap{BackCenter, SideStereo3dB},
1002 constexpr std::array X61Downmix{
1003 InputRemixMap{BackLeft, BackCenter3dB},
1004 InputRemixMap{BackRight, BackCenter3dB},
1006 constexpr std::array X71Downmix{
1007 InputRemixMap{BackCenter, BackStereo3dB},
1011 std::unique_ptr<Compressor> CreateDeviceLimiter(const ALCdevice *device, const float threshold)
1013 static constexpr bool AutoKnee{true};
1014 static constexpr bool AutoAttack{true};
1015 static constexpr bool AutoRelease{true};
1016 static constexpr bool AutoPostGain{true};
1017 static constexpr bool AutoDeclip{true};
1018 static constexpr float LookAheadTime{0.001f};
1019 static constexpr float HoldTime{0.002f};
1020 static constexpr float PreGainDb{0.0f};
1021 static constexpr float PostGainDb{0.0f};
1022 static constexpr float Ratio{std::numeric_limits<float>::infinity()};
1023 static constexpr float KneeDb{0.0f};
1024 static constexpr float AttackTime{0.02f};
1025 static constexpr float ReleaseTime{0.2f};
1027 return Compressor::Create(device->RealOut.Buffer.size(), static_cast<float>(device->Frequency),
1028 AutoKnee, AutoAttack, AutoRelease, AutoPostGain, AutoDeclip, LookAheadTime, HoldTime,
1029 PreGainDb, PostGainDb, threshold, Ratio, KneeDb, AttackTime, ReleaseTime);
1033 * Updates the device's base clock time with however many samples have been
1034 * done. This is used so frequency changes on the device don't cause the time
1035 * to jump forward or back. Must not be called while the device is running/
1036 * mixing.
1038 inline void UpdateClockBase(ALCdevice *device)
1040 const auto mixLock = device->getWriteMixLock();
1042 auto samplesDone = device->mSamplesDone.load(std::memory_order_relaxed);
1043 auto clockBase = device->mClockBase.load(std::memory_order_relaxed);
1045 clockBase += nanoseconds{seconds{samplesDone}} / device->Frequency;
1046 device->mClockBase.store(clockBase, std::memory_order_relaxed);
1047 device->mSamplesDone.store(0, std::memory_order_relaxed);
1051 * Updates device parameters according to the attribute list (caller is
1052 * responsible for holding the list lock).
1054 ALCenum UpdateDeviceParams(ALCdevice *device, const al::span<const int> attrList)
1056 if(attrList.empty() && device->Type == DeviceType::Loopback)
1058 WARN("Missing attributes for loopback device\n");
1059 return ALC_INVALID_VALUE;
1062 uint numMono{device->NumMonoSources};
1063 uint numStereo{device->NumStereoSources};
1064 uint numSends{device->NumAuxSends};
1065 std::optional<StereoEncoding> stereomode;
1066 std::optional<bool> optlimit;
1067 std::optional<uint> optsrate;
1068 std::optional<DevFmtChannels> optchans;
1069 std::optional<DevFmtType> opttype;
1070 std::optional<DevAmbiLayout> optlayout;
1071 std::optional<DevAmbiScaling> optscale;
1072 uint period_size{DefaultUpdateSize};
1073 uint buffer_size{DefaultUpdateSize * DefaultNumUpdates};
1074 int hrtf_id{-1};
1075 uint aorder{0u};
1077 if(device->Type != DeviceType::Loopback)
1079 /* Get default settings from the user configuration */
1081 if(auto freqopt = device->configValue<uint>({}, "frequency"))
1083 optsrate = std::clamp<uint>(*freqopt, MinOutputRate, MaxOutputRate);
1085 const double scale{static_cast<double>(*optsrate) / double{DefaultOutputRate}};
1086 period_size = static_cast<uint>(std::lround(period_size * scale));
1089 if(auto persizeopt = device->configValue<uint>({}, "period_size"))
1090 period_size = std::clamp(*persizeopt, 64u, 8192u);
1091 if(auto numperopt = device->configValue<uint>({}, "periods"))
1092 buffer_size = std::clamp(*numperopt, 2u, 16u) * period_size;
1093 else
1094 buffer_size = period_size * uint{DefaultNumUpdates};
1096 if(auto typeopt = device->configValue<std::string>({}, "sample-type"))
1098 struct TypeMap {
1099 std::string_view name;
1100 DevFmtType type;
1102 constexpr std::array typelist{
1103 TypeMap{"int8"sv, DevFmtByte },
1104 TypeMap{"uint8"sv, DevFmtUByte },
1105 TypeMap{"int16"sv, DevFmtShort },
1106 TypeMap{"uint16"sv, DevFmtUShort},
1107 TypeMap{"int32"sv, DevFmtInt },
1108 TypeMap{"uint32"sv, DevFmtUInt },
1109 TypeMap{"float32"sv, DevFmtFloat },
1112 const ALCchar *fmt{typeopt->c_str()};
1113 auto iter = std::find_if(typelist.begin(), typelist.end(),
1114 [svfmt=std::string_view{fmt}](const TypeMap &entry) -> bool
1115 { return al::case_compare(entry.name, svfmt) == 0; });
1116 if(iter == typelist.end())
1117 ERR("Unsupported sample-type: %s\n", fmt);
1118 else
1119 opttype = iter->type;
1121 if(auto chanopt = device->configValue<std::string>({}, "channels"))
1123 struct ChannelMap {
1124 std::string_view name;
1125 DevFmtChannels chans;
1126 uint8_t order;
1128 constexpr std::array chanlist{
1129 ChannelMap{"mono"sv, DevFmtMono, 0},
1130 ChannelMap{"stereo"sv, DevFmtStereo, 0},
1131 ChannelMap{"quad"sv, DevFmtQuad, 0},
1132 ChannelMap{"surround51"sv, DevFmtX51, 0},
1133 ChannelMap{"surround61"sv, DevFmtX61, 0},
1134 ChannelMap{"surround71"sv, DevFmtX71, 0},
1135 ChannelMap{"surround714"sv, DevFmtX714, 0},
1136 ChannelMap{"surround7144"sv, DevFmtX7144, 0},
1137 ChannelMap{"surround3d71"sv, DevFmtX3D71, 0},
1138 ChannelMap{"surround51rear"sv, DevFmtX51, 0},
1139 ChannelMap{"ambi1"sv, DevFmtAmbi3D, 1},
1140 ChannelMap{"ambi2"sv, DevFmtAmbi3D, 2},
1141 ChannelMap{"ambi3"sv, DevFmtAmbi3D, 3},
1144 const ALCchar *fmt{chanopt->c_str()};
1145 auto iter = std::find_if(chanlist.begin(), chanlist.end(),
1146 [svfmt=std::string_view{fmt}](const ChannelMap &entry) -> bool
1147 { return al::case_compare(entry.name, svfmt) == 0; });
1148 if(iter == chanlist.end())
1149 ERR("Unsupported channels: %s\n", fmt);
1150 else
1152 optchans = iter->chans;
1153 aorder = iter->order;
1156 if(auto ambiopt = device->configValue<std::string>({}, "ambi-format"sv))
1158 if(al::case_compare(*ambiopt, "fuma"sv) == 0)
1160 optlayout = DevAmbiLayout::FuMa;
1161 optscale = DevAmbiScaling::FuMa;
1163 else if(al::case_compare(*ambiopt, "acn+fuma"sv) == 0)
1165 optlayout = DevAmbiLayout::ACN;
1166 optscale = DevAmbiScaling::FuMa;
1168 else if(al::case_compare(*ambiopt, "ambix"sv) == 0
1169 || al::case_compare(*ambiopt, "acn+sn3d"sv) == 0)
1171 optlayout = DevAmbiLayout::ACN;
1172 optscale = DevAmbiScaling::SN3D;
1174 else if(al::case_compare(*ambiopt, "acn+n3d"sv) == 0)
1176 optlayout = DevAmbiLayout::ACN;
1177 optscale = DevAmbiScaling::N3D;
1179 else
1180 ERR("Unsupported ambi-format: %s\n", ambiopt->c_str());
1183 if(auto hrtfopt = device->configValue<std::string>({}, "hrtf"sv))
1185 WARN("general/hrtf is deprecated, please use stereo-encoding instead\n");
1187 if(al::case_compare(*hrtfopt, "true"sv) == 0)
1188 stereomode = StereoEncoding::Hrtf;
1189 else if(al::case_compare(*hrtfopt, "false"sv) == 0)
1191 if(!stereomode || *stereomode == StereoEncoding::Hrtf)
1192 stereomode = StereoEncoding::Default;
1194 else if(al::case_compare(*hrtfopt, "auto"sv) != 0)
1195 ERR("Unexpected hrtf value: %s\n", hrtfopt->c_str());
1199 if(auto encopt = device->configValue<std::string>({}, "stereo-encoding"sv))
1201 if(al::case_compare(*encopt, "basic"sv) == 0 || al::case_compare(*encopt, "panpot"sv) == 0)
1202 stereomode = StereoEncoding::Basic;
1203 else if(al::case_compare(*encopt, "uhj") == 0)
1204 stereomode = StereoEncoding::Uhj;
1205 else if(al::case_compare(*encopt, "hrtf") == 0)
1206 stereomode = StereoEncoding::Hrtf;
1207 else
1208 ERR("Unexpected stereo-encoding: %s\n", encopt->c_str());
1211 // Check for app-specified attributes
1212 if(!attrList.empty())
1214 ALenum outmode{ALC_ANY_SOFT};
1215 std::optional<bool> opthrtf;
1216 int freqAttr{};
1218 #define ATTRIBUTE(a) a: TRACE("%s = %d\n", #a, attrList[attrIdx + 1]);
1219 for(size_t attrIdx{0};attrIdx < attrList.size();attrIdx+=2)
1221 switch(attrList[attrIdx])
1223 case ATTRIBUTE(ALC_FORMAT_CHANNELS_SOFT)
1224 if(device->Type == DeviceType::Loopback)
1225 optchans = DevFmtChannelsFromEnum(attrList[attrIdx + 1]);
1226 break;
1228 case ATTRIBUTE(ALC_FORMAT_TYPE_SOFT)
1229 if(device->Type == DeviceType::Loopback)
1230 opttype = DevFmtTypeFromEnum(attrList[attrIdx + 1]);
1231 break;
1233 case ATTRIBUTE(ALC_FREQUENCY)
1234 freqAttr = attrList[attrIdx + 1];
1235 break;
1237 case ATTRIBUTE(ALC_AMBISONIC_LAYOUT_SOFT)
1238 if(device->Type == DeviceType::Loopback)
1239 optlayout = DevAmbiLayoutFromEnum(attrList[attrIdx + 1]);
1240 break;
1242 case ATTRIBUTE(ALC_AMBISONIC_SCALING_SOFT)
1243 if(device->Type == DeviceType::Loopback)
1244 optscale = DevAmbiScalingFromEnum(attrList[attrIdx + 1]);
1245 break;
1247 case ATTRIBUTE(ALC_AMBISONIC_ORDER_SOFT)
1248 if(device->Type == DeviceType::Loopback)
1249 aorder = static_cast<uint>(attrList[attrIdx + 1]);
1250 break;
1252 case ATTRIBUTE(ALC_MONO_SOURCES)
1253 numMono = static_cast<uint>(attrList[attrIdx + 1]);
1254 if(numMono > INT_MAX) numMono = 0;
1255 break;
1257 case ATTRIBUTE(ALC_STEREO_SOURCES)
1258 numStereo = static_cast<uint>(attrList[attrIdx + 1]);
1259 if(numStereo > INT_MAX) numStereo = 0;
1260 break;
1262 case ATTRIBUTE(ALC_MAX_AUXILIARY_SENDS)
1263 numSends = static_cast<uint>(attrList[attrIdx + 1]);
1264 if(numSends > uint{std::numeric_limits<int>::max()}) numSends = 0;
1265 else numSends = std::min(numSends, uint{MaxSendCount});
1266 break;
1268 case ATTRIBUTE(ALC_HRTF_SOFT)
1269 if(attrList[attrIdx + 1] == ALC_FALSE)
1270 opthrtf = false;
1271 else if(attrList[attrIdx + 1] == ALC_TRUE)
1272 opthrtf = true;
1273 else if(attrList[attrIdx + 1] == ALC_DONT_CARE_SOFT)
1274 opthrtf = std::nullopt;
1275 break;
1277 case ATTRIBUTE(ALC_HRTF_ID_SOFT)
1278 hrtf_id = attrList[attrIdx + 1];
1279 break;
1281 case ATTRIBUTE(ALC_OUTPUT_LIMITER_SOFT)
1282 if(attrList[attrIdx + 1] == ALC_FALSE)
1283 optlimit = false;
1284 else if(attrList[attrIdx + 1] == ALC_TRUE)
1285 optlimit = true;
1286 else if(attrList[attrIdx + 1] == ALC_DONT_CARE_SOFT)
1287 optlimit = std::nullopt;
1288 break;
1290 case ATTRIBUTE(ALC_OUTPUT_MODE_SOFT)
1291 outmode = attrList[attrIdx + 1];
1292 break;
1294 default:
1295 TRACE("0x%04X = %d (0x%x)\n", attrList[attrIdx],
1296 attrList[attrIdx + 1], attrList[attrIdx + 1]);
1297 break;
1300 #undef ATTRIBUTE
1302 if(device->Type == DeviceType::Loopback)
1304 if(!optchans || !opttype)
1305 return ALC_INVALID_VALUE;
1306 if(freqAttr < int{MinOutputRate} || freqAttr > int{MaxOutputRate})
1307 return ALC_INVALID_VALUE;
1308 if(*optchans == DevFmtAmbi3D)
1310 if(!optlayout || !optscale)
1311 return ALC_INVALID_VALUE;
1312 if(aorder < 1 || aorder > MaxAmbiOrder)
1313 return ALC_INVALID_VALUE;
1314 if((*optlayout == DevAmbiLayout::FuMa || *optscale == DevAmbiScaling::FuMa)
1315 && aorder > 3)
1316 return ALC_INVALID_VALUE;
1318 else if(*optchans == DevFmtStereo)
1320 if(opthrtf)
1322 if(*opthrtf)
1323 stereomode = StereoEncoding::Hrtf;
1324 else
1326 if(stereomode.value_or(StereoEncoding::Hrtf) == StereoEncoding::Hrtf)
1327 stereomode = StereoEncoding::Default;
1331 if(outmode == ALC_STEREO_BASIC_SOFT)
1332 stereomode = StereoEncoding::Basic;
1333 else if(outmode == ALC_STEREO_UHJ_SOFT)
1334 stereomode = StereoEncoding::Uhj;
1335 else if(outmode == ALC_STEREO_HRTF_SOFT)
1336 stereomode = StereoEncoding::Hrtf;
1339 optsrate = static_cast<uint>(freqAttr);
1341 else
1343 if(opthrtf)
1345 if(*opthrtf)
1346 stereomode = StereoEncoding::Hrtf;
1347 else
1349 if(stereomode.value_or(StereoEncoding::Hrtf) == StereoEncoding::Hrtf)
1350 stereomode = StereoEncoding::Default;
1354 if(outmode != ALC_ANY_SOFT)
1356 using OutputMode = ALCdevice::OutputMode;
1357 switch(OutputMode(outmode))
1359 case OutputMode::Any: break;
1360 case OutputMode::Mono: optchans = DevFmtMono; break;
1361 case OutputMode::Stereo: optchans = DevFmtStereo; break;
1362 case OutputMode::StereoBasic:
1363 optchans = DevFmtStereo;
1364 stereomode = StereoEncoding::Basic;
1365 break;
1366 case OutputMode::Uhj2:
1367 optchans = DevFmtStereo;
1368 stereomode = StereoEncoding::Uhj;
1369 break;
1370 case OutputMode::Hrtf:
1371 optchans = DevFmtStereo;
1372 stereomode = StereoEncoding::Hrtf;
1373 break;
1374 case OutputMode::Quad: optchans = DevFmtQuad; break;
1375 case OutputMode::X51: optchans = DevFmtX51; break;
1376 case OutputMode::X61: optchans = DevFmtX61; break;
1377 case OutputMode::X71: optchans = DevFmtX71; break;
1381 if(freqAttr)
1383 uint oldrate = optsrate.value_or(DefaultOutputRate);
1384 freqAttr = std::clamp<int>(freqAttr, MinOutputRate, MaxOutputRate);
1386 const double scale{static_cast<double>(freqAttr) / oldrate};
1387 period_size = static_cast<uint>(std::lround(period_size * scale));
1388 buffer_size = static_cast<uint>(std::lround(buffer_size * scale));
1389 optsrate = static_cast<uint>(freqAttr);
1393 /* If a context is already running on the device, stop playback so the
1394 * device attributes can be updated.
1396 if(device->mDeviceState == DeviceState::Playing)
1398 device->Backend->stop();
1399 device->mDeviceState = DeviceState::Unprepared;
1402 UpdateClockBase(device);
1405 if(device->mDeviceState == DeviceState::Playing)
1406 return ALC_NO_ERROR;
1408 device->mDeviceState = DeviceState::Unprepared;
1409 device->AvgSpeakerDist = 0.0f;
1410 device->mNFCtrlFilter = NfcFilter{};
1411 device->mUhjEncoder = nullptr;
1412 device->AmbiDecoder = nullptr;
1413 device->Bs2b = nullptr;
1414 device->PostProcess = nullptr;
1416 device->Limiter = nullptr;
1417 device->ChannelDelays = nullptr;
1419 std::fill(std::begin(device->HrtfAccumData), std::end(device->HrtfAccumData), float2{});
1421 device->Dry.AmbiMap.fill(BFChannelConfig{});
1422 device->Dry.Buffer = {};
1423 std::fill(std::begin(device->NumChannelsPerOrder), std::end(device->NumChannelsPerOrder), 0u);
1424 device->RealOut.RemixMap = {};
1425 device->RealOut.ChannelIndex.fill(InvalidChannelIndex);
1426 device->RealOut.Buffer = {};
1427 device->MixBuffer.clear();
1428 device->MixBuffer.shrink_to_fit();
1430 UpdateClockBase(device);
1431 device->FixedLatency = nanoseconds::zero();
1433 device->DitherDepth = 0.0f;
1434 device->DitherSeed = DitherRNGSeed;
1436 device->mHrtfStatus = ALC_HRTF_DISABLED_SOFT;
1438 /*************************************************************************
1439 * Update device format request
1442 if(device->Type == DeviceType::Loopback)
1444 device->Frequency = *optsrate;
1445 device->FmtChans = *optchans;
1446 device->FmtType = *opttype;
1447 if(device->FmtChans == DevFmtAmbi3D)
1449 device->mAmbiOrder = aorder;
1450 device->mAmbiLayout = *optlayout;
1451 device->mAmbiScale = *optscale;
1453 device->Flags.set(FrequencyRequest).set(ChannelsRequest).set(SampleTypeRequest);
1455 else
1457 device->FmtType = opttype.value_or(DevFmtTypeDefault);
1458 device->FmtChans = optchans.value_or(DevFmtChannelsDefault);
1459 device->mAmbiOrder = 0;
1460 device->BufferSize = buffer_size;
1461 device->UpdateSize = period_size;
1462 device->Frequency = optsrate.value_or(DefaultOutputRate);
1463 device->Flags.set(FrequencyRequest, optsrate.has_value())
1464 .set(ChannelsRequest, optchans.has_value())
1465 .set(SampleTypeRequest, opttype.has_value());
1467 if(device->FmtChans == DevFmtAmbi3D)
1469 device->mAmbiOrder = std::clamp(aorder, 1u, uint{MaxAmbiOrder});
1470 device->mAmbiLayout = optlayout.value_or(DevAmbiLayout::Default);
1471 device->mAmbiScale = optscale.value_or(DevAmbiScaling::Default);
1472 if(device->mAmbiOrder > 3
1473 && (device->mAmbiLayout == DevAmbiLayout::FuMa
1474 || device->mAmbiScale == DevAmbiScaling::FuMa))
1476 ERR("FuMa is incompatible with %d%s order ambisonics (up to 3rd order only)\n",
1477 device->mAmbiOrder, GetCounterSuffix(device->mAmbiOrder));
1478 device->mAmbiOrder = 3;
1483 TRACE("Pre-reset: %s%s, %s%s, %s%uhz, %u / %u buffer\n",
1484 device->Flags.test(ChannelsRequest)?"*":"", DevFmtChannelsString(device->FmtChans),
1485 device->Flags.test(SampleTypeRequest)?"*":"", DevFmtTypeString(device->FmtType),
1486 device->Flags.test(FrequencyRequest)?"*":"", device->Frequency,
1487 device->UpdateSize, device->BufferSize);
1489 const uint oldFreq{device->Frequency};
1490 const DevFmtChannels oldChans{device->FmtChans};
1491 const DevFmtType oldType{device->FmtType};
1492 try {
1493 auto backend = device->Backend.get();
1494 if(!backend->reset())
1495 throw al::backend_exception{al::backend_error::DeviceError, "Device reset failure"};
1497 catch(std::exception &e) {
1498 ERR("Device error: %s\n", e.what());
1499 device->handleDisconnect("%s", e.what());
1500 return ALC_INVALID_DEVICE;
1503 if(device->FmtChans != oldChans && device->Flags.test(ChannelsRequest))
1505 ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans),
1506 DevFmtChannelsString(device->FmtChans));
1507 device->Flags.reset(ChannelsRequest);
1509 if(device->FmtType != oldType && device->Flags.test(SampleTypeRequest))
1511 ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType),
1512 DevFmtTypeString(device->FmtType));
1513 device->Flags.reset(SampleTypeRequest);
1515 if(device->Frequency != oldFreq && device->Flags.test(FrequencyRequest))
1517 WARN("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency);
1518 device->Flags.reset(FrequencyRequest);
1521 TRACE("Post-reset: %s, %s, %uhz, %u / %u buffer\n",
1522 DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
1523 device->Frequency, device->UpdateSize, device->BufferSize);
1525 if(device->Type != DeviceType::Loopback)
1527 if(auto modeopt = device->configValue<std::string>({}, "stereo-mode"))
1529 if(al::case_compare(*modeopt, "headphones"sv) == 0)
1530 device->Flags.set(DirectEar);
1531 else if(al::case_compare(*modeopt, "speakers"sv) == 0)
1532 device->Flags.reset(DirectEar);
1533 else if(al::case_compare(*modeopt, "auto"sv) != 0)
1534 ERR("Unexpected stereo-mode: %s\n", modeopt->c_str());
1538 aluInitRenderer(device, hrtf_id, stereomode);
1540 /* Calculate the max number of sources, and split them between the mono and
1541 * stereo count given the requested number of stereo sources.
1543 if(auto srcsopt = device->configValue<uint>({}, "sources"sv))
1545 if(*srcsopt <= 0) numMono = 256;
1546 else numMono = std::max(*srcsopt, 16u);
1548 else
1550 numMono = std::min(numMono, std::numeric_limits<int>::max()-numStereo);
1551 numMono = std::max(numMono+numStereo, 256u);
1553 numStereo = std::min(numStereo, numMono);
1554 numMono -= numStereo;
1555 device->SourcesMax = numMono + numStereo;
1556 device->NumMonoSources = numMono;
1557 device->NumStereoSources = numStereo;
1559 if(auto sendsopt = device->configValue<uint>({}, "sends"sv))
1560 numSends = std::min(numSends, std::clamp(*sendsopt, 0u, uint{MaxSendCount}));
1561 device->NumAuxSends = numSends;
1563 TRACE("Max sources: %d (%d + %d), effect slots: %d, sends: %d\n",
1564 device->SourcesMax, device->NumMonoSources, device->NumStereoSources,
1565 device->AuxiliaryEffectSlotMax, device->NumAuxSends);
1567 switch(device->FmtChans)
1569 case DevFmtMono: break;
1570 case DevFmtStereo:
1571 if(!device->mUhjEncoder)
1572 device->RealOut.RemixMap = StereoDownmix;
1573 break;
1574 case DevFmtQuad: device->RealOut.RemixMap = QuadDownmix; break;
1575 case DevFmtX51: device->RealOut.RemixMap = X51Downmix; break;
1576 case DevFmtX61: device->RealOut.RemixMap = X61Downmix; break;
1577 case DevFmtX71: device->RealOut.RemixMap = X71Downmix; break;
1578 case DevFmtX714: device->RealOut.RemixMap = X71Downmix; break;
1579 case DevFmtX7144: device->RealOut.RemixMap = X71Downmix; break;
1580 case DevFmtX3D71: device->RealOut.RemixMap = X51Downmix; break;
1581 case DevFmtAmbi3D: break;
1584 size_t sample_delay{0};
1585 if(auto *encoder{device->mUhjEncoder.get()})
1586 sample_delay += encoder->getDelay();
1588 if(device->getConfigValueBool({}, "dither"sv, true))
1590 int depth{device->configValue<int>({}, "dither-depth"sv).value_or(0)};
1591 if(depth <= 0)
1593 switch(device->FmtType)
1595 case DevFmtByte:
1596 case DevFmtUByte:
1597 depth = 8;
1598 break;
1599 case DevFmtShort:
1600 case DevFmtUShort:
1601 depth = 16;
1602 break;
1603 case DevFmtInt:
1604 case DevFmtUInt:
1605 case DevFmtFloat:
1606 break;
1610 if(depth > 0)
1612 depth = std::clamp(depth, 2, 24);
1613 device->DitherDepth = std::pow(2.0f, static_cast<float>(depth-1));
1616 if(!(device->DitherDepth > 0.0f))
1617 TRACE("Dithering disabled\n");
1618 else
1619 TRACE("Dithering enabled (%d-bit, %g)\n", float2int(std::log2(device->DitherDepth)+0.5f)+1,
1620 device->DitherDepth);
1622 if(!optlimit)
1623 optlimit = device->configValue<bool>({}, "output-limiter");
1625 /* If the gain limiter is unset, use the limiter for integer-based output
1626 * (where samples must be clamped), and don't for floating-point (which can
1627 * take unclamped samples).
1629 if(!optlimit)
1631 switch(device->FmtType)
1633 case DevFmtByte:
1634 case DevFmtUByte:
1635 case DevFmtShort:
1636 case DevFmtUShort:
1637 case DevFmtInt:
1638 case DevFmtUInt:
1639 optlimit = true;
1640 break;
1641 case DevFmtFloat:
1642 break;
1645 if(!optlimit.value_or(false))
1646 TRACE("Output limiter disabled\n");
1647 else
1649 float thrshld{1.0f};
1650 switch(device->FmtType)
1652 case DevFmtByte:
1653 case DevFmtUByte:
1654 thrshld = 127.0f / 128.0f;
1655 break;
1656 case DevFmtShort:
1657 case DevFmtUShort:
1658 thrshld = 32767.0f / 32768.0f;
1659 break;
1660 case DevFmtInt:
1661 case DevFmtUInt:
1662 case DevFmtFloat:
1663 break;
1665 if(device->DitherDepth > 0.0f)
1666 thrshld -= 1.0f / device->DitherDepth;
1668 const float thrshld_dB{std::log10(thrshld) * 20.0f};
1669 auto limiter = CreateDeviceLimiter(device, thrshld_dB);
1671 sample_delay += limiter->getLookAhead();
1672 device->Limiter = std::move(limiter);
1673 TRACE("Output limiter enabled, %.4fdB limit\n", thrshld_dB);
1676 /* Convert the sample delay from samples to nanosamples to nanoseconds. */
1677 sample_delay = std::min<size_t>(sample_delay, std::numeric_limits<int>::max());
1678 device->FixedLatency += nanoseconds{seconds{sample_delay}} / device->Frequency;
1679 TRACE("Fixed device latency: %" PRId64 "ns\n", int64_t{device->FixedLatency.count()});
1681 FPUCtl mixer_mode{};
1682 auto reset_context = [device](ContextBase *ctxbase)
1684 auto *context = dynamic_cast<ALCcontext*>(ctxbase);
1685 assert(context != nullptr);
1686 if(!context) return;
1688 std::unique_lock<std::mutex> proplock{context->mPropLock};
1689 std::unique_lock<std::mutex> slotlock{context->mEffectSlotLock};
1691 /* Clear out unused effect slot clusters. */
1692 auto slot_cluster_not_in_use = [](ContextBase::EffectSlotCluster &clusterptr) -> bool
1694 return std::none_of(clusterptr->begin(), clusterptr->end(),
1695 std::mem_fn(&EffectSlot::InUse));
1697 auto slotcluster_end = std::remove_if(context->mEffectSlotClusters.begin(),
1698 context->mEffectSlotClusters.end(), slot_cluster_not_in_use);
1699 context->mEffectSlotClusters.erase(slotcluster_end, context->mEffectSlotClusters.end());
1701 /* Free all wet buffers. Any in use will be reallocated with an updated
1702 * configuration in aluInitEffectPanning.
1704 auto clear_wetbuffers = [](ContextBase::EffectSlotCluster &clusterptr)
1706 auto clear_buffer = [](EffectSlot &slot)
1708 slot.mWetBuffer.clear();
1709 slot.mWetBuffer.shrink_to_fit();
1710 slot.Wet.Buffer = {};
1712 std::for_each(clusterptr->begin(), clusterptr->end(), clear_buffer);
1714 std::for_each(context->mEffectSlotClusters.begin(), context->mEffectSlotClusters.end(),
1715 clear_wetbuffers);
1717 if(ALeffectslot *slot{context->mDefaultSlot.get()})
1719 auto *slotbase = slot->mSlot;
1720 aluInitEffectPanning(slotbase, context);
1722 if(auto *props = slotbase->Update.exchange(nullptr, std::memory_order_relaxed))
1723 AtomicReplaceHead(context->mFreeEffectSlotProps, props);
1725 EffectState *state{slot->Effect.State.get()};
1726 state->mOutTarget = device->Dry.Buffer;
1727 state->deviceUpdate(device, slot->Buffer);
1728 slot->mPropsDirty = true;
1731 if(EffectSlotArray *curarray{context->mActiveAuxSlots.load(std::memory_order_relaxed)})
1732 std::fill(curarray->begin()+ptrdiff_t(curarray->size()>>1), curarray->end(), nullptr);
1733 auto reset_slots = [device,context](EffectSlotSubList &sublist)
1735 uint64_t usemask{~sublist.FreeMask};
1736 while(usemask)
1738 const auto idx = static_cast<uint>(al::countr_zero(usemask));
1739 auto &slot = (*sublist.EffectSlots)[idx];
1740 usemask &= ~(1_u64 << idx);
1742 auto *slotbase = slot.mSlot;
1743 aluInitEffectPanning(slotbase, context);
1745 if(auto *props = slotbase->Update.exchange(nullptr, std::memory_order_relaxed))
1746 AtomicReplaceHead(context->mFreeEffectSlotProps, props);
1748 EffectState *state{slot.Effect.State.get()};
1749 state->mOutTarget = device->Dry.Buffer;
1750 state->deviceUpdate(device, slot.Buffer);
1751 slot.mPropsDirty = true;
1754 std::for_each(context->mEffectSlotList.begin(), context->mEffectSlotList.end(),
1755 reset_slots);
1757 /* Clear all effect slot props to let them get allocated again. */
1758 context->mEffectSlotPropClusters.clear();
1759 context->mFreeEffectSlotProps.store(nullptr, std::memory_order_relaxed);
1760 slotlock.unlock();
1762 std::unique_lock<std::mutex> srclock{context->mSourceLock};
1763 const uint num_sends{device->NumAuxSends};
1764 auto reset_sources = [num_sends](SourceSubList &sublist)
1766 uint64_t usemask{~sublist.FreeMask};
1767 while(usemask)
1769 const auto idx = static_cast<uint>(al::countr_zero(usemask));
1770 auto &source = (*sublist.Sources)[idx];
1771 usemask &= ~(1_u64 << idx);
1773 auto clear_send = [](ALsource::SendData &send) -> void
1775 if(send.Slot)
1776 DecrementRef(send.Slot->ref);
1777 send.Slot = nullptr;
1778 send.Gain = 1.0f;
1779 send.GainHF = 1.0f;
1780 send.HFReference = LowPassFreqRef;
1781 send.GainLF = 1.0f;
1782 send.LFReference = HighPassFreqRef;
1784 const auto sends = al::span{source.Send}.subspan(num_sends);
1785 std::for_each(sends.begin(), sends.end(), clear_send);
1787 source.mPropsDirty = true;
1790 std::for_each(context->mSourceList.begin(), context->mSourceList.end(), reset_sources);
1792 auto reset_voice = [device,num_sends,context](Voice *voice)
1794 /* Clear extraneous property set sends. */
1795 const auto sendparams = al::span{voice->mProps.Send}.subspan(num_sends);
1796 std::fill(sendparams.begin(), sendparams.end(), VoiceProps::SendData{});
1798 std::fill(voice->mSend.begin()+num_sends, voice->mSend.end(), Voice::TargetData{});
1799 auto clear_wetparams = [num_sends](Voice::ChannelData &chandata)
1801 const auto wetparams = al::span{chandata.mWetParams}.subspan(num_sends);
1802 std::fill(wetparams.begin(), wetparams.end(), SendParams{});
1804 std::for_each(voice->mChans.begin(), voice->mChans.end(), clear_wetparams);
1806 if(VoicePropsItem *props{voice->mUpdate.exchange(nullptr, std::memory_order_relaxed)})
1807 AtomicReplaceHead(context->mFreeVoiceProps, props);
1809 /* Force the voice to stopped if it was stopping. */
1810 Voice::State vstate{Voice::Stopping};
1811 voice->mPlayState.compare_exchange_strong(vstate, Voice::Stopped,
1812 std::memory_order_acquire, std::memory_order_acquire);
1813 if(voice->mSourceID.load(std::memory_order_relaxed) == 0u)
1814 return;
1816 voice->prepare(device);
1818 const auto voicespan = context->getVoicesSpan();
1819 std::for_each(voicespan.begin(), voicespan.end(), reset_voice);
1821 /* Clear all voice props to let them get allocated again. */
1822 context->mVoicePropClusters.clear();
1823 context->mFreeVoiceProps.store(nullptr, std::memory_order_relaxed);
1824 srclock.unlock();
1826 context->mPropsDirty = false;
1827 UpdateContextProps(context);
1828 UpdateAllEffectSlotProps(context);
1829 UpdateAllSourceProps(context);
1831 auto ctxspan = al::span{*device->mContexts.load()};
1832 std::for_each(ctxspan.begin(), ctxspan.end(), reset_context);
1833 mixer_mode.leave();
1835 device->mDeviceState = DeviceState::Configured;
1836 if(!device->Flags.test(DevicePaused))
1838 try {
1839 auto backend = device->Backend.get();
1840 backend->start();
1841 device->mDeviceState = DeviceState::Playing;
1843 catch(al::backend_exception& e) {
1844 ERR("%s\n", e.what());
1845 device->handleDisconnect("%s", e.what());
1846 return ALC_INVALID_DEVICE;
1848 TRACE("Post-start: %s, %s, %uhz, %u / %u buffer\n",
1849 DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
1850 device->Frequency, device->UpdateSize, device->BufferSize);
1853 return ALC_NO_ERROR;
1857 * Updates device parameters as above, and also first clears the disconnected
1858 * status, if set.
1860 bool ResetDeviceParams(ALCdevice *device, const al::span<const int> attrList)
1862 /* If the device was disconnected, reset it since we're opened anew. */
1863 if(!device->Connected.load(std::memory_order_relaxed)) UNLIKELY
1865 /* Make sure disconnection is finished before continuing on. */
1866 std::ignore = device->waitForMix();
1868 for(ContextBase *ctxbase : *device->mContexts.load(std::memory_order_acquire))
1870 auto *ctx = dynamic_cast<ALCcontext*>(ctxbase);
1871 assert(ctx != nullptr);
1872 if(!ctx || !ctx->mStopVoicesOnDisconnect.load(std::memory_order_acquire))
1873 continue;
1875 /* Clear any pending voice changes and reallocate voices to get a
1876 * clean restart.
1878 std::lock_guard<std::mutex> sourcelock{ctx->mSourceLock};
1879 auto *vchg = ctx->mCurrentVoiceChange.load(std::memory_order_acquire);
1880 while(auto *next = vchg->mNext.load(std::memory_order_acquire))
1881 vchg = next;
1882 ctx->mCurrentVoiceChange.store(vchg, std::memory_order_release);
1884 ctx->mVoicePropClusters.clear();
1885 ctx->mFreeVoiceProps.store(nullptr, std::memory_order_relaxed);
1887 ctx->mVoiceClusters.clear();
1888 ctx->allocVoices(std::max<size_t>(256,
1889 ctx->mActiveVoiceCount.load(std::memory_order_relaxed)));
1892 device->Connected.store(true);
1895 ALCenum err{UpdateDeviceParams(device, attrList)};
1896 if(err == ALC_NO_ERROR) LIKELY return ALC_TRUE;
1898 alcSetError(device, err);
1899 return ALC_FALSE;
1903 /** Checks if the device handle is valid, and returns a new reference if so. */
1904 DeviceRef VerifyDevice(ALCdevice *device)
1906 std::lock_guard<std::recursive_mutex> listlock{ListLock};
1907 auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
1908 if(iter != DeviceList.end() && *iter == device)
1910 (*iter)->add_ref();
1911 return DeviceRef{*iter};
1913 return nullptr;
1918 * Checks if the given context is valid, returning a new reference to it if so.
1920 ContextRef VerifyContext(ALCcontext *context)
1922 std::lock_guard<std::recursive_mutex> listlock{ListLock};
1923 auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context);
1924 if(iter != ContextList.end() && *iter == context)
1926 (*iter)->add_ref();
1927 return ContextRef{*iter};
1929 return nullptr;
1932 } // namespace
1934 FORCE_ALIGN void ALC_APIENTRY alsoft_set_log_callback(LPALSOFTLOGCALLBACK callback, void *userptr) noexcept
1936 al_set_log_callback(callback, userptr);
1939 /** Returns a new reference to the currently active context for this thread. */
1940 ContextRef GetContextRef() noexcept
1942 ALCcontext *context{ALCcontext::getThreadContext()};
1943 if(context)
1944 context->add_ref();
1945 else
1947 while(ALCcontext::sGlobalContextLock.exchange(true, std::memory_order_acquire)) {
1948 /* Wait to make sure another thread isn't trying to change the
1949 * current context and bring its refcount to 0.
1952 context = ALCcontext::sGlobalContext.load(std::memory_order_acquire);
1953 if(context) LIKELY context->add_ref();
1954 ALCcontext::sGlobalContextLock.store(false, std::memory_order_release);
1956 return ContextRef{context};
1959 void alcSetError(ALCdevice *device, ALCenum errorCode)
1961 WARN("Error generated on device %p, code 0x%04x\n", voidp{device}, errorCode);
1962 if(TrapALCError)
1964 #ifdef _WIN32
1965 /* DebugBreak() will cause an exception if there is no debugger */
1966 if(IsDebuggerPresent())
1967 DebugBreak();
1968 #elif defined(SIGTRAP)
1969 raise(SIGTRAP);
1970 #endif
1973 if(device)
1974 device->LastError.store(errorCode);
1975 else
1976 LastNullDeviceError.store(errorCode);
1979 /************************************************
1980 * Standard ALC functions
1981 ************************************************/
1983 ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device) noexcept
1985 if(!gProcessRunning)
1986 return ALC_INVALID_DEVICE;
1988 DeviceRef dev{VerifyDevice(device)};
1989 if(dev) return dev->LastError.exchange(ALC_NO_ERROR);
1990 return LastNullDeviceError.exchange(ALC_NO_ERROR);
1994 ALC_API void ALC_APIENTRY alcSuspendContext(ALCcontext *context) noexcept
1996 ContextRef ctx{VerifyContext(context)};
1997 if(!ctx)
1999 alcSetError(nullptr, ALC_INVALID_CONTEXT);
2000 return;
2003 if(ctx->mContextFlags.test(ContextFlags::DebugBit)) UNLIKELY
2004 ctx->debugMessage(DebugSource::API, DebugType::Portability, 0, DebugSeverity::Medium,
2005 "alcSuspendContext behavior is not portable -- some implementations suspend all "
2006 "rendering, some only defer property changes, and some are completely no-op; consider "
2007 "using alcDevicePauseSOFT to suspend all rendering, or alDeferUpdatesSOFT to only "
2008 "defer property changes");
2010 if(SuspendDefers)
2012 std::lock_guard<std::mutex> proplock{ctx->mPropLock};
2013 ctx->deferUpdates();
2017 ALC_API void ALC_APIENTRY alcProcessContext(ALCcontext *context) noexcept
2019 ContextRef ctx{VerifyContext(context)};
2020 if(!ctx)
2022 alcSetError(nullptr, ALC_INVALID_CONTEXT);
2023 return;
2026 if(ctx->mContextFlags.test(ContextFlags::DebugBit)) UNLIKELY
2027 ctx->debugMessage(DebugSource::API, DebugType::Portability, 1, DebugSeverity::Medium,
2028 "alcProcessContext behavior is not portable -- some implementations resume rendering, "
2029 "some apply deferred property changes, and some are completely no-op; consider using "
2030 "alcDeviceResumeSOFT to resume rendering, or alProcessUpdatesSOFT to apply deferred "
2031 "property changes");
2033 if(SuspendDefers)
2035 std::lock_guard<std::mutex> proplock{ctx->mPropLock};
2036 ctx->processUpdates();
2041 ALC_API auto ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param) noexcept -> const ALCchar*
2043 switch(param)
2045 case ALC_NO_ERROR: return GetNoErrorString();
2046 case ALC_INVALID_ENUM: return GetInvalidEnumString();
2047 case ALC_INVALID_VALUE: return GetInvalidValueString();
2048 case ALC_INVALID_DEVICE: return GetInvalidDeviceString();
2049 case ALC_INVALID_CONTEXT: return GetInvalidContextString();
2050 case ALC_OUT_OF_MEMORY: return GetOutOfMemoryString();
2052 case ALC_DEVICE_SPECIFIER:
2053 return GetDefaultName();
2055 case ALC_ALL_DEVICES_SPECIFIER:
2056 if(DeviceRef dev{VerifyDevice(Device)})
2058 if(dev->Type == DeviceType::Capture)
2060 alcSetError(dev.get(), ALC_INVALID_ENUM);
2061 return nullptr;
2063 if(dev->Type == DeviceType::Loopback)
2064 return GetDefaultName();
2066 auto statelock = std::lock_guard{dev->StateLock};
2067 return dev->mDeviceName.c_str();
2069 ProbeAllDevicesList();
2070 return alcAllDevicesList.c_str();
2072 case ALC_CAPTURE_DEVICE_SPECIFIER:
2073 if(DeviceRef dev{VerifyDevice(Device)})
2075 if(dev->Type != DeviceType::Capture)
2077 alcSetError(dev.get(), ALC_INVALID_ENUM);
2078 return nullptr;
2081 auto statelock = std::lock_guard{dev->StateLock};
2082 return dev->mDeviceName.c_str();
2084 ProbeCaptureDeviceList();
2085 return alcCaptureDeviceList.c_str();
2087 /* Default devices are always first in the list */
2088 case ALC_DEFAULT_DEVICE_SPECIFIER:
2089 return GetDefaultName();
2091 case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
2092 if(alcAllDevicesList.empty())
2093 ProbeAllDevicesList();
2095 /* Copy first entry as default. */
2096 if(alcAllDevicesArray.empty())
2097 return GetDefaultName();
2099 alcDefaultAllDevicesSpecifier = alcAllDevicesArray.front();
2100 return alcDefaultAllDevicesSpecifier.c_str();
2102 case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
2103 if(alcCaptureDeviceList.empty())
2104 ProbeCaptureDeviceList();
2106 /* Copy first entry as default. */
2107 if(alcCaptureDeviceArray.empty())
2108 return GetDefaultName();
2110 alcCaptureDefaultDeviceSpecifier = alcCaptureDeviceArray.front();
2111 return alcCaptureDefaultDeviceSpecifier.c_str();
2113 case ALC_EXTENSIONS:
2114 if(VerifyDevice(Device))
2115 return GetExtensionList();
2116 return GetNoDeviceExtList();
2118 case ALC_HRTF_SPECIFIER_SOFT:
2119 if(DeviceRef dev{VerifyDevice(Device)})
2121 std::lock_guard<std::mutex> statelock{dev->StateLock};
2122 return dev->mHrtf ? dev->mHrtfName.c_str() : "";
2124 alcSetError(nullptr, ALC_INVALID_DEVICE);
2125 return nullptr;
2127 default:
2128 alcSetError(VerifyDevice(Device).get(), ALC_INVALID_ENUM);
2131 return nullptr;
2135 static size_t GetIntegerv(ALCdevice *device, ALCenum param, const al::span<int> values)
2137 if(values.empty())
2139 alcSetError(device, ALC_INVALID_VALUE);
2140 return 0;
2143 if(!device)
2145 switch(param)
2147 case ALC_MAJOR_VERSION:
2148 values[0] = alcMajorVersion;
2149 return 1;
2150 case ALC_MINOR_VERSION:
2151 values[0] = alcMinorVersion;
2152 return 1;
2154 case ALC_EFX_MAJOR_VERSION:
2155 values[0] = alcEFXMajorVersion;
2156 return 1;
2157 case ALC_EFX_MINOR_VERSION:
2158 values[0] = alcEFXMinorVersion;
2159 return 1;
2160 case ALC_MAX_AUXILIARY_SENDS:
2161 values[0] = MaxSendCount;
2162 return 1;
2164 case ALC_ATTRIBUTES_SIZE:
2165 case ALC_ALL_ATTRIBUTES:
2166 case ALC_FREQUENCY:
2167 case ALC_REFRESH:
2168 case ALC_SYNC:
2169 case ALC_MONO_SOURCES:
2170 case ALC_STEREO_SOURCES:
2171 case ALC_CAPTURE_SAMPLES:
2172 case ALC_FORMAT_CHANNELS_SOFT:
2173 case ALC_FORMAT_TYPE_SOFT:
2174 case ALC_AMBISONIC_LAYOUT_SOFT:
2175 case ALC_AMBISONIC_SCALING_SOFT:
2176 case ALC_AMBISONIC_ORDER_SOFT:
2177 case ALC_MAX_AMBISONIC_ORDER_SOFT:
2178 alcSetError(nullptr, ALC_INVALID_DEVICE);
2179 return 0;
2181 default:
2182 alcSetError(nullptr, ALC_INVALID_ENUM);
2184 return 0;
2187 std::lock_guard<std::mutex> statelock{device->StateLock};
2188 if(device->Type == DeviceType::Capture)
2190 static constexpr int MaxCaptureAttributes{9};
2191 switch(param)
2193 case ALC_ATTRIBUTES_SIZE:
2194 values[0] = MaxCaptureAttributes;
2195 return 1;
2196 case ALC_ALL_ATTRIBUTES:
2197 if(values.size() >= MaxCaptureAttributes)
2199 size_t i{0};
2200 values[i++] = ALC_MAJOR_VERSION;
2201 values[i++] = alcMajorVersion;
2202 values[i++] = ALC_MINOR_VERSION;
2203 values[i++] = alcMinorVersion;
2204 values[i++] = ALC_CAPTURE_SAMPLES;
2205 values[i++] = static_cast<int>(device->Backend->availableSamples());
2206 values[i++] = ALC_CONNECTED;
2207 values[i++] = device->Connected.load(std::memory_order_relaxed);
2208 values[i++] = 0;
2209 assert(i == MaxCaptureAttributes);
2210 return i;
2212 alcSetError(device, ALC_INVALID_VALUE);
2213 return 0;
2215 case ALC_MAJOR_VERSION:
2216 values[0] = alcMajorVersion;
2217 return 1;
2218 case ALC_MINOR_VERSION:
2219 values[0] = alcMinorVersion;
2220 return 1;
2222 case ALC_CAPTURE_SAMPLES:
2223 values[0] = static_cast<int>(device->Backend->availableSamples());
2224 return 1;
2226 case ALC_CONNECTED:
2227 values[0] = device->Connected.load(std::memory_order_acquire);
2228 return 1;
2230 default:
2231 alcSetError(device, ALC_INVALID_ENUM);
2233 return 0;
2236 /* render device */
2237 auto NumAttrsForDevice = [](const ALCdevice *aldev) noexcept -> uint8_t
2239 if(aldev->Type == DeviceType::Loopback && aldev->FmtChans == DevFmtAmbi3D)
2240 return 37;
2241 return 31;
2243 switch(param)
2245 case ALC_ATTRIBUTES_SIZE:
2246 values[0] = NumAttrsForDevice(device);
2247 return 1;
2249 case ALC_ALL_ATTRIBUTES:
2250 if(values.size() >= NumAttrsForDevice(device))
2252 size_t i{0};
2253 values[i++] = ALC_MAJOR_VERSION;
2254 values[i++] = alcMajorVersion;
2255 values[i++] = ALC_MINOR_VERSION;
2256 values[i++] = alcMinorVersion;
2257 values[i++] = ALC_EFX_MAJOR_VERSION;
2258 values[i++] = alcEFXMajorVersion;
2259 values[i++] = ALC_EFX_MINOR_VERSION;
2260 values[i++] = alcEFXMinorVersion;
2262 values[i++] = ALC_FREQUENCY;
2263 values[i++] = static_cast<int>(device->Frequency);
2264 if(device->Type != DeviceType::Loopback)
2266 values[i++] = ALC_REFRESH;
2267 values[i++] = static_cast<int>(device->Frequency / device->UpdateSize);
2269 values[i++] = ALC_SYNC;
2270 values[i++] = ALC_FALSE;
2272 else
2274 if(device->FmtChans == DevFmtAmbi3D)
2276 values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
2277 values[i++] = EnumFromDevAmbi(device->mAmbiLayout);
2279 values[i++] = ALC_AMBISONIC_SCALING_SOFT;
2280 values[i++] = EnumFromDevAmbi(device->mAmbiScale);
2282 values[i++] = ALC_AMBISONIC_ORDER_SOFT;
2283 values[i++] = static_cast<int>(device->mAmbiOrder);
2286 values[i++] = ALC_FORMAT_CHANNELS_SOFT;
2287 values[i++] = EnumFromDevFmt(device->FmtChans);
2289 values[i++] = ALC_FORMAT_TYPE_SOFT;
2290 values[i++] = EnumFromDevFmt(device->FmtType);
2293 values[i++] = ALC_MONO_SOURCES;
2294 values[i++] = static_cast<int>(device->NumMonoSources);
2296 values[i++] = ALC_STEREO_SOURCES;
2297 values[i++] = static_cast<int>(device->NumStereoSources);
2299 values[i++] = ALC_MAX_AUXILIARY_SENDS;
2300 values[i++] = static_cast<int>(device->NumAuxSends);
2302 values[i++] = ALC_HRTF_SOFT;
2303 values[i++] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
2305 values[i++] = ALC_HRTF_STATUS_SOFT;
2306 values[i++] = device->mHrtfStatus;
2308 values[i++] = ALC_OUTPUT_LIMITER_SOFT;
2309 values[i++] = device->Limiter ? ALC_TRUE : ALC_FALSE;
2311 values[i++] = ALC_MAX_AMBISONIC_ORDER_SOFT;
2312 values[i++] = MaxAmbiOrder;
2314 values[i++] = ALC_OUTPUT_MODE_SOFT;
2315 values[i++] = static_cast<ALCenum>(device->getOutputMode1());
2317 values[i++] = 0;
2318 assert(i == NumAttrsForDevice(device));
2319 return i;
2321 alcSetError(device, ALC_INVALID_VALUE);
2322 return 0;
2324 case ALC_MAJOR_VERSION:
2325 values[0] = alcMajorVersion;
2326 return 1;
2328 case ALC_MINOR_VERSION:
2329 values[0] = alcMinorVersion;
2330 return 1;
2332 case ALC_EFX_MAJOR_VERSION:
2333 values[0] = alcEFXMajorVersion;
2334 return 1;
2336 case ALC_EFX_MINOR_VERSION:
2337 values[0] = alcEFXMinorVersion;
2338 return 1;
2340 case ALC_FREQUENCY:
2341 values[0] = static_cast<int>(device->Frequency);
2342 return 1;
2344 case ALC_REFRESH:
2345 if(device->Type == DeviceType::Loopback)
2347 alcSetError(device, ALC_INVALID_DEVICE);
2348 return 0;
2350 values[0] = static_cast<int>(device->Frequency / device->UpdateSize);
2351 return 1;
2353 case ALC_SYNC:
2354 if(device->Type == DeviceType::Loopback)
2356 alcSetError(device, ALC_INVALID_DEVICE);
2357 return 0;
2359 values[0] = ALC_FALSE;
2360 return 1;
2362 case ALC_FORMAT_CHANNELS_SOFT:
2363 if(device->Type != DeviceType::Loopback)
2365 alcSetError(device, ALC_INVALID_DEVICE);
2366 return 0;
2368 values[0] = EnumFromDevFmt(device->FmtChans);
2369 return 1;
2371 case ALC_FORMAT_TYPE_SOFT:
2372 if(device->Type != DeviceType::Loopback)
2374 alcSetError(device, ALC_INVALID_DEVICE);
2375 return 0;
2377 values[0] = EnumFromDevFmt(device->FmtType);
2378 return 1;
2380 case ALC_AMBISONIC_LAYOUT_SOFT:
2381 if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D)
2383 alcSetError(device, ALC_INVALID_DEVICE);
2384 return 0;
2386 values[0] = EnumFromDevAmbi(device->mAmbiLayout);
2387 return 1;
2389 case ALC_AMBISONIC_SCALING_SOFT:
2390 if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D)
2392 alcSetError(device, ALC_INVALID_DEVICE);
2393 return 0;
2395 values[0] = EnumFromDevAmbi(device->mAmbiScale);
2396 return 1;
2398 case ALC_AMBISONIC_ORDER_SOFT:
2399 if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D)
2401 alcSetError(device, ALC_INVALID_DEVICE);
2402 return 0;
2404 values[0] = static_cast<int>(device->mAmbiOrder);
2405 return 1;
2407 case ALC_MONO_SOURCES:
2408 values[0] = static_cast<int>(device->NumMonoSources);
2409 return 1;
2411 case ALC_STEREO_SOURCES:
2412 values[0] = static_cast<int>(device->NumStereoSources);
2413 return 1;
2415 case ALC_MAX_AUXILIARY_SENDS:
2416 values[0] = static_cast<int>(device->NumAuxSends);
2417 return 1;
2419 case ALC_CONNECTED:
2420 values[0] = device->Connected.load(std::memory_order_acquire);
2421 return 1;
2423 case ALC_HRTF_SOFT:
2424 values[0] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
2425 return 1;
2427 case ALC_HRTF_STATUS_SOFT:
2428 values[0] = device->mHrtfStatus;
2429 return 1;
2431 case ALC_NUM_HRTF_SPECIFIERS_SOFT:
2432 device->enumerateHrtfs();
2433 values[0] = static_cast<int>(std::min(device->mHrtfList.size(),
2434 size_t{std::numeric_limits<int>::max()}));
2435 return 1;
2437 case ALC_OUTPUT_LIMITER_SOFT:
2438 values[0] = device->Limiter ? ALC_TRUE : ALC_FALSE;
2439 return 1;
2441 case ALC_MAX_AMBISONIC_ORDER_SOFT:
2442 values[0] = MaxAmbiOrder;
2443 return 1;
2445 case ALC_OUTPUT_MODE_SOFT:
2446 values[0] = static_cast<ALCenum>(device->getOutputMode1());
2447 return 1;
2449 default:
2450 alcSetError(device, ALC_INVALID_ENUM);
2452 return 0;
2455 ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values) noexcept
2457 DeviceRef dev{VerifyDevice(device)};
2458 if(size <= 0 || values == nullptr)
2459 alcSetError(dev.get(), ALC_INVALID_VALUE);
2460 else
2461 GetIntegerv(dev.get(), param, {values, static_cast<uint>(size)});
2464 ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALCsizei size, ALCint64SOFT *values) noexcept
2466 DeviceRef dev{VerifyDevice(device)};
2467 if(size <= 0 || values == nullptr)
2469 alcSetError(dev.get(), ALC_INVALID_VALUE);
2470 return;
2472 const auto valuespan = al::span{values, static_cast<uint>(size)};
2473 if(!dev || dev->Type == DeviceType::Capture)
2475 auto ivals = std::vector<int>(valuespan.size());
2476 if(size_t got{GetIntegerv(dev.get(), pname, ivals)})
2477 std::copy_n(ivals.cbegin(), got, valuespan.begin());
2478 return;
2480 /* render device */
2481 auto NumAttrsForDevice = [](ALCdevice *aldev) noexcept -> size_t
2483 if(aldev->Type == DeviceType::Loopback && aldev->FmtChans == DevFmtAmbi3D)
2484 return 41;
2485 return 35;
2487 std::lock_guard<std::mutex> statelock{dev->StateLock};
2488 switch(pname)
2490 case ALC_ATTRIBUTES_SIZE:
2491 valuespan[0] = static_cast<ALCint64SOFT>(NumAttrsForDevice(dev.get()));
2492 break;
2494 case ALC_ALL_ATTRIBUTES:
2495 if(valuespan.size() < NumAttrsForDevice(dev.get()))
2496 alcSetError(dev.get(), ALC_INVALID_VALUE);
2497 else
2499 size_t i{0};
2500 valuespan[i++] = ALC_FREQUENCY;
2501 valuespan[i++] = dev->Frequency;
2503 if(dev->Type != DeviceType::Loopback)
2505 valuespan[i++] = ALC_REFRESH;
2506 valuespan[i++] = dev->Frequency / dev->UpdateSize;
2508 valuespan[i++] = ALC_SYNC;
2509 valuespan[i++] = ALC_FALSE;
2511 else
2513 valuespan[i++] = ALC_FORMAT_CHANNELS_SOFT;
2514 valuespan[i++] = EnumFromDevFmt(dev->FmtChans);
2516 valuespan[i++] = ALC_FORMAT_TYPE_SOFT;
2517 valuespan[i++] = EnumFromDevFmt(dev->FmtType);
2519 if(dev->FmtChans == DevFmtAmbi3D)
2521 valuespan[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
2522 valuespan[i++] = EnumFromDevAmbi(dev->mAmbiLayout);
2524 valuespan[i++] = ALC_AMBISONIC_SCALING_SOFT;
2525 valuespan[i++] = EnumFromDevAmbi(dev->mAmbiScale);
2527 valuespan[i++] = ALC_AMBISONIC_ORDER_SOFT;
2528 valuespan[i++] = dev->mAmbiOrder;
2532 valuespan[i++] = ALC_MONO_SOURCES;
2533 valuespan[i++] = dev->NumMonoSources;
2535 valuespan[i++] = ALC_STEREO_SOURCES;
2536 valuespan[i++] = dev->NumStereoSources;
2538 valuespan[i++] = ALC_MAX_AUXILIARY_SENDS;
2539 valuespan[i++] = dev->NumAuxSends;
2541 valuespan[i++] = ALC_HRTF_SOFT;
2542 valuespan[i++] = (dev->mHrtf ? ALC_TRUE : ALC_FALSE);
2544 valuespan[i++] = ALC_HRTF_STATUS_SOFT;
2545 valuespan[i++] = dev->mHrtfStatus;
2547 valuespan[i++] = ALC_OUTPUT_LIMITER_SOFT;
2548 valuespan[i++] = dev->Limiter ? ALC_TRUE : ALC_FALSE;
2550 ClockLatency clock{GetClockLatency(dev.get(), dev->Backend.get())};
2551 valuespan[i++] = ALC_DEVICE_CLOCK_SOFT;
2552 valuespan[i++] = clock.ClockTime.count();
2554 valuespan[i++] = ALC_DEVICE_LATENCY_SOFT;
2555 valuespan[i++] = clock.Latency.count();
2557 valuespan[i++] = ALC_OUTPUT_MODE_SOFT;
2558 valuespan[i++] = al::to_underlying(device->getOutputMode1());
2560 valuespan[i++] = 0;
2562 break;
2564 case ALC_DEVICE_CLOCK_SOFT:
2566 uint samplecount, refcount;
2567 nanoseconds basecount;
2568 do {
2569 refcount = dev->waitForMix();
2570 basecount = dev->mClockBase.load(std::memory_order_relaxed);
2571 samplecount = dev->mSamplesDone.load(std::memory_order_relaxed);
2572 std::atomic_thread_fence(std::memory_order_acquire);
2573 } while(refcount != dev->mMixCount.load(std::memory_order_relaxed));
2574 basecount += nanoseconds{seconds{samplecount}} / dev->Frequency;
2575 valuespan[0] = basecount.count();
2577 break;
2579 case ALC_DEVICE_LATENCY_SOFT:
2580 valuespan[0] = GetClockLatency(dev.get(), dev->Backend.get()).Latency.count();
2581 break;
2583 case ALC_DEVICE_CLOCK_LATENCY_SOFT:
2584 if(size < 2)
2585 alcSetError(dev.get(), ALC_INVALID_VALUE);
2586 else
2588 ClockLatency clock{GetClockLatency(dev.get(), dev->Backend.get())};
2589 valuespan[0] = clock.ClockTime.count();
2590 valuespan[1] = clock.Latency.count();
2592 break;
2594 default:
2595 auto ivals = std::vector<int>(valuespan.size());
2596 if(size_t got{GetIntegerv(dev.get(), pname, ivals)})
2597 std::copy_n(ivals.cbegin(), got, valuespan.begin());
2598 break;
2603 ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName) noexcept
2605 DeviceRef dev{VerifyDevice(device)};
2606 if(!extName)
2608 alcSetError(dev.get(), ALC_INVALID_VALUE);
2609 return ALC_FALSE;
2612 const std::string_view tofind{extName};
2613 const auto extlist = dev ? std::string_view{GetExtensionList()}
2614 : std::string_view{GetNoDeviceExtList()};
2615 auto matchpos = extlist.find(tofind);
2616 while(matchpos != std::string_view::npos)
2618 const auto endpos = matchpos + tofind.size();
2619 if((matchpos == 0 || std::isspace(extlist[matchpos-1]))
2620 && (endpos == extlist.size() || std::isspace(extlist[endpos])))
2621 return ALC_TRUE;
2622 matchpos = extlist.find(tofind, matchpos+1);
2624 return ALC_FALSE;
2628 ALCvoid* ALC_APIENTRY alcGetProcAddress2(ALCdevice *device, const ALCchar *funcName) noexcept
2629 { return alcGetProcAddress(device, funcName); }
2631 ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName) noexcept
2633 if(!funcName)
2635 DeviceRef dev{VerifyDevice(device)};
2636 alcSetError(dev.get(), ALC_INVALID_VALUE);
2637 return nullptr;
2640 #if ALSOFT_EAX
2641 if(eax_g_is_enabled)
2643 for(const auto &func : eaxFunctions)
2645 if(strcmp(func.funcName, funcName) == 0)
2646 return func.address;
2649 #endif
2650 for(const auto &func : alcFunctions)
2652 if(strcmp(func.funcName, funcName) == 0)
2653 return func.address;
2655 return nullptr;
2659 ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName) noexcept
2661 if(!enumName)
2663 DeviceRef dev{VerifyDevice(device)};
2664 alcSetError(dev.get(), ALC_INVALID_VALUE);
2665 return 0;
2668 #if ALSOFT_EAX
2669 if(eax_g_is_enabled)
2671 for(const auto &enm : eaxEnumerations)
2673 if(strcmp(enm.enumName, enumName) == 0)
2674 return enm.value;
2677 #endif
2678 for(const auto &enm : alcEnumerations)
2680 if(strcmp(enm.enumName, enumName) == 0)
2681 return enm.value;
2684 return 0;
2688 ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList) noexcept
2690 /* Explicitly hold the list lock while taking the StateLock in case the
2691 * device is asynchronously destroyed, to ensure this new context is
2692 * properly cleaned up after being made.
2694 std::unique_lock<std::recursive_mutex> listlock{ListLock};
2695 DeviceRef dev{VerifyDevice(device)};
2696 if(!dev || dev->Type == DeviceType::Capture || !dev->Connected.load(std::memory_order_relaxed))
2698 listlock.unlock();
2699 alcSetError(dev.get(), ALC_INVALID_DEVICE);
2700 return nullptr;
2702 std::unique_lock<std::mutex> statelock{dev->StateLock};
2703 listlock.unlock();
2705 dev->LastError.store(ALC_NO_ERROR);
2707 const auto attrSpan = SpanFromAttributeList(attrList);
2708 ALCenum err{UpdateDeviceParams(dev.get(), attrSpan)};
2709 if(err != ALC_NO_ERROR)
2711 alcSetError(dev.get(), err);
2712 return nullptr;
2715 ContextFlagBitset ctxflags{0};
2716 for(size_t i{0};i < attrSpan.size();i+=2)
2718 if(attrSpan[i] == ALC_CONTEXT_FLAGS_EXT)
2720 ctxflags = static_cast<ALuint>(attrSpan[i+1]);
2721 break;
2725 auto context = ContextRef{new(std::nothrow) ALCcontext{dev, ctxflags}};
2726 if(!context)
2728 alcSetError(dev.get(), ALC_OUT_OF_MEMORY);
2729 return nullptr;
2731 context->init();
2733 if(auto volopt = dev->configValue<float>({}, "volume-adjust"))
2735 const float valf{*volopt};
2736 if(!std::isfinite(valf))
2737 ERR("volume-adjust must be finite: %f\n", valf);
2738 else
2740 const float db{std::clamp(valf, -24.0f, 24.0f)};
2741 if(db != valf)
2742 WARN("volume-adjust clamped: %f, range: +/-%f\n", valf, 24.0f);
2743 context->mGainBoost = std::pow(10.0f, db/20.0f);
2744 TRACE("volume-adjust gain: %f\n", context->mGainBoost);
2749 using ContextArray = al::FlexArray<ContextBase*>;
2751 /* Allocate a new context array, which holds 1 more than the current/
2752 * old array.
2754 auto *oldarray = device->mContexts.load();
2755 auto newarray = ContextArray::Create(oldarray->size() + 1);
2757 /* Copy the current/old context handles to the new array, appending the
2758 * new context.
2760 auto iter = std::copy(oldarray->begin(), oldarray->end(), newarray->begin());
2761 *iter = context.get();
2763 /* Store the new context array in the device. Wait for any current mix
2764 * to finish before deleting the old array.
2766 auto prevarray = dev->mContexts.exchange(std::move(newarray));
2767 std::ignore = dev->waitForMix();
2769 statelock.unlock();
2772 listlock.lock();
2773 auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context.get());
2774 ContextList.emplace(iter, context.get());
2775 listlock.unlock();
2778 if(ALeffectslot *slot{context->mDefaultSlot.get()})
2780 ALenum sloterr{slot->initEffect(0, ALCcontext::sDefaultEffect.type,
2781 ALCcontext::sDefaultEffect.Props, context.get())};
2782 if(sloterr == AL_NO_ERROR)
2783 slot->updateProps(context.get());
2784 else
2785 ERR("Failed to initialize the default effect\n");
2788 TRACE("Created context %p\n", voidp{context.get()});
2789 return context.release();
2792 ALC_API void ALC_APIENTRY alcDestroyContext(ALCcontext *context) noexcept
2794 if(!gProcessRunning)
2795 return;
2797 std::unique_lock<std::recursive_mutex> listlock{ListLock};
2798 auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context);
2799 if(iter == ContextList.end() || *iter != context)
2801 listlock.unlock();
2802 alcSetError(nullptr, ALC_INVALID_CONTEXT);
2803 return;
2806 /* Hold a reference to this context so it remains valid until the ListLock
2807 * is released.
2809 ContextRef ctx{*iter};
2810 ContextList.erase(iter);
2812 ALCdevice *Device{ctx->mALDevice.get()};
2814 std::lock_guard<std::mutex> statelock{Device->StateLock};
2815 ctx->deinit();
2819 ALC_API auto ALC_APIENTRY alcGetCurrentContext() noexcept -> ALCcontext*
2821 ALCcontext *Context{ALCcontext::getThreadContext()};
2822 if(!Context) Context = ALCcontext::sGlobalContext.load();
2823 return Context;
2826 /** Returns the currently active thread-local context. */
2827 ALC_API auto ALC_APIENTRY alcGetThreadContext() noexcept -> ALCcontext*
2828 { return ALCcontext::getThreadContext(); }
2830 ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context) noexcept
2832 /* context must be valid or nullptr */
2833 ContextRef ctx;
2834 if(context)
2836 ctx = VerifyContext(context);
2837 if(!ctx)
2839 alcSetError(nullptr, ALC_INVALID_CONTEXT);
2840 return ALC_FALSE;
2843 /* Release this reference (if any) to store it in the GlobalContext
2844 * pointer. Take ownership of the reference (if any) that was previously
2845 * stored there, and let the reference go.
2847 while(ALCcontext::sGlobalContextLock.exchange(true, std::memory_order_acquire)) {
2848 /* Wait to make sure another thread isn't getting or trying to change
2849 * the current context as its refcount is decremented.
2852 ctx = ContextRef{ALCcontext::sGlobalContext.exchange(ctx.release())};
2853 ALCcontext::sGlobalContextLock.store(false, std::memory_order_release);
2855 /* Take ownership of the thread-local context reference (if any), clearing
2856 * the storage to null.
2858 ctx = ContextRef{ALCcontext::getThreadContext()};
2859 if(ctx) ALCcontext::setThreadContext(nullptr);
2860 /* Reset (decrement) the previous thread-local reference. */
2862 return ALC_TRUE;
2865 /** Makes the given context the active context for the current thread. */
2866 ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context) noexcept
2868 /* context must be valid or nullptr */
2869 ContextRef ctx;
2870 if(context)
2872 ctx = VerifyContext(context);
2873 if(!ctx)
2875 alcSetError(nullptr, ALC_INVALID_CONTEXT);
2876 return ALC_FALSE;
2879 /* context's reference count is already incremented */
2880 ContextRef old{ALCcontext::getThreadContext()};
2881 ALCcontext::setThreadContext(ctx.release());
2883 return ALC_TRUE;
2887 ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context) noexcept
2889 ContextRef ctx{VerifyContext(Context)};
2890 if(!ctx)
2892 alcSetError(nullptr, ALC_INVALID_CONTEXT);
2893 return nullptr;
2895 return ctx->mALDevice.get();
2899 ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName) noexcept
2901 InitConfig();
2903 if(!PlaybackFactory)
2905 alcSetError(nullptr, ALC_INVALID_VALUE);
2906 return nullptr;
2909 std::string_view devname{deviceName ? deviceName : ""};
2910 if(!devname.empty())
2912 TRACE("Opening playback device \"%.*s\"\n", al::sizei(devname), devname.data());
2913 if(al::case_compare(devname, GetDefaultName()) == 0
2914 #ifdef _WIN32
2915 /* Some old Windows apps hardcode these expecting OpenAL to use a
2916 * specific audio API, even when they're not enumerated. Creative's
2917 * router effectively ignores them too.
2919 || al::case_compare(devname, "DirectSound3D"sv) == 0
2920 || al::case_compare(devname, "DirectSound"sv) == 0
2921 || al::case_compare(devname, "MMSYSTEM"sv) == 0
2922 #endif
2923 /* Some old Linux apps hardcode configuration strings that were
2924 * supported by the OpenAL SI. We can't really do anything useful
2925 * with them, so just ignore.
2927 || al::starts_with(devname, "'("sv)
2928 || al::case_compare(devname, "openal-soft"sv) == 0)
2929 devname = {};
2930 else
2932 const auto prefix = GetDevicePrefix();
2933 if(!prefix.empty() && devname.size() > prefix.size()
2934 && al::starts_with(devname, prefix))
2935 devname = devname.substr(prefix.size());
2938 else
2939 TRACE("Opening default playback device\n");
2941 const uint DefaultSends{
2942 #if ALSOFT_EAX
2943 eax_g_is_enabled ? uint{EAX_MAX_FXSLOTS} :
2944 #endif // ALSOFT_EAX
2945 uint{DefaultSendCount}
2948 DeviceRef device{new(std::nothrow) ALCdevice{DeviceType::Playback}};
2949 if(!device)
2951 WARN("Failed to create playback device handle\n");
2952 alcSetError(nullptr, ALC_OUT_OF_MEMORY);
2953 return nullptr;
2956 /* Set output format */
2957 device->FmtChans = DevFmtChannelsDefault;
2958 device->FmtType = DevFmtTypeDefault;
2959 device->Frequency = DefaultOutputRate;
2960 device->UpdateSize = DefaultUpdateSize;
2961 device->BufferSize = DefaultUpdateSize * DefaultNumUpdates;
2963 device->SourcesMax = 256;
2964 device->NumStereoSources = 1;
2965 device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
2966 device->AuxiliaryEffectSlotMax = 64;
2967 device->NumAuxSends = DefaultSends;
2969 try {
2970 auto backend = PlaybackFactory->createBackend(device.get(), BackendType::Playback);
2971 std::lock_guard<std::recursive_mutex> listlock{ListLock};
2972 backend->open(devname);
2973 device->mDeviceName = std::string{GetDevicePrefix()}+backend->mDeviceName;
2974 device->Backend = std::move(backend);
2976 catch(al::backend_exception &e) {
2977 WARN("Failed to open playback device: %s\n", e.what());
2978 alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory)
2979 ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
2980 return nullptr;
2983 auto checkopt = [&device](const char *envname, const std::string_view optname)
2985 if(auto optval = al::getenv(envname)) return optval;
2986 return device->configValue<std::string>("game_compat", optname);
2988 if(auto overrideopt = checkopt("__ALSOFT_VENDOR_OVERRIDE", "vendor-override"sv))
2990 device->mVendorOverride = std::move(*overrideopt);
2991 TRACE("Overriding vendor string: \"%s\"\n", device->mVendorOverride.c_str());
2993 if(auto overrideopt = checkopt("__ALSOFT_VERSION_OVERRIDE", "version-override"sv))
2995 device->mVersionOverride = std::move(*overrideopt);
2996 TRACE("Overriding version string: \"%s\"\n", device->mVersionOverride.c_str());
2998 if(auto overrideopt = checkopt("__ALSOFT_RENDERER_OVERRIDE", "renderer-override"sv))
3000 device->mRendererOverride = std::move(*overrideopt);
3001 TRACE("Overriding renderer string: \"%s\"\n", device->mRendererOverride.c_str());
3005 std::lock_guard<std::recursive_mutex> listlock{ListLock};
3006 auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
3007 DeviceList.emplace(iter, device.get());
3010 TRACE("Created device %p, \"%s\"\n", voidp{device.get()}, device->mDeviceName.c_str());
3011 return device.release();
3014 ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device) noexcept
3016 if(!gProcessRunning)
3017 return ALC_FALSE;
3019 std::unique_lock<std::recursive_mutex> listlock{ListLock};
3020 auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
3021 if(iter == DeviceList.end() || *iter != device)
3023 alcSetError(nullptr, ALC_INVALID_DEVICE);
3024 return ALC_FALSE;
3026 if((*iter)->Type == DeviceType::Capture)
3028 alcSetError(*iter, ALC_INVALID_DEVICE);
3029 return ALC_FALSE;
3032 /* Erase the device, and any remaining contexts left on it, from their
3033 * respective lists.
3035 DeviceRef dev{*iter};
3036 DeviceList.erase(iter);
3038 std::unique_lock<std::mutex> statelock{dev->StateLock};
3039 std::vector<ContextRef> orphanctxs;
3040 for(ContextBase *ctx : *dev->mContexts.load())
3042 auto ctxiter = std::lower_bound(ContextList.begin(), ContextList.end(), ctx);
3043 if(ctxiter != ContextList.end() && *ctxiter == ctx)
3045 orphanctxs.emplace_back(*ctxiter);
3046 ContextList.erase(ctxiter);
3049 listlock.unlock();
3051 for(ContextRef &context : orphanctxs)
3053 WARN("Releasing orphaned context %p\n", voidp{context.get()});
3054 context->deinit();
3056 orphanctxs.clear();
3058 if(dev->mDeviceState == DeviceState::Playing)
3060 dev->Backend->stop();
3061 dev->mDeviceState = DeviceState::Configured;
3064 return ALC_TRUE;
3068 /************************************************
3069 * ALC capture functions
3070 ************************************************/
3071 ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples) noexcept
3073 InitConfig();
3075 if(!CaptureFactory)
3077 alcSetError(nullptr, ALC_INVALID_VALUE);
3078 return nullptr;
3081 if(samples <= 0)
3083 alcSetError(nullptr, ALC_INVALID_VALUE);
3084 return nullptr;
3087 std::string_view devname{deviceName ? deviceName : ""};
3088 if(!devname.empty())
3090 TRACE("Opening capture device \"%.*s\"\n", al::sizei(devname), devname.data());
3091 if(al::case_compare(devname, GetDefaultName()) == 0
3092 || al::case_compare(devname, "openal-soft"sv) == 0)
3093 devname = {};
3094 else
3096 const auto prefix = GetDevicePrefix();
3097 if(!prefix.empty() && devname.size() > prefix.size()
3098 && al::starts_with(devname, prefix))
3099 devname = devname.substr(prefix.size());
3102 else
3103 TRACE("Opening default capture device\n");
3105 DeviceRef device{new(std::nothrow) ALCdevice{DeviceType::Capture}};
3106 if(!device)
3108 WARN("Failed to create capture device handle\n");
3109 alcSetError(nullptr, ALC_OUT_OF_MEMORY);
3110 return nullptr;
3113 auto decompfmt = DecomposeDevFormat(format);
3114 if(!decompfmt)
3116 alcSetError(nullptr, ALC_INVALID_ENUM);
3117 return nullptr;
3120 device->Frequency = frequency;
3121 device->FmtChans = decompfmt->chans;
3122 device->FmtType = decompfmt->type;
3123 device->Flags.set(FrequencyRequest);
3124 device->Flags.set(ChannelsRequest);
3125 device->Flags.set(SampleTypeRequest);
3127 device->UpdateSize = static_cast<uint>(samples);
3128 device->BufferSize = static_cast<uint>(samples);
3130 TRACE("Capture format: %s, %s, %uhz, %u / %u buffer\n", DevFmtChannelsString(device->FmtChans),
3131 DevFmtTypeString(device->FmtType), device->Frequency, device->UpdateSize,
3132 device->BufferSize);
3134 try {
3135 auto backend = CaptureFactory->createBackend(device.get(), BackendType::Capture);
3136 std::lock_guard<std::recursive_mutex> listlock{ListLock};
3137 backend->open(devname);
3138 device->mDeviceName = std::string{GetDevicePrefix()}+backend->mDeviceName;
3139 device->Backend = std::move(backend);
3141 catch(al::backend_exception &e) {
3142 WARN("Failed to open capture device: %s\n", e.what());
3143 alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory)
3144 ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
3145 return nullptr;
3149 std::lock_guard<std::recursive_mutex> listlock{ListLock};
3150 auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
3151 DeviceList.emplace(iter, device.get());
3153 device->mDeviceState = DeviceState::Configured;
3155 TRACE("Created capture device %p, \"%s\"\n", voidp{device.get()}, device->mDeviceName.c_str());
3156 return device.release();
3159 ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device) noexcept
3161 if(!gProcessRunning)
3162 return ALC_FALSE;
3164 std::unique_lock<std::recursive_mutex> listlock{ListLock};
3165 auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
3166 if(iter == DeviceList.end() || *iter != device)
3168 alcSetError(nullptr, ALC_INVALID_DEVICE);
3169 return ALC_FALSE;
3171 if((*iter)->Type != DeviceType::Capture)
3173 alcSetError(*iter, ALC_INVALID_DEVICE);
3174 return ALC_FALSE;
3177 DeviceRef dev{*iter};
3178 DeviceList.erase(iter);
3179 listlock.unlock();
3181 std::lock_guard<std::mutex> statelock{dev->StateLock};
3182 if(dev->mDeviceState == DeviceState::Playing)
3184 dev->Backend->stop();
3185 dev->mDeviceState = DeviceState::Configured;
3188 return ALC_TRUE;
3191 ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device) noexcept
3193 DeviceRef dev{VerifyDevice(device)};
3194 if(!dev || dev->Type != DeviceType::Capture)
3196 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3197 return;
3200 std::lock_guard<std::mutex> statelock{dev->StateLock};
3201 if(!dev->Connected.load(std::memory_order_acquire)
3202 || dev->mDeviceState < DeviceState::Configured)
3203 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3204 else if(dev->mDeviceState != DeviceState::Playing)
3206 try {
3207 auto backend = dev->Backend.get();
3208 backend->start();
3209 dev->mDeviceState = DeviceState::Playing;
3211 catch(al::backend_exception& e) {
3212 ERR("%s\n", e.what());
3213 dev->handleDisconnect("%s", e.what());
3214 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3219 ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device) noexcept
3221 DeviceRef dev{VerifyDevice(device)};
3222 if(!dev || dev->Type != DeviceType::Capture)
3223 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3224 else
3226 std::lock_guard<std::mutex> statelock{dev->StateLock};
3227 if(dev->mDeviceState == DeviceState::Playing)
3229 dev->Backend->stop();
3230 dev->mDeviceState = DeviceState::Configured;
3235 ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) noexcept
3237 DeviceRef dev{VerifyDevice(device)};
3238 if(!dev || dev->Type != DeviceType::Capture)
3240 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3241 return;
3244 if(samples < 0 || (samples > 0 && buffer == nullptr))
3246 alcSetError(dev.get(), ALC_INVALID_VALUE);
3247 return;
3249 if(samples < 1)
3250 return;
3252 std::lock_guard<std::mutex> statelock{dev->StateLock};
3253 BackendBase *backend{dev->Backend.get()};
3255 const auto usamples = static_cast<uint>(samples);
3256 if(usamples > backend->availableSamples())
3258 alcSetError(dev.get(), ALC_INVALID_VALUE);
3259 return;
3262 backend->captureSamples(static_cast<std::byte*>(buffer), usamples);
3266 /************************************************
3267 * ALC loopback functions
3268 ************************************************/
3270 /** Open a loopback device, for manual rendering. */
3271 ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName) noexcept
3273 InitConfig();
3275 /* Make sure the device name, if specified, is us. */
3276 if(deviceName && strcmp(deviceName, GetDefaultName()) != 0)
3278 alcSetError(nullptr, ALC_INVALID_VALUE);
3279 return nullptr;
3282 const uint DefaultSends{
3283 #if ALSOFT_EAX
3284 eax_g_is_enabled ? uint{EAX_MAX_FXSLOTS} :
3285 #endif // ALSOFT_EAX
3286 uint{DefaultSendCount}
3289 DeviceRef device{new(std::nothrow) ALCdevice{DeviceType::Loopback}};
3290 if(!device)
3292 WARN("Failed to create loopback device handle\n");
3293 alcSetError(nullptr, ALC_OUT_OF_MEMORY);
3294 return nullptr;
3297 device->SourcesMax = 256;
3298 device->AuxiliaryEffectSlotMax = 64;
3299 device->NumAuxSends = DefaultSends;
3301 //Set output format
3302 device->BufferSize = 0;
3303 device->UpdateSize = 0;
3305 device->Frequency = DefaultOutputRate;
3306 device->FmtChans = DevFmtChannelsDefault;
3307 device->FmtType = DevFmtTypeDefault;
3309 device->NumStereoSources = 1;
3310 device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
3312 try {
3313 auto backend = LoopbackBackendFactory::getFactory().createBackend(device.get(),
3314 BackendType::Playback);
3315 backend->open("Loopback");
3316 device->mDeviceName = std::string{GetDevicePrefix()}+backend->mDeviceName;
3317 device->Backend = std::move(backend);
3319 catch(al::backend_exception &e) {
3320 WARN("Failed to open loopback device: %s\n", e.what());
3321 alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory)
3322 ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
3323 return nullptr;
3327 std::lock_guard<std::recursive_mutex> listlock{ListLock};
3328 auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
3329 DeviceList.emplace(iter, device.get());
3332 TRACE("Created loopback device %p\n", voidp{device.get()});
3333 return device.release();
3337 * Determines if the loopback device supports the given format for rendering.
3339 ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type) noexcept
3341 DeviceRef dev{VerifyDevice(device)};
3342 if(!dev || dev->Type != DeviceType::Loopback)
3343 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3344 else if(freq <= 0)
3345 alcSetError(dev.get(), ALC_INVALID_VALUE);
3346 else
3348 if(DevFmtTypeFromEnum(type).has_value() && DevFmtChannelsFromEnum(channels).has_value()
3349 && freq >= int{MinOutputRate} && freq <= int{MaxOutputRate})
3350 return ALC_TRUE;
3353 return ALC_FALSE;
3357 * Renders some samples into a buffer, using the format last set by the
3358 * attributes given to alcCreateContext.
3360 #if defined(__GNUC__) && defined(__i386__)
3361 /* Needed on x86-32 even without SSE codegen, since the mixer may still use SSE
3362 * and GCC assumes the stack is aligned (x86-64 ABI guarantees alignment).
3364 [[gnu::force_align_arg_pointer]]
3365 #endif
3366 ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) noexcept
3368 if(!device || device->Type != DeviceType::Loopback) UNLIKELY
3369 alcSetError(device, ALC_INVALID_DEVICE);
3370 else if(samples < 0 || (samples > 0 && buffer == nullptr)) UNLIKELY
3371 alcSetError(device, ALC_INVALID_VALUE);
3372 else
3373 device->renderSamples(buffer, static_cast<uint>(samples), device->channelsFromFmt());
3377 /************************************************
3378 * ALC DSP pause/resume functions
3379 ************************************************/
3381 /** Pause the DSP to stop audio processing. */
3382 ALC_API void ALC_APIENTRY alcDevicePauseSOFT(ALCdevice *device) noexcept
3384 DeviceRef dev{VerifyDevice(device)};
3385 if(!dev || dev->Type != DeviceType::Playback)
3386 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3387 else
3389 std::lock_guard<std::mutex> statelock{dev->StateLock};
3390 if(dev->mDeviceState == DeviceState::Playing)
3392 dev->Backend->stop();
3393 dev->mDeviceState = DeviceState::Configured;
3395 dev->Flags.set(DevicePaused);
3399 /** Resume the DSP to restart audio processing. */
3400 ALC_API void ALC_APIENTRY alcDeviceResumeSOFT(ALCdevice *device) noexcept
3402 DeviceRef dev{VerifyDevice(device)};
3403 if(!dev || dev->Type != DeviceType::Playback)
3405 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3406 return;
3409 std::lock_guard<std::mutex> statelock{dev->StateLock};
3410 if(!dev->Flags.test(DevicePaused))
3411 return;
3412 if(dev->mDeviceState < DeviceState::Configured)
3414 WARN("Cannot resume unconfigured device\n");
3415 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3416 return;
3418 if(!dev->Connected.load())
3420 WARN("Cannot resume a disconnected device\n");
3421 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3422 return;
3424 dev->Flags.reset(DevicePaused);
3425 if(dev->mContexts.load()->empty())
3426 return;
3428 try {
3429 auto backend = dev->Backend.get();
3430 backend->start();
3431 dev->mDeviceState = DeviceState::Playing;
3433 catch(al::backend_exception& e) {
3434 ERR("%s\n", e.what());
3435 dev->handleDisconnect("%s", e.what());
3436 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3437 return;
3439 TRACE("Post-resume: %s, %s, %uhz, %u / %u buffer\n",
3440 DevFmtChannelsString(dev->FmtChans), DevFmtTypeString(dev->FmtType),
3441 dev->Frequency, dev->UpdateSize, dev->BufferSize);
3445 /************************************************
3446 * ALC HRTF functions
3447 ************************************************/
3449 /** Gets a string parameter at the given index. */
3450 ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum paramName, ALCsizei index) noexcept
3452 DeviceRef dev{VerifyDevice(device)};
3453 if(!dev || dev->Type == DeviceType::Capture)
3454 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3455 else switch(paramName)
3457 case ALC_HRTF_SPECIFIER_SOFT:
3458 if(index >= 0 && static_cast<uint>(index) < dev->mHrtfList.size())
3459 return dev->mHrtfList[static_cast<uint>(index)].c_str();
3460 alcSetError(dev.get(), ALC_INVALID_VALUE);
3461 break;
3463 default:
3464 alcSetError(dev.get(), ALC_INVALID_ENUM);
3465 break;
3468 return nullptr;
3471 /** Resets the given device output, using the specified attribute list. */
3472 ALC_API ALCboolean ALC_APIENTRY alcResetDeviceSOFT(ALCdevice *device, const ALCint *attribs) noexcept
3474 std::unique_lock<std::recursive_mutex> listlock{ListLock};
3475 DeviceRef dev{VerifyDevice(device)};
3476 if(!dev || dev->Type == DeviceType::Capture)
3478 listlock.unlock();
3479 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3480 return ALC_FALSE;
3482 std::lock_guard<std::mutex> statelock{dev->StateLock};
3483 listlock.unlock();
3485 /* Force the backend to stop mixing first since we're resetting. Also reset
3486 * the connected state so lost devices can attempt recover.
3488 if(dev->mDeviceState == DeviceState::Playing)
3490 dev->Backend->stop();
3491 dev->mDeviceState = DeviceState::Configured;
3494 return ResetDeviceParams(dev.get(), SpanFromAttributeList(attribs)) ? ALC_TRUE : ALC_FALSE;
3498 /************************************************
3499 * ALC device reopen functions
3500 ************************************************/
3502 /** Reopens the given device output, using the specified name and attribute list. */
3503 FORCE_ALIGN ALCboolean ALC_APIENTRY alcReopenDeviceSOFT(ALCdevice *device,
3504 const ALCchar *deviceName, const ALCint *attribs) noexcept
3506 std::unique_lock<std::recursive_mutex> listlock{ListLock};
3507 DeviceRef dev{VerifyDevice(device)};
3508 if(!dev || dev->Type != DeviceType::Playback)
3510 listlock.unlock();
3511 alcSetError(dev.get(), ALC_INVALID_DEVICE);
3512 return ALC_FALSE;
3514 std::lock_guard<std::mutex> statelock{dev->StateLock};
3516 std::string_view devname{deviceName ? deviceName : ""};
3517 if(!devname.empty())
3519 if(devname.length() >= size_t{std::numeric_limits<int>::max()})
3521 ERR("Device name too long (%zu >= %d)\n", devname.length(),
3522 std::numeric_limits<int>::max());
3523 alcSetError(dev.get(), ALC_INVALID_VALUE);
3524 return ALC_FALSE;
3526 if(al::case_compare(devname, GetDefaultName()) == 0)
3527 devname = {};
3528 else
3530 const auto prefix = GetDevicePrefix();
3531 if(!prefix.empty() && devname.size() > prefix.size()
3532 && al::starts_with(devname, prefix))
3533 devname = devname.substr(prefix.size());
3537 /* Force the backend device to stop first since we're opening another one. */
3538 const bool wasPlaying{dev->mDeviceState == DeviceState::Playing};
3539 if(wasPlaying)
3541 dev->Backend->stop();
3542 dev->mDeviceState = DeviceState::Configured;
3545 BackendPtr newbackend;
3546 try {
3547 newbackend = PlaybackFactory->createBackend(dev.get(), BackendType::Playback);
3548 newbackend->open(devname);
3550 catch(al::backend_exception &e) {
3551 listlock.unlock();
3552 newbackend = nullptr;
3554 WARN("Failed to reopen playback device: %s\n", e.what());
3555 alcSetError(dev.get(), (e.errorCode() == al::backend_error::OutOfMemory)
3556 ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
3558 if(dev->Connected.load(std::memory_order_relaxed) && wasPlaying)
3560 try {
3561 auto backend = dev->Backend.get();
3562 backend->start();
3563 dev->mDeviceState = DeviceState::Playing;
3565 catch(al::backend_exception &be) {
3566 ERR("%s\n", be.what());
3567 dev->handleDisconnect("%s", be.what());
3570 return ALC_FALSE;
3572 listlock.unlock();
3573 dev->mDeviceName = std::string{GetDevicePrefix()}+newbackend->mDeviceName;
3574 dev->Backend = std::move(newbackend);
3575 dev->mDeviceState = DeviceState::Unprepared;
3576 TRACE("Reopened device %p, \"%s\"\n", voidp{dev.get()}, dev->mDeviceName.c_str());
3578 std::string{}.swap(dev->mVendorOverride);
3579 std::string{}.swap(dev->mVersionOverride);
3580 std::string{}.swap(dev->mRendererOverride);
3581 auto checkopt = [&dev](const char *envname, const std::string_view optname)
3583 if(auto optval = al::getenv(envname)) return optval;
3584 return dev->configValue<std::string>("game_compat", optname);
3586 if(auto overrideopt = checkopt("__ALSOFT_VENDOR_OVERRIDE", "vendor-override"sv))
3588 dev->mVendorOverride = std::move(*overrideopt);
3589 TRACE("Overriding vendor string: \"%s\"\n", dev->mVendorOverride.c_str());
3591 if(auto overrideopt = checkopt("__ALSOFT_VERSION_OVERRIDE", "version-override"sv))
3593 dev->mVersionOverride = std::move(*overrideopt);
3594 TRACE("Overriding version string: \"%s\"\n", dev->mVersionOverride.c_str());
3596 if(auto overrideopt = checkopt("__ALSOFT_RENDERER_OVERRIDE", "renderer-override"sv))
3598 dev->mRendererOverride = std::move(*overrideopt);
3599 TRACE("Overriding renderer string: \"%s\"\n", dev->mRendererOverride.c_str());
3602 /* Always return true even if resetting fails. It shouldn't fail, but this
3603 * is primarily to avoid confusion by the app seeing the function return
3604 * false while the device is on the new output anyway. We could try to
3605 * restore the old backend if this fails, but the configuration would be
3606 * changed with the new backend and would need to be reset again with the
3607 * old one, and the provided attributes may not be appropriate or desirable
3608 * for the old device.
3610 * In this way, we essentially act as if the function succeeded, but
3611 * immediately disconnects following it.
3613 ResetDeviceParams(dev.get(), SpanFromAttributeList(attribs));
3614 return ALC_TRUE;
3617 /************************************************
3618 * ALC event query functions
3619 ************************************************/
3621 FORCE_ALIGN ALCenum ALC_APIENTRY alcEventIsSupportedSOFT(ALCenum eventType, ALCenum deviceType) noexcept
3623 auto etype = alc::GetEventType(eventType);
3624 if(!etype)
3626 WARN("Invalid event type: 0x%04x\n", eventType);
3627 alcSetError(nullptr, ALC_INVALID_ENUM);
3628 return ALC_FALSE;
3631 auto supported = alc::EventSupport::NoSupport;
3632 switch(deviceType)
3634 case ALC_PLAYBACK_DEVICE_SOFT:
3635 if(PlaybackFactory)
3636 supported = PlaybackFactory->queryEventSupport(*etype, BackendType::Playback);
3637 return al::to_underlying(supported);
3639 case ALC_CAPTURE_DEVICE_SOFT:
3640 if(CaptureFactory)
3641 supported = CaptureFactory->queryEventSupport(*etype, BackendType::Capture);
3642 return al::to_underlying(supported);
3644 WARN("Invalid device type: 0x%04x\n", deviceType);
3645 alcSetError(nullptr, ALC_INVALID_ENUM);
3646 return ALC_FALSE;