alc.cpp 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195
  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. #include <exception>
  23. #include <algorithm>
  24. #include <array>
  25. #include <atomic>
  26. #include <cctype>
  27. #include <chrono>
  28. #include <cinttypes>
  29. #include <climits>
  30. #include <cmath>
  31. #include <csignal>
  32. #include <cstdint>
  33. #include <cstdio>
  34. #include <cstdlib>
  35. #include <cstring>
  36. #include <functional>
  37. #include <iterator>
  38. #include <limits>
  39. #include <memory>
  40. #include <mutex>
  41. #include <new>
  42. #include <numeric>
  43. #include <string>
  44. #include <thread>
  45. #include <utility>
  46. #include "AL/al.h"
  47. #include "AL/alc.h"
  48. #include "AL/alext.h"
  49. #include "AL/efx.h"
  50. #include "al/auxeffectslot.h"
  51. #include "al/effect.h"
  52. #include "al/event.h"
  53. #include "al/filter.h"
  54. #include "al/listener.h"
  55. #include "al/source.h"
  56. #include "alcmain.h"
  57. #include "albyte.h"
  58. #include "alconfig.h"
  59. #include "alcontext.h"
  60. #include "alexcpt.h"
  61. #include "almalloc.h"
  62. #include "alnumeric.h"
  63. #include "aloptional.h"
  64. #include "alspan.h"
  65. #include "alstring.h"
  66. #include "alu.h"
  67. #include "ambidefs.h"
  68. #include "atomic.h"
  69. #include "bformatdec.h"
  70. #include "bs2b.h"
  71. #include "compat.h"
  72. #include "cpu_caps.h"
  73. #include "devformat.h"
  74. #include "effects/base.h"
  75. #include "filters/nfc.h"
  76. #include "filters/splitter.h"
  77. #include "fpu_modes.h"
  78. #include "hrtf.h"
  79. #include "inprogext.h"
  80. #include "intrusive_ptr.h"
  81. #include "logging.h"
  82. #include "mastering.h"
  83. #include "opthelpers.h"
  84. #include "pragmadefs.h"
  85. #include "ringbuffer.h"
  86. #include "strutils.h"
  87. #include "threads.h"
  88. #include "uhjfilter.h"
  89. #include "vecmat.h"
  90. #include "vector.h"
  91. #include "backends/base.h"
  92. #include "backends/null.h"
  93. #include "backends/loopback.h"
  94. #ifdef HAVE_JACK
  95. #include "backends/jack.h"
  96. #endif
  97. #ifdef HAVE_PULSEAUDIO
  98. #include "backends/pulseaudio.h"
  99. #endif
  100. #ifdef HAVE_ALSA
  101. #include "backends/alsa.h"
  102. #endif
  103. #ifdef HAVE_WASAPI
  104. #include "backends/wasapi.h"
  105. #endif
  106. #ifdef HAVE_COREAUDIO
  107. #include "backends/coreaudio.h"
  108. #endif
  109. #ifdef HAVE_OPENSL
  110. #include "backends/opensl.h"
  111. #endif
  112. #ifdef HAVE_SOLARIS
  113. #include "backends/solaris.h"
  114. #endif
  115. #ifdef HAVE_SNDIO
  116. #include "backends/sndio.h"
  117. #endif
  118. #ifdef HAVE_OSS
  119. #include "backends/oss.h"
  120. #endif
  121. #ifdef HAVE_QSA
  122. #include "backends/qsa.h"
  123. #endif
  124. #ifdef HAVE_DSOUND
  125. #include "backends/dsound.h"
  126. #endif
  127. #ifdef HAVE_WINMM
  128. #include "backends/winmm.h"
  129. #endif
  130. #ifdef HAVE_PORTAUDIO
  131. #include "backends/portaudio.h"
  132. #endif
  133. #ifdef HAVE_SDL2
  134. #include "backends/sdl2.h"
  135. #endif
  136. #ifdef HAVE_WAVE
  137. #include "backends/wave.h"
  138. #endif
  139. namespace {
  140. using namespace std::placeholders;
  141. using std::chrono::seconds;
  142. using std::chrono::nanoseconds;
  143. /************************************************
  144. * Backends
  145. ************************************************/
  146. struct BackendInfo {
  147. const char *name;
  148. BackendFactory& (*getFactory)(void);
  149. };
  150. BackendInfo BackendList[] = {
  151. #ifdef HAVE_JACK
  152. { "jack", JackBackendFactory::getFactory },
  153. #endif
  154. #ifdef HAVE_PULSEAUDIO
  155. { "pulse", PulseBackendFactory::getFactory },
  156. #endif
  157. #ifdef HAVE_ALSA
  158. { "alsa", AlsaBackendFactory::getFactory },
  159. #endif
  160. #ifdef HAVE_WASAPI
  161. { "wasapi", WasapiBackendFactory::getFactory },
  162. #endif
  163. #ifdef HAVE_COREAUDIO
  164. { "core", CoreAudioBackendFactory::getFactory },
  165. #endif
  166. #ifdef HAVE_OPENSL
  167. { "opensl", OSLBackendFactory::getFactory },
  168. #endif
  169. #ifdef HAVE_SOLARIS
  170. { "solaris", SolarisBackendFactory::getFactory },
  171. #endif
  172. #ifdef HAVE_SNDIO
  173. { "sndio", SndIOBackendFactory::getFactory },
  174. #endif
  175. #ifdef HAVE_OSS
  176. { "oss", OSSBackendFactory::getFactory },
  177. #endif
  178. #ifdef HAVE_QSA
  179. { "qsa", QSABackendFactory::getFactory },
  180. #endif
  181. #ifdef HAVE_DSOUND
  182. { "dsound", DSoundBackendFactory::getFactory },
  183. #endif
  184. #ifdef HAVE_WINMM
  185. { "winmm", WinMMBackendFactory::getFactory },
  186. #endif
  187. #ifdef HAVE_PORTAUDIO
  188. { "port", PortBackendFactory::getFactory },
  189. #endif
  190. #ifdef HAVE_SDL2
  191. { "sdl2", SDL2BackendFactory::getFactory },
  192. #endif
  193. { "null", NullBackendFactory::getFactory },
  194. #ifdef HAVE_WAVE
  195. { "wave", WaveBackendFactory::getFactory },
  196. #endif
  197. };
  198. auto BackendListEnd = std::end(BackendList);
  199. BackendFactory *PlaybackFactory{};
  200. BackendFactory *CaptureFactory{};
  201. /************************************************
  202. * Functions, enums, and errors
  203. ************************************************/
  204. #define DECL(x) { #x, reinterpret_cast<void*>(x) }
  205. const struct {
  206. const ALCchar *funcName;
  207. ALCvoid *address;
  208. } alcFunctions[] = {
  209. DECL(alcCreateContext),
  210. DECL(alcMakeContextCurrent),
  211. DECL(alcProcessContext),
  212. DECL(alcSuspendContext),
  213. DECL(alcDestroyContext),
  214. DECL(alcGetCurrentContext),
  215. DECL(alcGetContextsDevice),
  216. DECL(alcOpenDevice),
  217. DECL(alcCloseDevice),
  218. DECL(alcGetError),
  219. DECL(alcIsExtensionPresent),
  220. DECL(alcGetProcAddress),
  221. DECL(alcGetEnumValue),
  222. DECL(alcGetString),
  223. DECL(alcGetIntegerv),
  224. DECL(alcCaptureOpenDevice),
  225. DECL(alcCaptureCloseDevice),
  226. DECL(alcCaptureStart),
  227. DECL(alcCaptureStop),
  228. DECL(alcCaptureSamples),
  229. DECL(alcSetThreadContext),
  230. DECL(alcGetThreadContext),
  231. DECL(alcLoopbackOpenDeviceSOFT),
  232. DECL(alcIsRenderFormatSupportedSOFT),
  233. DECL(alcRenderSamplesSOFT),
  234. DECL(alcDevicePauseSOFT),
  235. DECL(alcDeviceResumeSOFT),
  236. DECL(alcGetStringiSOFT),
  237. DECL(alcResetDeviceSOFT),
  238. DECL(alcGetInteger64vSOFT),
  239. DECL(alEnable),
  240. DECL(alDisable),
  241. DECL(alIsEnabled),
  242. DECL(alGetString),
  243. DECL(alGetBooleanv),
  244. DECL(alGetIntegerv),
  245. DECL(alGetFloatv),
  246. DECL(alGetDoublev),
  247. DECL(alGetBoolean),
  248. DECL(alGetInteger),
  249. DECL(alGetFloat),
  250. DECL(alGetDouble),
  251. DECL(alGetError),
  252. DECL(alIsExtensionPresent),
  253. DECL(alGetProcAddress),
  254. DECL(alGetEnumValue),
  255. DECL(alListenerf),
  256. DECL(alListener3f),
  257. DECL(alListenerfv),
  258. DECL(alListeneri),
  259. DECL(alListener3i),
  260. DECL(alListeneriv),
  261. DECL(alGetListenerf),
  262. DECL(alGetListener3f),
  263. DECL(alGetListenerfv),
  264. DECL(alGetListeneri),
  265. DECL(alGetListener3i),
  266. DECL(alGetListeneriv),
  267. DECL(alGenSources),
  268. DECL(alDeleteSources),
  269. DECL(alIsSource),
  270. DECL(alSourcef),
  271. DECL(alSource3f),
  272. DECL(alSourcefv),
  273. DECL(alSourcei),
  274. DECL(alSource3i),
  275. DECL(alSourceiv),
  276. DECL(alGetSourcef),
  277. DECL(alGetSource3f),
  278. DECL(alGetSourcefv),
  279. DECL(alGetSourcei),
  280. DECL(alGetSource3i),
  281. DECL(alGetSourceiv),
  282. DECL(alSourcePlayv),
  283. DECL(alSourceStopv),
  284. DECL(alSourceRewindv),
  285. DECL(alSourcePausev),
  286. DECL(alSourcePlay),
  287. DECL(alSourceStop),
  288. DECL(alSourceRewind),
  289. DECL(alSourcePause),
  290. DECL(alSourceQueueBuffers),
  291. DECL(alSourceUnqueueBuffers),
  292. DECL(alGenBuffers),
  293. DECL(alDeleteBuffers),
  294. DECL(alIsBuffer),
  295. DECL(alBufferData),
  296. DECL(alBufferf),
  297. DECL(alBuffer3f),
  298. DECL(alBufferfv),
  299. DECL(alBufferi),
  300. DECL(alBuffer3i),
  301. DECL(alBufferiv),
  302. DECL(alGetBufferf),
  303. DECL(alGetBuffer3f),
  304. DECL(alGetBufferfv),
  305. DECL(alGetBufferi),
  306. DECL(alGetBuffer3i),
  307. DECL(alGetBufferiv),
  308. DECL(alDopplerFactor),
  309. DECL(alDopplerVelocity),
  310. DECL(alSpeedOfSound),
  311. DECL(alDistanceModel),
  312. DECL(alGenFilters),
  313. DECL(alDeleteFilters),
  314. DECL(alIsFilter),
  315. DECL(alFilteri),
  316. DECL(alFilteriv),
  317. DECL(alFilterf),
  318. DECL(alFilterfv),
  319. DECL(alGetFilteri),
  320. DECL(alGetFilteriv),
  321. DECL(alGetFilterf),
  322. DECL(alGetFilterfv),
  323. DECL(alGenEffects),
  324. DECL(alDeleteEffects),
  325. DECL(alIsEffect),
  326. DECL(alEffecti),
  327. DECL(alEffectiv),
  328. DECL(alEffectf),
  329. DECL(alEffectfv),
  330. DECL(alGetEffecti),
  331. DECL(alGetEffectiv),
  332. DECL(alGetEffectf),
  333. DECL(alGetEffectfv),
  334. DECL(alGenAuxiliaryEffectSlots),
  335. DECL(alDeleteAuxiliaryEffectSlots),
  336. DECL(alIsAuxiliaryEffectSlot),
  337. DECL(alAuxiliaryEffectSloti),
  338. DECL(alAuxiliaryEffectSlotiv),
  339. DECL(alAuxiliaryEffectSlotf),
  340. DECL(alAuxiliaryEffectSlotfv),
  341. DECL(alGetAuxiliaryEffectSloti),
  342. DECL(alGetAuxiliaryEffectSlotiv),
  343. DECL(alGetAuxiliaryEffectSlotf),
  344. DECL(alGetAuxiliaryEffectSlotfv),
  345. DECL(alDeferUpdatesSOFT),
  346. DECL(alProcessUpdatesSOFT),
  347. DECL(alSourcedSOFT),
  348. DECL(alSource3dSOFT),
  349. DECL(alSourcedvSOFT),
  350. DECL(alGetSourcedSOFT),
  351. DECL(alGetSource3dSOFT),
  352. DECL(alGetSourcedvSOFT),
  353. DECL(alSourcei64SOFT),
  354. DECL(alSource3i64SOFT),
  355. DECL(alSourcei64vSOFT),
  356. DECL(alGetSourcei64SOFT),
  357. DECL(alGetSource3i64SOFT),
  358. DECL(alGetSourcei64vSOFT),
  359. DECL(alGetStringiSOFT),
  360. DECL(alBufferStorageSOFT),
  361. DECL(alMapBufferSOFT),
  362. DECL(alUnmapBufferSOFT),
  363. DECL(alFlushMappedBufferSOFT),
  364. DECL(alEventControlSOFT),
  365. DECL(alEventCallbackSOFT),
  366. DECL(alGetPointerSOFT),
  367. DECL(alGetPointervSOFT),
  368. };
  369. #undef DECL
  370. #define DECL(x) { #x, (x) }
  371. constexpr struct {
  372. const ALCchar *enumName;
  373. ALCenum value;
  374. } alcEnumerations[] = {
  375. DECL(ALC_INVALID),
  376. DECL(ALC_FALSE),
  377. DECL(ALC_TRUE),
  378. DECL(ALC_MAJOR_VERSION),
  379. DECL(ALC_MINOR_VERSION),
  380. DECL(ALC_ATTRIBUTES_SIZE),
  381. DECL(ALC_ALL_ATTRIBUTES),
  382. DECL(ALC_DEFAULT_DEVICE_SPECIFIER),
  383. DECL(ALC_DEVICE_SPECIFIER),
  384. DECL(ALC_ALL_DEVICES_SPECIFIER),
  385. DECL(ALC_DEFAULT_ALL_DEVICES_SPECIFIER),
  386. DECL(ALC_EXTENSIONS),
  387. DECL(ALC_FREQUENCY),
  388. DECL(ALC_REFRESH),
  389. DECL(ALC_SYNC),
  390. DECL(ALC_MONO_SOURCES),
  391. DECL(ALC_STEREO_SOURCES),
  392. DECL(ALC_CAPTURE_DEVICE_SPECIFIER),
  393. DECL(ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER),
  394. DECL(ALC_CAPTURE_SAMPLES),
  395. DECL(ALC_CONNECTED),
  396. DECL(ALC_EFX_MAJOR_VERSION),
  397. DECL(ALC_EFX_MINOR_VERSION),
  398. DECL(ALC_MAX_AUXILIARY_SENDS),
  399. DECL(ALC_FORMAT_CHANNELS_SOFT),
  400. DECL(ALC_FORMAT_TYPE_SOFT),
  401. DECL(ALC_MONO_SOFT),
  402. DECL(ALC_STEREO_SOFT),
  403. DECL(ALC_QUAD_SOFT),
  404. DECL(ALC_5POINT1_SOFT),
  405. DECL(ALC_6POINT1_SOFT),
  406. DECL(ALC_7POINT1_SOFT),
  407. DECL(ALC_BFORMAT3D_SOFT),
  408. DECL(ALC_BYTE_SOFT),
  409. DECL(ALC_UNSIGNED_BYTE_SOFT),
  410. DECL(ALC_SHORT_SOFT),
  411. DECL(ALC_UNSIGNED_SHORT_SOFT),
  412. DECL(ALC_INT_SOFT),
  413. DECL(ALC_UNSIGNED_INT_SOFT),
  414. DECL(ALC_FLOAT_SOFT),
  415. DECL(ALC_HRTF_SOFT),
  416. DECL(ALC_DONT_CARE_SOFT),
  417. DECL(ALC_HRTF_STATUS_SOFT),
  418. DECL(ALC_HRTF_DISABLED_SOFT),
  419. DECL(ALC_HRTF_ENABLED_SOFT),
  420. DECL(ALC_HRTF_DENIED_SOFT),
  421. DECL(ALC_HRTF_REQUIRED_SOFT),
  422. DECL(ALC_HRTF_HEADPHONES_DETECTED_SOFT),
  423. DECL(ALC_HRTF_UNSUPPORTED_FORMAT_SOFT),
  424. DECL(ALC_NUM_HRTF_SPECIFIERS_SOFT),
  425. DECL(ALC_HRTF_SPECIFIER_SOFT),
  426. DECL(ALC_HRTF_ID_SOFT),
  427. DECL(ALC_AMBISONIC_LAYOUT_SOFT),
  428. DECL(ALC_AMBISONIC_SCALING_SOFT),
  429. DECL(ALC_AMBISONIC_ORDER_SOFT),
  430. DECL(ALC_ACN_SOFT),
  431. DECL(ALC_FUMA_SOFT),
  432. DECL(ALC_N3D_SOFT),
  433. DECL(ALC_SN3D_SOFT),
  434. DECL(ALC_OUTPUT_LIMITER_SOFT),
  435. DECL(ALC_NO_ERROR),
  436. DECL(ALC_INVALID_DEVICE),
  437. DECL(ALC_INVALID_CONTEXT),
  438. DECL(ALC_INVALID_ENUM),
  439. DECL(ALC_INVALID_VALUE),
  440. DECL(ALC_OUT_OF_MEMORY),
  441. DECL(AL_INVALID),
  442. DECL(AL_NONE),
  443. DECL(AL_FALSE),
  444. DECL(AL_TRUE),
  445. DECL(AL_SOURCE_RELATIVE),
  446. DECL(AL_CONE_INNER_ANGLE),
  447. DECL(AL_CONE_OUTER_ANGLE),
  448. DECL(AL_PITCH),
  449. DECL(AL_POSITION),
  450. DECL(AL_DIRECTION),
  451. DECL(AL_VELOCITY),
  452. DECL(AL_LOOPING),
  453. DECL(AL_BUFFER),
  454. DECL(AL_GAIN),
  455. DECL(AL_MIN_GAIN),
  456. DECL(AL_MAX_GAIN),
  457. DECL(AL_ORIENTATION),
  458. DECL(AL_REFERENCE_DISTANCE),
  459. DECL(AL_ROLLOFF_FACTOR),
  460. DECL(AL_CONE_OUTER_GAIN),
  461. DECL(AL_MAX_DISTANCE),
  462. DECL(AL_SEC_OFFSET),
  463. DECL(AL_SAMPLE_OFFSET),
  464. DECL(AL_BYTE_OFFSET),
  465. DECL(AL_SOURCE_TYPE),
  466. DECL(AL_STATIC),
  467. DECL(AL_STREAMING),
  468. DECL(AL_UNDETERMINED),
  469. DECL(AL_METERS_PER_UNIT),
  470. DECL(AL_LOOP_POINTS_SOFT),
  471. DECL(AL_DIRECT_CHANNELS_SOFT),
  472. DECL(AL_DIRECT_FILTER),
  473. DECL(AL_AUXILIARY_SEND_FILTER),
  474. DECL(AL_AIR_ABSORPTION_FACTOR),
  475. DECL(AL_ROOM_ROLLOFF_FACTOR),
  476. DECL(AL_CONE_OUTER_GAINHF),
  477. DECL(AL_DIRECT_FILTER_GAINHF_AUTO),
  478. DECL(AL_AUXILIARY_SEND_FILTER_GAIN_AUTO),
  479. DECL(AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO),
  480. DECL(AL_SOURCE_STATE),
  481. DECL(AL_INITIAL),
  482. DECL(AL_PLAYING),
  483. DECL(AL_PAUSED),
  484. DECL(AL_STOPPED),
  485. DECL(AL_BUFFERS_QUEUED),
  486. DECL(AL_BUFFERS_PROCESSED),
  487. DECL(AL_FORMAT_MONO8),
  488. DECL(AL_FORMAT_MONO16),
  489. DECL(AL_FORMAT_MONO_FLOAT32),
  490. DECL(AL_FORMAT_MONO_DOUBLE_EXT),
  491. DECL(AL_FORMAT_STEREO8),
  492. DECL(AL_FORMAT_STEREO16),
  493. DECL(AL_FORMAT_STEREO_FLOAT32),
  494. DECL(AL_FORMAT_STEREO_DOUBLE_EXT),
  495. DECL(AL_FORMAT_MONO_IMA4),
  496. DECL(AL_FORMAT_STEREO_IMA4),
  497. DECL(AL_FORMAT_MONO_MSADPCM_SOFT),
  498. DECL(AL_FORMAT_STEREO_MSADPCM_SOFT),
  499. DECL(AL_FORMAT_QUAD8_LOKI),
  500. DECL(AL_FORMAT_QUAD16_LOKI),
  501. DECL(AL_FORMAT_QUAD8),
  502. DECL(AL_FORMAT_QUAD16),
  503. DECL(AL_FORMAT_QUAD32),
  504. DECL(AL_FORMAT_51CHN8),
  505. DECL(AL_FORMAT_51CHN16),
  506. DECL(AL_FORMAT_51CHN32),
  507. DECL(AL_FORMAT_61CHN8),
  508. DECL(AL_FORMAT_61CHN16),
  509. DECL(AL_FORMAT_61CHN32),
  510. DECL(AL_FORMAT_71CHN8),
  511. DECL(AL_FORMAT_71CHN16),
  512. DECL(AL_FORMAT_71CHN32),
  513. DECL(AL_FORMAT_REAR8),
  514. DECL(AL_FORMAT_REAR16),
  515. DECL(AL_FORMAT_REAR32),
  516. DECL(AL_FORMAT_MONO_MULAW),
  517. DECL(AL_FORMAT_MONO_MULAW_EXT),
  518. DECL(AL_FORMAT_STEREO_MULAW),
  519. DECL(AL_FORMAT_STEREO_MULAW_EXT),
  520. DECL(AL_FORMAT_QUAD_MULAW),
  521. DECL(AL_FORMAT_51CHN_MULAW),
  522. DECL(AL_FORMAT_61CHN_MULAW),
  523. DECL(AL_FORMAT_71CHN_MULAW),
  524. DECL(AL_FORMAT_REAR_MULAW),
  525. DECL(AL_FORMAT_MONO_ALAW_EXT),
  526. DECL(AL_FORMAT_STEREO_ALAW_EXT),
  527. DECL(AL_FORMAT_BFORMAT2D_8),
  528. DECL(AL_FORMAT_BFORMAT2D_16),
  529. DECL(AL_FORMAT_BFORMAT2D_FLOAT32),
  530. DECL(AL_FORMAT_BFORMAT2D_MULAW),
  531. DECL(AL_FORMAT_BFORMAT3D_8),
  532. DECL(AL_FORMAT_BFORMAT3D_16),
  533. DECL(AL_FORMAT_BFORMAT3D_FLOAT32),
  534. DECL(AL_FORMAT_BFORMAT3D_MULAW),
  535. DECL(AL_FREQUENCY),
  536. DECL(AL_BITS),
  537. DECL(AL_CHANNELS),
  538. DECL(AL_SIZE),
  539. DECL(AL_UNPACK_BLOCK_ALIGNMENT_SOFT),
  540. DECL(AL_PACK_BLOCK_ALIGNMENT_SOFT),
  541. DECL(AL_SOURCE_RADIUS),
  542. DECL(AL_STEREO_ANGLES),
  543. DECL(AL_UNUSED),
  544. DECL(AL_PENDING),
  545. DECL(AL_PROCESSED),
  546. DECL(AL_NO_ERROR),
  547. DECL(AL_INVALID_NAME),
  548. DECL(AL_INVALID_ENUM),
  549. DECL(AL_INVALID_VALUE),
  550. DECL(AL_INVALID_OPERATION),
  551. DECL(AL_OUT_OF_MEMORY),
  552. DECL(AL_VENDOR),
  553. DECL(AL_VERSION),
  554. DECL(AL_RENDERER),
  555. DECL(AL_EXTENSIONS),
  556. DECL(AL_DOPPLER_FACTOR),
  557. DECL(AL_DOPPLER_VELOCITY),
  558. DECL(AL_DISTANCE_MODEL),
  559. DECL(AL_SPEED_OF_SOUND),
  560. DECL(AL_SOURCE_DISTANCE_MODEL),
  561. DECL(AL_DEFERRED_UPDATES_SOFT),
  562. DECL(AL_GAIN_LIMIT_SOFT),
  563. DECL(AL_INVERSE_DISTANCE),
  564. DECL(AL_INVERSE_DISTANCE_CLAMPED),
  565. DECL(AL_LINEAR_DISTANCE),
  566. DECL(AL_LINEAR_DISTANCE_CLAMPED),
  567. DECL(AL_EXPONENT_DISTANCE),
  568. DECL(AL_EXPONENT_DISTANCE_CLAMPED),
  569. DECL(AL_FILTER_TYPE),
  570. DECL(AL_FILTER_NULL),
  571. DECL(AL_FILTER_LOWPASS),
  572. DECL(AL_FILTER_HIGHPASS),
  573. DECL(AL_FILTER_BANDPASS),
  574. DECL(AL_LOWPASS_GAIN),
  575. DECL(AL_LOWPASS_GAINHF),
  576. DECL(AL_HIGHPASS_GAIN),
  577. DECL(AL_HIGHPASS_GAINLF),
  578. DECL(AL_BANDPASS_GAIN),
  579. DECL(AL_BANDPASS_GAINHF),
  580. DECL(AL_BANDPASS_GAINLF),
  581. DECL(AL_EFFECT_TYPE),
  582. DECL(AL_EFFECT_NULL),
  583. DECL(AL_EFFECT_REVERB),
  584. DECL(AL_EFFECT_EAXREVERB),
  585. DECL(AL_EFFECT_CHORUS),
  586. DECL(AL_EFFECT_DISTORTION),
  587. DECL(AL_EFFECT_ECHO),
  588. DECL(AL_EFFECT_FLANGER),
  589. DECL(AL_EFFECT_PITCH_SHIFTER),
  590. DECL(AL_EFFECT_FREQUENCY_SHIFTER),
  591. DECL(AL_EFFECT_VOCAL_MORPHER),
  592. DECL(AL_EFFECT_RING_MODULATOR),
  593. DECL(AL_EFFECT_AUTOWAH),
  594. DECL(AL_EFFECT_COMPRESSOR),
  595. DECL(AL_EFFECT_EQUALIZER),
  596. DECL(AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT),
  597. DECL(AL_EFFECT_DEDICATED_DIALOGUE),
  598. DECL(AL_EFFECTSLOT_EFFECT),
  599. DECL(AL_EFFECTSLOT_GAIN),
  600. DECL(AL_EFFECTSLOT_AUXILIARY_SEND_AUTO),
  601. DECL(AL_EFFECTSLOT_NULL),
  602. DECL(AL_EAXREVERB_DENSITY),
  603. DECL(AL_EAXREVERB_DIFFUSION),
  604. DECL(AL_EAXREVERB_GAIN),
  605. DECL(AL_EAXREVERB_GAINHF),
  606. DECL(AL_EAXREVERB_GAINLF),
  607. DECL(AL_EAXREVERB_DECAY_TIME),
  608. DECL(AL_EAXREVERB_DECAY_HFRATIO),
  609. DECL(AL_EAXREVERB_DECAY_LFRATIO),
  610. DECL(AL_EAXREVERB_REFLECTIONS_GAIN),
  611. DECL(AL_EAXREVERB_REFLECTIONS_DELAY),
  612. DECL(AL_EAXREVERB_REFLECTIONS_PAN),
  613. DECL(AL_EAXREVERB_LATE_REVERB_GAIN),
  614. DECL(AL_EAXREVERB_LATE_REVERB_DELAY),
  615. DECL(AL_EAXREVERB_LATE_REVERB_PAN),
  616. DECL(AL_EAXREVERB_ECHO_TIME),
  617. DECL(AL_EAXREVERB_ECHO_DEPTH),
  618. DECL(AL_EAXREVERB_MODULATION_TIME),
  619. DECL(AL_EAXREVERB_MODULATION_DEPTH),
  620. DECL(AL_EAXREVERB_AIR_ABSORPTION_GAINHF),
  621. DECL(AL_EAXREVERB_HFREFERENCE),
  622. DECL(AL_EAXREVERB_LFREFERENCE),
  623. DECL(AL_EAXREVERB_ROOM_ROLLOFF_FACTOR),
  624. DECL(AL_EAXREVERB_DECAY_HFLIMIT),
  625. DECL(AL_REVERB_DENSITY),
  626. DECL(AL_REVERB_DIFFUSION),
  627. DECL(AL_REVERB_GAIN),
  628. DECL(AL_REVERB_GAINHF),
  629. DECL(AL_REVERB_DECAY_TIME),
  630. DECL(AL_REVERB_DECAY_HFRATIO),
  631. DECL(AL_REVERB_REFLECTIONS_GAIN),
  632. DECL(AL_REVERB_REFLECTIONS_DELAY),
  633. DECL(AL_REVERB_LATE_REVERB_GAIN),
  634. DECL(AL_REVERB_LATE_REVERB_DELAY),
  635. DECL(AL_REVERB_AIR_ABSORPTION_GAINHF),
  636. DECL(AL_REVERB_ROOM_ROLLOFF_FACTOR),
  637. DECL(AL_REVERB_DECAY_HFLIMIT),
  638. DECL(AL_CHORUS_WAVEFORM),
  639. DECL(AL_CHORUS_PHASE),
  640. DECL(AL_CHORUS_RATE),
  641. DECL(AL_CHORUS_DEPTH),
  642. DECL(AL_CHORUS_FEEDBACK),
  643. DECL(AL_CHORUS_DELAY),
  644. DECL(AL_DISTORTION_EDGE),
  645. DECL(AL_DISTORTION_GAIN),
  646. DECL(AL_DISTORTION_LOWPASS_CUTOFF),
  647. DECL(AL_DISTORTION_EQCENTER),
  648. DECL(AL_DISTORTION_EQBANDWIDTH),
  649. DECL(AL_ECHO_DELAY),
  650. DECL(AL_ECHO_LRDELAY),
  651. DECL(AL_ECHO_DAMPING),
  652. DECL(AL_ECHO_FEEDBACK),
  653. DECL(AL_ECHO_SPREAD),
  654. DECL(AL_FLANGER_WAVEFORM),
  655. DECL(AL_FLANGER_PHASE),
  656. DECL(AL_FLANGER_RATE),
  657. DECL(AL_FLANGER_DEPTH),
  658. DECL(AL_FLANGER_FEEDBACK),
  659. DECL(AL_FLANGER_DELAY),
  660. DECL(AL_FREQUENCY_SHIFTER_FREQUENCY),
  661. DECL(AL_FREQUENCY_SHIFTER_LEFT_DIRECTION),
  662. DECL(AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION),
  663. DECL(AL_RING_MODULATOR_FREQUENCY),
  664. DECL(AL_RING_MODULATOR_HIGHPASS_CUTOFF),
  665. DECL(AL_RING_MODULATOR_WAVEFORM),
  666. DECL(AL_PITCH_SHIFTER_COARSE_TUNE),
  667. DECL(AL_PITCH_SHIFTER_FINE_TUNE),
  668. DECL(AL_COMPRESSOR_ONOFF),
  669. DECL(AL_EQUALIZER_LOW_GAIN),
  670. DECL(AL_EQUALIZER_LOW_CUTOFF),
  671. DECL(AL_EQUALIZER_MID1_GAIN),
  672. DECL(AL_EQUALIZER_MID1_CENTER),
  673. DECL(AL_EQUALIZER_MID1_WIDTH),
  674. DECL(AL_EQUALIZER_MID2_GAIN),
  675. DECL(AL_EQUALIZER_MID2_CENTER),
  676. DECL(AL_EQUALIZER_MID2_WIDTH),
  677. DECL(AL_EQUALIZER_HIGH_GAIN),
  678. DECL(AL_EQUALIZER_HIGH_CUTOFF),
  679. DECL(AL_DEDICATED_GAIN),
  680. DECL(AL_AUTOWAH_ATTACK_TIME),
  681. DECL(AL_AUTOWAH_RELEASE_TIME),
  682. DECL(AL_AUTOWAH_RESONANCE),
  683. DECL(AL_AUTOWAH_PEAK_GAIN),
  684. DECL(AL_VOCAL_MORPHER_PHONEMEA),
  685. DECL(AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING),
  686. DECL(AL_VOCAL_MORPHER_PHONEMEB),
  687. DECL(AL_VOCAL_MORPHER_PHONEMEB_COARSE_TUNING),
  688. DECL(AL_VOCAL_MORPHER_WAVEFORM),
  689. DECL(AL_VOCAL_MORPHER_RATE),
  690. DECL(AL_NUM_RESAMPLERS_SOFT),
  691. DECL(AL_DEFAULT_RESAMPLER_SOFT),
  692. DECL(AL_SOURCE_RESAMPLER_SOFT),
  693. DECL(AL_RESAMPLER_NAME_SOFT),
  694. DECL(AL_SOURCE_SPATIALIZE_SOFT),
  695. DECL(AL_AUTO_SOFT),
  696. DECL(AL_MAP_READ_BIT_SOFT),
  697. DECL(AL_MAP_WRITE_BIT_SOFT),
  698. DECL(AL_MAP_PERSISTENT_BIT_SOFT),
  699. DECL(AL_PRESERVE_DATA_BIT_SOFT),
  700. DECL(AL_EVENT_CALLBACK_FUNCTION_SOFT),
  701. DECL(AL_EVENT_CALLBACK_USER_PARAM_SOFT),
  702. DECL(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT),
  703. DECL(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT),
  704. DECL(AL_EVENT_TYPE_ERROR_SOFT),
  705. DECL(AL_EVENT_TYPE_PERFORMANCE_SOFT),
  706. DECL(AL_EVENT_TYPE_DEPRECATED_SOFT),
  707. };
  708. #undef DECL
  709. constexpr ALCchar alcNoError[] = "No Error";
  710. constexpr ALCchar alcErrInvalidDevice[] = "Invalid Device";
  711. constexpr ALCchar alcErrInvalidContext[] = "Invalid Context";
  712. constexpr ALCchar alcErrInvalidEnum[] = "Invalid Enum";
  713. constexpr ALCchar alcErrInvalidValue[] = "Invalid Value";
  714. constexpr ALCchar alcErrOutOfMemory[] = "Out of Memory";
  715. /************************************************
  716. * Global variables
  717. ************************************************/
  718. /* Enumerated device names */
  719. constexpr ALCchar alcDefaultName[] = "OpenAL Soft\0";
  720. std::string alcAllDevicesList;
  721. std::string alcCaptureDeviceList;
  722. /* Default is always the first in the list */
  723. al::string alcDefaultAllDevicesSpecifier;
  724. al::string alcCaptureDefaultDeviceSpecifier;
  725. /* Default context extensions */
  726. constexpr ALchar alExtList[] =
  727. "AL_EXT_ALAW "
  728. "AL_EXT_BFORMAT "
  729. "AL_EXT_DOUBLE "
  730. "AL_EXT_EXPONENT_DISTANCE "
  731. "AL_EXT_FLOAT32 "
  732. "AL_EXT_IMA4 "
  733. "AL_EXT_LINEAR_DISTANCE "
  734. "AL_EXT_MCFORMATS "
  735. "AL_EXT_MULAW "
  736. "AL_EXT_MULAW_BFORMAT "
  737. "AL_EXT_MULAW_MCFORMATS "
  738. "AL_EXT_OFFSET "
  739. "AL_EXT_source_distance_model "
  740. "AL_EXT_SOURCE_RADIUS "
  741. "AL_EXT_STEREO_ANGLES "
  742. "AL_LOKI_quadriphonic "
  743. "AL_SOFT_block_alignment "
  744. "AL_SOFT_deferred_updates "
  745. "AL_SOFT_direct_channels "
  746. "AL_SOFTX_effect_chain "
  747. "AL_SOFTX_events "
  748. "AL_SOFTX_filter_gain_ex "
  749. "AL_SOFT_gain_clamp_ex "
  750. "AL_SOFT_loop_points "
  751. "AL_SOFTX_map_buffer "
  752. "AL_SOFT_MSADPCM "
  753. "AL_SOFT_source_latency "
  754. "AL_SOFT_source_length "
  755. "AL_SOFT_source_resampler "
  756. "AL_SOFT_source_spatialize";
  757. std::atomic<ALCenum> LastNullDeviceError{ALC_NO_ERROR};
  758. /* Thread-local current context */
  759. class ThreadCtx {
  760. ALCcontext *ctx{nullptr};
  761. public:
  762. ~ThreadCtx()
  763. {
  764. if(ctx)
  765. {
  766. const bool result{ctx->releaseIfNoDelete()};
  767. ERR("Context %p current for thread being destroyed%s!\n",
  768. decltype(std::declval<void*>()){ctx}, result ? "" : ", leak detected");
  769. }
  770. }
  771. ALCcontext *get() const noexcept { return ctx; }
  772. void set(ALCcontext *ctx_) noexcept { ctx = ctx_; }
  773. };
  774. thread_local ThreadCtx LocalContext;
  775. /* Process-wide current context */
  776. std::atomic<ALCcontext*> GlobalContext{nullptr};
  777. /* Flag to trap ALC device errors */
  778. bool TrapALCError{false};
  779. /* One-time configuration init control */
  780. std::once_flag alc_config_once{};
  781. /* Default effect that applies to sources that don't have an effect on send 0 */
  782. ALeffect DefaultEffect;
  783. /* Flag to specify if alcSuspendContext/alcProcessContext should defer/process
  784. * updates.
  785. */
  786. bool SuspendDefers{true};
  787. /* Initial seed for dithering. */
  788. constexpr ALuint DitherRNGSeed{22222u};
  789. /************************************************
  790. * ALC information
  791. ************************************************/
  792. constexpr ALCchar alcNoDeviceExtList[] =
  793. "ALC_ENUMERATE_ALL_EXT "
  794. "ALC_ENUMERATION_EXT "
  795. "ALC_EXT_CAPTURE "
  796. "ALC_EXT_thread_local_context "
  797. "ALC_SOFT_loopback";
  798. constexpr ALCchar alcExtensionList[] =
  799. "ALC_ENUMERATE_ALL_EXT "
  800. "ALC_ENUMERATION_EXT "
  801. "ALC_EXT_CAPTURE "
  802. "ALC_EXT_DEDICATED "
  803. "ALC_EXT_disconnect "
  804. "ALC_EXT_EFX "
  805. "ALC_EXT_thread_local_context "
  806. "ALC_SOFT_device_clock "
  807. "ALC_SOFT_HRTF "
  808. "ALC_SOFT_loopback "
  809. "ALC_SOFT_output_limiter "
  810. "ALC_SOFT_pause_device";
  811. constexpr ALCint alcMajorVersion = 1;
  812. constexpr ALCint alcMinorVersion = 1;
  813. constexpr ALCint alcEFXMajorVersion = 1;
  814. constexpr ALCint alcEFXMinorVersion = 0;
  815. /* To avoid extraneous allocations, a 0-sized FlexArray<ALCcontext*> is defined
  816. * globally as a sharable object. MSVC warns that a zero-sized array will have
  817. * zero objects here, so silence that.
  818. */
  819. DIAGNOSTIC_PUSH
  820. msc_pragma(warning(disable : 4815))
  821. al::FlexArray<ALCcontext*> EmptyContextArray{0u};
  822. DIAGNOSTIC_POP
  823. using DeviceRef = al::intrusive_ptr<ALCdevice>;
  824. /************************************************
  825. * Device lists
  826. ************************************************/
  827. al::vector<DeviceRef> DeviceList;
  828. al::vector<ContextRef> ContextList;
  829. std::recursive_mutex ListLock;
  830. void alc_initconfig(void)
  831. {
  832. if(auto loglevel = al::getenv("ALSOFT_LOGLEVEL"))
  833. {
  834. long lvl = strtol(loglevel->c_str(), nullptr, 0);
  835. if(lvl >= NoLog && lvl <= LogRef)
  836. gLogLevel = static_cast<LogLevel>(lvl);
  837. }
  838. if(auto logfile = al::getenv("ALSOFT_LOGFILE"))
  839. {
  840. #ifdef _WIN32
  841. std::wstring wname{utf8_to_wstr(logfile->c_str())};
  842. FILE *logf{_wfopen(wname.c_str(), L"wt")};
  843. #else
  844. FILE *logf{fopen(logfile->c_str(), "wt")};
  845. #endif
  846. if(logf) gLogFile = logf;
  847. else ERR("Failed to open log file '%s'\n", logfile->c_str());
  848. }
  849. TRACE("Initializing library v%s-%s %s\n", ALSOFT_VERSION, ALSOFT_GIT_COMMIT_HASH,
  850. ALSOFT_GIT_BRANCH);
  851. {
  852. al::string names;
  853. if(std::begin(BackendList) == BackendListEnd)
  854. names += "(none)";
  855. else
  856. {
  857. const al::span<const BackendInfo> infos{std::begin(BackendList), BackendListEnd};
  858. names += infos[0].name;
  859. for(const auto &backend : infos.subspan(1))
  860. {
  861. names += ", ";
  862. names += backend.name;
  863. }
  864. }
  865. TRACE("Supported backends: %s\n", names.c_str());
  866. }
  867. ReadALConfig();
  868. if(auto suspendmode = al::getenv("__ALSOFT_SUSPEND_CONTEXT"))
  869. {
  870. if(al::strcasecmp(suspendmode->c_str(), "ignore") == 0)
  871. {
  872. SuspendDefers = false;
  873. TRACE("Selected context suspend behavior, \"ignore\"\n");
  874. }
  875. else
  876. ERR("Unhandled context suspend behavior setting: \"%s\"\n", suspendmode->c_str());
  877. }
  878. int capfilter{0};
  879. #if defined(HAVE_SSE4_1)
  880. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
  881. #elif defined(HAVE_SSE3)
  882. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
  883. #elif defined(HAVE_SSE2)
  884. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2;
  885. #elif defined(HAVE_SSE)
  886. capfilter |= CPU_CAP_SSE;
  887. #endif
  888. #ifdef HAVE_NEON
  889. capfilter |= CPU_CAP_NEON;
  890. #endif
  891. if(auto cpuopt = ConfigValueStr(nullptr, nullptr, "disable-cpu-exts"))
  892. {
  893. const char *str{cpuopt->c_str()};
  894. if(al::strcasecmp(str, "all") == 0)
  895. capfilter = 0;
  896. else
  897. {
  898. const char *next = str;
  899. do {
  900. str = next;
  901. while(isspace(str[0]))
  902. str++;
  903. next = strchr(str, ',');
  904. if(!str[0] || str[0] == ',')
  905. continue;
  906. size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
  907. while(len > 0 && isspace(str[len-1]))
  908. len--;
  909. if(len == 3 && al::strncasecmp(str, "sse", len) == 0)
  910. capfilter &= ~CPU_CAP_SSE;
  911. else if(len == 4 && al::strncasecmp(str, "sse2", len) == 0)
  912. capfilter &= ~CPU_CAP_SSE2;
  913. else if(len == 4 && al::strncasecmp(str, "sse3", len) == 0)
  914. capfilter &= ~CPU_CAP_SSE3;
  915. else if(len == 6 && al::strncasecmp(str, "sse4.1", len) == 0)
  916. capfilter &= ~CPU_CAP_SSE4_1;
  917. else if(len == 4 && al::strncasecmp(str, "neon", len) == 0)
  918. capfilter &= ~CPU_CAP_NEON;
  919. else
  920. WARN("Invalid CPU extension \"%s\"\n", str);
  921. } while(next++);
  922. }
  923. }
  924. FillCPUCaps(capfilter);
  925. #ifdef _WIN32
  926. #define DEF_MIXER_PRIO 1
  927. #else
  928. #define DEF_MIXER_PRIO 0
  929. #endif
  930. RTPrioLevel = ConfigValueInt(nullptr, nullptr, "rt-prio").value_or(DEF_MIXER_PRIO);
  931. #undef DEF_MIXER_PRIO
  932. aluInit();
  933. aluInitMixer();
  934. auto traperr = al::getenv("ALSOFT_TRAP_ERROR");
  935. if(traperr && (al::strcasecmp(traperr->c_str(), "true") == 0
  936. || std::strtol(traperr->c_str(), nullptr, 0) == 1))
  937. {
  938. TrapALError = true;
  939. TrapALCError = true;
  940. }
  941. else
  942. {
  943. traperr = al::getenv("ALSOFT_TRAP_AL_ERROR");
  944. if(traperr)
  945. TrapALError = al::strcasecmp(traperr->c_str(), "true") == 0
  946. || strtol(traperr->c_str(), nullptr, 0) == 1;
  947. else
  948. TrapALError = !!GetConfigValueBool(nullptr, nullptr, "trap-al-error", false);
  949. traperr = al::getenv("ALSOFT_TRAP_ALC_ERROR");
  950. if(traperr)
  951. TrapALCError = al::strcasecmp(traperr->c_str(), "true") == 0
  952. || strtol(traperr->c_str(), nullptr, 0) == 1;
  953. else
  954. TrapALCError = !!GetConfigValueBool(nullptr, nullptr, "trap-alc-error", false);
  955. }
  956. if(auto boostopt = ConfigValueFloat(nullptr, "reverb", "boost"))
  957. {
  958. const float valf{std::isfinite(*boostopt) ? clampf(*boostopt, -24.0f, 24.0f) : 0.0f};
  959. ReverbBoost *= std::pow(10.0f, valf / 20.0f);
  960. }
  961. auto devopt = al::getenv("ALSOFT_DRIVERS");
  962. if(devopt || (devopt=ConfigValueStr(nullptr, nullptr, "drivers")))
  963. {
  964. auto backendlist_cur = std::begin(BackendList);
  965. bool endlist{true};
  966. const char *next{devopt->c_str()};
  967. do {
  968. const char *devs{next};
  969. while(isspace(devs[0]))
  970. devs++;
  971. next = strchr(devs, ',');
  972. const bool delitem{devs[0] == '-'};
  973. if(devs[0] == '-') devs++;
  974. if(!devs[0] || devs[0] == ',')
  975. {
  976. endlist = false;
  977. continue;
  978. }
  979. endlist = true;
  980. size_t len{next ? (static_cast<size_t>(next-devs)) : strlen(devs)};
  981. while(len > 0 && isspace(devs[len-1])) --len;
  982. #ifdef HAVE_WASAPI
  983. /* HACK: For backwards compatibility, convert backend references of
  984. * mmdevapi to wasapi. This should eventually be removed.
  985. */
  986. if(len == 8 && strncmp(devs, "mmdevapi", len) == 0)
  987. {
  988. devs = "wasapi";
  989. len = 6;
  990. }
  991. #endif
  992. auto find_backend = [devs,len](const BackendInfo &backend) -> bool
  993. { return len == strlen(backend.name) && strncmp(backend.name, devs, len) == 0; };
  994. auto this_backend = std::find_if(std::begin(BackendList), BackendListEnd,
  995. find_backend);
  996. if(this_backend == BackendListEnd)
  997. continue;
  998. if(delitem)
  999. BackendListEnd = std::move(this_backend+1, BackendListEnd, this_backend);
  1000. else
  1001. backendlist_cur = std::rotate(backendlist_cur, this_backend, this_backend+1);
  1002. } while(next++);
  1003. if(endlist)
  1004. BackendListEnd = backendlist_cur;
  1005. }
  1006. auto init_backend = [](BackendInfo &backend) -> bool
  1007. {
  1008. if(PlaybackFactory && CaptureFactory)
  1009. return true;
  1010. BackendFactory &factory = backend.getFactory();
  1011. if(!factory.init())
  1012. {
  1013. WARN("Failed to initialize backend \"%s\"\n", backend.name);
  1014. return true;
  1015. }
  1016. TRACE("Initialized backend \"%s\"\n", backend.name);
  1017. if(!PlaybackFactory && factory.querySupport(BackendType::Playback))
  1018. {
  1019. PlaybackFactory = &factory;
  1020. TRACE("Added \"%s\" for playback\n", backend.name);
  1021. }
  1022. if(!CaptureFactory && factory.querySupport(BackendType::Capture))
  1023. {
  1024. CaptureFactory = &factory;
  1025. TRACE("Added \"%s\" for capture\n", backend.name);
  1026. }
  1027. return false;
  1028. };
  1029. BackendListEnd = std::remove_if(std::begin(BackendList), BackendListEnd, init_backend);
  1030. LoopbackBackendFactory::getFactory().init();
  1031. if(!PlaybackFactory)
  1032. WARN("No playback backend available!\n");
  1033. if(!CaptureFactory)
  1034. WARN("No capture backend available!\n");
  1035. if(auto exclopt = ConfigValueStr(nullptr, nullptr, "excludefx"))
  1036. {
  1037. const char *next{exclopt->c_str()};
  1038. do {
  1039. const char *str{next};
  1040. next = strchr(str, ',');
  1041. if(!str[0] || next == str)
  1042. continue;
  1043. size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
  1044. for(const EffectList &effectitem : gEffectList)
  1045. {
  1046. if(len == strlen(effectitem.name) &&
  1047. strncmp(effectitem.name, str, len) == 0)
  1048. DisabledEffects[effectitem.type] = AL_TRUE;
  1049. }
  1050. } while(next++);
  1051. }
  1052. InitEffect(&DefaultEffect);
  1053. auto defrevopt = al::getenv("ALSOFT_DEFAULT_REVERB");
  1054. if(defrevopt || (defrevopt=ConfigValueStr(nullptr, nullptr, "default-reverb")))
  1055. LoadReverbPreset(defrevopt->c_str(), &DefaultEffect);
  1056. }
  1057. #define DO_INITCONFIG() std::call_once(alc_config_once, [](){alc_initconfig();})
  1058. /************************************************
  1059. * Device enumeration
  1060. ************************************************/
  1061. void ProbeAllDevicesList()
  1062. {
  1063. DO_INITCONFIG();
  1064. std::lock_guard<std::recursive_mutex> _{ListLock};
  1065. alcAllDevicesList.clear();
  1066. if(PlaybackFactory)
  1067. PlaybackFactory->probe(DevProbe::Playback, &alcAllDevicesList);
  1068. }
  1069. void ProbeCaptureDeviceList()
  1070. {
  1071. DO_INITCONFIG();
  1072. std::lock_guard<std::recursive_mutex> _{ListLock};
  1073. alcCaptureDeviceList.clear();
  1074. if(CaptureFactory)
  1075. CaptureFactory->probe(DevProbe::Capture, &alcCaptureDeviceList);
  1076. }
  1077. } // namespace
  1078. /* Mixing thread piority level */
  1079. ALint RTPrioLevel;
  1080. FILE *gLogFile{stderr};
  1081. #ifdef _DEBUG
  1082. LogLevel gLogLevel{LogWarning};
  1083. #else
  1084. LogLevel gLogLevel{LogError};
  1085. #endif
  1086. /************************************************
  1087. * Library initialization
  1088. ************************************************/
  1089. #if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC)
  1090. BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/)
  1091. {
  1092. switch(reason)
  1093. {
  1094. case DLL_PROCESS_ATTACH:
  1095. /* Pin the DLL so we won't get unloaded until the process terminates */
  1096. GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
  1097. reinterpret_cast<WCHAR*>(module), &module);
  1098. break;
  1099. }
  1100. return TRUE;
  1101. }
  1102. #endif
  1103. /************************************************
  1104. * Device format information
  1105. ************************************************/
  1106. const ALCchar *DevFmtTypeString(DevFmtType type) noexcept
  1107. {
  1108. switch(type)
  1109. {
  1110. case DevFmtByte: return "Signed Byte";
  1111. case DevFmtUByte: return "Unsigned Byte";
  1112. case DevFmtShort: return "Signed Short";
  1113. case DevFmtUShort: return "Unsigned Short";
  1114. case DevFmtInt: return "Signed Int";
  1115. case DevFmtUInt: return "Unsigned Int";
  1116. case DevFmtFloat: return "Float";
  1117. }
  1118. return "(unknown type)";
  1119. }
  1120. const ALCchar *DevFmtChannelsString(DevFmtChannels chans) noexcept
  1121. {
  1122. switch(chans)
  1123. {
  1124. case DevFmtMono: return "Mono";
  1125. case DevFmtStereo: return "Stereo";
  1126. case DevFmtQuad: return "Quadraphonic";
  1127. case DevFmtX51: return "5.1 Surround";
  1128. case DevFmtX51Rear: return "5.1 Surround (Rear)";
  1129. case DevFmtX61: return "6.1 Surround";
  1130. case DevFmtX71: return "7.1 Surround";
  1131. case DevFmtAmbi3D: return "Ambisonic 3D";
  1132. }
  1133. return "(unknown channels)";
  1134. }
  1135. ALuint BytesFromDevFmt(DevFmtType type) noexcept
  1136. {
  1137. switch(type)
  1138. {
  1139. case DevFmtByte: return sizeof(ALbyte);
  1140. case DevFmtUByte: return sizeof(ALubyte);
  1141. case DevFmtShort: return sizeof(ALshort);
  1142. case DevFmtUShort: return sizeof(ALushort);
  1143. case DevFmtInt: return sizeof(ALint);
  1144. case DevFmtUInt: return sizeof(ALuint);
  1145. case DevFmtFloat: return sizeof(ALfloat);
  1146. }
  1147. return 0;
  1148. }
  1149. ALuint ChannelsFromDevFmt(DevFmtChannels chans, ALuint ambiorder) noexcept
  1150. {
  1151. switch(chans)
  1152. {
  1153. case DevFmtMono: return 1;
  1154. case DevFmtStereo: return 2;
  1155. case DevFmtQuad: return 4;
  1156. case DevFmtX51: return 6;
  1157. case DevFmtX51Rear: return 6;
  1158. case DevFmtX61: return 7;
  1159. case DevFmtX71: return 8;
  1160. case DevFmtAmbi3D: return (ambiorder+1) * (ambiorder+1);
  1161. }
  1162. return 0;
  1163. }
  1164. struct DevFmtPair { DevFmtChannels chans; DevFmtType type; };
  1165. static al::optional<DevFmtPair> DecomposeDevFormat(ALenum format)
  1166. {
  1167. static const struct {
  1168. ALenum format;
  1169. DevFmtChannels channels;
  1170. DevFmtType type;
  1171. } list[] = {
  1172. { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
  1173. { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
  1174. { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
  1175. { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
  1176. { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
  1177. { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
  1178. { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
  1179. { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
  1180. { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
  1181. { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
  1182. { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
  1183. { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
  1184. { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
  1185. { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
  1186. { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
  1187. { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
  1188. { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
  1189. { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
  1190. };
  1191. for(const auto &item : list)
  1192. {
  1193. if(item.format == format)
  1194. return al::make_optional(DevFmtPair{item.channels, item.type});
  1195. }
  1196. return al::nullopt;
  1197. }
  1198. static ALCboolean IsValidALCType(ALCenum type)
  1199. {
  1200. switch(type)
  1201. {
  1202. case ALC_BYTE_SOFT:
  1203. case ALC_UNSIGNED_BYTE_SOFT:
  1204. case ALC_SHORT_SOFT:
  1205. case ALC_UNSIGNED_SHORT_SOFT:
  1206. case ALC_INT_SOFT:
  1207. case ALC_UNSIGNED_INT_SOFT:
  1208. case ALC_FLOAT_SOFT:
  1209. return ALC_TRUE;
  1210. }
  1211. return ALC_FALSE;
  1212. }
  1213. static ALCboolean IsValidALCChannels(ALCenum channels)
  1214. {
  1215. switch(channels)
  1216. {
  1217. case ALC_MONO_SOFT:
  1218. case ALC_STEREO_SOFT:
  1219. case ALC_QUAD_SOFT:
  1220. case ALC_5POINT1_SOFT:
  1221. case ALC_6POINT1_SOFT:
  1222. case ALC_7POINT1_SOFT:
  1223. case ALC_BFORMAT3D_SOFT:
  1224. return ALC_TRUE;
  1225. }
  1226. return ALC_FALSE;
  1227. }
  1228. static ALCboolean IsValidAmbiLayout(ALCenum layout)
  1229. {
  1230. switch(layout)
  1231. {
  1232. case ALC_ACN_SOFT:
  1233. case ALC_FUMA_SOFT:
  1234. return ALC_TRUE;
  1235. }
  1236. return ALC_FALSE;
  1237. }
  1238. static ALCboolean IsValidAmbiScaling(ALCenum scaling)
  1239. {
  1240. switch(scaling)
  1241. {
  1242. case ALC_N3D_SOFT:
  1243. case ALC_SN3D_SOFT:
  1244. case ALC_FUMA_SOFT:
  1245. return ALC_TRUE;
  1246. }
  1247. return ALC_FALSE;
  1248. }
  1249. /************************************************
  1250. * Miscellaneous ALC helpers
  1251. ************************************************/
  1252. /* SetDefaultWFXChannelOrder
  1253. *
  1254. * Sets the default channel order used by WaveFormatEx.
  1255. */
  1256. void SetDefaultWFXChannelOrder(ALCdevice *device)
  1257. {
  1258. device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX);
  1259. switch(device->FmtChans)
  1260. {
  1261. case DevFmtMono:
  1262. device->RealOut.ChannelIndex[FrontCenter] = 0;
  1263. break;
  1264. case DevFmtStereo:
  1265. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1266. device->RealOut.ChannelIndex[FrontRight] = 1;
  1267. break;
  1268. case DevFmtQuad:
  1269. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1270. device->RealOut.ChannelIndex[FrontRight] = 1;
  1271. device->RealOut.ChannelIndex[BackLeft] = 2;
  1272. device->RealOut.ChannelIndex[BackRight] = 3;
  1273. break;
  1274. case DevFmtX51:
  1275. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1276. device->RealOut.ChannelIndex[FrontRight] = 1;
  1277. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1278. device->RealOut.ChannelIndex[LFE] = 3;
  1279. device->RealOut.ChannelIndex[SideLeft] = 4;
  1280. device->RealOut.ChannelIndex[SideRight] = 5;
  1281. break;
  1282. case DevFmtX51Rear:
  1283. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1284. device->RealOut.ChannelIndex[FrontRight] = 1;
  1285. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1286. device->RealOut.ChannelIndex[LFE] = 3;
  1287. device->RealOut.ChannelIndex[BackLeft] = 4;
  1288. device->RealOut.ChannelIndex[BackRight] = 5;
  1289. break;
  1290. case DevFmtX61:
  1291. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1292. device->RealOut.ChannelIndex[FrontRight] = 1;
  1293. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1294. device->RealOut.ChannelIndex[LFE] = 3;
  1295. device->RealOut.ChannelIndex[BackCenter] = 4;
  1296. device->RealOut.ChannelIndex[SideLeft] = 5;
  1297. device->RealOut.ChannelIndex[SideRight] = 6;
  1298. break;
  1299. case DevFmtX71:
  1300. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1301. device->RealOut.ChannelIndex[FrontRight] = 1;
  1302. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1303. device->RealOut.ChannelIndex[LFE] = 3;
  1304. device->RealOut.ChannelIndex[BackLeft] = 4;
  1305. device->RealOut.ChannelIndex[BackRight] = 5;
  1306. device->RealOut.ChannelIndex[SideLeft] = 6;
  1307. device->RealOut.ChannelIndex[SideRight] = 7;
  1308. break;
  1309. case DevFmtAmbi3D:
  1310. device->RealOut.ChannelIndex[Aux0] = 0;
  1311. if(device->mAmbiOrder > 0)
  1312. {
  1313. device->RealOut.ChannelIndex[Aux1] = 1;
  1314. device->RealOut.ChannelIndex[Aux2] = 2;
  1315. device->RealOut.ChannelIndex[Aux3] = 3;
  1316. }
  1317. if(device->mAmbiOrder > 1)
  1318. {
  1319. device->RealOut.ChannelIndex[Aux4] = 4;
  1320. device->RealOut.ChannelIndex[Aux5] = 5;
  1321. device->RealOut.ChannelIndex[Aux6] = 6;
  1322. device->RealOut.ChannelIndex[Aux7] = 7;
  1323. device->RealOut.ChannelIndex[Aux8] = 8;
  1324. }
  1325. if(device->mAmbiOrder > 2)
  1326. {
  1327. device->RealOut.ChannelIndex[Aux9] = 9;
  1328. device->RealOut.ChannelIndex[Aux10] = 10;
  1329. device->RealOut.ChannelIndex[Aux11] = 11;
  1330. device->RealOut.ChannelIndex[Aux12] = 12;
  1331. device->RealOut.ChannelIndex[Aux13] = 13;
  1332. device->RealOut.ChannelIndex[Aux14] = 14;
  1333. device->RealOut.ChannelIndex[Aux15] = 15;
  1334. }
  1335. break;
  1336. }
  1337. }
  1338. /* SetDefaultChannelOrder
  1339. *
  1340. * Sets the default channel order used by most non-WaveFormatEx-based APIs.
  1341. */
  1342. void SetDefaultChannelOrder(ALCdevice *device)
  1343. {
  1344. device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX);
  1345. switch(device->FmtChans)
  1346. {
  1347. case DevFmtX51Rear:
  1348. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1349. device->RealOut.ChannelIndex[FrontRight] = 1;
  1350. device->RealOut.ChannelIndex[BackLeft] = 2;
  1351. device->RealOut.ChannelIndex[BackRight] = 3;
  1352. device->RealOut.ChannelIndex[FrontCenter] = 4;
  1353. device->RealOut.ChannelIndex[LFE] = 5;
  1354. return;
  1355. case DevFmtX71:
  1356. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1357. device->RealOut.ChannelIndex[FrontRight] = 1;
  1358. device->RealOut.ChannelIndex[BackLeft] = 2;
  1359. device->RealOut.ChannelIndex[BackRight] = 3;
  1360. device->RealOut.ChannelIndex[FrontCenter] = 4;
  1361. device->RealOut.ChannelIndex[LFE] = 5;
  1362. device->RealOut.ChannelIndex[SideLeft] = 6;
  1363. device->RealOut.ChannelIndex[SideRight] = 7;
  1364. return;
  1365. /* Same as WFX order */
  1366. case DevFmtMono:
  1367. case DevFmtStereo:
  1368. case DevFmtQuad:
  1369. case DevFmtX51:
  1370. case DevFmtX61:
  1371. case DevFmtAmbi3D:
  1372. SetDefaultWFXChannelOrder(device);
  1373. break;
  1374. }
  1375. }
  1376. void ALCcontext::processUpdates()
  1377. {
  1378. std::lock_guard<std::mutex> _{mPropLock};
  1379. if(mDeferUpdates.exchange(false))
  1380. {
  1381. /* Tell the mixer to stop applying updates, then wait for any active
  1382. * updating to finish, before providing updates.
  1383. */
  1384. mHoldUpdates.store(true, std::memory_order_release);
  1385. while((mUpdateCount.load(std::memory_order_acquire)&1) != 0)
  1386. std::this_thread::yield();
  1387. if(!mPropsClean.test_and_set(std::memory_order_acq_rel))
  1388. UpdateContextProps(this);
  1389. if(!mListener.PropsClean.test_and_set(std::memory_order_acq_rel))
  1390. UpdateListenerProps(this);
  1391. UpdateAllEffectSlotProps(this);
  1392. UpdateAllSourceProps(this);
  1393. /* Now with all updates declared, let the mixer continue applying them
  1394. * so they all happen at once.
  1395. */
  1396. mHoldUpdates.store(false, std::memory_order_release);
  1397. }
  1398. }
  1399. /* alcSetError
  1400. *
  1401. * Stores the latest ALC device error
  1402. */
  1403. static void alcSetError(ALCdevice *device, ALCenum errorCode)
  1404. {
  1405. WARN("Error generated on device %p, code 0x%04x\n", decltype(std::declval<void*>()){device},
  1406. errorCode);
  1407. if(TrapALCError)
  1408. {
  1409. #ifdef _WIN32
  1410. /* DebugBreak() will cause an exception if there is no debugger */
  1411. if(IsDebuggerPresent())
  1412. DebugBreak();
  1413. #elif defined(SIGTRAP)
  1414. raise(SIGTRAP);
  1415. #endif
  1416. }
  1417. if(device)
  1418. device->LastError.store(errorCode);
  1419. else
  1420. LastNullDeviceError.store(errorCode);
  1421. }
  1422. static std::unique_ptr<Compressor> CreateDeviceLimiter(const ALCdevice *device, const ALfloat threshold)
  1423. {
  1424. return CompressorInit(static_cast<ALuint>(device->RealOut.Buffer.size()),
  1425. static_cast<float>(device->Frequency), AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f,
  1426. 0.002f, 0.0f, 0.0f, threshold, INFINITY, 0.0f, 0.020f, 0.200f);
  1427. }
  1428. /* UpdateClockBase
  1429. *
  1430. * Updates the device's base clock time with however many samples have been
  1431. * done. This is used so frequency changes on the device don't cause the time
  1432. * to jump forward or back. Must not be called while the device is running/
  1433. * mixing.
  1434. */
  1435. static inline void UpdateClockBase(ALCdevice *device)
  1436. {
  1437. IncrementRef(device->MixCount);
  1438. device->ClockBase += nanoseconds{seconds{device->SamplesDone}} / device->Frequency;
  1439. device->SamplesDone = 0;
  1440. IncrementRef(device->MixCount);
  1441. }
  1442. /* UpdateDeviceParams
  1443. *
  1444. * Updates device parameters according to the attribute list (caller is
  1445. * responsible for holding the list lock).
  1446. */
  1447. static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
  1448. {
  1449. HrtfRequestMode hrtf_userreq{Hrtf_Default};
  1450. HrtfRequestMode hrtf_appreq{Hrtf_Default};
  1451. ALCenum gainLimiter{device->LimiterState};
  1452. const ALCuint old_sends{device->NumAuxSends};
  1453. ALCuint new_sends{device->NumAuxSends};
  1454. DevFmtChannels oldChans;
  1455. DevFmtType oldType;
  1456. ALboolean update_failed;
  1457. ALCsizei hrtf_id{-1};
  1458. ALCuint oldFreq;
  1459. if((!attrList || !attrList[0]) && device->Type == Loopback)
  1460. {
  1461. WARN("Missing attributes for loopback device\n");
  1462. return ALC_INVALID_VALUE;
  1463. }
  1464. // Check for attributes
  1465. if(attrList && attrList[0])
  1466. {
  1467. ALCenum alayout{AL_NONE};
  1468. ALCenum ascale{AL_NONE};
  1469. ALCenum schans{AL_NONE};
  1470. ALCenum stype{AL_NONE};
  1471. ALCsizei attrIdx{0};
  1472. ALCuint aorder{0};
  1473. ALCuint freq{0u};
  1474. ALuint numMono{device->NumMonoSources};
  1475. ALuint numStereo{device->NumStereoSources};
  1476. ALuint numSends{old_sends};
  1477. #define TRACE_ATTR(a, v) TRACE("%s = %d\n", #a, v)
  1478. while(attrList[attrIdx])
  1479. {
  1480. switch(attrList[attrIdx])
  1481. {
  1482. case ALC_FORMAT_CHANNELS_SOFT:
  1483. schans = attrList[attrIdx + 1];
  1484. TRACE_ATTR(ALC_FORMAT_CHANNELS_SOFT, schans);
  1485. break;
  1486. case ALC_FORMAT_TYPE_SOFT:
  1487. stype = attrList[attrIdx + 1];
  1488. TRACE_ATTR(ALC_FORMAT_TYPE_SOFT, stype);
  1489. break;
  1490. case ALC_FREQUENCY:
  1491. freq = static_cast<ALuint>(attrList[attrIdx + 1]);
  1492. TRACE_ATTR(ALC_FREQUENCY, freq);
  1493. break;
  1494. case ALC_AMBISONIC_LAYOUT_SOFT:
  1495. alayout = attrList[attrIdx + 1];
  1496. TRACE_ATTR(ALC_AMBISONIC_LAYOUT_SOFT, alayout);
  1497. break;
  1498. case ALC_AMBISONIC_SCALING_SOFT:
  1499. ascale = attrList[attrIdx + 1];
  1500. TRACE_ATTR(ALC_AMBISONIC_SCALING_SOFT, ascale);
  1501. break;
  1502. case ALC_AMBISONIC_ORDER_SOFT:
  1503. aorder = static_cast<ALuint>(attrList[attrIdx + 1]);
  1504. TRACE_ATTR(ALC_AMBISONIC_ORDER_SOFT, aorder);
  1505. break;
  1506. case ALC_MONO_SOURCES:
  1507. numMono = static_cast<ALuint>(attrList[attrIdx + 1]);
  1508. TRACE_ATTR(ALC_MONO_SOURCES, numMono);
  1509. if(numMono > INT_MAX) numMono = 0;
  1510. break;
  1511. case ALC_STEREO_SOURCES:
  1512. numStereo = static_cast<ALuint>(attrList[attrIdx + 1]);
  1513. TRACE_ATTR(ALC_STEREO_SOURCES, numStereo);
  1514. if(numStereo > INT_MAX) numStereo = 0;
  1515. break;
  1516. case ALC_MAX_AUXILIARY_SENDS:
  1517. numSends = static_cast<ALuint>(attrList[attrIdx + 1]);
  1518. TRACE_ATTR(ALC_MAX_AUXILIARY_SENDS, numSends);
  1519. if(numSends > INT_MAX) numSends = 0;
  1520. else numSends = minu(numSends, MAX_SENDS);
  1521. break;
  1522. case ALC_HRTF_SOFT:
  1523. TRACE_ATTR(ALC_HRTF_SOFT, attrList[attrIdx + 1]);
  1524. if(attrList[attrIdx + 1] == ALC_FALSE)
  1525. hrtf_appreq = Hrtf_Disable;
  1526. else if(attrList[attrIdx + 1] == ALC_TRUE)
  1527. hrtf_appreq = Hrtf_Enable;
  1528. else
  1529. hrtf_appreq = Hrtf_Default;
  1530. break;
  1531. case ALC_HRTF_ID_SOFT:
  1532. hrtf_id = attrList[attrIdx + 1];
  1533. TRACE_ATTR(ALC_HRTF_ID_SOFT, hrtf_id);
  1534. break;
  1535. case ALC_OUTPUT_LIMITER_SOFT:
  1536. gainLimiter = attrList[attrIdx + 1];
  1537. TRACE_ATTR(ALC_OUTPUT_LIMITER_SOFT, gainLimiter);
  1538. break;
  1539. default:
  1540. TRACE("0x%04X = %d (0x%x)\n", attrList[attrIdx],
  1541. attrList[attrIdx + 1], attrList[attrIdx + 1]);
  1542. break;
  1543. }
  1544. attrIdx += 2;
  1545. }
  1546. #undef TRACE_ATTR
  1547. const bool loopback{device->Type == Loopback};
  1548. if(loopback)
  1549. {
  1550. if(!schans || !stype || !freq)
  1551. {
  1552. WARN("Missing format for loopback device\n");
  1553. return ALC_INVALID_VALUE;
  1554. }
  1555. if(!IsValidALCChannels(schans) || !IsValidALCType(stype) || freq < MIN_OUTPUT_RATE)
  1556. return ALC_INVALID_VALUE;
  1557. if(schans == ALC_BFORMAT3D_SOFT)
  1558. {
  1559. if(!alayout || !ascale || !aorder)
  1560. {
  1561. WARN("Missing ambisonic info for loopback device\n");
  1562. return ALC_INVALID_VALUE;
  1563. }
  1564. if(!IsValidAmbiLayout(alayout) || !IsValidAmbiScaling(ascale))
  1565. return ALC_INVALID_VALUE;
  1566. if(aorder < 1 || aorder > MAX_AMBI_ORDER)
  1567. return ALC_INVALID_VALUE;
  1568. if((alayout == ALC_FUMA_SOFT || ascale == ALC_FUMA_SOFT) && aorder > 3)
  1569. return ALC_INVALID_VALUE;
  1570. }
  1571. }
  1572. /* If a context is already running on the device, stop playback so the
  1573. * device attributes can be updated.
  1574. */
  1575. if(device->Flags.get<DeviceRunning>())
  1576. device->Backend->stop();
  1577. device->Flags.unset<DeviceRunning>();
  1578. UpdateClockBase(device);
  1579. const char *devname{nullptr};
  1580. if(!loopback)
  1581. {
  1582. devname = device->DeviceName.c_str();
  1583. device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES;
  1584. device->UpdateSize = DEFAULT_UPDATE_SIZE;
  1585. device->Frequency = DEFAULT_OUTPUT_RATE;
  1586. freq = ConfigValueUInt(devname, nullptr, "frequency").value_or(freq);
  1587. if(freq < 1)
  1588. device->Flags.unset<FrequencyRequest>();
  1589. else
  1590. {
  1591. freq = maxu(freq, MIN_OUTPUT_RATE);
  1592. device->UpdateSize = (device->UpdateSize*freq + device->Frequency/2) /
  1593. device->Frequency;
  1594. device->BufferSize = (device->BufferSize*freq + device->Frequency/2) /
  1595. device->Frequency;
  1596. device->Frequency = freq;
  1597. device->Flags.set<FrequencyRequest>();
  1598. }
  1599. if(auto persizeopt = ConfigValueUInt(devname, nullptr, "period_size"))
  1600. device->UpdateSize = clampu(*persizeopt, 64, 8192);
  1601. if(auto peropt = ConfigValueUInt(devname, nullptr, "periods"))
  1602. device->BufferSize = device->UpdateSize * clampu(*peropt, 2, 16);
  1603. else
  1604. device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2);
  1605. }
  1606. else
  1607. {
  1608. device->Frequency = freq;
  1609. device->FmtChans = static_cast<DevFmtChannels>(schans);
  1610. device->FmtType = static_cast<DevFmtType>(stype);
  1611. if(schans == ALC_BFORMAT3D_SOFT)
  1612. {
  1613. device->mAmbiOrder = aorder;
  1614. device->mAmbiLayout = static_cast<AmbiLayout>(alayout);
  1615. device->mAmbiScale = static_cast<AmbiNorm>(ascale);
  1616. }
  1617. }
  1618. if(numMono > INT_MAX-numStereo)
  1619. numMono = INT_MAX-numStereo;
  1620. numMono += numStereo;
  1621. if(auto srcsopt = ConfigValueUInt(devname, nullptr, "sources"))
  1622. {
  1623. if(*srcsopt <= 0) numMono = 256;
  1624. else numMono = *srcsopt;
  1625. }
  1626. else
  1627. numMono = maxu(numMono, 256);
  1628. numStereo = minu(numStereo, numMono);
  1629. numMono -= numStereo;
  1630. device->SourcesMax = numMono + numStereo;
  1631. device->NumMonoSources = numMono;
  1632. device->NumStereoSources = numStereo;
  1633. if(auto sendsopt = ConfigValueInt(devname, nullptr, "sends"))
  1634. new_sends = minu(numSends, static_cast<ALuint>(clampi(*sendsopt, 0, MAX_SENDS)));
  1635. else
  1636. new_sends = numSends;
  1637. }
  1638. if(device->Flags.get<DeviceRunning>())
  1639. return ALC_NO_ERROR;
  1640. device->AvgSpeakerDist = 0.0f;
  1641. device->Uhj_Encoder = nullptr;
  1642. device->AmbiDecoder = nullptr;
  1643. device->Bs2b = nullptr;
  1644. device->PostProcess = nullptr;
  1645. device->Stablizer = nullptr;
  1646. device->Limiter = nullptr;
  1647. device->ChannelDelay.clear();
  1648. std::fill(std::begin(device->HrtfAccumData), std::end(device->HrtfAccumData), float2{});
  1649. device->Dry.AmbiMap.fill(BFChannelConfig{});
  1650. device->Dry.Buffer = {};
  1651. std::fill(std::begin(device->NumChannelsPerOrder), std::end(device->NumChannelsPerOrder), 0u);
  1652. device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX);
  1653. device->RealOut.Buffer = {};
  1654. device->MixBuffer.clear();
  1655. device->MixBuffer.shrink_to_fit();
  1656. UpdateClockBase(device);
  1657. device->FixedLatency = nanoseconds::zero();
  1658. device->DitherDepth = 0.0f;
  1659. device->DitherSeed = DitherRNGSeed;
  1660. /*************************************************************************
  1661. * Update device format request if HRTF is requested
  1662. */
  1663. device->HrtfStatus = ALC_HRTF_DISABLED_SOFT;
  1664. if(device->Type != Loopback)
  1665. {
  1666. if(auto hrtfopt = ConfigValueStr(device->DeviceName.c_str(), nullptr, "hrtf"))
  1667. {
  1668. const char *hrtf{hrtfopt->c_str()};
  1669. if(al::strcasecmp(hrtf, "true") == 0)
  1670. hrtf_userreq = Hrtf_Enable;
  1671. else if(al::strcasecmp(hrtf, "false") == 0)
  1672. hrtf_userreq = Hrtf_Disable;
  1673. else if(al::strcasecmp(hrtf, "auto") != 0)
  1674. ERR("Unexpected hrtf value: %s\n", hrtf);
  1675. }
  1676. if(hrtf_userreq == Hrtf_Enable || (hrtf_userreq != Hrtf_Disable && hrtf_appreq == Hrtf_Enable))
  1677. {
  1678. HrtfEntry *hrtf{nullptr};
  1679. if(device->HrtfList.empty())
  1680. device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
  1681. if(!device->HrtfList.empty())
  1682. {
  1683. if(hrtf_id >= 0 && static_cast<ALuint>(hrtf_id) < device->HrtfList.size())
  1684. hrtf = GetLoadedHrtf(device->HrtfList[static_cast<ALuint>(hrtf_id)].hrtf);
  1685. else
  1686. hrtf = GetLoadedHrtf(device->HrtfList.front().hrtf);
  1687. }
  1688. if(hrtf)
  1689. {
  1690. device->FmtChans = DevFmtStereo;
  1691. device->Frequency = hrtf->sampleRate;
  1692. device->Flags.set<ChannelsRequest, FrequencyRequest>();
  1693. if(HrtfEntry *oldhrtf{device->mHrtf})
  1694. oldhrtf->DecRef();
  1695. device->mHrtf = hrtf;
  1696. }
  1697. else
  1698. {
  1699. hrtf_userreq = Hrtf_Default;
  1700. hrtf_appreq = Hrtf_Disable;
  1701. device->HrtfStatus = ALC_HRTF_UNSUPPORTED_FORMAT_SOFT;
  1702. }
  1703. }
  1704. }
  1705. oldFreq = device->Frequency;
  1706. oldChans = device->FmtChans;
  1707. oldType = device->FmtType;
  1708. TRACE("Pre-reset: %s%s, %s%s, %s%uhz, %u / %u buffer\n",
  1709. device->Flags.get<ChannelsRequest>()?"*":"", DevFmtChannelsString(device->FmtChans),
  1710. device->Flags.get<SampleTypeRequest>()?"*":"", DevFmtTypeString(device->FmtType),
  1711. device->Flags.get<FrequencyRequest>()?"*":"", device->Frequency,
  1712. device->UpdateSize, device->BufferSize);
  1713. try {
  1714. if(device->Backend->reset() == false)
  1715. return ALC_INVALID_DEVICE;
  1716. }
  1717. catch(std::exception &e) {
  1718. ERR("Device reset failed: %s\n", e.what());
  1719. return ALC_INVALID_DEVICE;
  1720. }
  1721. if(device->FmtChans != oldChans && device->Flags.get<ChannelsRequest>())
  1722. {
  1723. ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans),
  1724. DevFmtChannelsString(device->FmtChans));
  1725. device->Flags.unset<ChannelsRequest>();
  1726. }
  1727. if(device->FmtType != oldType && device->Flags.get<SampleTypeRequest>())
  1728. {
  1729. ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType),
  1730. DevFmtTypeString(device->FmtType));
  1731. device->Flags.unset<SampleTypeRequest>();
  1732. }
  1733. if(device->Frequency != oldFreq && device->Flags.get<FrequencyRequest>())
  1734. {
  1735. WARN("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency);
  1736. device->Flags.unset<FrequencyRequest>();
  1737. }
  1738. TRACE("Post-reset: %s, %s, %uhz, %u / %u buffer\n",
  1739. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  1740. device->Frequency, device->UpdateSize, device->BufferSize);
  1741. aluInitRenderer(device, hrtf_id, hrtf_appreq, hrtf_userreq);
  1742. device->NumAuxSends = new_sends;
  1743. TRACE("Max sources: %d (%d + %d), effect slots: %d, sends: %d\n",
  1744. device->SourcesMax, device->NumMonoSources, device->NumStereoSources,
  1745. device->AuxiliaryEffectSlotMax, device->NumAuxSends);
  1746. /* Enable the stablizer only for formats that have front-left, front-right,
  1747. * and front-center outputs.
  1748. */
  1749. switch(device->FmtChans)
  1750. {
  1751. case DevFmtX51:
  1752. case DevFmtX51Rear:
  1753. case DevFmtX61:
  1754. case DevFmtX71:
  1755. if(GetConfigValueBool(device->DeviceName.c_str(), nullptr, "front-stablizer", 0))
  1756. {
  1757. auto stablizer = al::make_unique<FrontStablizer>();
  1758. /* Initialize band-splitting filters for the front-left and front-
  1759. * right channels, with a crossover at 5khz (could be higher).
  1760. */
  1761. const ALfloat scale{5000.0f / static_cast<ALfloat>(device->Frequency)};
  1762. stablizer->LFilter.init(scale);
  1763. stablizer->RFilter = stablizer->LFilter;
  1764. device->Stablizer = std::move(stablizer);
  1765. /* NOTE: Don't know why this has to be "copied" into a local static
  1766. * constexpr variable to avoid a reference on
  1767. * FrontStablizer::DelayLength...
  1768. */
  1769. constexpr size_t StablizerDelay{FrontStablizer::DelayLength};
  1770. device->FixedLatency += nanoseconds{seconds{StablizerDelay}} / device->Frequency;
  1771. }
  1772. break;
  1773. case DevFmtMono:
  1774. case DevFmtStereo:
  1775. case DevFmtQuad:
  1776. case DevFmtAmbi3D:
  1777. break;
  1778. }
  1779. TRACE("Front stablizer %s\n", device->Stablizer ? "enabled" : "disabled");
  1780. if(GetConfigValueBool(device->DeviceName.c_str(), nullptr, "dither", 1))
  1781. {
  1782. ALint depth{
  1783. ConfigValueInt(device->DeviceName.c_str(), nullptr, "dither-depth").value_or(0)};
  1784. if(depth <= 0)
  1785. {
  1786. switch(device->FmtType)
  1787. {
  1788. case DevFmtByte:
  1789. case DevFmtUByte:
  1790. depth = 8;
  1791. break;
  1792. case DevFmtShort:
  1793. case DevFmtUShort:
  1794. depth = 16;
  1795. break;
  1796. case DevFmtInt:
  1797. case DevFmtUInt:
  1798. case DevFmtFloat:
  1799. break;
  1800. }
  1801. }
  1802. if(depth > 0)
  1803. {
  1804. depth = clampi(depth, 2, 24);
  1805. device->DitherDepth = std::pow(2.0f, static_cast<ALfloat>(depth-1));
  1806. }
  1807. }
  1808. if(!(device->DitherDepth > 0.0f))
  1809. TRACE("Dithering disabled\n");
  1810. else
  1811. TRACE("Dithering enabled (%d-bit, %g)\n", float2int(std::log2(device->DitherDepth)+0.5f)+1,
  1812. device->DitherDepth);
  1813. device->LimiterState = gainLimiter;
  1814. if(auto limopt = ConfigValueBool(device->DeviceName.c_str(), nullptr, "output-limiter"))
  1815. gainLimiter = *limopt ? ALC_TRUE : ALC_FALSE;
  1816. /* Valid values for gainLimiter are ALC_DONT_CARE_SOFT, ALC_TRUE, and
  1817. * ALC_FALSE. For ALC_DONT_CARE_SOFT, use the limiter for integer-based
  1818. * output (where samples must be clamped), and don't for floating-point
  1819. * (which can take unclamped samples).
  1820. */
  1821. if(gainLimiter == ALC_DONT_CARE_SOFT)
  1822. {
  1823. switch(device->FmtType)
  1824. {
  1825. case DevFmtByte:
  1826. case DevFmtUByte:
  1827. case DevFmtShort:
  1828. case DevFmtUShort:
  1829. case DevFmtInt:
  1830. case DevFmtUInt:
  1831. gainLimiter = ALC_TRUE;
  1832. break;
  1833. case DevFmtFloat:
  1834. gainLimiter = ALC_FALSE;
  1835. break;
  1836. }
  1837. }
  1838. if(gainLimiter == ALC_FALSE)
  1839. TRACE("Output limiter disabled\n");
  1840. else
  1841. {
  1842. ALfloat thrshld = 1.0f;
  1843. switch(device->FmtType)
  1844. {
  1845. case DevFmtByte:
  1846. case DevFmtUByte:
  1847. thrshld = 127.0f / 128.0f;
  1848. break;
  1849. case DevFmtShort:
  1850. case DevFmtUShort:
  1851. thrshld = 32767.0f / 32768.0f;
  1852. break;
  1853. case DevFmtInt:
  1854. case DevFmtUInt:
  1855. case DevFmtFloat:
  1856. break;
  1857. }
  1858. if(device->DitherDepth > 0.0f)
  1859. thrshld -= 1.0f / device->DitherDepth;
  1860. const float thrshld_dB{std::log10(thrshld) * 20.0f};
  1861. auto limiter = CreateDeviceLimiter(device, thrshld_dB);
  1862. /* Convert the lookahead from samples to nanosamples to nanoseconds. */
  1863. device->FixedLatency += nanoseconds{seconds{limiter->getLookAhead()}} / device->Frequency;
  1864. device->Limiter = std::move(limiter);
  1865. TRACE("Output limiter enabled, %.4fdB limit\n", thrshld_dB);
  1866. }
  1867. TRACE("Fixed device latency: %" PRId64 "ns\n", int64_t{device->FixedLatency.count()});
  1868. /* Need to delay returning failure until replacement Send arrays have been
  1869. * allocated with the appropriate size.
  1870. */
  1871. update_failed = AL_FALSE;
  1872. FPUCtl mixer_mode{};
  1873. for(ALCcontext *context : *device->mContexts.load())
  1874. {
  1875. if(context->mDefaultSlot)
  1876. {
  1877. ALeffectslot *slot = context->mDefaultSlot.get();
  1878. aluInitEffectPanning(slot, device);
  1879. EffectState *state{slot->Effect.State};
  1880. state->mOutTarget = device->Dry.Buffer;
  1881. if(state->deviceUpdate(device) == AL_FALSE)
  1882. update_failed = AL_TRUE;
  1883. else
  1884. UpdateEffectSlotProps(slot, context);
  1885. }
  1886. std::unique_lock<std::mutex> proplock{context->mPropLock};
  1887. std::unique_lock<std::mutex> slotlock{context->mEffectSlotLock};
  1888. for(auto &sublist : context->mEffectSlotList)
  1889. {
  1890. uint64_t usemask = ~sublist.FreeMask;
  1891. while(usemask)
  1892. {
  1893. ALsizei idx = CTZ64(usemask);
  1894. ALeffectslot *slot = sublist.EffectSlots + idx;
  1895. usemask &= ~(1_u64 << idx);
  1896. aluInitEffectPanning(slot, device);
  1897. EffectState *state{slot->Effect.State};
  1898. state->mOutTarget = device->Dry.Buffer;
  1899. if(state->deviceUpdate(device) == AL_FALSE)
  1900. update_failed = AL_TRUE;
  1901. else
  1902. UpdateEffectSlotProps(slot, context);
  1903. }
  1904. }
  1905. slotlock.unlock();
  1906. std::unique_lock<std::mutex> srclock{context->mSourceLock};
  1907. for(auto &sublist : context->mSourceList)
  1908. {
  1909. uint64_t usemask = ~sublist.FreeMask;
  1910. while(usemask)
  1911. {
  1912. ALsizei idx = CTZ64(usemask);
  1913. ALsource *source = sublist.Sources + idx;
  1914. usemask &= ~(1_u64 << idx);
  1915. if(old_sends != device->NumAuxSends)
  1916. {
  1917. if(source->Send.size() > device->NumAuxSends)
  1918. {
  1919. auto clear_send = [](ALsource::SendData &send) -> void
  1920. {
  1921. if(send.Slot)
  1922. DecrementRef(send.Slot->ref);
  1923. send.Slot = nullptr;
  1924. };
  1925. auto send_begin = source->Send.begin() +
  1926. static_cast<ptrdiff_t>(device->NumAuxSends);
  1927. std::for_each(send_begin, source->Send.end(), clear_send);
  1928. }
  1929. source->Send.resize(device->NumAuxSends,
  1930. {nullptr, 1.0f, 1.0f, LOWPASSFREQREF, 1.0f, HIGHPASSFREQREF});
  1931. source->Send.shrink_to_fit();
  1932. }
  1933. source->PropsClean.clear(std::memory_order_release);
  1934. }
  1935. }
  1936. /* Clear any pre-existing voice property structs, in case the number of
  1937. * auxiliary sends is changing. Active sources will have updates
  1938. * respecified in UpdateAllSourceProps.
  1939. */
  1940. ALvoiceProps *vprops{context->mFreeVoiceProps.exchange(nullptr, std::memory_order_acq_rel)};
  1941. while(vprops)
  1942. {
  1943. ALvoiceProps *next = vprops->next.load(std::memory_order_relaxed);
  1944. delete vprops;
  1945. vprops = next;
  1946. }
  1947. if(device->NumAuxSends < old_sends)
  1948. {
  1949. const ALuint num_sends{device->NumAuxSends};
  1950. /* Clear extraneous property set sends. */
  1951. auto clear_sends = [num_sends](ALvoice &voice) -> void
  1952. {
  1953. std::fill(std::begin(voice.mProps.Send)+num_sends, std::end(voice.mProps.Send),
  1954. ALvoiceProps::SendData{});
  1955. std::fill(voice.mSend.begin()+num_sends, voice.mSend.end(), ALvoice::TargetData{});
  1956. auto clear_chan_sends = [num_sends](ALvoice::ChannelData &chandata) -> void
  1957. {
  1958. std::fill(chandata.mWetParams.begin()+num_sends, chandata.mWetParams.end(),
  1959. SendParams{});
  1960. };
  1961. std::for_each(voice.mChans.begin(), voice.mChans.end(), clear_chan_sends);
  1962. };
  1963. std::for_each(context->mVoices.begin(), context->mVoices.end(), clear_sends);
  1964. }
  1965. auto reset_voice = [device](ALvoice &voice) -> void
  1966. {
  1967. delete voice.mUpdate.exchange(nullptr, std::memory_order_acq_rel);
  1968. /* Force the voice to stopped if it was stopping. */
  1969. ALvoice::State vstate{ALvoice::Stopping};
  1970. voice.mPlayState.compare_exchange_strong(vstate, ALvoice::Stopped,
  1971. std::memory_order_acquire, std::memory_order_acquire);
  1972. if(voice.mSourceID.load(std::memory_order_relaxed) == 0u)
  1973. return;
  1974. if(device->AvgSpeakerDist > 0.0f)
  1975. {
  1976. /* Reinitialize the NFC filters for new parameters. */
  1977. const ALfloat w1{SPEEDOFSOUNDMETRESPERSEC /
  1978. (device->AvgSpeakerDist * static_cast<float>(device->Frequency))};
  1979. auto init_nfc = [w1](ALvoice::ChannelData &chandata) -> void
  1980. { chandata.mDryParams.NFCtrlFilter.init(w1); };
  1981. std::for_each(voice.mChans.begin(), voice.mChans.begin()+voice.mNumChannels,
  1982. init_nfc);
  1983. }
  1984. };
  1985. std::for_each(context->mVoices.begin(), context->mVoices.end(), reset_voice);
  1986. srclock.unlock();
  1987. context->mPropsClean.test_and_set(std::memory_order_release);
  1988. UpdateContextProps(context);
  1989. context->mListener.PropsClean.test_and_set(std::memory_order_release);
  1990. UpdateListenerProps(context);
  1991. UpdateAllSourceProps(context);
  1992. }
  1993. mixer_mode.leave();
  1994. if(update_failed)
  1995. return ALC_INVALID_DEVICE;
  1996. if(!device->Flags.get<DevicePaused>())
  1997. {
  1998. try {
  1999. auto backend = device->Backend.get();
  2000. if(!backend->start())
  2001. throw al::backend_exception{ALC_INVALID_DEVICE, "Backend error"};
  2002. device->Flags.set<DeviceRunning>();
  2003. }
  2004. catch(al::backend_exception& e) {
  2005. WARN("Failed to start playback: %s\n", e.what());
  2006. return ALC_INVALID_DEVICE;
  2007. }
  2008. }
  2009. return ALC_NO_ERROR;
  2010. }
  2011. ALCdevice::ALCdevice(DeviceType type) : Type{type}, mContexts{&EmptyContextArray}
  2012. {
  2013. }
  2014. /* ALCdevice::~ALCdevice
  2015. *
  2016. * Frees the device structure, and destroys any objects the app failed to
  2017. * delete. Called once there's no more references on the device.
  2018. */
  2019. ALCdevice::~ALCdevice()
  2020. {
  2021. TRACE("Freeing device %p\n", decltype(std::declval<void*>()){this});
  2022. Backend = nullptr;
  2023. size_t count{std::accumulate(BufferList.cbegin(), BufferList.cend(), size_t{0u},
  2024. [](size_t cur, const BufferSubList &sublist) noexcept -> size_t
  2025. { return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
  2026. )};
  2027. if(count > 0)
  2028. WARN("%zu Buffer%s not deleted\n", count, (count==1)?"":"s");
  2029. count = std::accumulate(EffectList.cbegin(), EffectList.cend(), size_t{0u},
  2030. [](size_t cur, const EffectSubList &sublist) noexcept -> size_t
  2031. { return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
  2032. );
  2033. if(count > 0)
  2034. WARN("%zu Effect%s not deleted\n", count, (count==1)?"":"s");
  2035. count = std::accumulate(FilterList.cbegin(), FilterList.cend(), size_t{0u},
  2036. [](size_t cur, const FilterSubList &sublist) noexcept -> size_t
  2037. { return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
  2038. );
  2039. if(count > 0)
  2040. WARN("%zu Filter%s not deleted\n", count, (count==1)?"":"s");
  2041. if(mHrtf)
  2042. mHrtf->DecRef();
  2043. mHrtf = nullptr;
  2044. auto *oldarray = mContexts.exchange(nullptr, std::memory_order_relaxed);
  2045. if(oldarray != &EmptyContextArray) delete oldarray;
  2046. }
  2047. /* VerifyDevice
  2048. *
  2049. * Checks if the device handle is valid, and returns a new reference if so.
  2050. */
  2051. static DeviceRef VerifyDevice(ALCdevice *device)
  2052. {
  2053. std::lock_guard<std::recursive_mutex> _{ListLock};
  2054. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device);
  2055. if(iter != DeviceList.cend() && *iter == device)
  2056. return *iter;
  2057. return nullptr;
  2058. }
  2059. ALCcontext::ALCcontext(al::intrusive_ptr<ALCdevice> device) : mDevice{std::move(device)}
  2060. {
  2061. mPropsClean.test_and_set(std::memory_order_relaxed);
  2062. }
  2063. ALCcontext::~ALCcontext()
  2064. {
  2065. TRACE("Freeing context %p\n", decltype(std::declval<void*>()){this});
  2066. size_t count{0};
  2067. ALcontextProps *cprops{mUpdate.exchange(nullptr, std::memory_order_relaxed)};
  2068. if(cprops)
  2069. {
  2070. ++count;
  2071. delete cprops;
  2072. }
  2073. cprops = mFreeContextProps.exchange(nullptr, std::memory_order_acquire);
  2074. while(cprops)
  2075. {
  2076. ALcontextProps *next{cprops->next.load(std::memory_order_relaxed)};
  2077. delete cprops;
  2078. cprops = next;
  2079. ++count;
  2080. }
  2081. TRACE("Freed %zu context property object%s\n", count, (count==1)?"":"s");
  2082. count = std::accumulate(mSourceList.cbegin(), mSourceList.cend(), size_t{0u},
  2083. [](size_t cur, const SourceSubList &sublist) noexcept -> size_t
  2084. { return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
  2085. );
  2086. if(count > 0)
  2087. WARN("%zu Source%s not deleted\n", count, (count==1)?"":"s");
  2088. mSourceList.clear();
  2089. mNumSources = 0;
  2090. count = 0;
  2091. ALeffectslotProps *eprops{mFreeEffectslotProps.exchange(nullptr, std::memory_order_acquire)};
  2092. while(eprops)
  2093. {
  2094. ALeffectslotProps *next{eprops->next.load(std::memory_order_relaxed)};
  2095. if(eprops->State) eprops->State->release();
  2096. delete eprops;
  2097. eprops = next;
  2098. ++count;
  2099. }
  2100. TRACE("Freed %zu AuxiliaryEffectSlot property object%s\n", count, (count==1)?"":"s");
  2101. delete mActiveAuxSlots.exchange(nullptr, std::memory_order_relaxed);
  2102. mDefaultSlot = nullptr;
  2103. count = std::accumulate(mEffectSlotList.cbegin(), mEffectSlotList.cend(), size_t{0u},
  2104. [](size_t cur, const EffectSlotSubList &sublist) noexcept -> size_t
  2105. { return cur + static_cast<ALuint>(POPCNT64(~sublist.FreeMask)); }
  2106. );
  2107. if(count > 0)
  2108. WARN("%zu AuxiliaryEffectSlot%s not deleted\n", count, (count==1)?"":"s");
  2109. mEffectSlotList.clear();
  2110. mNumEffectSlots = 0;
  2111. count = 0;
  2112. ALvoiceProps *vprops{mFreeVoiceProps.exchange(nullptr, std::memory_order_acquire)};
  2113. while(vprops)
  2114. {
  2115. ALvoiceProps *next{vprops->next.load(std::memory_order_relaxed)};
  2116. delete vprops;
  2117. vprops = next;
  2118. ++count;
  2119. }
  2120. TRACE("Freed %zu voice property object%s\n", count, (count==1)?"":"s");
  2121. mVoices.clear();
  2122. count = 0;
  2123. ALlistenerProps *lprops{mListener.Params.Update.exchange(nullptr, std::memory_order_relaxed)};
  2124. if(lprops)
  2125. {
  2126. ++count;
  2127. delete lprops;
  2128. }
  2129. lprops = mFreeListenerProps.exchange(nullptr, std::memory_order_acquire);
  2130. while(lprops)
  2131. {
  2132. ALlistenerProps *next{lprops->next.load(std::memory_order_relaxed)};
  2133. delete lprops;
  2134. lprops = next;
  2135. ++count;
  2136. }
  2137. TRACE("Freed %zu listener property object%s\n", count, (count==1)?"":"s");
  2138. if(mAsyncEvents)
  2139. {
  2140. count = 0;
  2141. auto evt_vec = mAsyncEvents->getReadVector();
  2142. if(evt_vec.first.len > 0)
  2143. {
  2144. al::destroy_n(reinterpret_cast<AsyncEvent*>(evt_vec.first.buf), evt_vec.first.len);
  2145. count += evt_vec.first.len;
  2146. }
  2147. if(evt_vec.second.len > 0)
  2148. {
  2149. al::destroy_n(reinterpret_cast<AsyncEvent*>(evt_vec.second.buf), evt_vec.second.len);
  2150. count += evt_vec.second.len;
  2151. }
  2152. if(count > 0)
  2153. TRACE("Destructed %zu orphaned event%s\n", count, (count==1)?"":"s");
  2154. mAsyncEvents->readAdvance(count);
  2155. }
  2156. }
  2157. void ALCcontext::init()
  2158. {
  2159. if(DefaultEffect.type != AL_EFFECT_NULL && mDevice->Type == Playback)
  2160. {
  2161. mDefaultSlot = std::unique_ptr<ALeffectslot>{new ALeffectslot{}};
  2162. if(InitEffectSlot(mDefaultSlot.get()) == AL_NO_ERROR)
  2163. aluInitEffectPanning(mDefaultSlot.get(), mDevice.get());
  2164. else
  2165. {
  2166. mDefaultSlot = nullptr;
  2167. ERR("Failed to initialize the default effect slot\n");
  2168. }
  2169. }
  2170. ALeffectslotArray *auxslots;
  2171. if(!mDefaultSlot)
  2172. auxslots = ALeffectslot::CreatePtrArray(0);
  2173. else
  2174. {
  2175. auxslots = ALeffectslot::CreatePtrArray(1);
  2176. (*auxslots)[0] = mDefaultSlot.get();
  2177. }
  2178. mActiveAuxSlots.store(auxslots, std::memory_order_relaxed);
  2179. mExtensionList = alExtList;
  2180. mListener.Params.Matrix = alu::Matrix::Identity();
  2181. mListener.Params.Velocity = alu::Vector{};
  2182. mListener.Params.Gain = mListener.Gain;
  2183. mListener.Params.MetersPerUnit = mListener.mMetersPerUnit;
  2184. mListener.Params.DopplerFactor = mDopplerFactor;
  2185. mListener.Params.SpeedOfSound = mSpeedOfSound * mDopplerVelocity;
  2186. mListener.Params.SourceDistanceModel = mSourceDistanceModel;
  2187. mListener.Params.mDistanceModel = mDistanceModel;
  2188. mAsyncEvents = CreateRingBuffer(511, sizeof(AsyncEvent), false);
  2189. StartEventThrd(this);
  2190. mVoices.reserve(256);
  2191. mVoices.resize(64);
  2192. }
  2193. bool ALCcontext::deinit()
  2194. {
  2195. if(LocalContext.get() == this)
  2196. {
  2197. WARN("%p released while current on thread\n", decltype(std::declval<void*>()){this});
  2198. LocalContext.set(nullptr);
  2199. release();
  2200. }
  2201. ALCcontext *origctx{this};
  2202. if(GlobalContext.compare_exchange_strong(origctx, nullptr))
  2203. release();
  2204. bool ret{};
  2205. /* First make sure this context exists in the device's list. */
  2206. auto *oldarray = mDevice->mContexts.load(std::memory_order_acquire);
  2207. if(auto toremove = static_cast<size_t>(std::count(oldarray->begin(), oldarray->end(), this)))
  2208. {
  2209. using ContextArray = al::FlexArray<ALCcontext*>;
  2210. auto alloc_ctx_array = [](const size_t count) -> ContextArray*
  2211. {
  2212. if(count == 0) return &EmptyContextArray;
  2213. return ContextArray::Create(count).release();
  2214. };
  2215. auto *newarray = alloc_ctx_array(oldarray->size() - toremove);
  2216. /* Copy the current/old context handles to the new array, excluding the
  2217. * given context.
  2218. */
  2219. std::copy_if(oldarray->begin(), oldarray->end(), newarray->begin(),
  2220. std::bind(std::not_equal_to<ALCcontext*>{}, _1, this));
  2221. /* Store the new context array in the device. Wait for any current mix
  2222. * to finish before deleting the old array.
  2223. */
  2224. mDevice->mContexts.store(newarray);
  2225. if(oldarray != &EmptyContextArray)
  2226. {
  2227. while((mDevice->MixCount.load(std::memory_order_acquire)&1))
  2228. std::this_thread::yield();
  2229. delete oldarray;
  2230. }
  2231. ret = !newarray->empty();
  2232. }
  2233. else
  2234. ret = !oldarray->empty();
  2235. StopEventThrd(this);
  2236. return ret;
  2237. }
  2238. /* VerifyContext
  2239. *
  2240. * Checks if the given context is valid, returning a new reference to it if so.
  2241. */
  2242. static ContextRef VerifyContext(ALCcontext *context)
  2243. {
  2244. std::lock_guard<std::recursive_mutex> _{ListLock};
  2245. auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context);
  2246. if(iter != ContextList.cend() && *iter == context)
  2247. return *iter;
  2248. return nullptr;
  2249. }
  2250. /* GetContextRef
  2251. *
  2252. * Returns a new reference to the currently active context for this thread.
  2253. */
  2254. ContextRef GetContextRef(void)
  2255. {
  2256. ALCcontext *context{LocalContext.get()};
  2257. if(context)
  2258. context->add_ref();
  2259. else
  2260. {
  2261. std::lock_guard<std::recursive_mutex> _{ListLock};
  2262. context = GlobalContext.load(std::memory_order_acquire);
  2263. if(context) context->add_ref();
  2264. }
  2265. return ContextRef{context};
  2266. }
  2267. /************************************************
  2268. * Standard ALC functions
  2269. ************************************************/
  2270. /* alcGetError
  2271. *
  2272. * Return last ALC generated error code for the given device
  2273. */
  2274. ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
  2275. START_API_FUNC
  2276. {
  2277. DeviceRef dev{VerifyDevice(device)};
  2278. if(dev) return dev->LastError.exchange(ALC_NO_ERROR);
  2279. return LastNullDeviceError.exchange(ALC_NO_ERROR);
  2280. }
  2281. END_API_FUNC
  2282. /* alcSuspendContext
  2283. *
  2284. * Suspends updates for the given context
  2285. */
  2286. ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *context)
  2287. START_API_FUNC
  2288. {
  2289. if(!SuspendDefers)
  2290. return;
  2291. ContextRef ctx{VerifyContext(context)};
  2292. if(!ctx)
  2293. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2294. else
  2295. ctx->deferUpdates();
  2296. }
  2297. END_API_FUNC
  2298. /* alcProcessContext
  2299. *
  2300. * Resumes processing updates for the given context
  2301. */
  2302. ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *context)
  2303. START_API_FUNC
  2304. {
  2305. if(!SuspendDefers)
  2306. return;
  2307. ContextRef ctx{VerifyContext(context)};
  2308. if(!ctx)
  2309. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2310. else
  2311. ctx->processUpdates();
  2312. }
  2313. END_API_FUNC
  2314. /* alcGetString
  2315. *
  2316. * Returns information about the device, and error strings
  2317. */
  2318. ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param)
  2319. START_API_FUNC
  2320. {
  2321. const ALCchar *value = nullptr;
  2322. switch(param)
  2323. {
  2324. case ALC_NO_ERROR:
  2325. value = alcNoError;
  2326. break;
  2327. case ALC_INVALID_ENUM:
  2328. value = alcErrInvalidEnum;
  2329. break;
  2330. case ALC_INVALID_VALUE:
  2331. value = alcErrInvalidValue;
  2332. break;
  2333. case ALC_INVALID_DEVICE:
  2334. value = alcErrInvalidDevice;
  2335. break;
  2336. case ALC_INVALID_CONTEXT:
  2337. value = alcErrInvalidContext;
  2338. break;
  2339. case ALC_OUT_OF_MEMORY:
  2340. value = alcErrOutOfMemory;
  2341. break;
  2342. case ALC_DEVICE_SPECIFIER:
  2343. value = alcDefaultName;
  2344. break;
  2345. case ALC_ALL_DEVICES_SPECIFIER:
  2346. if(DeviceRef dev{VerifyDevice(Device)})
  2347. value = dev->DeviceName.c_str();
  2348. else
  2349. {
  2350. ProbeAllDevicesList();
  2351. value = alcAllDevicesList.c_str();
  2352. }
  2353. break;
  2354. case ALC_CAPTURE_DEVICE_SPECIFIER:
  2355. if(DeviceRef dev{VerifyDevice(Device)})
  2356. value = dev->DeviceName.c_str();
  2357. else
  2358. {
  2359. ProbeCaptureDeviceList();
  2360. value = alcCaptureDeviceList.c_str();
  2361. }
  2362. break;
  2363. /* Default devices are always first in the list */
  2364. case ALC_DEFAULT_DEVICE_SPECIFIER:
  2365. value = alcDefaultName;
  2366. break;
  2367. case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
  2368. if(alcAllDevicesList.empty())
  2369. ProbeAllDevicesList();
  2370. /* Copy first entry as default. */
  2371. alcDefaultAllDevicesSpecifier = alcAllDevicesList.c_str();
  2372. value = alcDefaultAllDevicesSpecifier.c_str();
  2373. break;
  2374. case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
  2375. if(alcCaptureDeviceList.empty())
  2376. ProbeCaptureDeviceList();
  2377. /* Copy first entry as default. */
  2378. alcCaptureDefaultDeviceSpecifier = alcCaptureDeviceList.c_str();
  2379. value = alcCaptureDefaultDeviceSpecifier.c_str();
  2380. break;
  2381. case ALC_EXTENSIONS:
  2382. if(VerifyDevice(Device))
  2383. value = alcExtensionList;
  2384. else
  2385. value = alcNoDeviceExtList;
  2386. break;
  2387. case ALC_HRTF_SPECIFIER_SOFT:
  2388. if(DeviceRef dev{VerifyDevice(Device)})
  2389. {
  2390. std::lock_guard<std::mutex> _{dev->StateLock};
  2391. value = (dev->mHrtf ? dev->HrtfName.c_str() : "");
  2392. }
  2393. else
  2394. alcSetError(nullptr, ALC_INVALID_DEVICE);
  2395. break;
  2396. default:
  2397. alcSetError(VerifyDevice(Device).get(), ALC_INVALID_ENUM);
  2398. break;
  2399. }
  2400. return value;
  2401. }
  2402. END_API_FUNC
  2403. static inline ALCsizei NumAttrsForDevice(ALCdevice *device)
  2404. {
  2405. if(device->Type == Capture) return 9;
  2406. if(device->Type != Loopback) return 29;
  2407. if(device->FmtChans == DevFmtAmbi3D)
  2408. return 35;
  2409. return 29;
  2410. }
  2411. static size_t GetIntegerv(ALCdevice *device, ALCenum param, const al::span<ALCint> values)
  2412. {
  2413. size_t i;
  2414. if(values.empty())
  2415. {
  2416. alcSetError(device, ALC_INVALID_VALUE);
  2417. return 0;
  2418. }
  2419. if(!device)
  2420. {
  2421. switch(param)
  2422. {
  2423. case ALC_MAJOR_VERSION:
  2424. values[0] = alcMajorVersion;
  2425. return 1;
  2426. case ALC_MINOR_VERSION:
  2427. values[0] = alcMinorVersion;
  2428. return 1;
  2429. case ALC_ATTRIBUTES_SIZE:
  2430. case ALC_ALL_ATTRIBUTES:
  2431. case ALC_FREQUENCY:
  2432. case ALC_REFRESH:
  2433. case ALC_SYNC:
  2434. case ALC_MONO_SOURCES:
  2435. case ALC_STEREO_SOURCES:
  2436. case ALC_CAPTURE_SAMPLES:
  2437. case ALC_FORMAT_CHANNELS_SOFT:
  2438. case ALC_FORMAT_TYPE_SOFT:
  2439. case ALC_AMBISONIC_LAYOUT_SOFT:
  2440. case ALC_AMBISONIC_SCALING_SOFT:
  2441. case ALC_AMBISONIC_ORDER_SOFT:
  2442. case ALC_MAX_AMBISONIC_ORDER_SOFT:
  2443. alcSetError(nullptr, ALC_INVALID_DEVICE);
  2444. return 0;
  2445. default:
  2446. alcSetError(nullptr, ALC_INVALID_ENUM);
  2447. return 0;
  2448. }
  2449. return 0;
  2450. }
  2451. if(device->Type == Capture)
  2452. {
  2453. switch(param)
  2454. {
  2455. case ALC_ATTRIBUTES_SIZE:
  2456. values[0] = NumAttrsForDevice(device);
  2457. return 1;
  2458. case ALC_ALL_ATTRIBUTES:
  2459. i = 0;
  2460. if(values.size() < static_cast<size_t>(NumAttrsForDevice(device)))
  2461. alcSetError(device, ALC_INVALID_VALUE);
  2462. else
  2463. {
  2464. std::lock_guard<std::mutex> _{device->StateLock};
  2465. values[i++] = ALC_MAJOR_VERSION;
  2466. values[i++] = alcMajorVersion;
  2467. values[i++] = ALC_MINOR_VERSION;
  2468. values[i++] = alcMinorVersion;
  2469. values[i++] = ALC_CAPTURE_SAMPLES;
  2470. values[i++] = static_cast<int>(device->Backend->availableSamples());
  2471. values[i++] = ALC_CONNECTED;
  2472. values[i++] = device->Connected.load(std::memory_order_relaxed);
  2473. values[i++] = 0;
  2474. }
  2475. return i;
  2476. case ALC_MAJOR_VERSION:
  2477. values[0] = alcMajorVersion;
  2478. return 1;
  2479. case ALC_MINOR_VERSION:
  2480. values[0] = alcMinorVersion;
  2481. return 1;
  2482. case ALC_CAPTURE_SAMPLES:
  2483. {
  2484. std::lock_guard<std::mutex> _{device->StateLock};
  2485. values[0] = static_cast<int>(device->Backend->availableSamples());
  2486. }
  2487. return 1;
  2488. case ALC_CONNECTED:
  2489. {
  2490. std::lock_guard<std::mutex> _{device->StateLock};
  2491. values[0] = device->Connected.load(std::memory_order_acquire);
  2492. }
  2493. return 1;
  2494. default:
  2495. alcSetError(device, ALC_INVALID_ENUM);
  2496. }
  2497. return 0;
  2498. }
  2499. /* render device */
  2500. switch(param)
  2501. {
  2502. case ALC_ATTRIBUTES_SIZE:
  2503. values[0] = NumAttrsForDevice(device);
  2504. return 1;
  2505. case ALC_ALL_ATTRIBUTES:
  2506. i = 0;
  2507. if(values.size() < static_cast<size_t>(NumAttrsForDevice(device)))
  2508. alcSetError(device, ALC_INVALID_VALUE);
  2509. else
  2510. {
  2511. std::lock_guard<std::mutex> _{device->StateLock};
  2512. values[i++] = ALC_MAJOR_VERSION;
  2513. values[i++] = alcMajorVersion;
  2514. values[i++] = ALC_MINOR_VERSION;
  2515. values[i++] = alcMinorVersion;
  2516. values[i++] = ALC_EFX_MAJOR_VERSION;
  2517. values[i++] = alcEFXMajorVersion;
  2518. values[i++] = ALC_EFX_MINOR_VERSION;
  2519. values[i++] = alcEFXMinorVersion;
  2520. values[i++] = ALC_FREQUENCY;
  2521. values[i++] = static_cast<int>(device->Frequency);
  2522. if(device->Type != Loopback)
  2523. {
  2524. values[i++] = ALC_REFRESH;
  2525. values[i++] = static_cast<int>(device->Frequency / device->UpdateSize);
  2526. values[i++] = ALC_SYNC;
  2527. values[i++] = ALC_FALSE;
  2528. }
  2529. else
  2530. {
  2531. if(device->FmtChans == DevFmtAmbi3D)
  2532. {
  2533. values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
  2534. values[i++] = static_cast<ALCint>(device->mAmbiLayout);
  2535. values[i++] = ALC_AMBISONIC_SCALING_SOFT;
  2536. values[i++] = static_cast<ALCint>(device->mAmbiScale);
  2537. values[i++] = ALC_AMBISONIC_ORDER_SOFT;
  2538. values[i++] = static_cast<ALCint>(device->mAmbiOrder);
  2539. }
  2540. values[i++] = ALC_FORMAT_CHANNELS_SOFT;
  2541. values[i++] = device->FmtChans;
  2542. values[i++] = ALC_FORMAT_TYPE_SOFT;
  2543. values[i++] = device->FmtType;
  2544. }
  2545. values[i++] = ALC_MONO_SOURCES;
  2546. values[i++] = static_cast<int>(device->NumMonoSources);
  2547. values[i++] = ALC_STEREO_SOURCES;
  2548. values[i++] = static_cast<int>(device->NumStereoSources);
  2549. values[i++] = ALC_MAX_AUXILIARY_SENDS;
  2550. values[i++] = static_cast<ALCint>(device->NumAuxSends);
  2551. values[i++] = ALC_HRTF_SOFT;
  2552. values[i++] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
  2553. values[i++] = ALC_HRTF_STATUS_SOFT;
  2554. values[i++] = device->HrtfStatus;
  2555. values[i++] = ALC_OUTPUT_LIMITER_SOFT;
  2556. values[i++] = device->Limiter ? ALC_TRUE : ALC_FALSE;
  2557. values[i++] = ALC_MAX_AMBISONIC_ORDER_SOFT;
  2558. values[i++] = MAX_AMBI_ORDER;
  2559. values[i++] = 0;
  2560. }
  2561. return i;
  2562. case ALC_MAJOR_VERSION:
  2563. values[0] = alcMajorVersion;
  2564. return 1;
  2565. case ALC_MINOR_VERSION:
  2566. values[0] = alcMinorVersion;
  2567. return 1;
  2568. case ALC_EFX_MAJOR_VERSION:
  2569. values[0] = alcEFXMajorVersion;
  2570. return 1;
  2571. case ALC_EFX_MINOR_VERSION:
  2572. values[0] = alcEFXMinorVersion;
  2573. return 1;
  2574. case ALC_FREQUENCY:
  2575. values[0] = static_cast<int>(device->Frequency);
  2576. return 1;
  2577. case ALC_REFRESH:
  2578. if(device->Type == Loopback)
  2579. {
  2580. alcSetError(device, ALC_INVALID_DEVICE);
  2581. return 0;
  2582. }
  2583. {
  2584. std::lock_guard<std::mutex> _{device->StateLock};
  2585. values[0] = static_cast<int>(device->Frequency / device->UpdateSize);
  2586. }
  2587. return 1;
  2588. case ALC_SYNC:
  2589. if(device->Type == Loopback)
  2590. {
  2591. alcSetError(device, ALC_INVALID_DEVICE);
  2592. return 0;
  2593. }
  2594. values[0] = ALC_FALSE;
  2595. return 1;
  2596. case ALC_FORMAT_CHANNELS_SOFT:
  2597. if(device->Type != Loopback)
  2598. {
  2599. alcSetError(device, ALC_INVALID_DEVICE);
  2600. return 0;
  2601. }
  2602. values[0] = device->FmtChans;
  2603. return 1;
  2604. case ALC_FORMAT_TYPE_SOFT:
  2605. if(device->Type != Loopback)
  2606. {
  2607. alcSetError(device, ALC_INVALID_DEVICE);
  2608. return 0;
  2609. }
  2610. values[0] = device->FmtType;
  2611. return 1;
  2612. case ALC_AMBISONIC_LAYOUT_SOFT:
  2613. if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
  2614. {
  2615. alcSetError(device, ALC_INVALID_DEVICE);
  2616. return 0;
  2617. }
  2618. values[0] = static_cast<ALCint>(device->mAmbiLayout);
  2619. return 1;
  2620. case ALC_AMBISONIC_SCALING_SOFT:
  2621. if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
  2622. {
  2623. alcSetError(device, ALC_INVALID_DEVICE);
  2624. return 0;
  2625. }
  2626. values[0] = static_cast<ALCint>(device->mAmbiScale);
  2627. return 1;
  2628. case ALC_AMBISONIC_ORDER_SOFT:
  2629. if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
  2630. {
  2631. alcSetError(device, ALC_INVALID_DEVICE);
  2632. return 0;
  2633. }
  2634. values[0] = static_cast<int>(device->mAmbiOrder);
  2635. return 1;
  2636. case ALC_MONO_SOURCES:
  2637. values[0] = static_cast<int>(device->NumMonoSources);
  2638. return 1;
  2639. case ALC_STEREO_SOURCES:
  2640. values[0] = static_cast<int>(device->NumStereoSources);
  2641. return 1;
  2642. case ALC_MAX_AUXILIARY_SENDS:
  2643. values[0] = static_cast<ALCint>(device->NumAuxSends);
  2644. return 1;
  2645. case ALC_CONNECTED:
  2646. {
  2647. std::lock_guard<std::mutex> _{device->StateLock};
  2648. values[0] = device->Connected.load(std::memory_order_acquire);
  2649. }
  2650. return 1;
  2651. case ALC_HRTF_SOFT:
  2652. values[0] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
  2653. return 1;
  2654. case ALC_HRTF_STATUS_SOFT:
  2655. values[0] = device->HrtfStatus;
  2656. return 1;
  2657. case ALC_NUM_HRTF_SPECIFIERS_SOFT:
  2658. {
  2659. std::lock_guard<std::mutex> _{device->StateLock};
  2660. device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
  2661. values[0] = static_cast<ALCint>(minz(device->HrtfList.size(),
  2662. std::numeric_limits<ALCint>::max()));
  2663. }
  2664. return 1;
  2665. case ALC_OUTPUT_LIMITER_SOFT:
  2666. values[0] = device->Limiter ? ALC_TRUE : ALC_FALSE;
  2667. return 1;
  2668. case ALC_MAX_AMBISONIC_ORDER_SOFT:
  2669. values[0] = MAX_AMBI_ORDER;
  2670. return 1;
  2671. default:
  2672. alcSetError(device, ALC_INVALID_ENUM);
  2673. }
  2674. return 0;
  2675. }
  2676. /* alcGetIntegerv
  2677. *
  2678. * Returns information about the device and the version of OpenAL
  2679. */
  2680. ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values)
  2681. START_API_FUNC
  2682. {
  2683. DeviceRef dev{VerifyDevice(device)};
  2684. if(size <= 0 || values == nullptr)
  2685. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2686. else
  2687. GetIntegerv(dev.get(), param, {values, values+size});
  2688. }
  2689. END_API_FUNC
  2690. ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALCsizei size, ALCint64SOFT *values)
  2691. START_API_FUNC
  2692. {
  2693. DeviceRef dev{VerifyDevice(device)};
  2694. if(size <= 0 || values == nullptr)
  2695. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2696. else if(!dev || dev->Type == Capture)
  2697. {
  2698. auto ivals = al::vector<ALCint>(static_cast<ALuint>(size));
  2699. size_t got{GetIntegerv(dev.get(), pname, {ivals.data(), ivals.size()})};
  2700. std::copy_n(ivals.begin(), got, values);
  2701. return;
  2702. }
  2703. /* render device */
  2704. switch(pname)
  2705. {
  2706. case ALC_ATTRIBUTES_SIZE:
  2707. *values = NumAttrsForDevice(dev.get())+4;
  2708. break;
  2709. case ALC_ALL_ATTRIBUTES:
  2710. if(size < NumAttrsForDevice(dev.get())+4)
  2711. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2712. else
  2713. {
  2714. size_t i{0};
  2715. std::lock_guard<std::mutex> _{dev->StateLock};
  2716. values[i++] = ALC_FREQUENCY;
  2717. values[i++] = dev->Frequency;
  2718. if(dev->Type != Loopback)
  2719. {
  2720. values[i++] = ALC_REFRESH;
  2721. values[i++] = dev->Frequency / dev->UpdateSize;
  2722. values[i++] = ALC_SYNC;
  2723. values[i++] = ALC_FALSE;
  2724. }
  2725. else
  2726. {
  2727. if(dev->FmtChans == DevFmtAmbi3D)
  2728. {
  2729. values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
  2730. values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiLayout);
  2731. values[i++] = ALC_AMBISONIC_SCALING_SOFT;
  2732. values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiScale);
  2733. values[i++] = ALC_AMBISONIC_ORDER_SOFT;
  2734. values[i++] = dev->mAmbiOrder;
  2735. }
  2736. values[i++] = ALC_FORMAT_CHANNELS_SOFT;
  2737. values[i++] = dev->FmtChans;
  2738. values[i++] = ALC_FORMAT_TYPE_SOFT;
  2739. values[i++] = dev->FmtType;
  2740. }
  2741. values[i++] = ALC_MONO_SOURCES;
  2742. values[i++] = dev->NumMonoSources;
  2743. values[i++] = ALC_STEREO_SOURCES;
  2744. values[i++] = dev->NumStereoSources;
  2745. values[i++] = ALC_MAX_AUXILIARY_SENDS;
  2746. values[i++] = dev->NumAuxSends;
  2747. values[i++] = ALC_HRTF_SOFT;
  2748. values[i++] = (dev->mHrtf ? ALC_TRUE : ALC_FALSE);
  2749. values[i++] = ALC_HRTF_STATUS_SOFT;
  2750. values[i++] = dev->HrtfStatus;
  2751. values[i++] = ALC_OUTPUT_LIMITER_SOFT;
  2752. values[i++] = dev->Limiter ? ALC_TRUE : ALC_FALSE;
  2753. ClockLatency clock{GetClockLatency(dev.get())};
  2754. values[i++] = ALC_DEVICE_CLOCK_SOFT;
  2755. values[i++] = clock.ClockTime.count();
  2756. values[i++] = ALC_DEVICE_LATENCY_SOFT;
  2757. values[i++] = clock.Latency.count();
  2758. values[i++] = 0;
  2759. }
  2760. break;
  2761. case ALC_DEVICE_CLOCK_SOFT:
  2762. { std::lock_guard<std::mutex> _{dev->StateLock};
  2763. nanoseconds basecount;
  2764. ALuint samplecount;
  2765. ALuint refcount;
  2766. do {
  2767. while(((refcount=ReadRef(dev->MixCount))&1) != 0)
  2768. std::this_thread::yield();
  2769. basecount = dev->ClockBase;
  2770. samplecount = dev->SamplesDone;
  2771. } while(refcount != ReadRef(dev->MixCount));
  2772. basecount += nanoseconds{seconds{samplecount}} / dev->Frequency;
  2773. *values = basecount.count();
  2774. }
  2775. break;
  2776. case ALC_DEVICE_LATENCY_SOFT:
  2777. { std::lock_guard<std::mutex> _{dev->StateLock};
  2778. ClockLatency clock{GetClockLatency(dev.get())};
  2779. *values = clock.Latency.count();
  2780. }
  2781. break;
  2782. case ALC_DEVICE_CLOCK_LATENCY_SOFT:
  2783. if(size < 2)
  2784. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2785. else
  2786. {
  2787. std::lock_guard<std::mutex> _{dev->StateLock};
  2788. ClockLatency clock{GetClockLatency(dev.get())};
  2789. values[0] = clock.ClockTime.count();
  2790. values[1] = clock.Latency.count();
  2791. }
  2792. break;
  2793. default:
  2794. auto ivals = al::vector<ALCint>(static_cast<ALuint>(size));
  2795. size_t got{GetIntegerv(dev.get(), pname, {ivals.data(), ivals.size()})};
  2796. std::copy_n(ivals.begin(), got, values);
  2797. break;
  2798. }
  2799. }
  2800. END_API_FUNC
  2801. /* alcIsExtensionPresent
  2802. *
  2803. * Determines if there is support for a particular extension
  2804. */
  2805. ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
  2806. START_API_FUNC
  2807. {
  2808. DeviceRef dev{VerifyDevice(device)};
  2809. if(!extName)
  2810. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2811. else
  2812. {
  2813. size_t len = strlen(extName);
  2814. const char *ptr = (dev ? alcExtensionList : alcNoDeviceExtList);
  2815. while(ptr && *ptr)
  2816. {
  2817. if(al::strncasecmp(ptr, extName, len) == 0 && (ptr[len] == '\0' || isspace(ptr[len])))
  2818. return ALC_TRUE;
  2819. if((ptr=strchr(ptr, ' ')) != nullptr)
  2820. {
  2821. do {
  2822. ++ptr;
  2823. } while(isspace(*ptr));
  2824. }
  2825. }
  2826. }
  2827. return ALC_FALSE;
  2828. }
  2829. END_API_FUNC
  2830. /* alcGetProcAddress
  2831. *
  2832. * Retrieves the function address for a particular extension function
  2833. */
  2834. ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
  2835. START_API_FUNC
  2836. {
  2837. if(!funcName)
  2838. {
  2839. DeviceRef dev{VerifyDevice(device)};
  2840. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2841. }
  2842. else
  2843. {
  2844. for(const auto &func : alcFunctions)
  2845. {
  2846. if(strcmp(func.funcName, funcName) == 0)
  2847. return func.address;
  2848. }
  2849. }
  2850. return nullptr;
  2851. }
  2852. END_API_FUNC
  2853. /* alcGetEnumValue
  2854. *
  2855. * Get the value for a particular ALC enumeration name
  2856. */
  2857. ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
  2858. START_API_FUNC
  2859. {
  2860. if(!enumName)
  2861. {
  2862. DeviceRef dev{VerifyDevice(device)};
  2863. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2864. }
  2865. else
  2866. {
  2867. for(const auto &enm : alcEnumerations)
  2868. {
  2869. if(strcmp(enm.enumName, enumName) == 0)
  2870. return enm.value;
  2871. }
  2872. }
  2873. return 0;
  2874. }
  2875. END_API_FUNC
  2876. /* alcCreateContext
  2877. *
  2878. * Create and attach a context to the given device.
  2879. */
  2880. ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
  2881. START_API_FUNC
  2882. {
  2883. /* Explicitly hold the list lock while taking the StateLock in case the
  2884. * device is asynchronously destroyed, to ensure this new context is
  2885. * properly cleaned up after being made.
  2886. */
  2887. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  2888. DeviceRef dev{VerifyDevice(device)};
  2889. if(!dev || dev->Type == Capture || !dev->Connected.load(std::memory_order_relaxed))
  2890. {
  2891. listlock.unlock();
  2892. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2893. return nullptr;
  2894. }
  2895. std::unique_lock<std::mutex> statelock{dev->StateLock};
  2896. listlock.unlock();
  2897. dev->LastError.store(ALC_NO_ERROR);
  2898. ALCenum err{UpdateDeviceParams(dev.get(), attrList)};
  2899. if(err != ALC_NO_ERROR)
  2900. {
  2901. alcSetError(dev.get(), err);
  2902. if(err == ALC_INVALID_DEVICE)
  2903. aluHandleDisconnect(dev.get(), "Device update failure");
  2904. return nullptr;
  2905. }
  2906. ContextRef context{new ALCcontext{dev}};
  2907. context->init();
  2908. if(auto volopt = ConfigValueFloat(dev->DeviceName.c_str(), nullptr, "volume-adjust"))
  2909. {
  2910. const ALfloat valf{*volopt};
  2911. if(!std::isfinite(valf))
  2912. ERR("volume-adjust must be finite: %f\n", valf);
  2913. else
  2914. {
  2915. const ALfloat db{clampf(valf, -24.0f, 24.0f)};
  2916. if(db != valf)
  2917. WARN("volume-adjust clamped: %f, range: +/-%f\n", valf, 24.0f);
  2918. context->mGainBoost = std::pow(10.0f, db/20.0f);
  2919. TRACE("volume-adjust gain: %f\n", context->mGainBoost);
  2920. }
  2921. }
  2922. UpdateListenerProps(context.get());
  2923. {
  2924. using ContextArray = al::FlexArray<ALCcontext*>;
  2925. /* Allocate a new context array, which holds 1 more than the current/
  2926. * old array.
  2927. */
  2928. auto *oldarray = device->mContexts.load();
  2929. const size_t newcount{oldarray->size()+1};
  2930. std::unique_ptr<ContextArray> newarray{ContextArray::Create(newcount)};
  2931. /* Copy the current/old context handles to the new array, appending the
  2932. * new context.
  2933. */
  2934. auto iter = std::copy(oldarray->begin(), oldarray->end(), newarray->begin());
  2935. *iter = context.get();
  2936. /* Store the new context array in the device. Wait for any current mix
  2937. * to finish before deleting the old array.
  2938. */
  2939. dev->mContexts.store(newarray.release());
  2940. if(oldarray != &EmptyContextArray)
  2941. {
  2942. while((dev->MixCount.load(std::memory_order_acquire)&1))
  2943. std::this_thread::yield();
  2944. delete oldarray;
  2945. }
  2946. }
  2947. statelock.unlock();
  2948. {
  2949. std::lock_guard<std::recursive_mutex> _{ListLock};
  2950. auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context.get());
  2951. ContextList.emplace(iter, context);
  2952. }
  2953. if(context->mDefaultSlot)
  2954. {
  2955. if(InitializeEffect(context.get(), context->mDefaultSlot.get(), &DefaultEffect) == AL_NO_ERROR)
  2956. UpdateEffectSlotProps(context->mDefaultSlot.get(), context.get());
  2957. else
  2958. ERR("Failed to initialize the default effect\n");
  2959. }
  2960. TRACE("Created context %p\n", decltype(std::declval<void*>()){context.get()});
  2961. return context.get();
  2962. }
  2963. END_API_FUNC
  2964. /* alcDestroyContext
  2965. *
  2966. * Remove a context from its device
  2967. */
  2968. ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
  2969. START_API_FUNC
  2970. {
  2971. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  2972. auto iter = std::lower_bound(ContextList.begin(), ContextList.end(), context);
  2973. if(iter == ContextList.end() || *iter != context)
  2974. {
  2975. listlock.unlock();
  2976. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2977. return;
  2978. }
  2979. /* Hold an extra reference to this context so it remains valid until the
  2980. * ListLock is released.
  2981. */
  2982. ContextRef ctx{std::move(*iter)};
  2983. ContextList.erase(iter);
  2984. ALCdevice *Device{ctx->mDevice.get()};
  2985. std::lock_guard<std::mutex> _{Device->StateLock};
  2986. if(!ctx->deinit() && Device->Flags.get<DeviceRunning>())
  2987. {
  2988. Device->Backend->stop();
  2989. Device->Flags.unset<DeviceRunning>();
  2990. }
  2991. }
  2992. END_API_FUNC
  2993. /* alcGetCurrentContext
  2994. *
  2995. * Returns the currently active context on the calling thread
  2996. */
  2997. ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(void)
  2998. START_API_FUNC
  2999. {
  3000. ALCcontext *Context{LocalContext.get()};
  3001. if(!Context) Context = GlobalContext.load();
  3002. return Context;
  3003. }
  3004. END_API_FUNC
  3005. /* alcGetThreadContext
  3006. *
  3007. * Returns the currently active thread-local context
  3008. */
  3009. ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
  3010. START_API_FUNC
  3011. { return LocalContext.get(); }
  3012. END_API_FUNC
  3013. /* alcMakeContextCurrent
  3014. *
  3015. * Makes the given context the active process-wide context, and removes the
  3016. * thread-local context for the calling thread.
  3017. */
  3018. ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
  3019. START_API_FUNC
  3020. {
  3021. /* context must be valid or nullptr */
  3022. ContextRef ctx;
  3023. if(context)
  3024. {
  3025. ctx = VerifyContext(context);
  3026. if(!ctx)
  3027. {
  3028. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  3029. return ALC_FALSE;
  3030. }
  3031. }
  3032. /* Release this reference (if any) to store it in the GlobalContext
  3033. * pointer. Take ownership of the reference (if any) that was previously
  3034. * stored there.
  3035. */
  3036. ctx = ContextRef{GlobalContext.exchange(ctx.release())};
  3037. /* Reset (decrement) the previous global reference by replacing it with the
  3038. * thread-local context. Take ownership of the thread-local context
  3039. * reference (if any), clearing the storage to null.
  3040. */
  3041. ctx = ContextRef{LocalContext.get()};
  3042. if(ctx) LocalContext.set(nullptr);
  3043. /* Reset (decrement) the previous thread-local reference. */
  3044. return ALC_TRUE;
  3045. }
  3046. END_API_FUNC
  3047. /* alcSetThreadContext
  3048. *
  3049. * Makes the given context the active context for the current thread
  3050. */
  3051. ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
  3052. START_API_FUNC
  3053. {
  3054. /* context must be valid or nullptr */
  3055. ContextRef ctx;
  3056. if(context)
  3057. {
  3058. ctx = VerifyContext(context);
  3059. if(!ctx)
  3060. {
  3061. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  3062. return ALC_FALSE;
  3063. }
  3064. }
  3065. /* context's reference count is already incremented */
  3066. ContextRef old{LocalContext.get()};
  3067. LocalContext.set(ctx.release());
  3068. return ALC_TRUE;
  3069. }
  3070. END_API_FUNC
  3071. /* alcGetContextsDevice
  3072. *
  3073. * Returns the device that a particular context is attached to
  3074. */
  3075. ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
  3076. START_API_FUNC
  3077. {
  3078. ContextRef ctx{VerifyContext(Context)};
  3079. if(!ctx)
  3080. {
  3081. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  3082. return nullptr;
  3083. }
  3084. return ctx->mDevice.get();
  3085. }
  3086. END_API_FUNC
  3087. /* alcOpenDevice
  3088. *
  3089. * Opens the named device.
  3090. */
  3091. ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
  3092. START_API_FUNC
  3093. {
  3094. DO_INITCONFIG();
  3095. if(!PlaybackFactory)
  3096. {
  3097. alcSetError(nullptr, ALC_INVALID_VALUE);
  3098. return nullptr;
  3099. }
  3100. if(deviceName)
  3101. {
  3102. if(!deviceName[0] || al::strcasecmp(deviceName, alcDefaultName) == 0
  3103. #ifdef _WIN32
  3104. /* Some old Windows apps hardcode these expecting OpenAL to use a
  3105. * specific audio API, even when they're not enumerated. Creative's
  3106. * router effectively ignores them too.
  3107. */
  3108. || al::strcasecmp(deviceName, "DirectSound3D") == 0
  3109. || al::strcasecmp(deviceName, "DirectSound") == 0
  3110. || al::strcasecmp(deviceName, "MMSYSTEM") == 0
  3111. #endif
  3112. || al::strcasecmp(deviceName, "openal-soft") == 0)
  3113. deviceName = nullptr;
  3114. }
  3115. DeviceRef device{new ALCdevice{Playback}};
  3116. /* Set output format */
  3117. device->FmtChans = DevFmtChannelsDefault;
  3118. device->FmtType = DevFmtTypeDefault;
  3119. device->Frequency = DEFAULT_OUTPUT_RATE;
  3120. device->UpdateSize = DEFAULT_UPDATE_SIZE;
  3121. device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES;
  3122. device->SourcesMax = 256;
  3123. device->AuxiliaryEffectSlotMax = 64;
  3124. device->NumAuxSends = DEFAULT_SENDS;
  3125. try {
  3126. auto backend = PlaybackFactory->createBackend(device.get(), BackendType::Playback);
  3127. backend->open(deviceName);
  3128. device->Backend = std::move(backend);
  3129. }
  3130. catch(al::backend_exception &e) {
  3131. WARN("Failed to open playback device: %s\n", e.what());
  3132. alcSetError(nullptr, e.errorCode());
  3133. return nullptr;
  3134. }
  3135. deviceName = device->DeviceName.c_str();
  3136. if(auto chanopt = ConfigValueStr(deviceName, nullptr, "channels"))
  3137. {
  3138. static const struct ChannelMap {
  3139. const char name[16];
  3140. DevFmtChannels chans;
  3141. ALuint order;
  3142. } chanlist[] = {
  3143. { "mono", DevFmtMono, 0 },
  3144. { "stereo", DevFmtStereo, 0 },
  3145. { "quad", DevFmtQuad, 0 },
  3146. { "surround51", DevFmtX51, 0 },
  3147. { "surround61", DevFmtX61, 0 },
  3148. { "surround71", DevFmtX71, 0 },
  3149. { "surround51rear", DevFmtX51Rear, 0 },
  3150. { "ambi1", DevFmtAmbi3D, 1 },
  3151. { "ambi2", DevFmtAmbi3D, 2 },
  3152. { "ambi3", DevFmtAmbi3D, 3 },
  3153. };
  3154. const ALCchar *fmt{chanopt->c_str()};
  3155. auto iter = std::find_if(std::begin(chanlist), std::end(chanlist),
  3156. [fmt](const ChannelMap &entry) -> bool
  3157. { return al::strcasecmp(entry.name, fmt) == 0; }
  3158. );
  3159. if(iter == std::end(chanlist))
  3160. ERR("Unsupported channels: %s\n", fmt);
  3161. else
  3162. {
  3163. device->FmtChans = iter->chans;
  3164. device->mAmbiOrder = iter->order;
  3165. device->Flags.set<ChannelsRequest>();
  3166. }
  3167. }
  3168. if(auto typeopt = ConfigValueStr(deviceName, nullptr, "sample-type"))
  3169. {
  3170. static const struct TypeMap {
  3171. const char name[16];
  3172. DevFmtType type;
  3173. } typelist[] = {
  3174. { "int8", DevFmtByte },
  3175. { "uint8", DevFmtUByte },
  3176. { "int16", DevFmtShort },
  3177. { "uint16", DevFmtUShort },
  3178. { "int32", DevFmtInt },
  3179. { "uint32", DevFmtUInt },
  3180. { "float32", DevFmtFloat },
  3181. };
  3182. const ALCchar *fmt{typeopt->c_str()};
  3183. auto iter = std::find_if(std::begin(typelist), std::end(typelist),
  3184. [fmt](const TypeMap &entry) -> bool
  3185. { return al::strcasecmp(entry.name, fmt) == 0; }
  3186. );
  3187. if(iter == std::end(typelist))
  3188. ERR("Unsupported sample-type: %s\n", fmt);
  3189. else
  3190. {
  3191. device->FmtType = iter->type;
  3192. device->Flags.set<SampleTypeRequest>();
  3193. }
  3194. }
  3195. if(ALuint freq{ConfigValueUInt(deviceName, nullptr, "frequency").value_or(0)})
  3196. {
  3197. if(freq < MIN_OUTPUT_RATE)
  3198. {
  3199. ERR("%uhz request clamped to %uhz minimum\n", freq, MIN_OUTPUT_RATE);
  3200. freq = MIN_OUTPUT_RATE;
  3201. }
  3202. device->UpdateSize = (device->UpdateSize*freq + device->Frequency/2) / device->Frequency;
  3203. device->BufferSize = (device->BufferSize*freq + device->Frequency/2) / device->Frequency;
  3204. device->Frequency = freq;
  3205. device->Flags.set<FrequencyRequest>();
  3206. }
  3207. if(auto persizeopt = ConfigValueUInt(deviceName, nullptr, "period_size"))
  3208. device->UpdateSize = clampu(*persizeopt, 64, 8192);
  3209. if(auto peropt = ConfigValueUInt(deviceName, nullptr, "periods"))
  3210. device->BufferSize = device->UpdateSize * clampu(*peropt, 2, 16);
  3211. else
  3212. device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2);
  3213. if(auto srcsopt = ConfigValueUInt(deviceName, nullptr, "sources"))
  3214. {
  3215. if(*srcsopt > 0) device->SourcesMax = *srcsopt;
  3216. }
  3217. if(auto slotsopt = ConfigValueUInt(deviceName, nullptr, "slots"))
  3218. {
  3219. if(*slotsopt > 0)
  3220. device->AuxiliaryEffectSlotMax = minu(*slotsopt, INT_MAX);
  3221. }
  3222. if(auto sendsopt = ConfigValueInt(deviceName, nullptr, "sends"))
  3223. device->NumAuxSends = clampu(DEFAULT_SENDS, 0,
  3224. static_cast<ALuint>(clampi(*sendsopt, 0, MAX_SENDS)));
  3225. device->NumStereoSources = 1;
  3226. device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
  3227. if(auto ambiopt = ConfigValueStr(deviceName, nullptr, "ambi-format"))
  3228. {
  3229. const ALCchar *fmt{ambiopt->c_str()};
  3230. if(al::strcasecmp(fmt, "fuma") == 0)
  3231. {
  3232. if(device->mAmbiOrder > 3)
  3233. ERR("FuMa is incompatible with %d%s order ambisonics (up to third-order only)\n",
  3234. device->mAmbiOrder,
  3235. (((device->mAmbiOrder%100)/10) == 1) ? "th" :
  3236. ((device->mAmbiOrder%10) == 1) ? "st" :
  3237. ((device->mAmbiOrder%10) == 2) ? "nd" :
  3238. ((device->mAmbiOrder%10) == 3) ? "rd" : "th");
  3239. else
  3240. {
  3241. device->mAmbiLayout = AmbiLayout::FuMa;
  3242. device->mAmbiScale = AmbiNorm::FuMa;
  3243. }
  3244. }
  3245. else if(al::strcasecmp(fmt, "ambix") == 0 || al::strcasecmp(fmt, "acn+sn3d") == 0)
  3246. {
  3247. device->mAmbiLayout = AmbiLayout::ACN;
  3248. device->mAmbiScale = AmbiNorm::SN3D;
  3249. }
  3250. else if(al::strcasecmp(fmt, "acn+n3d") == 0)
  3251. {
  3252. device->mAmbiLayout = AmbiLayout::ACN;
  3253. device->mAmbiScale = AmbiNorm::N3D;
  3254. }
  3255. else
  3256. ERR("Unsupported ambi-format: %s\n", fmt);
  3257. }
  3258. {
  3259. std::lock_guard<std::recursive_mutex> _{ListLock};
  3260. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  3261. DeviceList.emplace(iter, device);
  3262. }
  3263. TRACE("Created device %p, \"%s\"\n", decltype(std::declval<void*>()){device.get()},
  3264. device->DeviceName.c_str());
  3265. return device.get();
  3266. }
  3267. END_API_FUNC
  3268. /* alcCloseDevice
  3269. *
  3270. * Closes the given device.
  3271. */
  3272. ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device)
  3273. START_API_FUNC
  3274. {
  3275. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3276. auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
  3277. if(iter == DeviceList.end() || *iter != device)
  3278. {
  3279. alcSetError(nullptr, ALC_INVALID_DEVICE);
  3280. return ALC_FALSE;
  3281. }
  3282. if((*iter)->Type == Capture)
  3283. {
  3284. alcSetError(iter->get(), ALC_INVALID_DEVICE);
  3285. return ALC_FALSE;
  3286. }
  3287. /* Erase the device, and any remaining contexts left on it, from their
  3288. * respective lists.
  3289. */
  3290. DeviceRef dev{std::move(*iter)};
  3291. DeviceList.erase(iter);
  3292. std::unique_lock<std::mutex> statelock{dev->StateLock};
  3293. al::vector<ContextRef> orphanctxs;
  3294. for(ALCcontext *ctx : *dev->mContexts.load())
  3295. {
  3296. auto ctxiter = std::lower_bound(ContextList.begin(), ContextList.end(), ctx);
  3297. if(ctxiter != ContextList.end() && *ctxiter == ctx)
  3298. {
  3299. orphanctxs.emplace_back(std::move(*ctxiter));
  3300. ContextList.erase(ctxiter);
  3301. }
  3302. }
  3303. listlock.unlock();
  3304. for(ContextRef &context : orphanctxs)
  3305. {
  3306. WARN("Releasing orphaned context %p\n", decltype(std::declval<void*>()){context.get()});
  3307. context->deinit();
  3308. }
  3309. orphanctxs.clear();
  3310. if(dev->Flags.get<DeviceRunning>())
  3311. dev->Backend->stop();
  3312. dev->Flags.unset<DeviceRunning>();
  3313. return ALC_TRUE;
  3314. }
  3315. END_API_FUNC
  3316. /************************************************
  3317. * ALC capture functions
  3318. ************************************************/
  3319. ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples)
  3320. START_API_FUNC
  3321. {
  3322. DO_INITCONFIG();
  3323. if(!CaptureFactory)
  3324. {
  3325. alcSetError(nullptr, ALC_INVALID_VALUE);
  3326. return nullptr;
  3327. }
  3328. if(samples <= 0)
  3329. {
  3330. alcSetError(nullptr, ALC_INVALID_VALUE);
  3331. return nullptr;
  3332. }
  3333. if(deviceName)
  3334. {
  3335. if(!deviceName[0] || al::strcasecmp(deviceName, alcDefaultName) == 0
  3336. || al::strcasecmp(deviceName, "openal-soft") == 0)
  3337. deviceName = nullptr;
  3338. }
  3339. DeviceRef device{new ALCdevice{Capture}};
  3340. auto decompfmt = DecomposeDevFormat(format);
  3341. if(!decompfmt)
  3342. {
  3343. alcSetError(nullptr, ALC_INVALID_ENUM);
  3344. return nullptr;
  3345. }
  3346. device->Frequency = frequency;
  3347. device->FmtChans = decompfmt->chans;
  3348. device->FmtType = decompfmt->type;
  3349. device->Flags.set<FrequencyRequest, ChannelsRequest, SampleTypeRequest>();
  3350. device->UpdateSize = static_cast<ALuint>(samples);
  3351. device->BufferSize = static_cast<ALuint>(samples);
  3352. try {
  3353. TRACE("Capture format: %s, %s, %uhz, %u / %u buffer\n",
  3354. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  3355. device->Frequency, device->UpdateSize, device->BufferSize);
  3356. auto backend = CaptureFactory->createBackend(device.get(), BackendType::Capture);
  3357. backend->open(deviceName);
  3358. device->Backend = std::move(backend);
  3359. }
  3360. catch(al::backend_exception &e) {
  3361. WARN("Failed to open capture device: %s\n", e.what());
  3362. alcSetError(nullptr, e.errorCode());
  3363. return nullptr;
  3364. }
  3365. {
  3366. std::lock_guard<std::recursive_mutex> _{ListLock};
  3367. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  3368. DeviceList.emplace(iter, device);
  3369. }
  3370. TRACE("Created capture device %p, \"%s\"\n", decltype(std::declval<void*>()){device.get()},
  3371. device->DeviceName.c_str());
  3372. return device.get();
  3373. }
  3374. END_API_FUNC
  3375. ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device)
  3376. START_API_FUNC
  3377. {
  3378. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3379. auto iter = std::lower_bound(DeviceList.begin(), DeviceList.end(), device);
  3380. if(iter == DeviceList.end() || *iter != device)
  3381. {
  3382. alcSetError(nullptr, ALC_INVALID_DEVICE);
  3383. return ALC_FALSE;
  3384. }
  3385. if((*iter)->Type != Capture)
  3386. {
  3387. alcSetError(iter->get(), ALC_INVALID_DEVICE);
  3388. return ALC_FALSE;
  3389. }
  3390. DeviceRef dev{std::move(*iter)};
  3391. DeviceList.erase(iter);
  3392. listlock.unlock();
  3393. std::lock_guard<std::mutex> _{dev->StateLock};
  3394. if(dev->Flags.get<DeviceRunning>())
  3395. dev->Backend->stop();
  3396. dev->Flags.unset<DeviceRunning>();
  3397. return ALC_TRUE;
  3398. }
  3399. END_API_FUNC
  3400. ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
  3401. START_API_FUNC
  3402. {
  3403. DeviceRef dev{VerifyDevice(device)};
  3404. if(!dev || dev->Type != Capture)
  3405. {
  3406. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3407. return;
  3408. }
  3409. std::lock_guard<std::mutex> _{dev->StateLock};
  3410. if(!dev->Connected.load(std::memory_order_acquire))
  3411. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3412. else if(!dev->Flags.get<DeviceRunning>())
  3413. {
  3414. try {
  3415. auto backend = dev->Backend.get();
  3416. if(!backend->start())
  3417. throw al::backend_exception{ALC_INVALID_DEVICE, "Device start failure"};
  3418. dev->Flags.set<DeviceRunning>();
  3419. }
  3420. catch(al::backend_exception& e) {
  3421. aluHandleDisconnect(dev.get(), "%s", e.what());
  3422. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3423. }
  3424. }
  3425. }
  3426. END_API_FUNC
  3427. ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
  3428. START_API_FUNC
  3429. {
  3430. DeviceRef dev{VerifyDevice(device)};
  3431. if(!dev || dev->Type != Capture)
  3432. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3433. else
  3434. {
  3435. std::lock_guard<std::mutex> _{dev->StateLock};
  3436. if(dev->Flags.get<DeviceRunning>())
  3437. dev->Backend->stop();
  3438. dev->Flags.unset<DeviceRunning>();
  3439. }
  3440. }
  3441. END_API_FUNC
  3442. ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
  3443. START_API_FUNC
  3444. {
  3445. DeviceRef dev{VerifyDevice(device)};
  3446. if(!dev || dev->Type != Capture)
  3447. {
  3448. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3449. return;
  3450. }
  3451. if(samples < 0 || (samples > 0 && buffer == nullptr))
  3452. {
  3453. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3454. return;
  3455. }
  3456. if(samples < 1)
  3457. return;
  3458. std::lock_guard<std::mutex> _{dev->StateLock};
  3459. BackendBase *backend{dev->Backend.get()};
  3460. const auto usamples = static_cast<ALCuint>(samples);
  3461. if(usamples > backend->availableSamples())
  3462. {
  3463. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3464. return;
  3465. }
  3466. auto *bbuffer = static_cast<al::byte*>(buffer);
  3467. if(ALCenum err{backend->captureSamples(bbuffer, usamples)})
  3468. alcSetError(dev.get(), err);
  3469. }
  3470. END_API_FUNC
  3471. /************************************************
  3472. * ALC loopback functions
  3473. ************************************************/
  3474. /* alcLoopbackOpenDeviceSOFT
  3475. *
  3476. * Open a loopback device, for manual rendering.
  3477. */
  3478. ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName)
  3479. START_API_FUNC
  3480. {
  3481. DO_INITCONFIG();
  3482. /* Make sure the device name, if specified, is us. */
  3483. if(deviceName && strcmp(deviceName, alcDefaultName) != 0)
  3484. {
  3485. alcSetError(nullptr, ALC_INVALID_VALUE);
  3486. return nullptr;
  3487. }
  3488. DeviceRef device{new ALCdevice{Loopback}};
  3489. device->SourcesMax = 256;
  3490. device->AuxiliaryEffectSlotMax = 64;
  3491. device->NumAuxSends = DEFAULT_SENDS;
  3492. //Set output format
  3493. device->BufferSize = 0;
  3494. device->UpdateSize = 0;
  3495. device->Frequency = DEFAULT_OUTPUT_RATE;
  3496. device->FmtChans = DevFmtChannelsDefault;
  3497. device->FmtType = DevFmtTypeDefault;
  3498. if(auto srcsopt = ConfigValueUInt(nullptr, nullptr, "sources"))
  3499. {
  3500. if(*srcsopt > 0) device->SourcesMax = *srcsopt;
  3501. }
  3502. if(auto slotsopt = ConfigValueUInt(nullptr, nullptr, "slots"))
  3503. {
  3504. if(*slotsopt > 0)
  3505. device->AuxiliaryEffectSlotMax = minu(*slotsopt, INT_MAX);
  3506. }
  3507. if(auto sendsopt = ConfigValueInt(nullptr, nullptr, "sends"))
  3508. device->NumAuxSends = clampu(DEFAULT_SENDS, 0,
  3509. static_cast<ALuint>(clampi(*sendsopt, 0, MAX_SENDS)));
  3510. device->NumStereoSources = 1;
  3511. device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
  3512. try {
  3513. auto backend = LoopbackBackendFactory::getFactory().createBackend(device.get(),
  3514. BackendType::Playback);
  3515. backend->open("Loopback");
  3516. device->Backend = std::move(backend);
  3517. }
  3518. catch(al::backend_exception &e) {
  3519. WARN("Failed to open loopback device: %s\n", e.what());
  3520. alcSetError(nullptr, e.errorCode());
  3521. return nullptr;
  3522. }
  3523. {
  3524. std::lock_guard<std::recursive_mutex> _{ListLock};
  3525. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  3526. DeviceList.emplace(iter, device);
  3527. }
  3528. TRACE("Created loopback device %p\n", decltype(std::declval<void*>()){device.get()});
  3529. return device.get();
  3530. }
  3531. END_API_FUNC
  3532. /* alcIsRenderFormatSupportedSOFT
  3533. *
  3534. * Determines if the loopback device supports the given format for rendering.
  3535. */
  3536. ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
  3537. START_API_FUNC
  3538. {
  3539. DeviceRef dev{VerifyDevice(device)};
  3540. if(!dev || dev->Type != Loopback)
  3541. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3542. else if(freq <= 0)
  3543. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3544. else
  3545. {
  3546. if(IsValidALCType(type) && IsValidALCChannels(channels) && freq >= MIN_OUTPUT_RATE)
  3547. return ALC_TRUE;
  3548. }
  3549. return ALC_FALSE;
  3550. }
  3551. END_API_FUNC
  3552. /* alcRenderSamplesSOFT
  3553. *
  3554. * Renders some samples into a buffer, using the format last set by the
  3555. * attributes given to alcCreateContext.
  3556. */
  3557. FORCE_ALIGN ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
  3558. START_API_FUNC
  3559. {
  3560. DeviceRef dev{VerifyDevice(device)};
  3561. if(!dev || dev->Type != Loopback)
  3562. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3563. else if(samples < 0 || (samples > 0 && buffer == nullptr))
  3564. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3565. else
  3566. {
  3567. BackendLockGuard _{*dev->Backend};
  3568. aluMixData(dev.get(), buffer, static_cast<ALuint>(samples));
  3569. }
  3570. }
  3571. END_API_FUNC
  3572. /************************************************
  3573. * ALC DSP pause/resume functions
  3574. ************************************************/
  3575. /* alcDevicePauseSOFT
  3576. *
  3577. * Pause the DSP to stop audio processing.
  3578. */
  3579. ALC_API void ALC_APIENTRY alcDevicePauseSOFT(ALCdevice *device)
  3580. START_API_FUNC
  3581. {
  3582. DeviceRef dev{VerifyDevice(device)};
  3583. if(!dev || dev->Type != Playback)
  3584. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3585. else
  3586. {
  3587. std::lock_guard<std::mutex> _{dev->StateLock};
  3588. if(dev->Flags.get<DeviceRunning>())
  3589. dev->Backend->stop();
  3590. dev->Flags.unset<DeviceRunning>();
  3591. dev->Flags.set<DevicePaused>();
  3592. }
  3593. }
  3594. END_API_FUNC
  3595. /* alcDeviceResumeSOFT
  3596. *
  3597. * Resume the DSP to restart audio processing.
  3598. */
  3599. ALC_API void ALC_APIENTRY alcDeviceResumeSOFT(ALCdevice *device)
  3600. START_API_FUNC
  3601. {
  3602. DeviceRef dev{VerifyDevice(device)};
  3603. if(!dev || dev->Type != Playback)
  3604. {
  3605. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3606. return;
  3607. }
  3608. std::lock_guard<std::mutex> _{dev->StateLock};
  3609. if(!dev->Flags.get<DevicePaused>())
  3610. return;
  3611. dev->Flags.unset<DevicePaused>();
  3612. if(dev->mContexts.load()->empty())
  3613. return;
  3614. try {
  3615. auto backend = dev->Backend.get();
  3616. if(!backend->start())
  3617. throw al::backend_exception{ALC_INVALID_DEVICE, "Device start failure"};
  3618. dev->Flags.set<DeviceRunning>();
  3619. }
  3620. catch(al::backend_exception& e) {
  3621. aluHandleDisconnect(dev.get(), "%s", e.what());
  3622. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3623. }
  3624. }
  3625. END_API_FUNC
  3626. /************************************************
  3627. * ALC HRTF functions
  3628. ************************************************/
  3629. /* alcGetStringiSOFT
  3630. *
  3631. * Gets a string parameter at the given index.
  3632. */
  3633. ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum paramName, ALCsizei index)
  3634. START_API_FUNC
  3635. {
  3636. DeviceRef dev{VerifyDevice(device)};
  3637. if(!dev || dev->Type == Capture)
  3638. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3639. else switch(paramName)
  3640. {
  3641. case ALC_HRTF_SPECIFIER_SOFT:
  3642. if(index >= 0 && static_cast<size_t>(index) < dev->HrtfList.size())
  3643. return dev->HrtfList[static_cast<ALuint>(index)].name.c_str();
  3644. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3645. break;
  3646. default:
  3647. alcSetError(dev.get(), ALC_INVALID_ENUM);
  3648. break;
  3649. }
  3650. return nullptr;
  3651. }
  3652. END_API_FUNC
  3653. /* alcResetDeviceSOFT
  3654. *
  3655. * Resets the given device output, using the specified attribute list.
  3656. */
  3657. ALC_API ALCboolean ALC_APIENTRY alcResetDeviceSOFT(ALCdevice *device, const ALCint *attribs)
  3658. START_API_FUNC
  3659. {
  3660. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3661. DeviceRef dev{VerifyDevice(device)};
  3662. if(!dev || dev->Type == Capture)
  3663. {
  3664. listlock.unlock();
  3665. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3666. return ALC_FALSE;
  3667. }
  3668. std::lock_guard<std::mutex> _{dev->StateLock};
  3669. listlock.unlock();
  3670. /* Force the backend to stop mixing first since we're resetting. Also reset
  3671. * the connected state so lost devices can attempt recover.
  3672. */
  3673. if(dev->Flags.get<DeviceRunning>())
  3674. dev->Backend->stop();
  3675. dev->Flags.unset<DeviceRunning>();
  3676. device->Connected.store(true);
  3677. ALCenum err{UpdateDeviceParams(dev.get(), attribs)};
  3678. if LIKELY(err == ALC_NO_ERROR) return ALC_TRUE;
  3679. alcSetError(dev.get(), err);
  3680. if(err == ALC_INVALID_DEVICE)
  3681. aluHandleDisconnect(dev.get(), "Device start failure");
  3682. return ALC_FALSE;
  3683. }
  3684. END_API_FUNC