alc.cpp 117 KB

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