alc.cpp 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698
  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.
  8. *
  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.
  13. *
  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
  19. */
  20. #include "config.h"
  21. #include "config_backends.h"
  22. #include "config_simd.h"
  23. #include "version.h"
  24. #ifdef _WIN32
  25. #define WIN32_LEAN_AND_MEAN
  26. #include <windows.h>
  27. #endif
  28. #include <algorithm>
  29. #include <array>
  30. #include <atomic>
  31. #include <bitset>
  32. #include <cassert>
  33. #include <cctype>
  34. #include <chrono>
  35. #include <climits>
  36. #include <cmath>
  37. #include <csignal>
  38. #include <cstddef>
  39. #include <cstdio>
  40. #include <cstdlib>
  41. #include <cstring>
  42. #include <exception>
  43. #include <functional>
  44. #include <iterator>
  45. #include <limits>
  46. #include <memory>
  47. #include <mutex>
  48. #include <new>
  49. #include <optional>
  50. #include <stdexcept>
  51. #include <string>
  52. #include <string_view>
  53. #include <tuple>
  54. #include <utility>
  55. #include <vector>
  56. #include "AL/al.h"
  57. #include "AL/alc.h"
  58. #include "AL/alext.h"
  59. #include "AL/efx.h"
  60. #include "al/auxeffectslot.h"
  61. #include "al/buffer.h"
  62. #include "al/debug.h"
  63. #include "al/effect.h"
  64. #include "al/filter.h"
  65. #include "al/source.h"
  66. #include "alc/events.h"
  67. #include "albit.h"
  68. #include "alconfig.h"
  69. #include "almalloc.h"
  70. #include "alnumbers.h"
  71. #include "alnumeric.h"
  72. #include "alspan.h"
  73. #include "alstring.h"
  74. #include "alu.h"
  75. #include "atomic.h"
  76. #include "context.h"
  77. #include "core/ambidefs.h"
  78. #include "core/bformatdec.h"
  79. #include "core/bs2b.h"
  80. #include "core/context.h"
  81. #include "core/cpu_caps.h"
  82. #include "core/devformat.h"
  83. #include "core/device.h"
  84. #include "core/effects/base.h"
  85. #include "core/effectslot.h"
  86. #include "core/filters/nfc.h"
  87. #include "core/helpers.h"
  88. #include "core/mastering.h"
  89. #include "core/fpu_ctrl.h"
  90. #include "core/logging.h"
  91. #include "core/uhjfilter.h"
  92. #include "core/voice.h"
  93. #include "core/voice_change.h"
  94. #include "device.h"
  95. #include "effects/base.h"
  96. #include "export_list.h"
  97. #include "flexarray.h"
  98. #include "fmt/core.h"
  99. #include "inprogext.h"
  100. #include "intrusive_ptr.h"
  101. #include "opthelpers.h"
  102. #include "strutils.h"
  103. #include "backends/base.h"
  104. #include "backends/null.h"
  105. #include "backends/loopback.h"
  106. #if HAVE_PIPEWIRE
  107. #include "backends/pipewire.h"
  108. #endif
  109. #if HAVE_JACK
  110. #include "backends/jack.h"
  111. #endif
  112. #if HAVE_PULSEAUDIO
  113. #include "backends/pulseaudio.h"
  114. #endif
  115. #if HAVE_ALSA
  116. #include "backends/alsa.h"
  117. #endif
  118. #if HAVE_WASAPI
  119. #include "backends/wasapi.h"
  120. #endif
  121. #if HAVE_COREAUDIO
  122. #include "backends/coreaudio.h"
  123. #endif
  124. #if HAVE_OPENSL
  125. #include "backends/opensl.h"
  126. #endif
  127. #if HAVE_OBOE
  128. #include "backends/oboe.h"
  129. #endif
  130. #if HAVE_SOLARIS
  131. #include "backends/solaris.h"
  132. #endif
  133. #if HAVE_SNDIO
  134. #include "backends/sndio.hpp"
  135. #endif
  136. #if HAVE_OSS
  137. #include "backends/oss.h"
  138. #endif
  139. #if HAVE_DSOUND
  140. #include "backends/dsound.h"
  141. #endif
  142. #if HAVE_WINMM
  143. #include "backends/winmm.h"
  144. #endif
  145. #if HAVE_PORTAUDIO
  146. #include "backends/portaudio.hpp"
  147. #endif
  148. #if HAVE_SDL3
  149. #include "backends/sdl3.h"
  150. #endif
  151. #if HAVE_SDL2
  152. #include "backends/sdl2.h"
  153. #endif
  154. #if HAVE_OTHERIO
  155. #include "backends/otherio.h"
  156. #endif
  157. #if HAVE_WAVE
  158. #include "backends/wave.h"
  159. #endif
  160. #if ALSOFT_EAX
  161. #include "al/eax/api.h"
  162. #include "al/eax/globals.h"
  163. #endif
  164. /************************************************
  165. * Library initialization
  166. ************************************************/
  167. #if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC)
  168. BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/)
  169. {
  170. switch(reason)
  171. {
  172. case DLL_PROCESS_ATTACH:
  173. /* Pin the DLL so we won't get unloaded until the process terminates */
  174. GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
  175. reinterpret_cast<WCHAR*>(module), &module);
  176. break;
  177. }
  178. return TRUE;
  179. }
  180. #endif
  181. namespace {
  182. using namespace std::string_view_literals;
  183. using std::chrono::seconds;
  184. using std::chrono::nanoseconds;
  185. using voidp = void*;
  186. using float2 = std::array<float,2>;
  187. auto gProcessRunning = true;
  188. struct ProcessWatcher {
  189. ProcessWatcher() = default;
  190. ProcessWatcher(const ProcessWatcher&) = delete;
  191. ProcessWatcher& operator=(const ProcessWatcher&) = delete;
  192. ~ProcessWatcher() { gProcessRunning = false; }
  193. };
  194. ProcessWatcher gProcessWatcher;
  195. /************************************************
  196. * Backends
  197. ************************************************/
  198. struct BackendInfo {
  199. const char *name;
  200. BackendFactory& (*getFactory)();
  201. };
  202. std::array BackendList{
  203. #if HAVE_PIPEWIRE
  204. BackendInfo{"pipewire", PipeWireBackendFactory::getFactory},
  205. #endif
  206. #if HAVE_PULSEAUDIO
  207. BackendInfo{"pulse", PulseBackendFactory::getFactory},
  208. #endif
  209. #if HAVE_WASAPI
  210. BackendInfo{"wasapi", WasapiBackendFactory::getFactory},
  211. #endif
  212. #if HAVE_COREAUDIO
  213. BackendInfo{"core", CoreAudioBackendFactory::getFactory},
  214. #endif
  215. #if HAVE_OBOE
  216. BackendInfo{"oboe", OboeBackendFactory::getFactory},
  217. #endif
  218. #if HAVE_OPENSL
  219. BackendInfo{"opensl", OSLBackendFactory::getFactory},
  220. #endif
  221. #if HAVE_ALSA
  222. BackendInfo{"alsa", AlsaBackendFactory::getFactory},
  223. #endif
  224. #if HAVE_SOLARIS
  225. BackendInfo{"solaris", SolarisBackendFactory::getFactory},
  226. #endif
  227. #if HAVE_SNDIO
  228. BackendInfo{"sndio", SndIOBackendFactory::getFactory},
  229. #endif
  230. #if HAVE_OSS
  231. BackendInfo{"oss", OSSBackendFactory::getFactory},
  232. #endif
  233. #if HAVE_DSOUND
  234. BackendInfo{"dsound", DSoundBackendFactory::getFactory},
  235. #endif
  236. #if HAVE_WINMM
  237. BackendInfo{"winmm", WinMMBackendFactory::getFactory},
  238. #endif
  239. #if HAVE_PORTAUDIO
  240. BackendInfo{"port", PortBackendFactory::getFactory},
  241. #endif
  242. #if HAVE_SDL3
  243. BackendInfo{"sdl3", SDL3BackendFactory::getFactory},
  244. #endif
  245. #if HAVE_SDL2
  246. BackendInfo{"sdl2", SDL2BackendFactory::getFactory},
  247. #endif
  248. #if HAVE_JACK
  249. BackendInfo{"jack", JackBackendFactory::getFactory},
  250. #endif
  251. #if HAVE_OTHERIO
  252. BackendInfo{"otherio", OtherIOBackendFactory::getFactory},
  253. #endif
  254. BackendInfo{"null", NullBackendFactory::getFactory},
  255. #if HAVE_WAVE
  256. BackendInfo{"wave", WaveBackendFactory::getFactory},
  257. #endif
  258. };
  259. BackendFactory *PlaybackFactory{};
  260. BackendFactory *CaptureFactory{};
  261. [[nodiscard]] constexpr auto GetNoErrorString() noexcept { return "No Error"; }
  262. [[nodiscard]] constexpr auto GetInvalidDeviceString() noexcept { return "Invalid Device"; }
  263. [[nodiscard]] constexpr auto GetInvalidContextString() noexcept { return "Invalid Context"; }
  264. [[nodiscard]] constexpr auto GetInvalidEnumString() noexcept { return "Invalid Enum"; }
  265. [[nodiscard]] constexpr auto GetInvalidValueString() noexcept { return "Invalid Value"; }
  266. [[nodiscard]] constexpr auto GetOutOfMemoryString() noexcept { return "Out of Memory"; }
  267. [[nodiscard]] constexpr auto GetDefaultName() noexcept { return "OpenAL Soft\0"; }
  268. #ifdef _WIN32
  269. [[nodiscard]] constexpr auto GetDevicePrefix() noexcept { return "OpenAL Soft on "sv; }
  270. #else
  271. [[nodiscard]] constexpr auto GetDevicePrefix() noexcept { return std::string_view{}; }
  272. #endif
  273. /************************************************
  274. * Global variables
  275. ************************************************/
  276. /* Enumerated device names */
  277. std::vector<std::string> alcAllDevicesArray;
  278. std::vector<std::string> alcCaptureDeviceArray;
  279. std::string alcAllDevicesList;
  280. std::string alcCaptureDeviceList;
  281. /* Default is always the first in the list */
  282. std::string alcDefaultAllDevicesSpecifier;
  283. std::string alcCaptureDefaultDeviceSpecifier;
  284. std::atomic<ALCenum> LastNullDeviceError{ALC_NO_ERROR};
  285. /* Flag to trap ALC device errors */
  286. bool TrapALCError{false};
  287. /* One-time configuration init control */
  288. std::once_flag alc_config_once{};
  289. /* Flag to specify if alcSuspendContext/alcProcessContext should defer/process
  290. * updates.
  291. */
  292. bool SuspendDefers{true};
  293. /* Initial seed for dithering. */
  294. constexpr uint DitherRNGSeed{22222u};
  295. /************************************************
  296. * ALC information
  297. ************************************************/
  298. [[nodiscard]] constexpr auto GetNoDeviceExtList() noexcept -> const char*
  299. {
  300. return "ALC_ENUMERATE_ALL_EXT "
  301. "ALC_ENUMERATION_EXT "
  302. "ALC_EXT_CAPTURE "
  303. "ALC_EXT_direct_context "
  304. "ALC_EXT_EFX "
  305. "ALC_EXT_thread_local_context "
  306. "ALC_SOFT_loopback "
  307. "ALC_SOFT_loopback_bformat "
  308. "ALC_SOFT_reopen_device "
  309. "ALC_SOFT_system_events";
  310. }
  311. [[nodiscard]] constexpr auto GetExtensionList() noexcept -> const char*
  312. {
  313. return "ALC_ENUMERATE_ALL_EXT "
  314. "ALC_ENUMERATION_EXT "
  315. "ALC_EXT_CAPTURE "
  316. "ALC_EXT_debug "
  317. "ALC_EXT_DEDICATED "
  318. "ALC_EXT_direct_context "
  319. "ALC_EXT_disconnect "
  320. "ALC_EXT_EFX "
  321. "ALC_EXT_thread_local_context "
  322. "ALC_SOFT_device_clock "
  323. "ALC_SOFT_HRTF "
  324. "ALC_SOFT_loopback "
  325. "ALC_SOFT_loopback_bformat "
  326. "ALC_SOFT_output_limiter "
  327. "ALC_SOFT_output_mode "
  328. "ALC_SOFT_pause_device "
  329. "ALC_SOFT_reopen_device "
  330. "ALC_SOFT_system_events";
  331. }
  332. constexpr int alcMajorVersion{1};
  333. constexpr int alcMinorVersion{1};
  334. constexpr int alcEFXMajorVersion{1};
  335. constexpr int alcEFXMinorVersion{0};
  336. using DeviceRef = al::intrusive_ptr<al::Device>;
  337. /************************************************
  338. * Device lists
  339. ************************************************/
  340. std::vector<al::Device*> DeviceList;
  341. std::vector<ALCcontext*> ContextList;
  342. std::recursive_mutex ListLock;
  343. void alc_initconfig()
  344. {
  345. if(auto loglevel = al::getenv("ALSOFT_LOGLEVEL"))
  346. {
  347. long lvl = strtol(loglevel->c_str(), nullptr, 0);
  348. if(lvl >= static_cast<long>(LogLevel::Trace))
  349. gLogLevel = LogLevel::Trace;
  350. else if(lvl <= static_cast<long>(LogLevel::Disable))
  351. gLogLevel = LogLevel::Disable;
  352. else
  353. gLogLevel = static_cast<LogLevel>(lvl);
  354. }
  355. #ifdef _WIN32
  356. if(const auto logfile = al::getenv(L"ALSOFT_LOGFILE"))
  357. {
  358. FILE *logf{_wfopen(logfile->c_str(), L"wt")};
  359. if(logf) gLogFile = logf;
  360. else
  361. {
  362. auto u8name = wstr_to_utf8(*logfile);
  363. ERR("Failed to open log file '{}'", u8name);
  364. }
  365. }
  366. #else
  367. if(const auto logfile = al::getenv("ALSOFT_LOGFILE"))
  368. {
  369. FILE *logf{fopen(logfile->c_str(), "wt")};
  370. if(logf) gLogFile = logf;
  371. else ERR("Failed to open log file '{}'", *logfile);
  372. }
  373. #endif
  374. TRACE("Initializing library v{}-{} {}", ALSOFT_VERSION, ALSOFT_GIT_COMMIT_HASH,
  375. ALSOFT_GIT_BRANCH);
  376. {
  377. std::string names;
  378. if(std::size(BackendList) < 1)
  379. names = "(none)";
  380. else
  381. {
  382. const al::span<const BackendInfo> infos{BackendList};
  383. names = infos[0].name;
  384. for(const auto &backend : infos.subspan<1>())
  385. {
  386. names += ", ";
  387. names += backend.name;
  388. }
  389. }
  390. TRACE("Supported backends: {}", names);
  391. }
  392. ReadALConfig();
  393. if(auto suspendmode = al::getenv("__ALSOFT_SUSPEND_CONTEXT"))
  394. {
  395. if(al::case_compare(*suspendmode, "ignore"sv) == 0)
  396. {
  397. SuspendDefers = false;
  398. TRACE("Selected context suspend behavior, \"ignore\"");
  399. }
  400. else
  401. ERR("Unhandled context suspend behavior setting: \"{}\"", *suspendmode);
  402. }
  403. int capfilter{0};
  404. #if HAVE_SSE4_1
  405. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
  406. #elif HAVE_SSE3
  407. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
  408. #elif HAVE_SSE2
  409. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2;
  410. #elif HAVE_SSE
  411. capfilter |= CPU_CAP_SSE;
  412. #endif
  413. #if HAVE_NEON
  414. capfilter |= CPU_CAP_NEON;
  415. #endif
  416. if(auto cpuopt = ConfigValueStr({}, {}, "disable-cpu-exts"sv))
  417. {
  418. std::string_view cpulist{*cpuopt};
  419. if(al::case_compare(cpulist, "all"sv) == 0)
  420. capfilter = 0;
  421. else while(!cpulist.empty())
  422. {
  423. auto nextpos = std::min(cpulist.find(','), cpulist.size());
  424. auto entry = cpulist.substr(0, nextpos);
  425. while(nextpos < cpulist.size() && cpulist[nextpos] == ',')
  426. ++nextpos;
  427. cpulist.remove_prefix(nextpos);
  428. while(!entry.empty() && std::isspace(entry.front()))
  429. entry.remove_prefix(1);
  430. while(!entry.empty() && std::isspace(entry.back()))
  431. entry.remove_suffix(1);
  432. if(entry.empty())
  433. continue;
  434. if(al::case_compare(entry, "sse"sv) == 0)
  435. capfilter &= ~CPU_CAP_SSE;
  436. else if(al::case_compare(entry, "sse2"sv) == 0)
  437. capfilter &= ~CPU_CAP_SSE2;
  438. else if(al::case_compare(entry, "sse3"sv) == 0)
  439. capfilter &= ~CPU_CAP_SSE3;
  440. else if(al::case_compare(entry, "sse4.1"sv) == 0)
  441. capfilter &= ~CPU_CAP_SSE4_1;
  442. else if(al::case_compare(entry, "neon"sv) == 0)
  443. capfilter &= ~CPU_CAP_NEON;
  444. else
  445. WARN("Invalid CPU extension \"{}\"", entry);
  446. }
  447. }
  448. if(auto cpuopt = GetCPUInfo())
  449. {
  450. if(!cpuopt->mVendor.empty() || !cpuopt->mName.empty())
  451. {
  452. TRACE("Vendor ID: \"{}\"", cpuopt->mVendor);
  453. TRACE("Name: \"{}\"", cpuopt->mName);
  454. }
  455. const int caps{cpuopt->mCaps};
  456. TRACE("Extensions:{}{}{}{}{}{}",
  457. ((capfilter&CPU_CAP_SSE) ?(caps&CPU_CAP_SSE) ?" +SSE"sv : " -SSE"sv : ""sv),
  458. ((capfilter&CPU_CAP_SSE2) ?(caps&CPU_CAP_SSE2) ?" +SSE2"sv : " -SSE2"sv : ""sv),
  459. ((capfilter&CPU_CAP_SSE3) ?(caps&CPU_CAP_SSE3) ?" +SSE3"sv : " -SSE3"sv : ""sv),
  460. ((capfilter&CPU_CAP_SSE4_1)?(caps&CPU_CAP_SSE4_1)?" +SSE4.1"sv : " -SSE4.1"sv : ""sv),
  461. ((capfilter&CPU_CAP_NEON) ?(caps&CPU_CAP_NEON) ?" +NEON"sv : " -NEON"sv : ""sv),
  462. (!capfilter) ? " -none-"sv : ""sv);
  463. CPUCapFlags = caps & capfilter;
  464. }
  465. if(auto priopt = ConfigValueInt({}, {}, "rt-prio"sv))
  466. RTPrioLevel = *priopt;
  467. if(auto limopt = ConfigValueBool({}, {}, "rt-time-limit"sv))
  468. AllowRTTimeLimit = *limopt;
  469. {
  470. CompatFlagBitset compatflags{};
  471. auto checkflag = [](const char *envname, const std::string_view optname) -> bool
  472. {
  473. if(auto optval = al::getenv(envname))
  474. {
  475. return al::case_compare(*optval, "true"sv) == 0
  476. || strtol(optval->c_str(), nullptr, 0) == 1;
  477. }
  478. return GetConfigValueBool({}, "game_compat", optname, false);
  479. };
  480. sBufferSubDataCompat = checkflag("__ALSOFT_ENABLE_SUB_DATA_EXT", "enable-sub-data-ext"sv);
  481. compatflags.set(CompatFlags::ReverseX, checkflag("__ALSOFT_REVERSE_X", "reverse-x"sv));
  482. compatflags.set(CompatFlags::ReverseY, checkflag("__ALSOFT_REVERSE_Y", "reverse-y"sv));
  483. compatflags.set(CompatFlags::ReverseZ, checkflag("__ALSOFT_REVERSE_Z", "reverse-z"sv));
  484. aluInit(compatflags, ConfigValueFloat({}, "game_compat"sv, "nfc-scale"sv).value_or(1.0f));
  485. }
  486. Voice::InitMixer(ConfigValueStr({}, {}, "resampler"sv));
  487. if(auto uhjfiltopt = ConfigValueStr({}, "uhj"sv, "decode-filter"sv))
  488. {
  489. if(al::case_compare(*uhjfiltopt, "fir256"sv) == 0)
  490. UhjDecodeQuality = UhjQualityType::FIR256;
  491. else if(al::case_compare(*uhjfiltopt, "fir512"sv) == 0)
  492. UhjDecodeQuality = UhjQualityType::FIR512;
  493. else if(al::case_compare(*uhjfiltopt, "iir"sv) == 0)
  494. UhjDecodeQuality = UhjQualityType::IIR;
  495. else
  496. WARN("Unsupported uhj/decode-filter: {}", *uhjfiltopt);
  497. }
  498. if(auto uhjfiltopt = ConfigValueStr({}, "uhj"sv, "encode-filter"sv))
  499. {
  500. if(al::case_compare(*uhjfiltopt, "fir256"sv) == 0)
  501. UhjEncodeQuality = UhjQualityType::FIR256;
  502. else if(al::case_compare(*uhjfiltopt, "fir512"sv) == 0)
  503. UhjEncodeQuality = UhjQualityType::FIR512;
  504. else if(al::case_compare(*uhjfiltopt, "iir"sv) == 0)
  505. UhjEncodeQuality = UhjQualityType::IIR;
  506. else
  507. WARN("Unsupported uhj/encode-filter: {}", *uhjfiltopt);
  508. }
  509. if(auto traperr = al::getenv("ALSOFT_TRAP_ERROR"); traperr
  510. && (al::case_compare(*traperr, "true"sv) == 0
  511. || std::strtol(traperr->c_str(), nullptr, 0) == 1))
  512. {
  513. TrapALError = true;
  514. TrapALCError = true;
  515. }
  516. else
  517. {
  518. traperr = al::getenv("ALSOFT_TRAP_AL_ERROR");
  519. if(traperr)
  520. TrapALError = al::case_compare(*traperr, "true"sv) == 0
  521. || strtol(traperr->c_str(), nullptr, 0) == 1;
  522. else
  523. TrapALError = GetConfigValueBool({}, {}, "trap-al-error"sv, false);
  524. traperr = al::getenv("ALSOFT_TRAP_ALC_ERROR");
  525. if(traperr)
  526. TrapALCError = al::case_compare(*traperr, "true"sv) == 0
  527. || strtol(traperr->c_str(), nullptr, 0) == 1;
  528. else
  529. TrapALCError = GetConfigValueBool({}, {}, "trap-alc-error"sv, false);
  530. }
  531. if(auto boostopt = ConfigValueFloat({}, "reverb"sv, "boost"sv))
  532. {
  533. const float valf{std::isfinite(*boostopt) ? std::clamp(*boostopt, -24.0f, 24.0f) : 0.0f};
  534. ReverbBoost *= std::pow(10.0f, valf / 20.0f);
  535. }
  536. auto BackendListEnd = BackendList.end();
  537. auto devopt = al::getenv("ALSOFT_DRIVERS");
  538. if(!devopt) devopt = ConfigValueStr({}, {}, "drivers"sv);
  539. if(devopt)
  540. {
  541. auto backendlist_cur = BackendList.begin();
  542. bool endlist{true};
  543. std::string_view drvlist{*devopt};
  544. while(!drvlist.empty())
  545. {
  546. auto nextpos = std::min(drvlist.find(','), drvlist.size());
  547. auto entry = drvlist.substr(0, nextpos);
  548. endlist = true;
  549. if(nextpos < drvlist.size())
  550. {
  551. endlist = false;
  552. while(nextpos < drvlist.size() && drvlist[nextpos] == ',')
  553. ++nextpos;
  554. }
  555. drvlist.remove_prefix(nextpos);
  556. while(!entry.empty() && std::isspace(entry.front()))
  557. entry.remove_prefix(1);
  558. const bool delitem{!entry.empty() && entry.front() == '-'};
  559. if(delitem) entry.remove_prefix(1);
  560. while(!entry.empty() && std::isspace(entry.back()))
  561. entry.remove_suffix(1);
  562. if(entry.empty())
  563. continue;
  564. #ifdef HAVE_WASAPI
  565. /* HACK: For backwards compatibility, convert backend references of
  566. * mmdevapi to wasapi. This should eventually be removed.
  567. */
  568. if(entry == "mmdevapi"sv)
  569. entry = "wasapi"sv;
  570. #endif
  571. auto find_backend = [entry](const BackendInfo &backend) -> bool
  572. { return entry == backend.name; };
  573. auto this_backend = std::find_if(BackendList.begin(), BackendListEnd, find_backend);
  574. if(this_backend == BackendListEnd)
  575. continue;
  576. if(delitem)
  577. BackendListEnd = std::move(this_backend+1, BackendListEnd, this_backend);
  578. else
  579. backendlist_cur = std::rotate(backendlist_cur, this_backend, this_backend+1);
  580. }
  581. if(endlist)
  582. BackendListEnd = backendlist_cur;
  583. }
  584. else
  585. {
  586. /* Exclude the null and wave writer backends from being considered by
  587. * default. This ensures there will be no available devices if none of
  588. * the normal backends are usable, rather than pretending there is a
  589. * device but outputs nowhere.
  590. */
  591. while(BackendListEnd != BackendList.begin())
  592. {
  593. --BackendListEnd;
  594. if(BackendListEnd->name == "null"sv)
  595. break;
  596. }
  597. }
  598. auto init_backend = [](BackendInfo &backend) -> void
  599. {
  600. if(PlaybackFactory && CaptureFactory)
  601. return;
  602. BackendFactory &factory = backend.getFactory();
  603. if(!factory.init())
  604. {
  605. WARN("Failed to initialize backend \"{}\"", backend.name);
  606. return;
  607. }
  608. TRACE("Initialized backend \"{}\"", backend.name);
  609. if(!PlaybackFactory && factory.querySupport(BackendType::Playback))
  610. {
  611. PlaybackFactory = &factory;
  612. TRACE("Added \"{}\" for playback", backend.name);
  613. }
  614. if(!CaptureFactory && factory.querySupport(BackendType::Capture))
  615. {
  616. CaptureFactory = &factory;
  617. TRACE("Added \"{}\" for capture", backend.name);
  618. }
  619. };
  620. std::for_each(BackendList.begin(), BackendListEnd, init_backend);
  621. LoopbackBackendFactory::getFactory().init();
  622. if(!PlaybackFactory)
  623. WARN("No playback backend available!");
  624. if(!CaptureFactory)
  625. WARN("No capture backend available!");
  626. if(auto exclopt = ConfigValueStr({}, {}, "excludefx"sv))
  627. {
  628. std::string_view exclude{*exclopt};
  629. while(!exclude.empty())
  630. {
  631. const auto nextpos = exclude.find(',');
  632. const auto entry = exclude.substr(0, nextpos);
  633. exclude.remove_prefix((nextpos < exclude.size()) ? nextpos+1 : exclude.size());
  634. std::for_each(gEffectList.cbegin(), gEffectList.cend(),
  635. [entry](const EffectList &effectitem) noexcept
  636. {
  637. if(entry == std::data(effectitem.name))
  638. DisabledEffects.set(effectitem.type);
  639. });
  640. }
  641. }
  642. InitEffect(&ALCcontext::sDefaultEffect);
  643. auto defrevopt = al::getenv("ALSOFT_DEFAULT_REVERB");
  644. if(!defrevopt) defrevopt = ConfigValueStr({}, {}, "default-reverb"sv);
  645. if(defrevopt) LoadReverbPreset(*defrevopt, &ALCcontext::sDefaultEffect);
  646. #if ALSOFT_EAX
  647. if(const auto eax_enable_opt = ConfigValueBool({}, "eax", "enable"))
  648. {
  649. eax_g_is_enabled = *eax_enable_opt;
  650. if(!eax_g_is_enabled)
  651. TRACE("EAX disabled by a configuration.");
  652. }
  653. else
  654. eax_g_is_enabled = true;
  655. if((DisabledEffects.test(EAXREVERB_EFFECT) || DisabledEffects.test(CHORUS_EFFECT))
  656. && eax_g_is_enabled)
  657. {
  658. eax_g_is_enabled = false;
  659. TRACE("EAX disabled because {} disabled.",
  660. (DisabledEffects.test(EAXREVERB_EFFECT) && DisabledEffects.test(CHORUS_EFFECT))
  661. ? "EAXReverb and Chorus are"sv :
  662. DisabledEffects.test(EAXREVERB_EFFECT) ? "EAXReverb is"sv :
  663. DisabledEffects.test(CHORUS_EFFECT) ? "Chorus is"sv : ""sv);
  664. }
  665. if(eax_g_is_enabled)
  666. {
  667. if(auto optval = al::getenv("ALSOFT_EAX_TRACE_COMMITS"))
  668. {
  669. EaxTraceCommits = al::case_compare(*optval, "true"sv) == 0
  670. || strtol(optval->c_str(), nullptr, 0) == 1;
  671. }
  672. else
  673. EaxTraceCommits = GetConfigValueBool({}, "eax"sv, "trace-commits"sv, false);
  674. }
  675. #endif // ALSOFT_EAX
  676. }
  677. inline void InitConfig()
  678. { std::call_once(alc_config_once, [](){alc_initconfig();}); }
  679. /************************************************
  680. * Device enumeration
  681. ************************************************/
  682. void ProbeAllDevicesList()
  683. {
  684. InitConfig();
  685. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  686. if(!PlaybackFactory)
  687. {
  688. decltype(alcAllDevicesArray){}.swap(alcAllDevicesArray);
  689. decltype(alcAllDevicesList){}.swap(alcAllDevicesList);
  690. }
  691. else
  692. {
  693. alcAllDevicesArray = PlaybackFactory->enumerate(BackendType::Playback);
  694. if(const auto prefix = GetDevicePrefix(); !prefix.empty())
  695. std::for_each(alcAllDevicesArray.begin(), alcAllDevicesArray.end(),
  696. [prefix](std::string &name) { name.insert(0, prefix); });
  697. decltype(alcAllDevicesList){}.swap(alcAllDevicesList);
  698. if(alcAllDevicesArray.empty())
  699. alcAllDevicesList += '\0';
  700. else for(auto &devname : alcAllDevicesArray)
  701. alcAllDevicesList.append(devname) += '\0';
  702. }
  703. }
  704. void ProbeCaptureDeviceList()
  705. {
  706. InitConfig();
  707. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  708. if(!CaptureFactory)
  709. {
  710. decltype(alcCaptureDeviceArray){}.swap(alcCaptureDeviceArray);
  711. decltype(alcCaptureDeviceList){}.swap(alcCaptureDeviceList);
  712. }
  713. else
  714. {
  715. alcCaptureDeviceArray = CaptureFactory->enumerate(BackendType::Capture);
  716. if(const auto prefix = GetDevicePrefix(); !prefix.empty())
  717. std::for_each(alcCaptureDeviceArray.begin(), alcCaptureDeviceArray.end(),
  718. [prefix](std::string &name) { name.insert(0, prefix); });
  719. decltype(alcCaptureDeviceList){}.swap(alcCaptureDeviceList);
  720. if(alcCaptureDeviceArray.empty())
  721. alcCaptureDeviceList += '\0';
  722. else for(auto &devname : alcCaptureDeviceArray)
  723. alcCaptureDeviceList.append(devname) += '\0';
  724. }
  725. }
  726. al::span<const ALCint> SpanFromAttributeList(const ALCint *attribs) noexcept
  727. {
  728. al::span<const ALCint> attrSpan;
  729. if(attribs)
  730. {
  731. const ALCint *attrEnd{attribs};
  732. while(*attrEnd != 0)
  733. attrEnd += 2; /* NOLINT(cppcoreguidelines-pro-bounds-pointer-arithmetic) */
  734. attrSpan = {attribs, attrEnd};
  735. }
  736. return attrSpan;
  737. }
  738. struct DevFmtPair { DevFmtChannels chans; DevFmtType type; };
  739. std::optional<DevFmtPair> DecomposeDevFormat(ALenum format)
  740. {
  741. struct FormatType {
  742. ALenum format;
  743. DevFmtChannels channels;
  744. DevFmtType type;
  745. };
  746. static constexpr std::array list{
  747. FormatType{AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte},
  748. FormatType{AL_FORMAT_MONO16, DevFmtMono, DevFmtShort},
  749. FormatType{AL_FORMAT_MONO_I32, DevFmtMono, DevFmtInt},
  750. FormatType{AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat},
  751. FormatType{AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte},
  752. FormatType{AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort},
  753. FormatType{AL_FORMAT_STEREO_I32, DevFmtStereo, DevFmtInt},
  754. FormatType{AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat},
  755. FormatType{AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte},
  756. FormatType{AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort},
  757. FormatType{AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat},
  758. FormatType{AL_FORMAT_QUAD_I32, DevFmtQuad, DevFmtInt},
  759. FormatType{AL_FORMAT_QUAD_FLOAT32, DevFmtQuad, DevFmtFloat},
  760. FormatType{AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte},
  761. FormatType{AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort},
  762. FormatType{AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat},
  763. FormatType{AL_FORMAT_51CHN_I32, DevFmtX51, DevFmtInt},
  764. FormatType{AL_FORMAT_51CHN_FLOAT32, DevFmtX51, DevFmtFloat},
  765. FormatType{AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte},
  766. FormatType{AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort},
  767. FormatType{AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat},
  768. FormatType{AL_FORMAT_61CHN_I32, DevFmtX61, DevFmtInt},
  769. FormatType{AL_FORMAT_61CHN_FLOAT32, DevFmtX61, DevFmtFloat},
  770. FormatType{AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte},
  771. FormatType{AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort},
  772. FormatType{AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat},
  773. FormatType{AL_FORMAT_71CHN_I32, DevFmtX71, DevFmtInt},
  774. FormatType{AL_FORMAT_71CHN_FLOAT32, DevFmtX71, DevFmtFloat},
  775. };
  776. for(const auto &item : list)
  777. {
  778. if(item.format == format)
  779. return DevFmtPair{item.channels, item.type};
  780. }
  781. return std::nullopt;
  782. }
  783. std::optional<DevFmtType> DevFmtTypeFromEnum(ALCenum type)
  784. {
  785. switch(type)
  786. {
  787. case ALC_BYTE_SOFT: return DevFmtByte;
  788. case ALC_UNSIGNED_BYTE_SOFT: return DevFmtUByte;
  789. case ALC_SHORT_SOFT: return DevFmtShort;
  790. case ALC_UNSIGNED_SHORT_SOFT: return DevFmtUShort;
  791. case ALC_INT_SOFT: return DevFmtInt;
  792. case ALC_UNSIGNED_INT_SOFT: return DevFmtUInt;
  793. case ALC_FLOAT_SOFT: return DevFmtFloat;
  794. }
  795. WARN("Unsupported format type: {:#04x}", as_unsigned(type));
  796. return std::nullopt;
  797. }
  798. ALCenum EnumFromDevFmt(DevFmtType type)
  799. {
  800. switch(type)
  801. {
  802. case DevFmtByte: return ALC_BYTE_SOFT;
  803. case DevFmtUByte: return ALC_UNSIGNED_BYTE_SOFT;
  804. case DevFmtShort: return ALC_SHORT_SOFT;
  805. case DevFmtUShort: return ALC_UNSIGNED_SHORT_SOFT;
  806. case DevFmtInt: return ALC_INT_SOFT;
  807. case DevFmtUInt: return ALC_UNSIGNED_INT_SOFT;
  808. case DevFmtFloat: return ALC_FLOAT_SOFT;
  809. }
  810. throw std::runtime_error{fmt::format("Invalid DevFmtType: {}", int{al::to_underlying(type)})};
  811. }
  812. std::optional<DevFmtChannels> DevFmtChannelsFromEnum(ALCenum channels)
  813. {
  814. switch(channels)
  815. {
  816. case ALC_MONO_SOFT: return DevFmtMono;
  817. case ALC_STEREO_SOFT: return DevFmtStereo;
  818. case ALC_QUAD_SOFT: return DevFmtQuad;
  819. case ALC_5POINT1_SOFT: return DevFmtX51;
  820. case ALC_6POINT1_SOFT: return DevFmtX61;
  821. case ALC_7POINT1_SOFT: return DevFmtX71;
  822. case ALC_BFORMAT3D_SOFT: return DevFmtAmbi3D;
  823. }
  824. WARN("Unsupported format channels: {:#04x}", as_unsigned(channels));
  825. return std::nullopt;
  826. }
  827. ALCenum EnumFromDevFmt(DevFmtChannels channels)
  828. {
  829. switch(channels)
  830. {
  831. case DevFmtMono: return ALC_MONO_SOFT;
  832. case DevFmtStereo: return ALC_STEREO_SOFT;
  833. case DevFmtQuad: return ALC_QUAD_SOFT;
  834. case DevFmtX51: return ALC_5POINT1_SOFT;
  835. case DevFmtX61: return ALC_6POINT1_SOFT;
  836. case DevFmtX71: return ALC_7POINT1_SOFT;
  837. case DevFmtAmbi3D: return ALC_BFORMAT3D_SOFT;
  838. /* FIXME: Shouldn't happen. */
  839. case DevFmtX714:
  840. case DevFmtX7144:
  841. case DevFmtX3D71: break;
  842. }
  843. throw std::runtime_error{fmt::format("Invalid DevFmtChannels: {}",
  844. int{al::to_underlying(channels)})};
  845. }
  846. std::optional<DevAmbiLayout> DevAmbiLayoutFromEnum(ALCenum layout)
  847. {
  848. switch(layout)
  849. {
  850. case ALC_FUMA_SOFT: return DevAmbiLayout::FuMa;
  851. case ALC_ACN_SOFT: return DevAmbiLayout::ACN;
  852. }
  853. WARN("Unsupported ambisonic layout: {:#04x}", as_unsigned(layout));
  854. return std::nullopt;
  855. }
  856. ALCenum EnumFromDevAmbi(DevAmbiLayout layout)
  857. {
  858. switch(layout)
  859. {
  860. case DevAmbiLayout::FuMa: return ALC_FUMA_SOFT;
  861. case DevAmbiLayout::ACN: return ALC_ACN_SOFT;
  862. }
  863. throw std::runtime_error{fmt::format("Invalid DevAmbiLayout: {}",
  864. int{al::to_underlying(layout)})};
  865. }
  866. std::optional<DevAmbiScaling> DevAmbiScalingFromEnum(ALCenum scaling)
  867. {
  868. switch(scaling)
  869. {
  870. case ALC_FUMA_SOFT: return DevAmbiScaling::FuMa;
  871. case ALC_SN3D_SOFT: return DevAmbiScaling::SN3D;
  872. case ALC_N3D_SOFT: return DevAmbiScaling::N3D;
  873. }
  874. WARN("Unsupported ambisonic scaling: {:#04x}", as_unsigned(scaling));
  875. return std::nullopt;
  876. }
  877. ALCenum EnumFromDevAmbi(DevAmbiScaling scaling)
  878. {
  879. switch(scaling)
  880. {
  881. case DevAmbiScaling::FuMa: return ALC_FUMA_SOFT;
  882. case DevAmbiScaling::SN3D: return ALC_SN3D_SOFT;
  883. case DevAmbiScaling::N3D: return ALC_N3D_SOFT;
  884. }
  885. throw std::runtime_error{fmt::format("Invalid DevAmbiScaling: {}",
  886. int{al::to_underlying(scaling)})};
  887. }
  888. /* Downmixing channel arrays, to map a device format's missing channels to
  889. * existing ones. Based on what PipeWire does, though simplified.
  890. */
  891. constexpr float inv_sqrt2f{static_cast<float>(1.0 / al::numbers::sqrt2)};
  892. constexpr std::array FrontStereo3dB{
  893. InputRemixMap::TargetMix{FrontLeft, inv_sqrt2f},
  894. InputRemixMap::TargetMix{FrontRight, inv_sqrt2f}
  895. };
  896. constexpr std::array FrontStereo6dB{
  897. InputRemixMap::TargetMix{FrontLeft, 0.5f},
  898. InputRemixMap::TargetMix{FrontRight, 0.5f}
  899. };
  900. constexpr std::array SideStereo3dB{
  901. InputRemixMap::TargetMix{SideLeft, inv_sqrt2f},
  902. InputRemixMap::TargetMix{SideRight, inv_sqrt2f}
  903. };
  904. constexpr std::array BackStereo3dB{
  905. InputRemixMap::TargetMix{BackLeft, inv_sqrt2f},
  906. InputRemixMap::TargetMix{BackRight, inv_sqrt2f}
  907. };
  908. constexpr std::array FrontLeft3dB{InputRemixMap::TargetMix{FrontLeft, inv_sqrt2f}};
  909. constexpr std::array FrontRight3dB{InputRemixMap::TargetMix{FrontRight, inv_sqrt2f}};
  910. constexpr std::array SideLeft0dB{InputRemixMap::TargetMix{SideLeft, 1.0f}};
  911. constexpr std::array SideRight0dB{InputRemixMap::TargetMix{SideRight, 1.0f}};
  912. constexpr std::array BackLeft0dB{InputRemixMap::TargetMix{BackLeft, 1.0f}};
  913. constexpr std::array BackRight0dB{InputRemixMap::TargetMix{BackRight, 1.0f}};
  914. constexpr std::array BackCenter3dB{InputRemixMap::TargetMix{BackCenter, inv_sqrt2f}};
  915. constexpr std::array StereoDownmix{
  916. InputRemixMap{FrontCenter, FrontStereo3dB},
  917. InputRemixMap{SideLeft, FrontLeft3dB},
  918. InputRemixMap{SideRight, FrontRight3dB},
  919. InputRemixMap{BackLeft, FrontLeft3dB},
  920. InputRemixMap{BackRight, FrontRight3dB},
  921. InputRemixMap{BackCenter, FrontStereo6dB},
  922. };
  923. constexpr std::array QuadDownmix{
  924. InputRemixMap{FrontCenter, FrontStereo3dB},
  925. InputRemixMap{SideLeft, BackLeft0dB},
  926. InputRemixMap{SideRight, BackRight0dB},
  927. InputRemixMap{BackCenter, BackStereo3dB},
  928. };
  929. constexpr std::array X51Downmix{
  930. InputRemixMap{BackLeft, SideLeft0dB},
  931. InputRemixMap{BackRight, SideRight0dB},
  932. InputRemixMap{BackCenter, SideStereo3dB},
  933. };
  934. constexpr std::array X61Downmix{
  935. InputRemixMap{BackLeft, BackCenter3dB},
  936. InputRemixMap{BackRight, BackCenter3dB},
  937. };
  938. constexpr std::array X71Downmix{
  939. InputRemixMap{BackCenter, BackStereo3dB},
  940. };
  941. auto CreateDeviceLimiter(const al::Device *device, const float threshold)
  942. -> std::unique_ptr<Compressor>
  943. {
  944. static constexpr float LookAheadTime{0.001f};
  945. static constexpr float HoldTime{0.002f};
  946. static constexpr float PreGainDb{0.0f};
  947. static constexpr float PostGainDb{0.0f};
  948. static constexpr float Ratio{std::numeric_limits<float>::infinity()};
  949. static constexpr float KneeDb{0.0f};
  950. static constexpr float AttackTime{0.02f};
  951. static constexpr float ReleaseTime{0.2f};
  952. const auto flags = Compressor::FlagBits{}.set(Compressor::AutoKnee).set(Compressor::AutoAttack)
  953. .set(Compressor::AutoRelease).set(Compressor::AutoPostGain).set(Compressor::AutoDeclip);
  954. return Compressor::Create(device->RealOut.Buffer.size(),
  955. static_cast<float>(device->mSampleRate), flags, LookAheadTime, HoldTime, PreGainDb,
  956. PostGainDb, threshold, Ratio, KneeDb, AttackTime, ReleaseTime);
  957. }
  958. /**
  959. * Updates the device's base clock time with however many samples have been
  960. * done. This is used so frequency changes on the device don't cause the time
  961. * to jump forward or back. Must not be called while the device is running/
  962. * mixing.
  963. */
  964. inline void UpdateClockBase(al::Device *device)
  965. {
  966. using std::chrono::duration_cast;
  967. const auto mixLock = device->getWriteMixLock();
  968. auto clockBaseSec = device->mClockBaseSec.load(std::memory_order_relaxed);
  969. auto clockBaseNSec = nanoseconds{device->mClockBaseNSec.load(std::memory_order_relaxed)};
  970. clockBaseNSec += nanoseconds{seconds{device->mSamplesDone.load(std::memory_order_relaxed)}}
  971. / device->mSampleRate;
  972. clockBaseSec += duration_cast<DeviceBase::seconds32>(clockBaseNSec);
  973. clockBaseNSec %= seconds{1};
  974. device->mClockBaseSec.store(clockBaseSec, std::memory_order_relaxed);
  975. device->mClockBaseNSec.store(duration_cast<DeviceBase::nanoseconds32>(clockBaseNSec),
  976. std::memory_order_relaxed);
  977. device->mSamplesDone.store(0, std::memory_order_relaxed);
  978. }
  979. /**
  980. * Updates device parameters according to the attribute list (caller is
  981. * responsible for holding the list lock).
  982. */
  983. auto UpdateDeviceParams(al::Device *device, const al::span<const int> attrList) -> ALCenum
  984. {
  985. if(attrList.empty() && device->Type == DeviceType::Loopback)
  986. {
  987. WARN("Missing attributes for loopback device");
  988. return ALC_INVALID_VALUE;
  989. }
  990. uint numMono{device->NumMonoSources};
  991. uint numStereo{device->NumStereoSources};
  992. uint numSends{device->NumAuxSends};
  993. std::optional<StereoEncoding> stereomode;
  994. std::optional<bool> optlimit;
  995. std::optional<uint> optsrate;
  996. std::optional<DevFmtChannels> optchans;
  997. std::optional<DevFmtType> opttype;
  998. std::optional<DevAmbiLayout> optlayout;
  999. std::optional<DevAmbiScaling> optscale;
  1000. uint period_size{DefaultUpdateSize};
  1001. uint buffer_size{DefaultUpdateSize * DefaultNumUpdates};
  1002. int hrtf_id{-1};
  1003. uint aorder{0u};
  1004. if(device->Type != DeviceType::Loopback)
  1005. {
  1006. /* Get default settings from the user configuration */
  1007. if(auto freqopt = device->configValue<uint>({}, "frequency"))
  1008. {
  1009. optsrate = std::clamp<uint>(*freqopt, MinOutputRate, MaxOutputRate);
  1010. const double scale{static_cast<double>(*optsrate) / double{DefaultOutputRate}};
  1011. period_size = static_cast<uint>(std::lround(period_size * scale));
  1012. }
  1013. if(auto persizeopt = device->configValue<uint>({}, "period_size"))
  1014. period_size = std::clamp(*persizeopt, 64u, 8192u);
  1015. if(auto numperopt = device->configValue<uint>({}, "periods"))
  1016. buffer_size = std::clamp(*numperopt, 2u, 16u) * period_size;
  1017. else
  1018. buffer_size = period_size * uint{DefaultNumUpdates};
  1019. if(auto typeopt = device->configValue<std::string>({}, "sample-type"))
  1020. {
  1021. struct TypeMap {
  1022. std::string_view name;
  1023. DevFmtType type;
  1024. };
  1025. constexpr std::array typelist{
  1026. TypeMap{"int8"sv, DevFmtByte },
  1027. TypeMap{"uint8"sv, DevFmtUByte },
  1028. TypeMap{"int16"sv, DevFmtShort },
  1029. TypeMap{"uint16"sv, DevFmtUShort},
  1030. TypeMap{"int32"sv, DevFmtInt },
  1031. TypeMap{"uint32"sv, DevFmtUInt },
  1032. TypeMap{"float32"sv, DevFmtFloat },
  1033. };
  1034. auto iter = std::find_if(typelist.begin(), typelist.end(),
  1035. [svfmt=std::string_view{*typeopt}](const TypeMap &entry) -> bool
  1036. { return al::case_compare(entry.name, svfmt) == 0; });
  1037. if(iter == typelist.end())
  1038. ERR("Unsupported sample-type: {}", *typeopt);
  1039. else
  1040. opttype = iter->type;
  1041. }
  1042. if(auto chanopt = device->configValue<std::string>({}, "channels"))
  1043. {
  1044. struct ChannelMap {
  1045. std::string_view name;
  1046. DevFmtChannels chans;
  1047. uint8_t order;
  1048. };
  1049. constexpr std::array chanlist{
  1050. ChannelMap{"mono"sv, DevFmtMono, 0},
  1051. ChannelMap{"stereo"sv, DevFmtStereo, 0},
  1052. ChannelMap{"quad"sv, DevFmtQuad, 0},
  1053. ChannelMap{"surround51"sv, DevFmtX51, 0},
  1054. ChannelMap{"surround61"sv, DevFmtX61, 0},
  1055. ChannelMap{"surround71"sv, DevFmtX71, 0},
  1056. ChannelMap{"surround714"sv, DevFmtX714, 0},
  1057. ChannelMap{"surround7144"sv, DevFmtX7144, 0},
  1058. ChannelMap{"surround3d71"sv, DevFmtX3D71, 0},
  1059. ChannelMap{"surround51rear"sv, DevFmtX51, 0},
  1060. ChannelMap{"ambi1"sv, DevFmtAmbi3D, 1},
  1061. ChannelMap{"ambi2"sv, DevFmtAmbi3D, 2},
  1062. ChannelMap{"ambi3"sv, DevFmtAmbi3D, 3},
  1063. };
  1064. auto iter = std::find_if(chanlist.begin(), chanlist.end(),
  1065. [svfmt=std::string_view{*chanopt}](const ChannelMap &entry) -> bool
  1066. { return al::case_compare(entry.name, svfmt) == 0; });
  1067. if(iter == chanlist.end())
  1068. ERR("Unsupported channels: {}", *chanopt);
  1069. else
  1070. {
  1071. optchans = iter->chans;
  1072. aorder = iter->order;
  1073. }
  1074. }
  1075. if(auto ambiopt = device->configValue<std::string>({}, "ambi-format"sv))
  1076. {
  1077. if(al::case_compare(*ambiopt, "fuma"sv) == 0)
  1078. {
  1079. optlayout = DevAmbiLayout::FuMa;
  1080. optscale = DevAmbiScaling::FuMa;
  1081. }
  1082. else if(al::case_compare(*ambiopt, "acn+fuma"sv) == 0)
  1083. {
  1084. optlayout = DevAmbiLayout::ACN;
  1085. optscale = DevAmbiScaling::FuMa;
  1086. }
  1087. else if(al::case_compare(*ambiopt, "ambix"sv) == 0
  1088. || al::case_compare(*ambiopt, "acn+sn3d"sv) == 0)
  1089. {
  1090. optlayout = DevAmbiLayout::ACN;
  1091. optscale = DevAmbiScaling::SN3D;
  1092. }
  1093. else if(al::case_compare(*ambiopt, "acn+n3d"sv) == 0)
  1094. {
  1095. optlayout = DevAmbiLayout::ACN;
  1096. optscale = DevAmbiScaling::N3D;
  1097. }
  1098. else
  1099. ERR("Unsupported ambi-format: {}", *ambiopt);
  1100. }
  1101. if(auto hrtfopt = device->configValue<std::string>({}, "hrtf"sv))
  1102. {
  1103. WARN("general/hrtf is deprecated, please use stereo-encoding instead");
  1104. if(al::case_compare(*hrtfopt, "true"sv) == 0)
  1105. stereomode = StereoEncoding::Hrtf;
  1106. else if(al::case_compare(*hrtfopt, "false"sv) == 0)
  1107. {
  1108. if(!stereomode || *stereomode == StereoEncoding::Hrtf)
  1109. stereomode = StereoEncoding::Default;
  1110. }
  1111. else if(al::case_compare(*hrtfopt, "auto"sv) != 0)
  1112. ERR("Unexpected hrtf value: {}", *hrtfopt);
  1113. }
  1114. }
  1115. if(auto encopt = device->configValue<std::string>({}, "stereo-encoding"sv))
  1116. {
  1117. if(al::case_compare(*encopt, "basic"sv) == 0 || al::case_compare(*encopt, "panpot"sv) == 0)
  1118. stereomode = StereoEncoding::Basic;
  1119. else if(al::case_compare(*encopt, "uhj") == 0)
  1120. stereomode = StereoEncoding::Uhj;
  1121. else if(al::case_compare(*encopt, "hrtf") == 0)
  1122. stereomode = StereoEncoding::Hrtf;
  1123. else
  1124. ERR("Unexpected stereo-encoding: {}", *encopt);
  1125. }
  1126. // Check for app-specified attributes
  1127. if(!attrList.empty())
  1128. {
  1129. ALenum outmode{ALC_ANY_SOFT};
  1130. std::optional<bool> opthrtf;
  1131. int freqAttr{};
  1132. #define ATTRIBUTE(a) a: TRACE("{} = {}", #a, attrList[attrIdx + 1]);
  1133. #define ATTRIBUTE_HEX(a) a: TRACE("{} = {:#x}", #a, as_unsigned(attrList[attrIdx + 1]));
  1134. for(size_t attrIdx{0};attrIdx < attrList.size();attrIdx+=2)
  1135. {
  1136. switch(attrList[attrIdx])
  1137. {
  1138. case ATTRIBUTE_HEX(ALC_FORMAT_CHANNELS_SOFT)
  1139. if(device->Type == DeviceType::Loopback)
  1140. optchans = DevFmtChannelsFromEnum(attrList[attrIdx + 1]);
  1141. break;
  1142. case ATTRIBUTE_HEX(ALC_FORMAT_TYPE_SOFT)
  1143. if(device->Type == DeviceType::Loopback)
  1144. opttype = DevFmtTypeFromEnum(attrList[attrIdx + 1]);
  1145. break;
  1146. case ATTRIBUTE(ALC_FREQUENCY)
  1147. freqAttr = attrList[attrIdx + 1];
  1148. break;
  1149. case ATTRIBUTE_HEX(ALC_AMBISONIC_LAYOUT_SOFT)
  1150. if(device->Type == DeviceType::Loopback)
  1151. optlayout = DevAmbiLayoutFromEnum(attrList[attrIdx + 1]);
  1152. break;
  1153. case ATTRIBUTE_HEX(ALC_AMBISONIC_SCALING_SOFT)
  1154. if(device->Type == DeviceType::Loopback)
  1155. optscale = DevAmbiScalingFromEnum(attrList[attrIdx + 1]);
  1156. break;
  1157. case ATTRIBUTE(ALC_AMBISONIC_ORDER_SOFT)
  1158. if(device->Type == DeviceType::Loopback)
  1159. aorder = static_cast<uint>(attrList[attrIdx + 1]);
  1160. break;
  1161. case ATTRIBUTE(ALC_MONO_SOURCES)
  1162. numMono = static_cast<uint>(attrList[attrIdx + 1]);
  1163. if(numMono > INT_MAX) numMono = 0;
  1164. break;
  1165. case ATTRIBUTE(ALC_STEREO_SOURCES)
  1166. numStereo = static_cast<uint>(attrList[attrIdx + 1]);
  1167. if(numStereo > INT_MAX) numStereo = 0;
  1168. break;
  1169. case ATTRIBUTE(ALC_MAX_AUXILIARY_SENDS)
  1170. numSends = static_cast<uint>(attrList[attrIdx + 1]);
  1171. if(numSends > uint{std::numeric_limits<int>::max()}) numSends = 0;
  1172. else numSends = std::min(numSends, uint{MaxSendCount});
  1173. break;
  1174. case ATTRIBUTE(ALC_HRTF_SOFT)
  1175. if(attrList[attrIdx + 1] == ALC_FALSE)
  1176. opthrtf = false;
  1177. else if(attrList[attrIdx + 1] == ALC_TRUE)
  1178. opthrtf = true;
  1179. else if(attrList[attrIdx + 1] == ALC_DONT_CARE_SOFT)
  1180. opthrtf = std::nullopt;
  1181. break;
  1182. case ATTRIBUTE(ALC_HRTF_ID_SOFT)
  1183. hrtf_id = attrList[attrIdx + 1];
  1184. break;
  1185. case ATTRIBUTE(ALC_OUTPUT_LIMITER_SOFT)
  1186. if(attrList[attrIdx + 1] == ALC_FALSE)
  1187. optlimit = false;
  1188. else if(attrList[attrIdx + 1] == ALC_TRUE)
  1189. optlimit = true;
  1190. else if(attrList[attrIdx + 1] == ALC_DONT_CARE_SOFT)
  1191. optlimit = std::nullopt;
  1192. break;
  1193. case ATTRIBUTE_HEX(ALC_OUTPUT_MODE_SOFT)
  1194. outmode = attrList[attrIdx + 1];
  1195. break;
  1196. case ATTRIBUTE_HEX(ALC_CONTEXT_FLAGS_EXT)
  1197. /* Handled in alcCreateContext */
  1198. break;
  1199. case ATTRIBUTE(ALC_SYNC)
  1200. /* Ignored attribute */
  1201. break;
  1202. default:
  1203. TRACE("{:#04x} = {} ({:#x})", as_unsigned(attrList[attrIdx]),
  1204. attrList[attrIdx + 1], as_unsigned(attrList[attrIdx + 1]));
  1205. break;
  1206. }
  1207. }
  1208. #undef ATTRIBUTE_HEX
  1209. #undef ATTRIBUTE
  1210. if(device->Type == DeviceType::Loopback)
  1211. {
  1212. if(!optchans || !opttype)
  1213. return ALC_INVALID_VALUE;
  1214. if(freqAttr < int{MinOutputRate} || freqAttr > int{MaxOutputRate})
  1215. return ALC_INVALID_VALUE;
  1216. if(*optchans == DevFmtAmbi3D)
  1217. {
  1218. if(!optlayout || !optscale)
  1219. return ALC_INVALID_VALUE;
  1220. if(aorder < 1 || aorder > MaxAmbiOrder)
  1221. return ALC_INVALID_VALUE;
  1222. if((*optlayout == DevAmbiLayout::FuMa || *optscale == DevAmbiScaling::FuMa)
  1223. && aorder > 3)
  1224. return ALC_INVALID_VALUE;
  1225. }
  1226. else if(*optchans == DevFmtStereo)
  1227. {
  1228. if(opthrtf)
  1229. {
  1230. if(*opthrtf)
  1231. stereomode = StereoEncoding::Hrtf;
  1232. else
  1233. {
  1234. if(stereomode.value_or(StereoEncoding::Hrtf) == StereoEncoding::Hrtf)
  1235. stereomode = StereoEncoding::Default;
  1236. }
  1237. }
  1238. if(outmode == ALC_STEREO_BASIC_SOFT)
  1239. stereomode = StereoEncoding::Basic;
  1240. else if(outmode == ALC_STEREO_UHJ_SOFT)
  1241. stereomode = StereoEncoding::Uhj;
  1242. else if(outmode == ALC_STEREO_HRTF_SOFT)
  1243. stereomode = StereoEncoding::Hrtf;
  1244. }
  1245. optsrate = static_cast<uint>(freqAttr);
  1246. }
  1247. else
  1248. {
  1249. if(opthrtf)
  1250. {
  1251. if(*opthrtf)
  1252. stereomode = StereoEncoding::Hrtf;
  1253. else
  1254. {
  1255. if(stereomode.value_or(StereoEncoding::Hrtf) == StereoEncoding::Hrtf)
  1256. stereomode = StereoEncoding::Default;
  1257. }
  1258. }
  1259. if(outmode != ALC_ANY_SOFT)
  1260. {
  1261. using OutputMode = al::Device::OutputMode;
  1262. switch(OutputMode(outmode))
  1263. {
  1264. case OutputMode::Any: break;
  1265. case OutputMode::Mono: optchans = DevFmtMono; break;
  1266. case OutputMode::Stereo: optchans = DevFmtStereo; break;
  1267. case OutputMode::StereoBasic:
  1268. optchans = DevFmtStereo;
  1269. stereomode = StereoEncoding::Basic;
  1270. break;
  1271. case OutputMode::Uhj2:
  1272. optchans = DevFmtStereo;
  1273. stereomode = StereoEncoding::Uhj;
  1274. break;
  1275. case OutputMode::Hrtf:
  1276. optchans = DevFmtStereo;
  1277. stereomode = StereoEncoding::Hrtf;
  1278. break;
  1279. case OutputMode::Quad: optchans = DevFmtQuad; break;
  1280. case OutputMode::X51: optchans = DevFmtX51; break;
  1281. case OutputMode::X61: optchans = DevFmtX61; break;
  1282. case OutputMode::X71: optchans = DevFmtX71; break;
  1283. }
  1284. }
  1285. if(freqAttr)
  1286. {
  1287. uint oldrate = optsrate.value_or(DefaultOutputRate);
  1288. freqAttr = std::clamp<int>(freqAttr, MinOutputRate, MaxOutputRate);
  1289. const double scale{static_cast<double>(freqAttr) / oldrate};
  1290. period_size = static_cast<uint>(std::lround(period_size * scale));
  1291. buffer_size = static_cast<uint>(std::lround(buffer_size * scale));
  1292. optsrate = static_cast<uint>(freqAttr);
  1293. }
  1294. }
  1295. /* If a context is already running on the device, stop playback so the
  1296. * device attributes can be updated.
  1297. */
  1298. if(device->mDeviceState == DeviceState::Playing)
  1299. {
  1300. device->Backend->stop();
  1301. device->mDeviceState = DeviceState::Unprepared;
  1302. }
  1303. UpdateClockBase(device);
  1304. }
  1305. if(device->mDeviceState == DeviceState::Playing)
  1306. return ALC_NO_ERROR;
  1307. device->mDeviceState = DeviceState::Unprepared;
  1308. device->AvgSpeakerDist = 0.0f;
  1309. device->mNFCtrlFilter = NfcFilter{};
  1310. device->mUhjEncoder = nullptr;
  1311. device->AmbiDecoder = nullptr;
  1312. device->Bs2b = nullptr;
  1313. device->PostProcess = nullptr;
  1314. device->Limiter = nullptr;
  1315. device->ChannelDelays = nullptr;
  1316. std::fill(std::begin(device->HrtfAccumData), std::end(device->HrtfAccumData), float2{});
  1317. device->Dry.AmbiMap.fill(BFChannelConfig{});
  1318. device->Dry.Buffer = {};
  1319. std::fill(std::begin(device->NumChannelsPerOrder), std::end(device->NumChannelsPerOrder), 0u);
  1320. device->RealOut.RemixMap = {};
  1321. device->RealOut.ChannelIndex.fill(InvalidChannelIndex);
  1322. device->RealOut.Buffer = {};
  1323. device->MixBuffer.clear();
  1324. device->MixBuffer.shrink_to_fit();
  1325. UpdateClockBase(device);
  1326. device->FixedLatency = nanoseconds::zero();
  1327. device->DitherDepth = 0.0f;
  1328. device->DitherSeed = DitherRNGSeed;
  1329. device->mHrtfStatus = ALC_HRTF_DISABLED_SOFT;
  1330. /*************************************************************************
  1331. * Update device format request
  1332. */
  1333. if(device->Type == DeviceType::Loopback)
  1334. {
  1335. device->mSampleRate = *optsrate;
  1336. device->FmtChans = *optchans;
  1337. device->FmtType = *opttype;
  1338. if(device->FmtChans == DevFmtAmbi3D)
  1339. {
  1340. device->mAmbiOrder = aorder;
  1341. device->mAmbiLayout = *optlayout;
  1342. device->mAmbiScale = *optscale;
  1343. }
  1344. device->Flags.set(FrequencyRequest).set(ChannelsRequest).set(SampleTypeRequest);
  1345. }
  1346. else
  1347. {
  1348. device->FmtType = opttype.value_or(DevFmtTypeDefault);
  1349. device->FmtChans = optchans.value_or(DevFmtChannelsDefault);
  1350. device->mAmbiOrder = 0;
  1351. device->mBufferSize = buffer_size;
  1352. device->mUpdateSize = period_size;
  1353. device->mSampleRate = optsrate.value_or(DefaultOutputRate);
  1354. device->Flags.set(FrequencyRequest, optsrate.has_value())
  1355. .set(ChannelsRequest, optchans.has_value())
  1356. .set(SampleTypeRequest, opttype.has_value());
  1357. if(device->FmtChans == DevFmtAmbi3D)
  1358. {
  1359. device->mAmbiOrder = std::clamp(aorder, 1u, uint{MaxAmbiOrder});
  1360. device->mAmbiLayout = optlayout.value_or(DevAmbiLayout::Default);
  1361. device->mAmbiScale = optscale.value_or(DevAmbiScaling::Default);
  1362. if(device->mAmbiOrder > 3
  1363. && (device->mAmbiLayout == DevAmbiLayout::FuMa
  1364. || device->mAmbiScale == DevAmbiScaling::FuMa))
  1365. {
  1366. ERR("FuMa is incompatible with {}{} order ambisonics (up to 3rd order only)",
  1367. device->mAmbiOrder, GetCounterSuffix(device->mAmbiOrder));
  1368. device->mAmbiOrder = 3;
  1369. }
  1370. }
  1371. }
  1372. TRACE("Pre-reset: {}{}, {}{}, {}{}hz, {} / {} buffer",
  1373. device->Flags.test(ChannelsRequest)?"*":"", DevFmtChannelsString(device->FmtChans),
  1374. device->Flags.test(SampleTypeRequest)?"*":"", DevFmtTypeString(device->FmtType),
  1375. device->Flags.test(FrequencyRequest)?"*":"", device->mSampleRate,
  1376. device->mUpdateSize, device->mBufferSize);
  1377. const uint oldFreq{device->mSampleRate};
  1378. const DevFmtChannels oldChans{device->FmtChans};
  1379. const DevFmtType oldType{device->FmtType};
  1380. try {
  1381. auto backend = device->Backend.get();
  1382. if(!backend->reset())
  1383. throw al::backend_exception{al::backend_error::DeviceError, "Device reset failure"};
  1384. }
  1385. catch(std::exception &e) {
  1386. ERR("Device error: {}", e.what());
  1387. device->handleDisconnect("{}", e.what());
  1388. return ALC_INVALID_DEVICE;
  1389. }
  1390. if(device->FmtChans != oldChans && device->Flags.test(ChannelsRequest))
  1391. {
  1392. ERR("Failed to set {}, got {} instead", DevFmtChannelsString(oldChans),
  1393. DevFmtChannelsString(device->FmtChans));
  1394. device->Flags.reset(ChannelsRequest);
  1395. }
  1396. if(device->FmtType != oldType && device->Flags.test(SampleTypeRequest))
  1397. {
  1398. ERR("Failed to set {}, got {} instead", DevFmtTypeString(oldType),
  1399. DevFmtTypeString(device->FmtType));
  1400. device->Flags.reset(SampleTypeRequest);
  1401. }
  1402. if(device->mSampleRate != oldFreq && device->Flags.test(FrequencyRequest))
  1403. {
  1404. WARN("Failed to set {}hz, got {}hz instead", oldFreq, device->mSampleRate);
  1405. device->Flags.reset(FrequencyRequest);
  1406. }
  1407. TRACE("Post-reset: {}, {}, {}hz, {} / {} buffer",
  1408. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  1409. device->mSampleRate, device->mUpdateSize, device->mBufferSize);
  1410. if(device->Type != DeviceType::Loopback)
  1411. {
  1412. if(auto modeopt = device->configValue<std::string>({}, "stereo-mode"))
  1413. {
  1414. if(al::case_compare(*modeopt, "headphones"sv) == 0)
  1415. device->Flags.set(DirectEar);
  1416. else if(al::case_compare(*modeopt, "speakers"sv) == 0)
  1417. device->Flags.reset(DirectEar);
  1418. else if(al::case_compare(*modeopt, "auto"sv) != 0)
  1419. ERR("Unexpected stereo-mode: {}", *modeopt);
  1420. }
  1421. }
  1422. aluInitRenderer(device, hrtf_id, stereomode);
  1423. /* Calculate the max number of sources, and split them between the mono and
  1424. * stereo count given the requested number of stereo sources.
  1425. */
  1426. if(auto srcsopt = device->configValue<uint>({}, "sources"sv))
  1427. {
  1428. if(*srcsopt <= 0) numMono = 256;
  1429. else numMono = std::max(*srcsopt, 16u);
  1430. }
  1431. else
  1432. {
  1433. numMono = std::min(numMono, std::numeric_limits<int>::max()-numStereo);
  1434. numMono = std::max(numMono+numStereo, 256u);
  1435. }
  1436. numStereo = std::min(numStereo, numMono);
  1437. numMono -= numStereo;
  1438. device->SourcesMax = numMono + numStereo;
  1439. device->NumMonoSources = numMono;
  1440. device->NumStereoSources = numStereo;
  1441. if(auto sendsopt = device->configValue<uint>({}, "sends"sv))
  1442. numSends = std::min(numSends, std::clamp(*sendsopt, 0u, uint{MaxSendCount}));
  1443. device->NumAuxSends = numSends;
  1444. TRACE("Max sources: {} ({} + {}), effect slots: {}, sends: {}",
  1445. device->SourcesMax, device->NumMonoSources, device->NumStereoSources,
  1446. device->AuxiliaryEffectSlotMax, device->NumAuxSends);
  1447. switch(device->FmtChans)
  1448. {
  1449. case DevFmtMono: break;
  1450. case DevFmtStereo:
  1451. if(!device->mUhjEncoder)
  1452. device->RealOut.RemixMap = StereoDownmix;
  1453. break;
  1454. case DevFmtQuad: device->RealOut.RemixMap = QuadDownmix; break;
  1455. case DevFmtX51: device->RealOut.RemixMap = X51Downmix; break;
  1456. case DevFmtX61: device->RealOut.RemixMap = X61Downmix; break;
  1457. case DevFmtX71: device->RealOut.RemixMap = X71Downmix; break;
  1458. case DevFmtX714: device->RealOut.RemixMap = X71Downmix; break;
  1459. case DevFmtX7144: device->RealOut.RemixMap = X71Downmix; break;
  1460. case DevFmtX3D71: device->RealOut.RemixMap = X51Downmix; break;
  1461. case DevFmtAmbi3D: break;
  1462. }
  1463. size_t sample_delay{0};
  1464. if(auto *encoder{device->mUhjEncoder.get()})
  1465. sample_delay += encoder->getDelay();
  1466. if(device->getConfigValueBool({}, "dither"sv, true))
  1467. {
  1468. int depth{device->configValue<int>({}, "dither-depth"sv).value_or(0)};
  1469. if(depth <= 0)
  1470. {
  1471. switch(device->FmtType)
  1472. {
  1473. case DevFmtByte:
  1474. case DevFmtUByte:
  1475. depth = 8;
  1476. break;
  1477. case DevFmtShort:
  1478. case DevFmtUShort:
  1479. depth = 16;
  1480. break;
  1481. case DevFmtInt:
  1482. case DevFmtUInt:
  1483. case DevFmtFloat:
  1484. break;
  1485. }
  1486. }
  1487. if(depth > 0)
  1488. {
  1489. depth = std::clamp(depth, 2, 24);
  1490. device->DitherDepth = std::pow(2.0f, static_cast<float>(depth-1));
  1491. }
  1492. }
  1493. if(!(device->DitherDepth > 0.0f))
  1494. TRACE("Dithering disabled");
  1495. else
  1496. TRACE("Dithering enabled ({}-bit, {:g})",
  1497. float2int(std::log2(device->DitherDepth)+0.5f)+1, device->DitherDepth);
  1498. if(!optlimit)
  1499. optlimit = device->configValue<bool>({}, "output-limiter");
  1500. /* If the gain limiter is unset, use the limiter for integer-based output
  1501. * (where samples must be clamped), and don't for floating-point (which can
  1502. * take unclamped samples).
  1503. */
  1504. if(!optlimit)
  1505. {
  1506. switch(device->FmtType)
  1507. {
  1508. case DevFmtByte:
  1509. case DevFmtUByte:
  1510. case DevFmtShort:
  1511. case DevFmtUShort:
  1512. case DevFmtInt:
  1513. case DevFmtUInt:
  1514. optlimit = true;
  1515. break;
  1516. case DevFmtFloat:
  1517. break;
  1518. }
  1519. }
  1520. if(!optlimit.value_or(false))
  1521. TRACE("Output limiter disabled");
  1522. else
  1523. {
  1524. float thrshld{1.0f};
  1525. switch(device->FmtType)
  1526. {
  1527. case DevFmtByte:
  1528. case DevFmtUByte:
  1529. thrshld = 127.0f / 128.0f;
  1530. break;
  1531. case DevFmtShort:
  1532. case DevFmtUShort:
  1533. thrshld = 32767.0f / 32768.0f;
  1534. break;
  1535. case DevFmtInt:
  1536. case DevFmtUInt:
  1537. case DevFmtFloat:
  1538. break;
  1539. }
  1540. if(device->DitherDepth > 0.0f)
  1541. thrshld -= 1.0f / device->DitherDepth;
  1542. const float thrshld_dB{std::log10(thrshld) * 20.0f};
  1543. auto limiter = CreateDeviceLimiter(device, thrshld_dB);
  1544. sample_delay += limiter->getLookAhead();
  1545. device->Limiter = std::move(limiter);
  1546. TRACE("Output limiter enabled, {:.4f}dB limit", thrshld_dB);
  1547. }
  1548. /* Convert the sample delay from samples to nanosamples to nanoseconds. */
  1549. sample_delay = std::min<size_t>(sample_delay, std::numeric_limits<int>::max());
  1550. device->FixedLatency += nanoseconds{seconds{sample_delay}} / device->mSampleRate;
  1551. TRACE("Fixed device latency: {}ns", device->FixedLatency.count());
  1552. FPUCtl mixer_mode{};
  1553. auto reset_context = [device](ContextBase *ctxbase)
  1554. {
  1555. auto *context = dynamic_cast<ALCcontext*>(ctxbase);
  1556. assert(context != nullptr);
  1557. if(!context) return;
  1558. std::unique_lock<std::mutex> proplock{context->mPropLock};
  1559. std::unique_lock<std::mutex> slotlock{context->mEffectSlotLock};
  1560. /* Clear out unused effect slot clusters. */
  1561. auto slot_cluster_not_in_use = [](ContextBase::EffectSlotCluster &clusterptr) -> bool
  1562. {
  1563. return std::none_of(clusterptr->begin(), clusterptr->end(),
  1564. std::mem_fn(&EffectSlot::InUse));
  1565. };
  1566. auto slotcluster_end = std::remove_if(context->mEffectSlotClusters.begin(),
  1567. context->mEffectSlotClusters.end(), slot_cluster_not_in_use);
  1568. context->mEffectSlotClusters.erase(slotcluster_end, context->mEffectSlotClusters.end());
  1569. /* Free all wet buffers. Any in use will be reallocated with an updated
  1570. * configuration in aluInitEffectPanning.
  1571. */
  1572. auto clear_wetbuffers = [](ContextBase::EffectSlotCluster &clusterptr)
  1573. {
  1574. auto clear_buffer = [](EffectSlot &slot)
  1575. {
  1576. slot.mWetBuffer.clear();
  1577. slot.mWetBuffer.shrink_to_fit();
  1578. slot.Wet.Buffer = {};
  1579. };
  1580. std::for_each(clusterptr->begin(), clusterptr->end(), clear_buffer);
  1581. };
  1582. std::for_each(context->mEffectSlotClusters.begin(), context->mEffectSlotClusters.end(),
  1583. clear_wetbuffers);
  1584. if(ALeffectslot *slot{context->mDefaultSlot.get()})
  1585. {
  1586. auto *slotbase = slot->mSlot;
  1587. aluInitEffectPanning(slotbase, context);
  1588. if(auto *props = slotbase->Update.exchange(nullptr, std::memory_order_relaxed))
  1589. AtomicReplaceHead(context->mFreeEffectSlotProps, props);
  1590. EffectState *state{slot->Effect.State.get()};
  1591. state->mOutTarget = device->Dry.Buffer;
  1592. state->deviceUpdate(device, slot->Buffer);
  1593. slot->mPropsDirty = true;
  1594. }
  1595. if(EffectSlotArray *curarray{context->mActiveAuxSlots.load(std::memory_order_relaxed)})
  1596. std::fill(curarray->begin()+ptrdiff_t(curarray->size()>>1), curarray->end(), nullptr);
  1597. auto reset_slots = [device,context](EffectSlotSubList &sublist)
  1598. {
  1599. uint64_t usemask{~sublist.FreeMask};
  1600. while(usemask)
  1601. {
  1602. const auto idx = static_cast<uint>(al::countr_zero(usemask));
  1603. auto &slot = (*sublist.EffectSlots)[idx];
  1604. usemask &= ~(1_u64 << idx);
  1605. auto *slotbase = slot.mSlot;
  1606. aluInitEffectPanning(slotbase, context);
  1607. if(auto *props = slotbase->Update.exchange(nullptr, std::memory_order_relaxed))
  1608. AtomicReplaceHead(context->mFreeEffectSlotProps, props);
  1609. EffectState *state{slot.Effect.State.get()};
  1610. state->mOutTarget = device->Dry.Buffer;
  1611. state->deviceUpdate(device, slot.Buffer);
  1612. slot.mPropsDirty = true;
  1613. }
  1614. };
  1615. std::for_each(context->mEffectSlotList.begin(), context->mEffectSlotList.end(),
  1616. reset_slots);
  1617. /* Clear all effect slot props to let them get allocated again. */
  1618. context->mEffectSlotPropClusters.clear();
  1619. context->mFreeEffectSlotProps.store(nullptr, std::memory_order_relaxed);
  1620. slotlock.unlock();
  1621. std::unique_lock<std::mutex> srclock{context->mSourceLock};
  1622. const uint num_sends{device->NumAuxSends};
  1623. auto reset_sources = [num_sends](SourceSubList &sublist)
  1624. {
  1625. uint64_t usemask{~sublist.FreeMask};
  1626. while(usemask)
  1627. {
  1628. const auto idx = static_cast<uint>(al::countr_zero(usemask));
  1629. auto &source = (*sublist.Sources)[idx];
  1630. usemask &= ~(1_u64 << idx);
  1631. auto clear_send = [](ALsource::SendData &send) -> void
  1632. {
  1633. if(send.Slot)
  1634. DecrementRef(send.Slot->ref);
  1635. send.Slot = nullptr;
  1636. send.Gain = 1.0f;
  1637. send.GainHF = 1.0f;
  1638. send.HFReference = LowPassFreqRef;
  1639. send.GainLF = 1.0f;
  1640. send.LFReference = HighPassFreqRef;
  1641. };
  1642. const auto sends = al::span{source.Send}.subspan(num_sends);
  1643. std::for_each(sends.begin(), sends.end(), clear_send);
  1644. source.mPropsDirty = true;
  1645. }
  1646. };
  1647. std::for_each(context->mSourceList.begin(), context->mSourceList.end(), reset_sources);
  1648. auto reset_voice = [device,num_sends,context](Voice *voice)
  1649. {
  1650. /* Clear extraneous property set sends. */
  1651. const auto sendparams = al::span{voice->mProps.Send}.subspan(num_sends);
  1652. std::fill(sendparams.begin(), sendparams.end(), VoiceProps::SendData{});
  1653. std::fill(voice->mSend.begin()+num_sends, voice->mSend.end(), Voice::TargetData{});
  1654. auto clear_wetparams = [num_sends](Voice::ChannelData &chandata)
  1655. {
  1656. const auto wetparams = al::span{chandata.mWetParams}.subspan(num_sends);
  1657. std::fill(wetparams.begin(), wetparams.end(), SendParams{});
  1658. };
  1659. std::for_each(voice->mChans.begin(), voice->mChans.end(), clear_wetparams);
  1660. if(VoicePropsItem *props{voice->mUpdate.exchange(nullptr, std::memory_order_relaxed)})
  1661. AtomicReplaceHead(context->mFreeVoiceProps, props);
  1662. /* Force the voice to stopped if it was stopping. */
  1663. Voice::State vstate{Voice::Stopping};
  1664. voice->mPlayState.compare_exchange_strong(vstate, Voice::Stopped,
  1665. std::memory_order_acquire, std::memory_order_acquire);
  1666. if(voice->mSourceID.load(std::memory_order_relaxed) == 0u)
  1667. return;
  1668. voice->prepare(device);
  1669. };
  1670. const auto voicespan = context->getVoicesSpan();
  1671. std::for_each(voicespan.begin(), voicespan.end(), reset_voice);
  1672. /* Clear all voice props to let them get allocated again. */
  1673. context->mVoicePropClusters.clear();
  1674. context->mFreeVoiceProps.store(nullptr, std::memory_order_relaxed);
  1675. srclock.unlock();
  1676. context->mPropsDirty = false;
  1677. UpdateContextProps(context);
  1678. UpdateAllEffectSlotProps(context);
  1679. UpdateAllSourceProps(context);
  1680. };
  1681. auto ctxspan = al::span{*device->mContexts.load()};
  1682. std::for_each(ctxspan.begin(), ctxspan.end(), reset_context);
  1683. mixer_mode.leave();
  1684. device->mDeviceState = DeviceState::Configured;
  1685. if(!device->Flags.test(DevicePaused))
  1686. {
  1687. try {
  1688. auto backend = device->Backend.get();
  1689. backend->start();
  1690. device->mDeviceState = DeviceState::Playing;
  1691. }
  1692. catch(al::backend_exception& e) {
  1693. ERR("{}", e.what());
  1694. device->handleDisconnect("{}", e.what());
  1695. return ALC_INVALID_DEVICE;
  1696. }
  1697. TRACE("Post-start: {}, {}, {}hz, {} / {} buffer",
  1698. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  1699. device->mSampleRate, device->mUpdateSize, device->mBufferSize);
  1700. }
  1701. return ALC_NO_ERROR;
  1702. }
  1703. /**
  1704. * Updates device parameters as above, and also first clears the disconnected
  1705. * status, if set.
  1706. */
  1707. auto ResetDeviceParams(al::Device *device, const al::span<const int> attrList) -> bool
  1708. {
  1709. /* If the device was disconnected, reset it since we're opened anew. */
  1710. if(!device->Connected.load(std::memory_order_relaxed)) UNLIKELY
  1711. {
  1712. /* Make sure disconnection is finished before continuing on. */
  1713. std::ignore = device->waitForMix();
  1714. for(ContextBase *ctxbase : *device->mContexts.load(std::memory_order_acquire))
  1715. {
  1716. auto *ctx = dynamic_cast<ALCcontext*>(ctxbase);
  1717. assert(ctx != nullptr);
  1718. if(!ctx || !ctx->mStopVoicesOnDisconnect.load(std::memory_order_acquire))
  1719. continue;
  1720. /* Clear any pending voice changes and reallocate voices to get a
  1721. * clean restart.
  1722. */
  1723. std::lock_guard<std::mutex> sourcelock{ctx->mSourceLock};
  1724. auto *vchg = ctx->mCurrentVoiceChange.load(std::memory_order_acquire);
  1725. while(auto *next = vchg->mNext.load(std::memory_order_acquire))
  1726. vchg = next;
  1727. ctx->mCurrentVoiceChange.store(vchg, std::memory_order_release);
  1728. ctx->mVoicePropClusters.clear();
  1729. ctx->mFreeVoiceProps.store(nullptr, std::memory_order_relaxed);
  1730. ctx->mVoiceClusters.clear();
  1731. ctx->allocVoices(std::max<size_t>(256,
  1732. ctx->mActiveVoiceCount.load(std::memory_order_relaxed)));
  1733. }
  1734. device->Connected.store(true);
  1735. }
  1736. ALCenum err{UpdateDeviceParams(device, attrList)};
  1737. if(err == ALC_NO_ERROR) LIKELY return ALC_TRUE;
  1738. alcSetError(device, err);
  1739. return ALC_FALSE;
  1740. }
  1741. /** Checks if the device handle is valid, and returns a new reference if so. */
  1742. DeviceRef VerifyDevice(ALCdevice *device)
  1743. {
  1744. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  1745. auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
  1746. if(iter != DeviceList.end() && *iter == device)
  1747. {
  1748. (*iter)->add_ref();
  1749. return DeviceRef{*iter};
  1750. }
  1751. return nullptr;
  1752. }
  1753. /**
  1754. * Checks if the given context is valid, returning a new reference to it if so.
  1755. */
  1756. ContextRef VerifyContext(ALCcontext *context)
  1757. {
  1758. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  1759. auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context);
  1760. if(iter != ContextList.end() && *iter == context)
  1761. {
  1762. (*iter)->add_ref();
  1763. return ContextRef{*iter};
  1764. }
  1765. return nullptr;
  1766. }
  1767. } // namespace
  1768. FORCE_ALIGN void ALC_APIENTRY alsoft_set_log_callback(LPALSOFTLOGCALLBACK callback, void *userptr) noexcept
  1769. {
  1770. al_set_log_callback(callback, userptr);
  1771. }
  1772. /** Returns a new reference to the currently active context for this thread. */
  1773. ContextRef GetContextRef() noexcept
  1774. {
  1775. ALCcontext *context{ALCcontext::getThreadContext()};
  1776. if(context)
  1777. context->add_ref();
  1778. else
  1779. {
  1780. while(ALCcontext::sGlobalContextLock.exchange(true, std::memory_order_acquire)) {
  1781. /* Wait to make sure another thread isn't trying to change the
  1782. * current context and bring its refcount to 0.
  1783. */
  1784. }
  1785. context = ALCcontext::sGlobalContext.load(std::memory_order_acquire);
  1786. if(context) LIKELY context->add_ref();
  1787. ALCcontext::sGlobalContextLock.store(false, std::memory_order_release);
  1788. }
  1789. return ContextRef{context};
  1790. }
  1791. void alcSetError(al::Device *device, ALCenum errorCode)
  1792. {
  1793. WARN("Error generated on device {}, code {:#04x}", voidp{device}, as_unsigned(errorCode));
  1794. if(TrapALCError)
  1795. {
  1796. #ifdef _WIN32
  1797. /* DebugBreak() will cause an exception if there is no debugger */
  1798. if(IsDebuggerPresent())
  1799. DebugBreak();
  1800. #elif defined(SIGTRAP)
  1801. raise(SIGTRAP);
  1802. #endif
  1803. }
  1804. if(device)
  1805. device->LastError.store(errorCode);
  1806. else
  1807. LastNullDeviceError.store(errorCode);
  1808. }
  1809. /************************************************
  1810. * Standard ALC functions
  1811. ************************************************/
  1812. ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device) noexcept
  1813. {
  1814. if(!gProcessRunning)
  1815. return ALC_INVALID_DEVICE;
  1816. DeviceRef dev{VerifyDevice(device)};
  1817. if(dev) return dev->LastError.exchange(ALC_NO_ERROR);
  1818. return LastNullDeviceError.exchange(ALC_NO_ERROR);
  1819. }
  1820. ALC_API void ALC_APIENTRY alcSuspendContext(ALCcontext *context) noexcept
  1821. {
  1822. ContextRef ctx{VerifyContext(context)};
  1823. if(!ctx)
  1824. {
  1825. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  1826. return;
  1827. }
  1828. if(ctx->mContextFlags.test(ContextFlags::DebugBit)) UNLIKELY
  1829. ctx->debugMessage(DebugSource::API, DebugType::Portability, 0, DebugSeverity::Medium,
  1830. "alcSuspendContext behavior is not portable -- some implementations suspend all "
  1831. "rendering, some only defer property changes, and some are completely no-op; consider "
  1832. "using alcDevicePauseSOFT to suspend all rendering, or alDeferUpdatesSOFT to only "
  1833. "defer property changes");
  1834. if(SuspendDefers)
  1835. {
  1836. std::lock_guard<std::mutex> proplock{ctx->mPropLock};
  1837. ctx->deferUpdates();
  1838. }
  1839. }
  1840. ALC_API void ALC_APIENTRY alcProcessContext(ALCcontext *context) noexcept
  1841. {
  1842. ContextRef ctx{VerifyContext(context)};
  1843. if(!ctx)
  1844. {
  1845. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  1846. return;
  1847. }
  1848. if(ctx->mContextFlags.test(ContextFlags::DebugBit)) UNLIKELY
  1849. ctx->debugMessage(DebugSource::API, DebugType::Portability, 1, DebugSeverity::Medium,
  1850. "alcProcessContext behavior is not portable -- some implementations resume rendering, "
  1851. "some apply deferred property changes, and some are completely no-op; consider using "
  1852. "alcDeviceResumeSOFT to resume rendering, or alProcessUpdatesSOFT to apply deferred "
  1853. "property changes");
  1854. if(SuspendDefers)
  1855. {
  1856. std::lock_guard<std::mutex> proplock{ctx->mPropLock};
  1857. ctx->processUpdates();
  1858. }
  1859. }
  1860. ALC_API auto ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param) noexcept -> const ALCchar*
  1861. {
  1862. switch(param)
  1863. {
  1864. case ALC_NO_ERROR: return GetNoErrorString();
  1865. case ALC_INVALID_ENUM: return GetInvalidEnumString();
  1866. case ALC_INVALID_VALUE: return GetInvalidValueString();
  1867. case ALC_INVALID_DEVICE: return GetInvalidDeviceString();
  1868. case ALC_INVALID_CONTEXT: return GetInvalidContextString();
  1869. case ALC_OUT_OF_MEMORY: return GetOutOfMemoryString();
  1870. case ALC_DEVICE_SPECIFIER:
  1871. return GetDefaultName();
  1872. case ALC_ALL_DEVICES_SPECIFIER:
  1873. if(DeviceRef dev{VerifyDevice(Device)})
  1874. {
  1875. if(dev->Type == DeviceType::Capture)
  1876. {
  1877. alcSetError(dev.get(), ALC_INVALID_ENUM);
  1878. return nullptr;
  1879. }
  1880. if(dev->Type == DeviceType::Loopback)
  1881. return GetDefaultName();
  1882. auto statelock = std::lock_guard{dev->StateLock};
  1883. return dev->mDeviceName.c_str();
  1884. }
  1885. ProbeAllDevicesList();
  1886. return alcAllDevicesList.c_str();
  1887. case ALC_CAPTURE_DEVICE_SPECIFIER:
  1888. if(DeviceRef dev{VerifyDevice(Device)})
  1889. {
  1890. if(dev->Type != DeviceType::Capture)
  1891. {
  1892. alcSetError(dev.get(), ALC_INVALID_ENUM);
  1893. return nullptr;
  1894. }
  1895. auto statelock = std::lock_guard{dev->StateLock};
  1896. return dev->mDeviceName.c_str();
  1897. }
  1898. ProbeCaptureDeviceList();
  1899. return alcCaptureDeviceList.c_str();
  1900. /* Default devices are always first in the list */
  1901. case ALC_DEFAULT_DEVICE_SPECIFIER:
  1902. return GetDefaultName();
  1903. case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
  1904. if(alcAllDevicesList.empty())
  1905. ProbeAllDevicesList();
  1906. /* Copy first entry as default. */
  1907. if(!alcAllDevicesArray.empty())
  1908. alcDefaultAllDevicesSpecifier = alcAllDevicesArray.front();
  1909. else
  1910. alcDefaultAllDevicesSpecifier.clear();
  1911. return alcDefaultAllDevicesSpecifier.c_str();
  1912. case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
  1913. if(alcCaptureDeviceList.empty())
  1914. ProbeCaptureDeviceList();
  1915. /* Copy first entry as default. */
  1916. if(!alcCaptureDeviceArray.empty())
  1917. alcCaptureDefaultDeviceSpecifier = alcCaptureDeviceArray.front();
  1918. else
  1919. alcCaptureDefaultDeviceSpecifier.clear();
  1920. return alcCaptureDefaultDeviceSpecifier.c_str();
  1921. case ALC_EXTENSIONS:
  1922. if(VerifyDevice(Device))
  1923. return GetExtensionList();
  1924. return GetNoDeviceExtList();
  1925. case ALC_HRTF_SPECIFIER_SOFT:
  1926. if(DeviceRef dev{VerifyDevice(Device)})
  1927. {
  1928. std::lock_guard<std::mutex> statelock{dev->StateLock};
  1929. return dev->mHrtf ? dev->mHrtfName.c_str() : "";
  1930. }
  1931. alcSetError(nullptr, ALC_INVALID_DEVICE);
  1932. return nullptr;
  1933. default:
  1934. alcSetError(VerifyDevice(Device).get(), ALC_INVALID_ENUM);
  1935. }
  1936. return nullptr;
  1937. }
  1938. namespace {
  1939. auto GetIntegerv(al::Device *device, ALCenum param, const al::span<int> values) -> size_t
  1940. {
  1941. if(values.empty())
  1942. {
  1943. alcSetError(device, ALC_INVALID_VALUE);
  1944. return 0;
  1945. }
  1946. if(!device)
  1947. {
  1948. switch(param)
  1949. {
  1950. case ALC_MAJOR_VERSION:
  1951. values[0] = alcMajorVersion;
  1952. return 1;
  1953. case ALC_MINOR_VERSION:
  1954. values[0] = alcMinorVersion;
  1955. return 1;
  1956. case ALC_EFX_MAJOR_VERSION:
  1957. values[0] = alcEFXMajorVersion;
  1958. return 1;
  1959. case ALC_EFX_MINOR_VERSION:
  1960. values[0] = alcEFXMinorVersion;
  1961. return 1;
  1962. case ALC_MAX_AUXILIARY_SENDS:
  1963. values[0] = MaxSendCount;
  1964. return 1;
  1965. case ALC_ATTRIBUTES_SIZE:
  1966. case ALC_ALL_ATTRIBUTES:
  1967. case ALC_FREQUENCY:
  1968. case ALC_REFRESH:
  1969. case ALC_SYNC:
  1970. case ALC_MONO_SOURCES:
  1971. case ALC_STEREO_SOURCES:
  1972. case ALC_CAPTURE_SAMPLES:
  1973. case ALC_FORMAT_CHANNELS_SOFT:
  1974. case ALC_FORMAT_TYPE_SOFT:
  1975. case ALC_AMBISONIC_LAYOUT_SOFT:
  1976. case ALC_AMBISONIC_SCALING_SOFT:
  1977. case ALC_AMBISONIC_ORDER_SOFT:
  1978. case ALC_MAX_AMBISONIC_ORDER_SOFT:
  1979. alcSetError(nullptr, ALC_INVALID_DEVICE);
  1980. return 0;
  1981. default:
  1982. alcSetError(nullptr, ALC_INVALID_ENUM);
  1983. }
  1984. return 0;
  1985. }
  1986. std::lock_guard<std::mutex> statelock{device->StateLock};
  1987. if(device->Type == DeviceType::Capture)
  1988. {
  1989. static constexpr int MaxCaptureAttributes{9};
  1990. switch(param)
  1991. {
  1992. case ALC_ATTRIBUTES_SIZE:
  1993. values[0] = MaxCaptureAttributes;
  1994. return 1;
  1995. case ALC_ALL_ATTRIBUTES:
  1996. if(values.size() >= MaxCaptureAttributes)
  1997. {
  1998. size_t i{0};
  1999. values[i++] = ALC_MAJOR_VERSION;
  2000. values[i++] = alcMajorVersion;
  2001. values[i++] = ALC_MINOR_VERSION;
  2002. values[i++] = alcMinorVersion;
  2003. values[i++] = ALC_CAPTURE_SAMPLES;
  2004. values[i++] = static_cast<int>(device->Backend->availableSamples());
  2005. values[i++] = ALC_CONNECTED;
  2006. values[i++] = device->Connected.load(std::memory_order_relaxed);
  2007. values[i++] = 0;
  2008. assert(i == MaxCaptureAttributes);
  2009. return i;
  2010. }
  2011. alcSetError(device, ALC_INVALID_VALUE);
  2012. return 0;
  2013. case ALC_MAJOR_VERSION:
  2014. values[0] = alcMajorVersion;
  2015. return 1;
  2016. case ALC_MINOR_VERSION:
  2017. values[0] = alcMinorVersion;
  2018. return 1;
  2019. case ALC_CAPTURE_SAMPLES:
  2020. values[0] = static_cast<int>(device->Backend->availableSamples());
  2021. return 1;
  2022. case ALC_CONNECTED:
  2023. values[0] = device->Connected.load(std::memory_order_acquire);
  2024. return 1;
  2025. default:
  2026. alcSetError(device, ALC_INVALID_ENUM);
  2027. }
  2028. return 0;
  2029. }
  2030. /* render device */
  2031. auto NumAttrsForDevice = [device]() noexcept -> uint8_t
  2032. {
  2033. if(device->Type == DeviceType::Loopback && device->FmtChans == DevFmtAmbi3D)
  2034. return 37;
  2035. return 31;
  2036. };
  2037. switch(param)
  2038. {
  2039. case ALC_ATTRIBUTES_SIZE:
  2040. values[0] = NumAttrsForDevice();
  2041. return 1;
  2042. case ALC_ALL_ATTRIBUTES:
  2043. if(values.size() >= NumAttrsForDevice())
  2044. {
  2045. size_t i{0};
  2046. values[i++] = ALC_MAJOR_VERSION;
  2047. values[i++] = alcMajorVersion;
  2048. values[i++] = ALC_MINOR_VERSION;
  2049. values[i++] = alcMinorVersion;
  2050. values[i++] = ALC_EFX_MAJOR_VERSION;
  2051. values[i++] = alcEFXMajorVersion;
  2052. values[i++] = ALC_EFX_MINOR_VERSION;
  2053. values[i++] = alcEFXMinorVersion;
  2054. values[i++] = ALC_FREQUENCY;
  2055. values[i++] = static_cast<int>(device->mSampleRate);
  2056. if(device->Type != DeviceType::Loopback)
  2057. {
  2058. values[i++] = ALC_REFRESH;
  2059. values[i++] = static_cast<int>(device->mSampleRate / device->mUpdateSize);
  2060. values[i++] = ALC_SYNC;
  2061. values[i++] = ALC_FALSE;
  2062. }
  2063. else
  2064. {
  2065. if(device->FmtChans == DevFmtAmbi3D)
  2066. {
  2067. values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
  2068. values[i++] = EnumFromDevAmbi(device->mAmbiLayout);
  2069. values[i++] = ALC_AMBISONIC_SCALING_SOFT;
  2070. values[i++] = EnumFromDevAmbi(device->mAmbiScale);
  2071. values[i++] = ALC_AMBISONIC_ORDER_SOFT;
  2072. values[i++] = static_cast<int>(device->mAmbiOrder);
  2073. }
  2074. values[i++] = ALC_FORMAT_CHANNELS_SOFT;
  2075. values[i++] = EnumFromDevFmt(device->FmtChans);
  2076. values[i++] = ALC_FORMAT_TYPE_SOFT;
  2077. values[i++] = EnumFromDevFmt(device->FmtType);
  2078. }
  2079. values[i++] = ALC_MONO_SOURCES;
  2080. values[i++] = static_cast<int>(device->NumMonoSources);
  2081. values[i++] = ALC_STEREO_SOURCES;
  2082. values[i++] = static_cast<int>(device->NumStereoSources);
  2083. values[i++] = ALC_MAX_AUXILIARY_SENDS;
  2084. values[i++] = static_cast<int>(device->NumAuxSends);
  2085. values[i++] = ALC_HRTF_SOFT;
  2086. values[i++] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
  2087. values[i++] = ALC_HRTF_STATUS_SOFT;
  2088. values[i++] = device->mHrtfStatus;
  2089. values[i++] = ALC_OUTPUT_LIMITER_SOFT;
  2090. values[i++] = device->Limiter ? ALC_TRUE : ALC_FALSE;
  2091. values[i++] = ALC_MAX_AMBISONIC_ORDER_SOFT;
  2092. values[i++] = MaxAmbiOrder;
  2093. values[i++] = ALC_OUTPUT_MODE_SOFT;
  2094. values[i++] = static_cast<ALCenum>(device->getOutputMode1());
  2095. values[i++] = 0;
  2096. assert(i == NumAttrsForDevice());
  2097. return i;
  2098. }
  2099. alcSetError(device, ALC_INVALID_VALUE);
  2100. return 0;
  2101. case ALC_MAJOR_VERSION:
  2102. values[0] = alcMajorVersion;
  2103. return 1;
  2104. case ALC_MINOR_VERSION:
  2105. values[0] = alcMinorVersion;
  2106. return 1;
  2107. case ALC_EFX_MAJOR_VERSION:
  2108. values[0] = alcEFXMajorVersion;
  2109. return 1;
  2110. case ALC_EFX_MINOR_VERSION:
  2111. values[0] = alcEFXMinorVersion;
  2112. return 1;
  2113. case ALC_FREQUENCY:
  2114. values[0] = static_cast<int>(device->mSampleRate);
  2115. return 1;
  2116. case ALC_REFRESH:
  2117. if(device->Type == DeviceType::Loopback)
  2118. {
  2119. alcSetError(device, ALC_INVALID_DEVICE);
  2120. return 0;
  2121. }
  2122. values[0] = static_cast<int>(device->mSampleRate / device->mUpdateSize);
  2123. return 1;
  2124. case ALC_SYNC:
  2125. if(device->Type == DeviceType::Loopback)
  2126. {
  2127. alcSetError(device, ALC_INVALID_DEVICE);
  2128. return 0;
  2129. }
  2130. values[0] = ALC_FALSE;
  2131. return 1;
  2132. case ALC_FORMAT_CHANNELS_SOFT:
  2133. if(device->Type != DeviceType::Loopback)
  2134. {
  2135. alcSetError(device, ALC_INVALID_DEVICE);
  2136. return 0;
  2137. }
  2138. values[0] = EnumFromDevFmt(device->FmtChans);
  2139. return 1;
  2140. case ALC_FORMAT_TYPE_SOFT:
  2141. if(device->Type != DeviceType::Loopback)
  2142. {
  2143. alcSetError(device, ALC_INVALID_DEVICE);
  2144. return 0;
  2145. }
  2146. values[0] = EnumFromDevFmt(device->FmtType);
  2147. return 1;
  2148. case ALC_AMBISONIC_LAYOUT_SOFT:
  2149. if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D)
  2150. {
  2151. alcSetError(device, ALC_INVALID_DEVICE);
  2152. return 0;
  2153. }
  2154. values[0] = EnumFromDevAmbi(device->mAmbiLayout);
  2155. return 1;
  2156. case ALC_AMBISONIC_SCALING_SOFT:
  2157. if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D)
  2158. {
  2159. alcSetError(device, ALC_INVALID_DEVICE);
  2160. return 0;
  2161. }
  2162. values[0] = EnumFromDevAmbi(device->mAmbiScale);
  2163. return 1;
  2164. case ALC_AMBISONIC_ORDER_SOFT:
  2165. if(device->Type != DeviceType::Loopback || device->FmtChans != DevFmtAmbi3D)
  2166. {
  2167. alcSetError(device, ALC_INVALID_DEVICE);
  2168. return 0;
  2169. }
  2170. values[0] = static_cast<int>(device->mAmbiOrder);
  2171. return 1;
  2172. case ALC_MONO_SOURCES:
  2173. values[0] = static_cast<int>(device->NumMonoSources);
  2174. return 1;
  2175. case ALC_STEREO_SOURCES:
  2176. values[0] = static_cast<int>(device->NumStereoSources);
  2177. return 1;
  2178. case ALC_MAX_AUXILIARY_SENDS:
  2179. values[0] = static_cast<int>(device->NumAuxSends);
  2180. return 1;
  2181. case ALC_CONNECTED:
  2182. values[0] = device->Connected.load(std::memory_order_acquire);
  2183. return 1;
  2184. case ALC_HRTF_SOFT:
  2185. values[0] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
  2186. return 1;
  2187. case ALC_HRTF_STATUS_SOFT:
  2188. values[0] = device->mHrtfStatus;
  2189. return 1;
  2190. case ALC_NUM_HRTF_SPECIFIERS_SOFT:
  2191. device->enumerateHrtfs();
  2192. values[0] = static_cast<int>(std::min(device->mHrtfList.size(),
  2193. size_t{std::numeric_limits<int>::max()}));
  2194. return 1;
  2195. case ALC_OUTPUT_LIMITER_SOFT:
  2196. values[0] = device->Limiter ? ALC_TRUE : ALC_FALSE;
  2197. return 1;
  2198. case ALC_MAX_AMBISONIC_ORDER_SOFT:
  2199. values[0] = MaxAmbiOrder;
  2200. return 1;
  2201. case ALC_OUTPUT_MODE_SOFT:
  2202. values[0] = static_cast<ALCenum>(device->getOutputMode1());
  2203. return 1;
  2204. default:
  2205. alcSetError(device, ALC_INVALID_ENUM);
  2206. }
  2207. return 0;
  2208. }
  2209. } // namespace
  2210. ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values) noexcept
  2211. {
  2212. DeviceRef dev{VerifyDevice(device)};
  2213. if(size <= 0 || values == nullptr)
  2214. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2215. else
  2216. GetIntegerv(dev.get(), param, {values, static_cast<uint>(size)});
  2217. }
  2218. ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALCsizei size, ALCint64SOFT *values) noexcept
  2219. {
  2220. DeviceRef dev{VerifyDevice(device)};
  2221. if(size <= 0 || values == nullptr)
  2222. {
  2223. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2224. return;
  2225. }
  2226. const auto valuespan = al::span{values, static_cast<uint>(size)};
  2227. if(!dev || dev->Type == DeviceType::Capture)
  2228. {
  2229. auto ivals = std::vector<int>(valuespan.size());
  2230. if(size_t got{GetIntegerv(dev.get(), pname, ivals)})
  2231. std::copy_n(ivals.cbegin(), got, valuespan.begin());
  2232. return;
  2233. }
  2234. /* render device */
  2235. auto NumAttrsForDevice = [](al::Device *aldev) noexcept -> size_t
  2236. {
  2237. if(aldev->Type == DeviceType::Loopback && aldev->FmtChans == DevFmtAmbi3D)
  2238. return 41;
  2239. return 35;
  2240. };
  2241. std::lock_guard<std::mutex> statelock{dev->StateLock};
  2242. switch(pname)
  2243. {
  2244. case ALC_ATTRIBUTES_SIZE:
  2245. valuespan[0] = static_cast<ALCint64SOFT>(NumAttrsForDevice(dev.get()));
  2246. break;
  2247. case ALC_ALL_ATTRIBUTES:
  2248. if(valuespan.size() < NumAttrsForDevice(dev.get()))
  2249. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2250. else
  2251. {
  2252. size_t i{0};
  2253. valuespan[i++] = ALC_FREQUENCY;
  2254. valuespan[i++] = dev->mSampleRate;
  2255. if(dev->Type != DeviceType::Loopback)
  2256. {
  2257. valuespan[i++] = ALC_REFRESH;
  2258. valuespan[i++] = dev->mSampleRate / dev->mUpdateSize;
  2259. valuespan[i++] = ALC_SYNC;
  2260. valuespan[i++] = ALC_FALSE;
  2261. }
  2262. else
  2263. {
  2264. valuespan[i++] = ALC_FORMAT_CHANNELS_SOFT;
  2265. valuespan[i++] = EnumFromDevFmt(dev->FmtChans);
  2266. valuespan[i++] = ALC_FORMAT_TYPE_SOFT;
  2267. valuespan[i++] = EnumFromDevFmt(dev->FmtType);
  2268. if(dev->FmtChans == DevFmtAmbi3D)
  2269. {
  2270. valuespan[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
  2271. valuespan[i++] = EnumFromDevAmbi(dev->mAmbiLayout);
  2272. valuespan[i++] = ALC_AMBISONIC_SCALING_SOFT;
  2273. valuespan[i++] = EnumFromDevAmbi(dev->mAmbiScale);
  2274. valuespan[i++] = ALC_AMBISONIC_ORDER_SOFT;
  2275. valuespan[i++] = dev->mAmbiOrder;
  2276. }
  2277. }
  2278. valuespan[i++] = ALC_MONO_SOURCES;
  2279. valuespan[i++] = dev->NumMonoSources;
  2280. valuespan[i++] = ALC_STEREO_SOURCES;
  2281. valuespan[i++] = dev->NumStereoSources;
  2282. valuespan[i++] = ALC_MAX_AUXILIARY_SENDS;
  2283. valuespan[i++] = dev->NumAuxSends;
  2284. valuespan[i++] = ALC_HRTF_SOFT;
  2285. valuespan[i++] = (dev->mHrtf ? ALC_TRUE : ALC_FALSE);
  2286. valuespan[i++] = ALC_HRTF_STATUS_SOFT;
  2287. valuespan[i++] = dev->mHrtfStatus;
  2288. valuespan[i++] = ALC_OUTPUT_LIMITER_SOFT;
  2289. valuespan[i++] = dev->Limiter ? ALC_TRUE : ALC_FALSE;
  2290. ClockLatency clock{GetClockLatency(dev.get(), dev->Backend.get())};
  2291. valuespan[i++] = ALC_DEVICE_CLOCK_SOFT;
  2292. valuespan[i++] = clock.ClockTime.count();
  2293. valuespan[i++] = ALC_DEVICE_LATENCY_SOFT;
  2294. valuespan[i++] = clock.Latency.count();
  2295. valuespan[i++] = ALC_OUTPUT_MODE_SOFT;
  2296. valuespan[i++] = al::to_underlying(dev->getOutputMode1());
  2297. valuespan[i++] = 0;
  2298. }
  2299. break;
  2300. case ALC_DEVICE_CLOCK_SOFT:
  2301. {
  2302. uint samplecount, refcount;
  2303. seconds clocksec;
  2304. nanoseconds clocknsec;
  2305. do {
  2306. refcount = dev->waitForMix();
  2307. samplecount = dev->mSamplesDone.load(std::memory_order_relaxed);
  2308. clocksec = dev->mClockBaseSec.load(std::memory_order_relaxed);
  2309. clocknsec = dev->mClockBaseNSec.load(std::memory_order_relaxed);
  2310. std::atomic_thread_fence(std::memory_order_acquire);
  2311. } while(refcount != dev->mMixCount.load(std::memory_order_relaxed));
  2312. valuespan[0] = nanoseconds{clocksec + nanoseconds{clocknsec}
  2313. + nanoseconds{seconds{samplecount}}/dev->mSampleRate}.count();
  2314. }
  2315. break;
  2316. case ALC_DEVICE_LATENCY_SOFT:
  2317. valuespan[0] = GetClockLatency(dev.get(), dev->Backend.get()).Latency.count();
  2318. break;
  2319. case ALC_DEVICE_CLOCK_LATENCY_SOFT:
  2320. if(size < 2)
  2321. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2322. else
  2323. {
  2324. ClockLatency clock{GetClockLatency(dev.get(), dev->Backend.get())};
  2325. valuespan[0] = clock.ClockTime.count();
  2326. valuespan[1] = clock.Latency.count();
  2327. }
  2328. break;
  2329. default:
  2330. auto ivals = std::vector<int>(valuespan.size());
  2331. if(size_t got{GetIntegerv(dev.get(), pname, ivals)})
  2332. std::copy_n(ivals.cbegin(), got, valuespan.begin());
  2333. break;
  2334. }
  2335. }
  2336. ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName) noexcept
  2337. {
  2338. DeviceRef dev{VerifyDevice(device)};
  2339. if(!extName)
  2340. {
  2341. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2342. return ALC_FALSE;
  2343. }
  2344. const std::string_view tofind{extName};
  2345. const auto extlist = dev ? std::string_view{GetExtensionList()}
  2346. : std::string_view{GetNoDeviceExtList()};
  2347. auto matchpos = extlist.find(tofind);
  2348. while(matchpos != std::string_view::npos)
  2349. {
  2350. const auto endpos = matchpos + tofind.size();
  2351. if((matchpos == 0 || std::isspace(extlist[matchpos-1]))
  2352. && (endpos == extlist.size() || std::isspace(extlist[endpos])))
  2353. return ALC_TRUE;
  2354. matchpos = extlist.find(tofind, matchpos+1);
  2355. }
  2356. return ALC_FALSE;
  2357. }
  2358. ALCvoid* ALC_APIENTRY alcGetProcAddress2(ALCdevice *device, const ALCchar *funcName) noexcept
  2359. { return alcGetProcAddress(device, funcName); }
  2360. ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName) noexcept
  2361. {
  2362. if(!funcName)
  2363. {
  2364. DeviceRef dev{VerifyDevice(device)};
  2365. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2366. return nullptr;
  2367. }
  2368. #if ALSOFT_EAX
  2369. if(eax_g_is_enabled)
  2370. {
  2371. for(const auto &func : eaxFunctions)
  2372. {
  2373. if(strcmp(func.funcName, funcName) == 0)
  2374. return func.address;
  2375. }
  2376. }
  2377. #endif
  2378. for(const auto &func : alcFunctions)
  2379. {
  2380. if(strcmp(func.funcName, funcName) == 0)
  2381. return func.address;
  2382. }
  2383. return nullptr;
  2384. }
  2385. ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName) noexcept
  2386. {
  2387. if(!enumName)
  2388. {
  2389. DeviceRef dev{VerifyDevice(device)};
  2390. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2391. return 0;
  2392. }
  2393. #if ALSOFT_EAX
  2394. if(eax_g_is_enabled)
  2395. {
  2396. for(const auto &enm : eaxEnumerations)
  2397. {
  2398. if(strcmp(enm.enumName, enumName) == 0)
  2399. return enm.value;
  2400. }
  2401. }
  2402. #endif
  2403. for(const auto &enm : alcEnumerations)
  2404. {
  2405. if(strcmp(enm.enumName, enumName) == 0)
  2406. return enm.value;
  2407. }
  2408. return 0;
  2409. }
  2410. ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList) noexcept
  2411. {
  2412. /* Explicitly hold the list lock while taking the StateLock in case the
  2413. * device is asynchronously destroyed, to ensure this new context is
  2414. * properly cleaned up after being made.
  2415. */
  2416. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  2417. DeviceRef dev{VerifyDevice(device)};
  2418. if(!dev || dev->Type == DeviceType::Capture || !dev->Connected.load(std::memory_order_relaxed))
  2419. {
  2420. listlock.unlock();
  2421. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2422. return nullptr;
  2423. }
  2424. std::unique_lock<std::mutex> statelock{dev->StateLock};
  2425. listlock.unlock();
  2426. dev->LastError.store(ALC_NO_ERROR);
  2427. const auto attrSpan = SpanFromAttributeList(attrList);
  2428. ALCenum err{UpdateDeviceParams(dev.get(), attrSpan)};
  2429. if(err != ALC_NO_ERROR)
  2430. {
  2431. alcSetError(dev.get(), err);
  2432. return nullptr;
  2433. }
  2434. ContextFlagBitset ctxflags{0};
  2435. for(size_t i{0};i < attrSpan.size();i+=2)
  2436. {
  2437. if(attrSpan[i] == ALC_CONTEXT_FLAGS_EXT)
  2438. {
  2439. ctxflags = static_cast<ALuint>(attrSpan[i+1]);
  2440. break;
  2441. }
  2442. }
  2443. auto context = ContextRef{new(std::nothrow) ALCcontext{dev, ctxflags}};
  2444. if(!context)
  2445. {
  2446. alcSetError(dev.get(), ALC_OUT_OF_MEMORY);
  2447. return nullptr;
  2448. }
  2449. context->init();
  2450. if(auto volopt = dev->configValue<float>({}, "volume-adjust"))
  2451. {
  2452. const float valf{*volopt};
  2453. if(!std::isfinite(valf))
  2454. ERR("volume-adjust must be finite: {:f}", valf);
  2455. else
  2456. {
  2457. const float db{std::clamp(valf, -24.0f, 24.0f)};
  2458. if(db != valf)
  2459. WARN("volume-adjust clamped: {:f}, range: +/-24", valf);
  2460. context->mGainBoost = std::pow(10.0f, db/20.0f);
  2461. TRACE("volume-adjust gain: {:f}", context->mGainBoost);
  2462. }
  2463. }
  2464. {
  2465. using ContextArray = al::FlexArray<ContextBase*>;
  2466. /* Allocate a new context array, which holds 1 more than the current/
  2467. * old array.
  2468. */
  2469. auto *oldarray = dev->mContexts.load();
  2470. auto newarray = ContextArray::Create(oldarray->size() + 1);
  2471. /* Copy the current/old context handles to the new array, appending the
  2472. * new context.
  2473. */
  2474. auto iter = std::copy(oldarray->begin(), oldarray->end(), newarray->begin());
  2475. *iter = context.get();
  2476. /* Store the new context array in the device. Wait for any current mix
  2477. * to finish before deleting the old array.
  2478. */
  2479. auto prevarray = dev->mContexts.exchange(std::move(newarray));
  2480. std::ignore = dev->waitForMix();
  2481. }
  2482. statelock.unlock();
  2483. {
  2484. listlock.lock();
  2485. auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context.get());
  2486. ContextList.emplace(iter, context.get());
  2487. listlock.unlock();
  2488. }
  2489. if(ALeffectslot *slot{context->mDefaultSlot.get()})
  2490. {
  2491. ALenum sloterr{slot->initEffect(0, ALCcontext::sDefaultEffect.type,
  2492. ALCcontext::sDefaultEffect.Props, context.get())};
  2493. if(sloterr == AL_NO_ERROR)
  2494. slot->updateProps(context.get());
  2495. else
  2496. ERR("Failed to initialize the default effect");
  2497. }
  2498. TRACE("Created context {}", voidp{context.get()});
  2499. return context.release();
  2500. }
  2501. ALC_API void ALC_APIENTRY alcDestroyContext(ALCcontext *context) noexcept
  2502. {
  2503. if(!gProcessRunning)
  2504. return;
  2505. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  2506. auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context);
  2507. if(iter == ContextList.end() || *iter != context)
  2508. {
  2509. listlock.unlock();
  2510. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2511. return;
  2512. }
  2513. /* Hold a reference to this context so it remains valid until the ListLock
  2514. * is released.
  2515. */
  2516. ContextRef ctx{*iter};
  2517. ContextList.erase(iter);
  2518. auto *Device = ctx->mALDevice.get();
  2519. std::lock_guard<std::mutex> statelock{Device->StateLock};
  2520. ctx->deinit();
  2521. }
  2522. ALC_API auto ALC_APIENTRY alcGetCurrentContext() noexcept -> ALCcontext*
  2523. {
  2524. ALCcontext *Context{ALCcontext::getThreadContext()};
  2525. if(!Context) Context = ALCcontext::sGlobalContext.load();
  2526. return Context;
  2527. }
  2528. /** Returns the currently active thread-local context. */
  2529. ALC_API auto ALC_APIENTRY alcGetThreadContext() noexcept -> ALCcontext*
  2530. { return ALCcontext::getThreadContext(); }
  2531. ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context) noexcept
  2532. {
  2533. /* context must be valid or nullptr */
  2534. ContextRef ctx;
  2535. if(context)
  2536. {
  2537. ctx = VerifyContext(context);
  2538. if(!ctx)
  2539. {
  2540. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2541. return ALC_FALSE;
  2542. }
  2543. }
  2544. /* Release this reference (if any) to store it in the GlobalContext
  2545. * pointer. Take ownership of the reference (if any) that was previously
  2546. * stored there, and let the reference go.
  2547. */
  2548. while(ALCcontext::sGlobalContextLock.exchange(true, std::memory_order_acquire)) {
  2549. /* Wait to make sure another thread isn't getting or trying to change
  2550. * the current context as its refcount is decremented.
  2551. */
  2552. }
  2553. ctx = ContextRef{ALCcontext::sGlobalContext.exchange(ctx.release())};
  2554. ALCcontext::sGlobalContextLock.store(false, std::memory_order_release);
  2555. /* Take ownership of the thread-local context reference (if any), clearing
  2556. * the storage to null.
  2557. */
  2558. ctx = ContextRef{ALCcontext::getThreadContext()};
  2559. if(ctx) ALCcontext::setThreadContext(nullptr);
  2560. /* Reset (decrement) the previous thread-local reference. */
  2561. return ALC_TRUE;
  2562. }
  2563. /** Makes the given context the active context for the current thread. */
  2564. ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context) noexcept
  2565. {
  2566. /* context must be valid or nullptr */
  2567. ContextRef ctx;
  2568. if(context)
  2569. {
  2570. ctx = VerifyContext(context);
  2571. if(!ctx)
  2572. {
  2573. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2574. return ALC_FALSE;
  2575. }
  2576. }
  2577. /* context's reference count is already incremented */
  2578. ContextRef old{ALCcontext::getThreadContext()};
  2579. ALCcontext::setThreadContext(ctx.release());
  2580. return ALC_TRUE;
  2581. }
  2582. ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context) noexcept
  2583. {
  2584. ContextRef ctx{VerifyContext(Context)};
  2585. if(!ctx)
  2586. {
  2587. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2588. return nullptr;
  2589. }
  2590. return ctx->mALDevice.get();
  2591. }
  2592. ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName) noexcept
  2593. {
  2594. InitConfig();
  2595. if(!PlaybackFactory)
  2596. {
  2597. alcSetError(nullptr, ALC_INVALID_VALUE);
  2598. return nullptr;
  2599. }
  2600. std::string_view devname{deviceName ? deviceName : ""};
  2601. if(!devname.empty())
  2602. {
  2603. TRACE("Opening playback device \"{}\"", devname);
  2604. if(al::case_compare(devname, GetDefaultName()) == 0
  2605. #ifdef _WIN32
  2606. /* Some old Windows apps hardcode these expecting OpenAL to use a
  2607. * specific audio API, even when they're not enumerated. Creative's
  2608. * router effectively ignores them too.
  2609. */
  2610. || al::case_compare(devname, "DirectSound3D"sv) == 0
  2611. || al::case_compare(devname, "DirectSound"sv) == 0
  2612. || al::case_compare(devname, "MMSYSTEM"sv) == 0
  2613. #endif
  2614. /* Some old Linux apps hardcode configuration strings that were
  2615. * supported by the OpenAL SI. We can't really do anything useful
  2616. * with them, so just ignore.
  2617. */
  2618. || al::starts_with(devname, "'("sv)
  2619. || al::case_compare(devname, "openal-soft"sv) == 0)
  2620. devname = {};
  2621. else
  2622. {
  2623. const auto prefix = GetDevicePrefix();
  2624. if(!prefix.empty() && devname.size() > prefix.size()
  2625. && al::starts_with(devname, prefix))
  2626. devname = devname.substr(prefix.size());
  2627. }
  2628. }
  2629. else
  2630. TRACE("Opening default playback device");
  2631. const uint DefaultSends{
  2632. #if ALSOFT_EAX
  2633. eax_g_is_enabled ? uint{EAX_MAX_FXSLOTS} :
  2634. #endif // ALSOFT_EAX
  2635. uint{DefaultSendCount}
  2636. };
  2637. auto device = DeviceRef{new(std::nothrow) al::Device{DeviceType::Playback}};
  2638. if(!device)
  2639. {
  2640. WARN("Failed to create playback device handle");
  2641. alcSetError(nullptr, ALC_OUT_OF_MEMORY);
  2642. return nullptr;
  2643. }
  2644. /* Set output format */
  2645. device->FmtChans = DevFmtChannelsDefault;
  2646. device->FmtType = DevFmtTypeDefault;
  2647. device->mSampleRate = DefaultOutputRate;
  2648. device->mUpdateSize = DefaultUpdateSize;
  2649. device->mBufferSize = DefaultUpdateSize * DefaultNumUpdates;
  2650. device->SourcesMax = 256;
  2651. device->NumStereoSources = 1;
  2652. device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
  2653. device->AuxiliaryEffectSlotMax = 64;
  2654. device->NumAuxSends = DefaultSends;
  2655. try {
  2656. auto backend = PlaybackFactory->createBackend(device.get(), BackendType::Playback);
  2657. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  2658. backend->open(devname);
  2659. device->mDeviceName = std::string{GetDevicePrefix()}+backend->mDeviceName;
  2660. device->Backend = std::move(backend);
  2661. }
  2662. catch(al::backend_exception &e) {
  2663. WARN("Failed to open playback device: {}", e.what());
  2664. alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory)
  2665. ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
  2666. return nullptr;
  2667. }
  2668. auto checkopt = [&device](const char *envname, const std::string_view optname)
  2669. {
  2670. if(auto optval = al::getenv(envname)) return optval;
  2671. return device->configValue<std::string>("game_compat", optname);
  2672. };
  2673. if(auto overrideopt = checkopt("__ALSOFT_VENDOR_OVERRIDE", "vendor-override"sv))
  2674. {
  2675. device->mVendorOverride = std::move(*overrideopt);
  2676. TRACE("Overriding vendor string: \"{}\"", device->mVendorOverride);
  2677. }
  2678. if(auto overrideopt = checkopt("__ALSOFT_VERSION_OVERRIDE", "version-override"sv))
  2679. {
  2680. device->mVersionOverride = std::move(*overrideopt);
  2681. TRACE("Overriding version string: \"{}\"", device->mVersionOverride);
  2682. }
  2683. if(auto overrideopt = checkopt("__ALSOFT_RENDERER_OVERRIDE", "renderer-override"sv))
  2684. {
  2685. device->mRendererOverride = std::move(*overrideopt);
  2686. TRACE("Overriding renderer string: \"{}\"", device->mRendererOverride);
  2687. }
  2688. {
  2689. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  2690. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  2691. DeviceList.emplace(iter, device.get());
  2692. }
  2693. TRACE("Created device {}, \"{}\"", voidp{device.get()}, device->mDeviceName);
  2694. return device.release();
  2695. }
  2696. ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device) noexcept
  2697. {
  2698. if(!gProcessRunning)
  2699. return ALC_FALSE;
  2700. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  2701. auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
  2702. if(iter == DeviceList.end() || *iter != device)
  2703. {
  2704. alcSetError(nullptr, ALC_INVALID_DEVICE);
  2705. return ALC_FALSE;
  2706. }
  2707. if((*iter)->Type == DeviceType::Capture)
  2708. {
  2709. alcSetError(*iter, ALC_INVALID_DEVICE);
  2710. return ALC_FALSE;
  2711. }
  2712. /* Erase the device, and any remaining contexts left on it, from their
  2713. * respective lists.
  2714. */
  2715. DeviceRef dev{*iter};
  2716. DeviceList.erase(iter);
  2717. std::unique_lock<std::mutex> statelock{dev->StateLock};
  2718. std::vector<ContextRef> orphanctxs;
  2719. for(ContextBase *ctx : *dev->mContexts.load())
  2720. {
  2721. auto ctxiter = std::lower_bound(ContextList.begin(), ContextList.end(), ctx);
  2722. if(ctxiter != ContextList.end() && *ctxiter == ctx)
  2723. {
  2724. orphanctxs.emplace_back(*ctxiter);
  2725. ContextList.erase(ctxiter);
  2726. }
  2727. }
  2728. listlock.unlock();
  2729. for(ContextRef &context : orphanctxs)
  2730. {
  2731. WARN("Releasing orphaned context {}", voidp{context.get()});
  2732. context->deinit();
  2733. }
  2734. orphanctxs.clear();
  2735. if(dev->mDeviceState == DeviceState::Playing)
  2736. {
  2737. dev->Backend->stop();
  2738. dev->mDeviceState = DeviceState::Configured;
  2739. }
  2740. return ALC_TRUE;
  2741. }
  2742. /************************************************
  2743. * ALC capture functions
  2744. ************************************************/
  2745. ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples) noexcept
  2746. {
  2747. InitConfig();
  2748. if(!CaptureFactory)
  2749. {
  2750. alcSetError(nullptr, ALC_INVALID_VALUE);
  2751. return nullptr;
  2752. }
  2753. if(samples <= 0)
  2754. {
  2755. alcSetError(nullptr, ALC_INVALID_VALUE);
  2756. return nullptr;
  2757. }
  2758. std::string_view devname{deviceName ? deviceName : ""};
  2759. if(!devname.empty())
  2760. {
  2761. TRACE("Opening capture device \"{}\"", devname);
  2762. if(al::case_compare(devname, GetDefaultName()) == 0
  2763. || al::case_compare(devname, "openal-soft"sv) == 0)
  2764. devname = {};
  2765. else
  2766. {
  2767. const auto prefix = GetDevicePrefix();
  2768. if(!prefix.empty() && devname.size() > prefix.size()
  2769. && al::starts_with(devname, prefix))
  2770. devname = devname.substr(prefix.size());
  2771. }
  2772. }
  2773. else
  2774. TRACE("Opening default capture device");
  2775. auto device = DeviceRef{new(std::nothrow) al::Device{DeviceType::Capture}};
  2776. if(!device)
  2777. {
  2778. WARN("Failed to create capture device handle");
  2779. alcSetError(nullptr, ALC_OUT_OF_MEMORY);
  2780. return nullptr;
  2781. }
  2782. auto decompfmt = DecomposeDevFormat(format);
  2783. if(!decompfmt)
  2784. {
  2785. alcSetError(nullptr, ALC_INVALID_ENUM);
  2786. return nullptr;
  2787. }
  2788. device->mSampleRate = frequency;
  2789. device->FmtChans = decompfmt->chans;
  2790. device->FmtType = decompfmt->type;
  2791. device->Flags.set(FrequencyRequest);
  2792. device->Flags.set(ChannelsRequest);
  2793. device->Flags.set(SampleTypeRequest);
  2794. device->mUpdateSize = static_cast<uint>(samples);
  2795. device->mBufferSize = static_cast<uint>(samples);
  2796. TRACE("Capture format: {}, {}, {}hz, {} / {} buffer",
  2797. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  2798. device->mSampleRate, device->mUpdateSize, device->mBufferSize);
  2799. try {
  2800. auto backend = CaptureFactory->createBackend(device.get(), BackendType::Capture);
  2801. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  2802. backend->open(devname);
  2803. device->mDeviceName = std::string{GetDevicePrefix()}+backend->mDeviceName;
  2804. device->Backend = std::move(backend);
  2805. }
  2806. catch(al::backend_exception &e) {
  2807. WARN("Failed to open capture device: {}", e.what());
  2808. alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory)
  2809. ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
  2810. return nullptr;
  2811. }
  2812. {
  2813. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  2814. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  2815. DeviceList.emplace(iter, device.get());
  2816. }
  2817. device->mDeviceState = DeviceState::Configured;
  2818. TRACE("Created capture device {}, \"{}\"", voidp{device.get()}, device->mDeviceName);
  2819. return device.release();
  2820. }
  2821. ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device) noexcept
  2822. {
  2823. if(!gProcessRunning)
  2824. return ALC_FALSE;
  2825. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  2826. auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
  2827. if(iter == DeviceList.end() || *iter != device)
  2828. {
  2829. alcSetError(nullptr, ALC_INVALID_DEVICE);
  2830. return ALC_FALSE;
  2831. }
  2832. if((*iter)->Type != DeviceType::Capture)
  2833. {
  2834. alcSetError(*iter, ALC_INVALID_DEVICE);
  2835. return ALC_FALSE;
  2836. }
  2837. DeviceRef dev{*iter};
  2838. DeviceList.erase(iter);
  2839. listlock.unlock();
  2840. std::lock_guard<std::mutex> statelock{dev->StateLock};
  2841. if(dev->mDeviceState == DeviceState::Playing)
  2842. {
  2843. dev->Backend->stop();
  2844. dev->mDeviceState = DeviceState::Configured;
  2845. }
  2846. return ALC_TRUE;
  2847. }
  2848. ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device) noexcept
  2849. {
  2850. DeviceRef dev{VerifyDevice(device)};
  2851. if(!dev || dev->Type != DeviceType::Capture)
  2852. {
  2853. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2854. return;
  2855. }
  2856. std::lock_guard<std::mutex> statelock{dev->StateLock};
  2857. if(!dev->Connected.load(std::memory_order_acquire)
  2858. || dev->mDeviceState < DeviceState::Configured)
  2859. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2860. else if(dev->mDeviceState != DeviceState::Playing)
  2861. {
  2862. try {
  2863. auto backend = dev->Backend.get();
  2864. backend->start();
  2865. dev->mDeviceState = DeviceState::Playing;
  2866. }
  2867. catch(al::backend_exception& e) {
  2868. ERR("{}", e.what());
  2869. dev->handleDisconnect("{}", e.what());
  2870. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2871. }
  2872. }
  2873. }
  2874. ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device) noexcept
  2875. {
  2876. DeviceRef dev{VerifyDevice(device)};
  2877. if(!dev || dev->Type != DeviceType::Capture)
  2878. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2879. else
  2880. {
  2881. std::lock_guard<std::mutex> statelock{dev->StateLock};
  2882. if(dev->mDeviceState == DeviceState::Playing)
  2883. {
  2884. dev->Backend->stop();
  2885. dev->mDeviceState = DeviceState::Configured;
  2886. }
  2887. }
  2888. }
  2889. ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) noexcept
  2890. {
  2891. DeviceRef dev{VerifyDevice(device)};
  2892. if(!dev || dev->Type != DeviceType::Capture)
  2893. {
  2894. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2895. return;
  2896. }
  2897. if(samples < 0 || (samples > 0 && buffer == nullptr))
  2898. {
  2899. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2900. return;
  2901. }
  2902. if(samples < 1)
  2903. return;
  2904. std::lock_guard<std::mutex> statelock{dev->StateLock};
  2905. BackendBase *backend{dev->Backend.get()};
  2906. const auto usamples = static_cast<uint>(samples);
  2907. if(usamples > backend->availableSamples())
  2908. {
  2909. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2910. return;
  2911. }
  2912. backend->captureSamples(static_cast<std::byte*>(buffer), usamples);
  2913. }
  2914. /************************************************
  2915. * ALC loopback functions
  2916. ************************************************/
  2917. /** Open a loopback device, for manual rendering. */
  2918. ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName) noexcept
  2919. {
  2920. InitConfig();
  2921. /* Make sure the device name, if specified, is us. */
  2922. if(deviceName && strcmp(deviceName, GetDefaultName()) != 0)
  2923. {
  2924. alcSetError(nullptr, ALC_INVALID_VALUE);
  2925. return nullptr;
  2926. }
  2927. const uint DefaultSends{
  2928. #if ALSOFT_EAX
  2929. eax_g_is_enabled ? uint{EAX_MAX_FXSLOTS} :
  2930. #endif // ALSOFT_EAX
  2931. uint{DefaultSendCount}
  2932. };
  2933. auto device = DeviceRef{new(std::nothrow) al::Device{DeviceType::Loopback}};
  2934. if(!device)
  2935. {
  2936. WARN("Failed to create loopback device handle");
  2937. alcSetError(nullptr, ALC_OUT_OF_MEMORY);
  2938. return nullptr;
  2939. }
  2940. device->SourcesMax = 256;
  2941. device->AuxiliaryEffectSlotMax = 64;
  2942. device->NumAuxSends = DefaultSends;
  2943. //Set output format
  2944. device->mBufferSize = 0;
  2945. device->mUpdateSize = 0;
  2946. device->mSampleRate = DefaultOutputRate;
  2947. device->FmtChans = DevFmtChannelsDefault;
  2948. device->FmtType = DevFmtTypeDefault;
  2949. device->NumStereoSources = 1;
  2950. device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
  2951. try {
  2952. auto backend = LoopbackBackendFactory::getFactory().createBackend(device.get(),
  2953. BackendType::Playback);
  2954. backend->open("Loopback");
  2955. device->mDeviceName = std::string{GetDevicePrefix()}+backend->mDeviceName;
  2956. device->Backend = std::move(backend);
  2957. }
  2958. catch(al::backend_exception &e) {
  2959. WARN("Failed to open loopback device: {}", e.what());
  2960. alcSetError(nullptr, (e.errorCode() == al::backend_error::OutOfMemory)
  2961. ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
  2962. return nullptr;
  2963. }
  2964. {
  2965. std::lock_guard<std::recursive_mutex> listlock{ListLock};
  2966. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  2967. DeviceList.emplace(iter, device.get());
  2968. }
  2969. TRACE("Created loopback device {}", voidp{device.get()});
  2970. return device.release();
  2971. }
  2972. /**
  2973. * Determines if the loopback device supports the given format for rendering.
  2974. */
  2975. ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type) noexcept
  2976. {
  2977. DeviceRef dev{VerifyDevice(device)};
  2978. if(!dev || dev->Type != DeviceType::Loopback)
  2979. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2980. else if(freq <= 0)
  2981. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2982. else
  2983. {
  2984. if(DevFmtTypeFromEnum(type).has_value() && DevFmtChannelsFromEnum(channels).has_value()
  2985. && freq >= int{MinOutputRate} && freq <= int{MaxOutputRate})
  2986. return ALC_TRUE;
  2987. }
  2988. return ALC_FALSE;
  2989. }
  2990. /**
  2991. * Renders some samples into a buffer, using the format last set by the
  2992. * attributes given to alcCreateContext.
  2993. */
  2994. #if defined(__GNUC__) && defined(__i386__)
  2995. /* Needed on x86-32 even without SSE codegen, since the mixer may still use SSE
  2996. * and GCC assumes the stack is aligned (x86-64 ABI guarantees alignment).
  2997. */
  2998. [[gnu::force_align_arg_pointer]]
  2999. #endif
  3000. ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples) noexcept
  3001. {
  3002. auto aldev = dynamic_cast<al::Device*>(device);
  3003. if(!aldev || aldev->Type != DeviceType::Loopback) UNLIKELY
  3004. alcSetError(aldev, ALC_INVALID_DEVICE);
  3005. else if(samples < 0 || (samples > 0 && buffer == nullptr)) UNLIKELY
  3006. alcSetError(aldev, ALC_INVALID_VALUE);
  3007. else
  3008. aldev->renderSamples(buffer, static_cast<uint>(samples), aldev->channelsFromFmt());
  3009. }
  3010. /************************************************
  3011. * ALC DSP pause/resume functions
  3012. ************************************************/
  3013. /** Pause the DSP to stop audio processing. */
  3014. ALC_API void ALC_APIENTRY alcDevicePauseSOFT(ALCdevice *device) noexcept
  3015. {
  3016. DeviceRef dev{VerifyDevice(device)};
  3017. if(!dev || dev->Type != DeviceType::Playback)
  3018. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3019. else
  3020. {
  3021. std::lock_guard<std::mutex> statelock{dev->StateLock};
  3022. if(dev->mDeviceState == DeviceState::Playing)
  3023. {
  3024. dev->Backend->stop();
  3025. dev->mDeviceState = DeviceState::Configured;
  3026. }
  3027. dev->Flags.set(DevicePaused);
  3028. }
  3029. }
  3030. /** Resume the DSP to restart audio processing. */
  3031. ALC_API void ALC_APIENTRY alcDeviceResumeSOFT(ALCdevice *device) noexcept
  3032. {
  3033. DeviceRef dev{VerifyDevice(device)};
  3034. if(!dev || dev->Type != DeviceType::Playback)
  3035. {
  3036. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3037. return;
  3038. }
  3039. std::lock_guard<std::mutex> statelock{dev->StateLock};
  3040. if(!dev->Flags.test(DevicePaused))
  3041. return;
  3042. if(dev->mDeviceState < DeviceState::Configured)
  3043. {
  3044. WARN("Cannot resume unconfigured device");
  3045. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3046. return;
  3047. }
  3048. if(!dev->Connected.load())
  3049. {
  3050. WARN("Cannot resume a disconnected device");
  3051. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3052. return;
  3053. }
  3054. dev->Flags.reset(DevicePaused);
  3055. if(dev->mContexts.load()->empty())
  3056. return;
  3057. try {
  3058. auto backend = dev->Backend.get();
  3059. backend->start();
  3060. dev->mDeviceState = DeviceState::Playing;
  3061. }
  3062. catch(al::backend_exception& e) {
  3063. ERR("{}", e.what());
  3064. dev->handleDisconnect("{}", e.what());
  3065. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3066. return;
  3067. }
  3068. TRACE("Post-resume: {}, {}, {}hz, {} / {} buffer",
  3069. DevFmtChannelsString(dev->FmtChans), DevFmtTypeString(dev->FmtType),
  3070. dev->mSampleRate, dev->mUpdateSize, dev->mBufferSize);
  3071. }
  3072. /************************************************
  3073. * ALC HRTF functions
  3074. ************************************************/
  3075. /** Gets a string parameter at the given index. */
  3076. ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum paramName, ALCsizei index) noexcept
  3077. {
  3078. DeviceRef dev{VerifyDevice(device)};
  3079. if(!dev || dev->Type == DeviceType::Capture)
  3080. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3081. else switch(paramName)
  3082. {
  3083. case ALC_HRTF_SPECIFIER_SOFT:
  3084. if(index >= 0 && static_cast<uint>(index) < dev->mHrtfList.size())
  3085. return dev->mHrtfList[static_cast<uint>(index)].c_str();
  3086. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3087. break;
  3088. default:
  3089. alcSetError(dev.get(), ALC_INVALID_ENUM);
  3090. break;
  3091. }
  3092. return nullptr;
  3093. }
  3094. /** Resets the given device output, using the specified attribute list. */
  3095. ALC_API ALCboolean ALC_APIENTRY alcResetDeviceSOFT(ALCdevice *device, const ALCint *attribs) noexcept
  3096. {
  3097. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3098. DeviceRef dev{VerifyDevice(device)};
  3099. if(!dev || dev->Type == DeviceType::Capture)
  3100. {
  3101. listlock.unlock();
  3102. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3103. return ALC_FALSE;
  3104. }
  3105. std::lock_guard<std::mutex> statelock{dev->StateLock};
  3106. listlock.unlock();
  3107. /* Force the backend to stop mixing first since we're resetting. Also reset
  3108. * the connected state so lost devices can attempt recover.
  3109. */
  3110. if(dev->mDeviceState == DeviceState::Playing)
  3111. {
  3112. dev->Backend->stop();
  3113. dev->mDeviceState = DeviceState::Configured;
  3114. }
  3115. return ResetDeviceParams(dev.get(), SpanFromAttributeList(attribs)) ? ALC_TRUE : ALC_FALSE;
  3116. }
  3117. /************************************************
  3118. * ALC device reopen functions
  3119. ************************************************/
  3120. /** Reopens the given device output, using the specified name and attribute list. */
  3121. FORCE_ALIGN ALCboolean ALC_APIENTRY alcReopenDeviceSOFT(ALCdevice *device,
  3122. const ALCchar *deviceName, const ALCint *attribs) noexcept
  3123. {
  3124. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3125. DeviceRef dev{VerifyDevice(device)};
  3126. if(!dev || dev->Type != DeviceType::Playback)
  3127. {
  3128. listlock.unlock();
  3129. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3130. return ALC_FALSE;
  3131. }
  3132. std::lock_guard<std::mutex> statelock{dev->StateLock};
  3133. std::string_view devname{deviceName ? deviceName : ""};
  3134. if(!devname.empty())
  3135. {
  3136. if(devname.length() >= size_t{std::numeric_limits<int>::max()})
  3137. {
  3138. ERR("Device name too long ({} >= {})", devname.length(),
  3139. std::numeric_limits<int>::max());
  3140. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3141. return ALC_FALSE;
  3142. }
  3143. if(al::case_compare(devname, GetDefaultName()) == 0)
  3144. devname = {};
  3145. else
  3146. {
  3147. const auto prefix = GetDevicePrefix();
  3148. if(!prefix.empty() && devname.size() > prefix.size()
  3149. && al::starts_with(devname, prefix))
  3150. devname = devname.substr(prefix.size());
  3151. }
  3152. }
  3153. /* Force the backend device to stop first since we're opening another one. */
  3154. const bool wasPlaying{dev->mDeviceState == DeviceState::Playing};
  3155. if(wasPlaying)
  3156. {
  3157. dev->Backend->stop();
  3158. dev->mDeviceState = DeviceState::Configured;
  3159. }
  3160. BackendPtr newbackend;
  3161. try {
  3162. newbackend = PlaybackFactory->createBackend(dev.get(), BackendType::Playback);
  3163. newbackend->open(devname);
  3164. }
  3165. catch(al::backend_exception &e) {
  3166. listlock.unlock();
  3167. newbackend = nullptr;
  3168. WARN("Failed to reopen playback device: {}", e.what());
  3169. alcSetError(dev.get(), (e.errorCode() == al::backend_error::OutOfMemory)
  3170. ? ALC_OUT_OF_MEMORY : ALC_INVALID_VALUE);
  3171. if(dev->Connected.load(std::memory_order_relaxed) && wasPlaying)
  3172. {
  3173. try {
  3174. auto backend = dev->Backend.get();
  3175. backend->start();
  3176. dev->mDeviceState = DeviceState::Playing;
  3177. }
  3178. catch(al::backend_exception &be) {
  3179. ERR("{}", be.what());
  3180. dev->handleDisconnect("{}", be.what());
  3181. }
  3182. }
  3183. return ALC_FALSE;
  3184. }
  3185. listlock.unlock();
  3186. dev->mDeviceName = std::string{GetDevicePrefix()}+newbackend->mDeviceName;
  3187. dev->Backend = std::move(newbackend);
  3188. dev->mDeviceState = DeviceState::Unprepared;
  3189. TRACE("Reopened device {}, \"{}\"", voidp{dev.get()}, dev->mDeviceName);
  3190. std::string{}.swap(dev->mVendorOverride);
  3191. std::string{}.swap(dev->mVersionOverride);
  3192. std::string{}.swap(dev->mRendererOverride);
  3193. auto checkopt = [&dev](const char *envname, const std::string_view optname)
  3194. {
  3195. if(auto optval = al::getenv(envname)) return optval;
  3196. return dev->configValue<std::string>("game_compat", optname);
  3197. };
  3198. if(auto overrideopt = checkopt("__ALSOFT_VENDOR_OVERRIDE", "vendor-override"sv))
  3199. {
  3200. dev->mVendorOverride = std::move(*overrideopt);
  3201. TRACE("Overriding vendor string: \"{}\"", dev->mVendorOverride);
  3202. }
  3203. if(auto overrideopt = checkopt("__ALSOFT_VERSION_OVERRIDE", "version-override"sv))
  3204. {
  3205. dev->mVersionOverride = std::move(*overrideopt);
  3206. TRACE("Overriding version string: \"{}\"", dev->mVersionOverride);
  3207. }
  3208. if(auto overrideopt = checkopt("__ALSOFT_RENDERER_OVERRIDE", "renderer-override"sv))
  3209. {
  3210. dev->mRendererOverride = std::move(*overrideopt);
  3211. TRACE("Overriding renderer string: \"{}\"", dev->mRendererOverride);
  3212. }
  3213. /* Always return true even if resetting fails. It shouldn't fail, but this
  3214. * is primarily to avoid confusion by the app seeing the function return
  3215. * false while the device is on the new output anyway. We could try to
  3216. * restore the old backend if this fails, but the configuration would be
  3217. * changed with the new backend and would need to be reset again with the
  3218. * old one, and the provided attributes may not be appropriate or desirable
  3219. * for the old device.
  3220. *
  3221. * In this way, we essentially act as if the function succeeded, but
  3222. * immediately disconnects following it.
  3223. */
  3224. ResetDeviceParams(dev.get(), SpanFromAttributeList(attribs));
  3225. return ALC_TRUE;
  3226. }
  3227. /************************************************
  3228. * ALC event query functions
  3229. ************************************************/
  3230. FORCE_ALIGN ALCenum ALC_APIENTRY alcEventIsSupportedSOFT(ALCenum eventType, ALCenum deviceType) noexcept
  3231. {
  3232. auto etype = alc::GetEventType(eventType);
  3233. if(!etype)
  3234. {
  3235. WARN("Invalid event type: {:#04x}", as_unsigned(eventType));
  3236. alcSetError(nullptr, ALC_INVALID_ENUM);
  3237. return ALC_FALSE;
  3238. }
  3239. auto supported = alc::EventSupport::NoSupport;
  3240. switch(deviceType)
  3241. {
  3242. case ALC_PLAYBACK_DEVICE_SOFT:
  3243. if(PlaybackFactory)
  3244. supported = PlaybackFactory->queryEventSupport(*etype, BackendType::Playback);
  3245. return al::to_underlying(supported);
  3246. case ALC_CAPTURE_DEVICE_SOFT:
  3247. if(CaptureFactory)
  3248. supported = CaptureFactory->queryEventSupport(*etype, BackendType::Capture);
  3249. return al::to_underlying(supported);
  3250. }
  3251. WARN("Invalid device type: {:#04x}", as_unsigned(deviceType));
  3252. alcSetError(nullptr, ALC_INVALID_ENUM);
  3253. return ALC_FALSE;
  3254. }