source.cpp 168 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086
  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 "source.h"
  22. #include <algorithm>
  23. #include <array>
  24. #include <atomic>
  25. #include <bitset>
  26. #include <cassert>
  27. #include <chrono>
  28. #include <cmath>
  29. #include <cstdint>
  30. #include <cstdio>
  31. #include <iterator>
  32. #include <functional>
  33. #include <limits>
  34. #include <memory>
  35. #include <mutex>
  36. #include <numeric>
  37. #include <optional>
  38. #include <stdexcept>
  39. #include <string>
  40. #include <string_view>
  41. #include <tuple>
  42. #include <type_traits>
  43. #include <unordered_map>
  44. #include <utility>
  45. #include <vector>
  46. #include "AL/al.h"
  47. #include "AL/alc.h"
  48. #include "AL/alext.h"
  49. #include "AL/efx.h"
  50. #include "albit.h"
  51. #include "alc/backends/base.h"
  52. #include "alc/context.h"
  53. #include "alc/device.h"
  54. #include "alc/inprogext.h"
  55. #include "almalloc.h"
  56. #include "alnumeric.h"
  57. #include "alspan.h"
  58. #include "atomic.h"
  59. #include "auxeffectslot.h"
  60. #include "buffer.h"
  61. #include "core/buffer_storage.h"
  62. #include "core/except.h"
  63. #include "core/logging.h"
  64. #include "core/mixer/defs.h"
  65. #include "core/voice_change.h"
  66. #include "direct_defs.h"
  67. #include "filter.h"
  68. #include "flexarray.h"
  69. #include "intrusive_ptr.h"
  70. #include "opthelpers.h"
  71. #if ALSOFT_EAX
  72. #include "eax/api.h"
  73. #include "eax/call.h"
  74. #include "eax/fx_slot_index.h"
  75. #include "eax/utils.h"
  76. #endif
  77. namespace {
  78. using SubListAllocator = al::allocator<std::array<ALsource,64>>;
  79. using std::chrono::nanoseconds;
  80. using seconds_d = std::chrono::duration<double>;
  81. using source_store_array = std::array<ALsource*,3>;
  82. using source_store_vector = std::vector<ALsource*>;
  83. using source_store_variant = std::variant<std::monostate,source_store_array,source_store_vector>;
  84. using namespace std::string_view_literals;
  85. Voice *GetSourceVoice(ALsource *source, ALCcontext *context)
  86. {
  87. auto voicelist = context->getVoicesSpan();
  88. ALuint idx{source->VoiceIdx};
  89. if(idx < voicelist.size())
  90. {
  91. ALuint sid{source->id};
  92. Voice *voice = voicelist[idx];
  93. if(voice->mSourceID.load(std::memory_order_acquire) == sid)
  94. return voice;
  95. }
  96. source->VoiceIdx = InvalidVoiceIndex;
  97. return nullptr;
  98. }
  99. void UpdateSourceProps(const ALsource *source, Voice *voice, ALCcontext *context)
  100. {
  101. /* Get an unused property container, or allocate a new one as needed. */
  102. VoicePropsItem *props{context->mFreeVoiceProps.load(std::memory_order_acquire)};
  103. if(!props)
  104. {
  105. context->allocVoiceProps();
  106. props = context->mFreeVoiceProps.load(std::memory_order_acquire);
  107. }
  108. VoicePropsItem *next;
  109. do {
  110. next = props->next.load(std::memory_order_relaxed);
  111. } while(context->mFreeVoiceProps.compare_exchange_weak(props, next,
  112. std::memory_order_acq_rel, std::memory_order_acquire) == false);
  113. props->Pitch = source->Pitch;
  114. props->Gain = source->Gain;
  115. props->OuterGain = source->OuterGain;
  116. props->MinGain = source->MinGain;
  117. props->MaxGain = source->MaxGain;
  118. props->InnerAngle = source->InnerAngle;
  119. props->OuterAngle = source->OuterAngle;
  120. props->RefDistance = source->RefDistance;
  121. props->MaxDistance = source->MaxDistance;
  122. props->RolloffFactor = source->RolloffFactor
  123. #if ALSOFT_EAX
  124. + source->RolloffFactor2
  125. #endif
  126. ;
  127. props->Position = source->Position;
  128. props->Velocity = source->Velocity;
  129. props->Direction = source->Direction;
  130. props->OrientAt = source->OrientAt;
  131. props->OrientUp = source->OrientUp;
  132. props->HeadRelative = source->HeadRelative;
  133. props->mDistanceModel = source->mDistanceModel;
  134. props->mResampler = source->mResampler;
  135. props->DirectChannels = source->DirectChannels;
  136. props->mSpatializeMode = source->mSpatialize;
  137. props->DryGainHFAuto = source->DryGainHFAuto;
  138. props->WetGainAuto = source->WetGainAuto;
  139. props->WetGainHFAuto = source->WetGainHFAuto;
  140. props->OuterGainHF = source->OuterGainHF;
  141. props->AirAbsorptionFactor = source->AirAbsorptionFactor;
  142. props->RoomRolloffFactor = source->RoomRolloffFactor;
  143. props->DopplerFactor = source->DopplerFactor;
  144. props->StereoPan = source->StereoPan;
  145. props->Radius = source->Radius;
  146. props->EnhWidth = source->EnhWidth;
  147. props->Panning = source->mPanningEnabled ? source->mPan : 0.0f;
  148. props->Direct.Gain = source->Direct.Gain;
  149. props->Direct.GainHF = source->Direct.GainHF;
  150. props->Direct.HFReference = source->Direct.HFReference;
  151. props->Direct.GainLF = source->Direct.GainLF;
  152. props->Direct.LFReference = source->Direct.LFReference;
  153. auto copy_send = [](const ALsource::SendData &srcsend) noexcept -> VoiceProps::SendData
  154. {
  155. VoiceProps::SendData ret{};
  156. ret.Slot = srcsend.Slot ? srcsend.Slot->mSlot : nullptr;
  157. ret.Gain = srcsend.Gain;
  158. ret.GainHF = srcsend.GainHF;
  159. ret.HFReference = srcsend.HFReference;
  160. ret.GainLF = srcsend.GainLF;
  161. ret.LFReference = srcsend.LFReference;
  162. return ret;
  163. };
  164. std::transform(source->Send.cbegin(), source->Send.cend(), props->Send.begin(), copy_send);
  165. if(!props->Send[0].Slot && context->mDefaultSlot)
  166. props->Send[0].Slot = context->mDefaultSlot->mSlot;
  167. /* Set the new container for updating internal parameters. */
  168. props = voice->mUpdate.exchange(props, std::memory_order_acq_rel);
  169. if(props)
  170. {
  171. /* If there was an unused update container, put it back in the
  172. * freelist.
  173. */
  174. AtomicReplaceHead(context->mFreeVoiceProps, props);
  175. }
  176. }
  177. /* GetSourceSampleOffset
  178. *
  179. * Gets the current read offset for the given Source, in 32.32 fixed-point
  180. * samples. The offset is relative to the start of the queue (not the start of
  181. * the current buffer).
  182. */
  183. int64_t GetSourceSampleOffset(ALsource *Source, ALCcontext *context, nanoseconds *clocktime)
  184. {
  185. auto *device = context->mALDevice.get();
  186. const VoiceBufferItem *Current{};
  187. int64_t readPos{};
  188. uint refcount{};
  189. Voice *voice{};
  190. do {
  191. refcount = device->waitForMix();
  192. *clocktime = device->getClockTime();
  193. voice = GetSourceVoice(Source, context);
  194. if(voice)
  195. {
  196. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  197. readPos = int64_t{voice->mPosition.load(std::memory_order_relaxed)} << MixerFracBits;
  198. readPos += voice->mPositionFrac.load(std::memory_order_relaxed);
  199. }
  200. std::atomic_thread_fence(std::memory_order_acquire);
  201. } while(refcount != device->mMixCount.load(std::memory_order_relaxed));
  202. if(!voice)
  203. return 0;
  204. for(auto &item : Source->mQueue)
  205. {
  206. if(&item == Current) break;
  207. readPos += int64_t{item.mSampleLen} << MixerFracBits;
  208. }
  209. if(readPos > std::numeric_limits<int64_t>::max() >> (32-MixerFracBits))
  210. return std::numeric_limits<int64_t>::max();
  211. return readPos << (32-MixerFracBits);
  212. }
  213. /* GetSourceSecOffset
  214. *
  215. * Gets the current read offset for the given Source, in seconds. The offset is
  216. * relative to the start of the queue (not the start of the current buffer).
  217. */
  218. double GetSourceSecOffset(ALsource *Source, ALCcontext *context, nanoseconds *clocktime)
  219. {
  220. auto *device = context->mALDevice.get();
  221. const VoiceBufferItem *Current{};
  222. int64_t readPos{};
  223. uint refcount{};
  224. Voice *voice{};
  225. do {
  226. refcount = device->waitForMix();
  227. *clocktime = device->getClockTime();
  228. voice = GetSourceVoice(Source, context);
  229. if(voice)
  230. {
  231. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  232. readPos = int64_t{voice->mPosition.load(std::memory_order_relaxed)} << MixerFracBits;
  233. readPos += voice->mPositionFrac.load(std::memory_order_relaxed);
  234. }
  235. std::atomic_thread_fence(std::memory_order_acquire);
  236. } while(refcount != device->mMixCount.load(std::memory_order_relaxed));
  237. if(!voice)
  238. return 0.0f;
  239. const ALbuffer *BufferFmt{nullptr};
  240. auto BufferList = Source->mQueue.cbegin();
  241. while(BufferList != Source->mQueue.cend() && al::to_address(BufferList) != Current)
  242. {
  243. if(!BufferFmt) BufferFmt = BufferList->mBuffer;
  244. readPos += int64_t{BufferList->mSampleLen} << MixerFracBits;
  245. ++BufferList;
  246. }
  247. while(BufferList != Source->mQueue.cend() && !BufferFmt)
  248. {
  249. BufferFmt = BufferList->mBuffer;
  250. ++BufferList;
  251. }
  252. ASSUME(BufferFmt != nullptr);
  253. return static_cast<double>(readPos) / double{MixerFracOne} / BufferFmt->mSampleRate;
  254. }
  255. /* GetSourceOffset
  256. *
  257. * Gets the current read offset for the given Source, in the appropriate format
  258. * (Bytes, Samples or Seconds). The offset is relative to the start of the
  259. * queue (not the start of the current buffer).
  260. */
  261. template<typename T>
  262. NOINLINE T GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context)
  263. {
  264. auto *device = context->mALDevice.get();
  265. const VoiceBufferItem *Current{};
  266. int64_t readPos{};
  267. uint readPosFrac{};
  268. uint refcount;
  269. Voice *voice;
  270. do {
  271. refcount = device->waitForMix();
  272. voice = GetSourceVoice(Source, context);
  273. if(voice)
  274. {
  275. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  276. readPos = voice->mPosition.load(std::memory_order_relaxed);
  277. readPosFrac = voice->mPositionFrac.load(std::memory_order_relaxed);
  278. }
  279. std::atomic_thread_fence(std::memory_order_acquire);
  280. } while(refcount != device->mMixCount.load(std::memory_order_relaxed));
  281. if(!voice)
  282. return T{0};
  283. const ALbuffer *BufferFmt{nullptr};
  284. auto BufferList = Source->mQueue.cbegin();
  285. while(BufferList != Source->mQueue.cend() && al::to_address(BufferList) != Current)
  286. {
  287. if(!BufferFmt) BufferFmt = BufferList->mBuffer;
  288. readPos += BufferList->mSampleLen;
  289. ++BufferList;
  290. }
  291. while(BufferList != Source->mQueue.cend() && !BufferFmt)
  292. {
  293. BufferFmt = BufferList->mBuffer;
  294. ++BufferList;
  295. }
  296. ASSUME(BufferFmt != nullptr);
  297. switch(name)
  298. {
  299. case AL_SEC_OFFSET:
  300. if constexpr(std::is_floating_point_v<T>)
  301. {
  302. auto offset = static_cast<T>(readPos) + static_cast<T>(readPosFrac)/T{MixerFracOne};
  303. return offset / static_cast<T>(BufferFmt->mSampleRate);
  304. }
  305. else
  306. {
  307. readPos /= BufferFmt->mSampleRate;
  308. return static_cast<T>(std::clamp<int64_t>(readPos, std::numeric_limits<T>::min(),
  309. std::numeric_limits<T>::max()));
  310. }
  311. case AL_SAMPLE_OFFSET:
  312. if constexpr(std::is_floating_point_v<T>)
  313. return static_cast<T>(readPos) + static_cast<T>(readPosFrac)/T{MixerFracOne};
  314. else
  315. return static_cast<T>(std::clamp<int64_t>(readPos, std::numeric_limits<T>::min(),
  316. std::numeric_limits<T>::max()));
  317. case AL_BYTE_OFFSET:
  318. /* Round down to the block boundary. */
  319. const auto BlockSize = ALuint{BufferFmt->blockSizeFromFmt()};
  320. readPos = readPos / BufferFmt->mBlockAlign * BlockSize;
  321. if constexpr(std::is_floating_point_v<T>)
  322. return static_cast<T>(readPos);
  323. else
  324. {
  325. if(readPos > std::numeric_limits<T>::max())
  326. return RoundDown(std::numeric_limits<T>::max(), static_cast<T>(BlockSize));
  327. if(readPos < std::numeric_limits<T>::min())
  328. return RoundUp(std::numeric_limits<T>::min(), static_cast<T>(BlockSize));
  329. return static_cast<T>(readPos);
  330. }
  331. }
  332. return T{0};
  333. }
  334. /* GetSourceLength
  335. *
  336. * Gets the length of the given Source's buffer queue, in the appropriate
  337. * format (Bytes, Samples or Seconds).
  338. */
  339. template<typename T>
  340. NOINLINE T GetSourceLength(const ALsource *source, ALenum name)
  341. {
  342. uint64_t length{0};
  343. const ALbuffer *BufferFmt{nullptr};
  344. for(auto &listitem : source->mQueue)
  345. {
  346. if(!BufferFmt)
  347. BufferFmt = listitem.mBuffer;
  348. length += listitem.mSampleLen;
  349. }
  350. if(length == 0 || !BufferFmt)
  351. return T{0};
  352. switch(name)
  353. {
  354. case AL_SEC_LENGTH_SOFT:
  355. if constexpr(std::is_floating_point_v<T>)
  356. return static_cast<T>(length) / static_cast<T>(BufferFmt->mSampleRate);
  357. else
  358. return static_cast<T>(std::min<uint64_t>(length/BufferFmt->mSampleRate,
  359. std::numeric_limits<T>::max()));
  360. case AL_SAMPLE_LENGTH_SOFT:
  361. if constexpr(std::is_floating_point_v<T>)
  362. return static_cast<T>(length);
  363. else
  364. return static_cast<T>(std::min<uint64_t>(length, std::numeric_limits<T>::max()));
  365. case AL_BYTE_LENGTH_SOFT:
  366. /* Round down to the block boundary. */
  367. const auto BlockSize = ALuint{BufferFmt->blockSizeFromFmt()};
  368. length = length / BufferFmt->mBlockAlign * BlockSize;
  369. if constexpr(std::is_floating_point_v<T>)
  370. return static_cast<T>(length);
  371. else
  372. {
  373. if(length > uint64_t{std::numeric_limits<T>::max()})
  374. return RoundDown(std::numeric_limits<T>::max(), static_cast<T>(BlockSize));
  375. return static_cast<T>(length);
  376. }
  377. }
  378. return T{0};
  379. }
  380. struct VoicePos {
  381. int pos;
  382. uint frac;
  383. ALbufferQueueItem *bufferitem;
  384. };
  385. /**
  386. * GetSampleOffset
  387. *
  388. * Retrieves the voice position, fixed-point fraction, and bufferlist item
  389. * using the given offset type and offset. If the offset is out of range,
  390. * returns an empty optional.
  391. */
  392. std::optional<VoicePos> GetSampleOffset(std::deque<ALbufferQueueItem> &BufferList,
  393. ALenum OffsetType, double Offset)
  394. {
  395. /* Find the first valid Buffer in the Queue */
  396. const ALbuffer *BufferFmt{nullptr};
  397. for(auto &item : BufferList)
  398. {
  399. BufferFmt = item.mBuffer;
  400. if(BufferFmt) break;
  401. }
  402. if(!BufferFmt) UNLIKELY
  403. return std::nullopt;
  404. /* Get sample frame offset */
  405. auto [offset, frac] = std::invoke([OffsetType,Offset,BufferFmt]() -> std::pair<int64_t,uint>
  406. {
  407. auto dbloff = double{};
  408. auto dblfrac = double{};
  409. switch(OffsetType)
  410. {
  411. case AL_SEC_OFFSET:
  412. dblfrac = std::modf(Offset*BufferFmt->mSampleRate, &dbloff);
  413. if(dblfrac < 0.0)
  414. {
  415. /* If there's a negative fraction, reduce the offset to "floor"
  416. * it, and convert the fraction to a percentage to the next
  417. * greater value (e.g. -2.75 -> -2 + -0.75 -> -3 + 0.25).
  418. */
  419. dbloff -= 1.0;
  420. dblfrac += 1.0;
  421. }
  422. return {static_cast<int64_t>(dbloff),
  423. static_cast<uint>(std::min(dblfrac*MixerFracOne, MixerFracOne-1.0))};
  424. case AL_SAMPLE_OFFSET:
  425. dblfrac = std::modf(Offset, &dbloff);
  426. if(dblfrac < 0.0)
  427. {
  428. dbloff -= 1.0;
  429. dblfrac += 1.0;
  430. }
  431. return {static_cast<int64_t>(dbloff),
  432. static_cast<uint>(std::min(dblfrac*MixerFracOne, MixerFracOne-1.0))};
  433. case AL_BYTE_OFFSET:
  434. /* Determine the ByteOffset (and ensure it is block aligned) */
  435. const auto blockoffset = std::floor(Offset / BufferFmt->blockSizeFromFmt());
  436. return {static_cast<int64_t>(blockoffset) * BufferFmt->mBlockAlign, 0u};
  437. }
  438. return {0_i64, 0u};
  439. });
  440. /* Find the bufferlist item this offset belongs to. */
  441. if(offset < 0)
  442. {
  443. if(offset < std::numeric_limits<int>::min())
  444. return std::nullopt;
  445. return VoicePos{static_cast<int>(offset), frac, &BufferList.front()};
  446. }
  447. if(BufferFmt->mCallback)
  448. return std::nullopt;
  449. for(auto &item : BufferList)
  450. {
  451. if(item.mSampleLen > offset)
  452. {
  453. /* Offset is in this buffer */
  454. return VoicePos{static_cast<int>(offset), frac, &item};
  455. }
  456. offset -= item.mSampleLen;
  457. }
  458. /* Offset is out of range of the queue */
  459. return std::nullopt;
  460. }
  461. void InitVoice(Voice *voice, ALsource *source, ALbufferQueueItem *BufferList, ALCcontext *context,
  462. al::Device *device)
  463. {
  464. voice->mLoopBuffer.store(source->Looping ? &source->mQueue.front() : nullptr,
  465. std::memory_order_relaxed);
  466. ALbuffer *buffer{BufferList->mBuffer};
  467. voice->mFrequency = buffer->mSampleRate;
  468. if(buffer->mChannels == FmtMono && source->mPanningEnabled)
  469. voice->mFmtChannels = FmtMonoDup;
  470. else if(buffer->mChannels == FmtStereo && source->mStereoMode == SourceStereo::Enhanced)
  471. voice->mFmtChannels = FmtSuperStereo;
  472. else
  473. voice->mFmtChannels = buffer->mChannels;
  474. voice->mFmtType = buffer->mType;
  475. voice->mFrameStep = buffer->channelsFromFmt();
  476. voice->mBytesPerBlock = buffer->blockSizeFromFmt();
  477. voice->mSamplesPerBlock = buffer->mBlockAlign;
  478. voice->mAmbiLayout = IsUHJ(voice->mFmtChannels) ? AmbiLayout::FuMa : buffer->mAmbiLayout;
  479. voice->mAmbiScaling = IsUHJ(voice->mFmtChannels) ? AmbiScaling::UHJ : buffer->mAmbiScaling;
  480. voice->mAmbiOrder = (voice->mFmtChannels == FmtSuperStereo) ? 1 : buffer->mAmbiOrder;
  481. if(buffer->mCallback) voice->mFlags.set(VoiceIsCallback);
  482. else if(source->SourceType == AL_STATIC) voice->mFlags.set(VoiceIsStatic);
  483. voice->mNumCallbackBlocks = 0;
  484. voice->mCallbackBlockBase = 0;
  485. voice->prepare(device);
  486. source->mPropsDirty = false;
  487. UpdateSourceProps(source, voice, context);
  488. voice->mSourceID.store(source->id, std::memory_order_release);
  489. }
  490. VoiceChange *GetVoiceChanger(ALCcontext *ctx)
  491. {
  492. VoiceChange *vchg{ctx->mVoiceChangeTail};
  493. if(vchg == ctx->mCurrentVoiceChange.load(std::memory_order_acquire)) UNLIKELY
  494. {
  495. ctx->allocVoiceChanges();
  496. vchg = ctx->mVoiceChangeTail;
  497. }
  498. ctx->mVoiceChangeTail = vchg->mNext.exchange(nullptr, std::memory_order_relaxed);
  499. return vchg;
  500. }
  501. void SendVoiceChanges(ALCcontext *ctx, VoiceChange *tail)
  502. {
  503. auto *device = ctx->mALDevice.get();
  504. VoiceChange *oldhead{ctx->mCurrentVoiceChange.load(std::memory_order_acquire)};
  505. while(VoiceChange *next{oldhead->mNext.load(std::memory_order_relaxed)})
  506. oldhead = next;
  507. oldhead->mNext.store(tail, std::memory_order_release);
  508. const bool connected{device->Connected.load(std::memory_order_acquire)};
  509. std::ignore = device->waitForMix();
  510. if(!connected) UNLIKELY
  511. {
  512. if(ctx->mStopVoicesOnDisconnect.load(std::memory_order_acquire))
  513. {
  514. /* If the device is disconnected and voices are stopped, just
  515. * ignore all pending changes.
  516. */
  517. VoiceChange *cur{ctx->mCurrentVoiceChange.load(std::memory_order_acquire)};
  518. while(VoiceChange *next{cur->mNext.load(std::memory_order_acquire)})
  519. {
  520. cur = next;
  521. if(Voice *voice{cur->mVoice})
  522. voice->mSourceID.store(0, std::memory_order_relaxed);
  523. }
  524. ctx->mCurrentVoiceChange.store(cur, std::memory_order_release);
  525. }
  526. }
  527. }
  528. auto SetVoiceOffset(Voice *oldvoice, const VoicePos &vpos, ALsource *source, ALCcontext *context,
  529. al::Device *device) -> bool
  530. {
  531. /* First, get a free voice to start at the new offset. */
  532. auto voicelist = context->getVoicesSpan();
  533. Voice *newvoice{};
  534. ALuint vidx{0};
  535. for(Voice *voice : voicelist)
  536. {
  537. if(voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  538. && voice->mSourceID.load(std::memory_order_relaxed) == 0u
  539. && voice->mPendingChange.load(std::memory_order_relaxed) == false)
  540. {
  541. newvoice = voice;
  542. break;
  543. }
  544. ++vidx;
  545. }
  546. if(!newvoice) UNLIKELY
  547. {
  548. auto &allvoices = *context->mVoices.load(std::memory_order_relaxed);
  549. if(allvoices.size() == voicelist.size())
  550. context->allocVoices(1);
  551. context->mActiveVoiceCount.fetch_add(1, std::memory_order_release);
  552. voicelist = context->getVoicesSpan();
  553. vidx = 0;
  554. for(Voice *voice : voicelist)
  555. {
  556. if(voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  557. && voice->mSourceID.load(std::memory_order_relaxed) == 0u
  558. && voice->mPendingChange.load(std::memory_order_relaxed) == false)
  559. {
  560. newvoice = voice;
  561. break;
  562. }
  563. ++vidx;
  564. }
  565. ASSUME(newvoice != nullptr);
  566. }
  567. /* Initialize the new voice and set its starting offset.
  568. * TODO: It might be better to have the VoiceChange processing copy the old
  569. * voice's mixing parameters (and pending update) insead of initializing it
  570. * all here. This would just need to set the minimum properties to link the
  571. * voice to the source and its position-dependent properties (including the
  572. * fading flag).
  573. */
  574. newvoice->mPlayState.store(Voice::Pending, std::memory_order_relaxed);
  575. newvoice->mPosition.store(vpos.pos, std::memory_order_relaxed);
  576. newvoice->mPositionFrac.store(vpos.frac, std::memory_order_relaxed);
  577. newvoice->mCurrentBuffer.store(vpos.bufferitem, std::memory_order_relaxed);
  578. newvoice->mStartTime = oldvoice->mStartTime;
  579. newvoice->mFlags.reset();
  580. if(vpos.pos > 0 || (vpos.pos == 0 && vpos.frac > 0)
  581. || vpos.bufferitem != &source->mQueue.front())
  582. newvoice->mFlags.set(VoiceIsFading);
  583. InitVoice(newvoice, source, vpos.bufferitem, context, device);
  584. source->VoiceIdx = vidx;
  585. /* Set the old voice as having a pending change, and send it off with the
  586. * new one with a new offset voice change.
  587. */
  588. oldvoice->mPendingChange.store(true, std::memory_order_relaxed);
  589. VoiceChange *vchg{GetVoiceChanger(context)};
  590. vchg->mOldVoice = oldvoice;
  591. vchg->mVoice = newvoice;
  592. vchg->mSourceID = source->id;
  593. vchg->mState = VChangeState::Restart;
  594. SendVoiceChanges(context, vchg);
  595. /* If the old voice still has a sourceID, it's still active and the change-
  596. * over will work on the next update.
  597. */
  598. if(oldvoice->mSourceID.load(std::memory_order_acquire) != 0u) LIKELY
  599. return true;
  600. /* Otherwise, if the new voice's state is not pending, the change-over
  601. * already happened.
  602. */
  603. if(newvoice->mPlayState.load(std::memory_order_acquire) != Voice::Pending)
  604. return true;
  605. /* Otherwise, wait for any current mix to finish and check one last time. */
  606. std::ignore = device->waitForMix();
  607. if(newvoice->mPlayState.load(std::memory_order_acquire) != Voice::Pending)
  608. return true;
  609. /* The change-over failed because the old voice stopped before the new
  610. * voice could start at the new offset. Let go of the new voice and have
  611. * the caller store the source offset since it's stopped.
  612. */
  613. newvoice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
  614. newvoice->mLoopBuffer.store(nullptr, std::memory_order_relaxed);
  615. newvoice->mSourceID.store(0u, std::memory_order_relaxed);
  616. newvoice->mPlayState.store(Voice::Stopped, std::memory_order_relaxed);
  617. return false;
  618. }
  619. /**
  620. * Returns if the last known state for the source was playing or paused. Does
  621. * not sync with the mixer voice.
  622. */
  623. inline bool IsPlayingOrPaused(ALsource *source)
  624. { return source->state == AL_PLAYING || source->state == AL_PAUSED; }
  625. /**
  626. * Returns an updated source state using the matching voice's status (or lack
  627. * thereof).
  628. */
  629. inline ALenum GetSourceState(ALsource *source, Voice *voice)
  630. {
  631. if(!voice && source->state == AL_PLAYING)
  632. source->state = AL_STOPPED;
  633. return source->state;
  634. }
  635. bool EnsureSources(ALCcontext *context, size_t needed)
  636. {
  637. size_t count{std::accumulate(context->mSourceList.cbegin(), context->mSourceList.cend(), 0_uz,
  638. [](size_t cur, const SourceSubList &sublist) noexcept -> size_t
  639. { return cur + static_cast<ALuint>(al::popcount(sublist.FreeMask)); })};
  640. try {
  641. while(needed > count)
  642. {
  643. if(context->mSourceList.size() >= 1<<25) UNLIKELY
  644. return false;
  645. SourceSubList sublist{};
  646. sublist.FreeMask = ~0_u64;
  647. sublist.Sources = SubListAllocator{}.allocate(1);
  648. context->mSourceList.emplace_back(std::move(sublist));
  649. count += std::tuple_size_v<SubListAllocator::value_type>;
  650. }
  651. }
  652. catch(...) {
  653. return false;
  654. }
  655. return true;
  656. }
  657. ALsource *AllocSource(ALCcontext *context) noexcept
  658. {
  659. auto sublist = std::find_if(context->mSourceList.begin(), context->mSourceList.end(),
  660. [](const SourceSubList &entry) noexcept -> bool
  661. { return entry.FreeMask != 0; });
  662. auto lidx = static_cast<ALuint>(std::distance(context->mSourceList.begin(), sublist));
  663. auto slidx = static_cast<ALuint>(al::countr_zero(sublist->FreeMask));
  664. ASSUME(slidx < 64);
  665. ALsource *source{al::construct_at(al::to_address(sublist->Sources->begin() + slidx))};
  666. #if ALSOFT_EAX
  667. source->eaxInitialize(context);
  668. #endif // ALSOFT_EAX
  669. /* Add 1 to avoid source ID 0. */
  670. source->id = ((lidx<<6) | slidx) + 1;
  671. context->mNumSources += 1;
  672. sublist->FreeMask &= ~(1_u64 << slidx);
  673. return source;
  674. }
  675. void FreeSource(ALCcontext *context, ALsource *source)
  676. {
  677. context->mSourceNames.erase(source->id);
  678. const ALuint id{source->id - 1};
  679. const size_t lidx{id >> 6};
  680. const ALuint slidx{id & 0x3f};
  681. if(Voice *voice{GetSourceVoice(source, context)})
  682. {
  683. VoiceChange *vchg{GetVoiceChanger(context)};
  684. voice->mPendingChange.store(true, std::memory_order_relaxed);
  685. vchg->mVoice = voice;
  686. vchg->mSourceID = source->id;
  687. vchg->mState = VChangeState::Stop;
  688. SendVoiceChanges(context, vchg);
  689. }
  690. std::destroy_at(source);
  691. context->mSourceList[lidx].FreeMask |= 1_u64 << slidx;
  692. context->mNumSources--;
  693. }
  694. inline ALsource *LookupSource(ALCcontext *context, ALuint id) noexcept
  695. {
  696. const size_t lidx{(id-1) >> 6};
  697. const ALuint slidx{(id-1) & 0x3f};
  698. if(lidx >= context->mSourceList.size()) UNLIKELY
  699. return nullptr;
  700. SourceSubList &sublist{context->mSourceList[lidx]};
  701. if(sublist.FreeMask & (1_u64 << slidx)) UNLIKELY
  702. return nullptr;
  703. return al::to_address(sublist.Sources->begin() + slidx);
  704. }
  705. auto LookupBuffer = [](al::Device *device, auto id) noexcept -> ALbuffer*
  706. {
  707. const auto lidx{(id-1) >> 6};
  708. const auto slidx{(id-1) & 0x3f};
  709. if(lidx >= device->BufferList.size()) UNLIKELY
  710. return nullptr;
  711. BufferSubList &sublist = device->BufferList[static_cast<size_t>(lidx)];
  712. if(sublist.FreeMask & (1_u64 << slidx)) UNLIKELY
  713. return nullptr;
  714. return al::to_address(sublist.Buffers->begin() + static_cast<size_t>(slidx));
  715. };
  716. auto LookupFilter = [](al::Device *device, auto id) noexcept -> ALfilter*
  717. {
  718. const auto lidx{(id-1) >> 6};
  719. const auto slidx{(id-1) & 0x3f};
  720. if(lidx >= device->FilterList.size()) UNLIKELY
  721. return nullptr;
  722. FilterSubList &sublist = device->FilterList[static_cast<size_t>(lidx)];
  723. if(sublist.FreeMask & (1_u64 << slidx)) UNLIKELY
  724. return nullptr;
  725. return al::to_address(sublist.Filters->begin() + static_cast<size_t>(slidx));
  726. };
  727. auto LookupEffectSlot = [](ALCcontext *context, auto id) noexcept -> ALeffectslot*
  728. {
  729. const auto lidx{(id-1) >> 6};
  730. const auto slidx{(id-1) & 0x3f};
  731. if(lidx >= context->mEffectSlotList.size()) UNLIKELY
  732. return nullptr;
  733. EffectSlotSubList &sublist{context->mEffectSlotList[static_cast<size_t>(lidx)]};
  734. if(sublist.FreeMask & (1_u64 << slidx)) UNLIKELY
  735. return nullptr;
  736. return al::to_address(sublist.EffectSlots->begin() + static_cast<size_t>(slidx));
  737. };
  738. auto StereoModeFromEnum = [](auto mode) noexcept -> std::optional<SourceStereo>
  739. {
  740. switch(mode)
  741. {
  742. case AL_NORMAL_SOFT: return SourceStereo::Normal;
  743. case AL_SUPER_STEREO_SOFT: return SourceStereo::Enhanced;
  744. }
  745. return std::nullopt;
  746. };
  747. ALenum EnumFromStereoMode(SourceStereo mode)
  748. {
  749. switch(mode)
  750. {
  751. case SourceStereo::Normal: return AL_NORMAL_SOFT;
  752. case SourceStereo::Enhanced: return AL_SUPER_STEREO_SOFT;
  753. }
  754. throw std::runtime_error{"Invalid SourceStereo: "+std::to_string(int(mode))};
  755. }
  756. auto SpatializeModeFromEnum = [](auto mode) noexcept -> std::optional<SpatializeMode>
  757. {
  758. switch(mode)
  759. {
  760. case AL_FALSE: return SpatializeMode::Off;
  761. case AL_TRUE: return SpatializeMode::On;
  762. case AL_AUTO_SOFT: return SpatializeMode::Auto;
  763. }
  764. return std::nullopt;
  765. };
  766. ALenum EnumFromSpatializeMode(SpatializeMode mode)
  767. {
  768. switch(mode)
  769. {
  770. case SpatializeMode::Off: return AL_FALSE;
  771. case SpatializeMode::On: return AL_TRUE;
  772. case SpatializeMode::Auto: return AL_AUTO_SOFT;
  773. }
  774. throw std::runtime_error{fmt::format("Invalid SpatializeMode: {}",
  775. int{al::to_underlying(mode)})};
  776. }
  777. auto DirectModeFromEnum = [](auto mode) noexcept -> std::optional<DirectMode>
  778. {
  779. switch(mode)
  780. {
  781. case AL_FALSE: return DirectMode::Off;
  782. case AL_DROP_UNMATCHED_SOFT: return DirectMode::DropMismatch;
  783. case AL_REMIX_UNMATCHED_SOFT: return DirectMode::RemixMismatch;
  784. }
  785. return std::nullopt;
  786. };
  787. ALenum EnumFromDirectMode(DirectMode mode)
  788. {
  789. switch(mode)
  790. {
  791. case DirectMode::Off: return AL_FALSE;
  792. case DirectMode::DropMismatch: return AL_DROP_UNMATCHED_SOFT;
  793. case DirectMode::RemixMismatch: return AL_REMIX_UNMATCHED_SOFT;
  794. }
  795. throw std::runtime_error{fmt::format("Invalid DirectMode: {}", int{al::to_underlying(mode)})};
  796. }
  797. auto DistanceModelFromALenum = [](auto model) noexcept -> std::optional<DistanceModel>
  798. {
  799. switch(model)
  800. {
  801. case AL_NONE: return DistanceModel::Disable;
  802. case AL_INVERSE_DISTANCE: return DistanceModel::Inverse;
  803. case AL_INVERSE_DISTANCE_CLAMPED: return DistanceModel::InverseClamped;
  804. case AL_LINEAR_DISTANCE: return DistanceModel::Linear;
  805. case AL_LINEAR_DISTANCE_CLAMPED: return DistanceModel::LinearClamped;
  806. case AL_EXPONENT_DISTANCE: return DistanceModel::Exponent;
  807. case AL_EXPONENT_DISTANCE_CLAMPED: return DistanceModel::ExponentClamped;
  808. }
  809. return std::nullopt;
  810. };
  811. ALenum ALenumFromDistanceModel(DistanceModel model)
  812. {
  813. switch(model)
  814. {
  815. case DistanceModel::Disable: return AL_NONE;
  816. case DistanceModel::Inverse: return AL_INVERSE_DISTANCE;
  817. case DistanceModel::InverseClamped: return AL_INVERSE_DISTANCE_CLAMPED;
  818. case DistanceModel::Linear: return AL_LINEAR_DISTANCE;
  819. case DistanceModel::LinearClamped: return AL_LINEAR_DISTANCE_CLAMPED;
  820. case DistanceModel::Exponent: return AL_EXPONENT_DISTANCE;
  821. case DistanceModel::ExponentClamped: return AL_EXPONENT_DISTANCE_CLAMPED;
  822. }
  823. throw std::runtime_error{fmt::format("Unexpected distance model: {}",
  824. int{al::to_underlying(model)})};
  825. }
  826. enum SourceProp : ALenum {
  827. srcPitch = AL_PITCH,
  828. srcGain = AL_GAIN,
  829. srcMinGain = AL_MIN_GAIN,
  830. srcMaxGain = AL_MAX_GAIN,
  831. srcMaxDistance = AL_MAX_DISTANCE,
  832. srcRolloffFactor = AL_ROLLOFF_FACTOR,
  833. srcDopplerFactor = AL_DOPPLER_FACTOR,
  834. srcConeOuterGain = AL_CONE_OUTER_GAIN,
  835. srcSecOffset = AL_SEC_OFFSET,
  836. srcSampleOffset = AL_SAMPLE_OFFSET,
  837. srcByteOffset = AL_BYTE_OFFSET,
  838. srcConeInnerAngle = AL_CONE_INNER_ANGLE,
  839. srcConeOuterAngle = AL_CONE_OUTER_ANGLE,
  840. srcRefDistance = AL_REFERENCE_DISTANCE,
  841. srcPosition = AL_POSITION,
  842. srcVelocity = AL_VELOCITY,
  843. srcDirection = AL_DIRECTION,
  844. srcSourceRelative = AL_SOURCE_RELATIVE,
  845. srcLooping = AL_LOOPING,
  846. srcBuffer = AL_BUFFER,
  847. srcSourceState = AL_SOURCE_STATE,
  848. srcBuffersQueued = AL_BUFFERS_QUEUED,
  849. srcBuffersProcessed = AL_BUFFERS_PROCESSED,
  850. srcSourceType = AL_SOURCE_TYPE,
  851. /* ALC_EXT_EFX */
  852. srcConeOuterGainHF = AL_CONE_OUTER_GAINHF,
  853. srcAirAbsorptionFactor = AL_AIR_ABSORPTION_FACTOR,
  854. srcRoomRolloffFactor = AL_ROOM_ROLLOFF_FACTOR,
  855. srcDirectFilterGainHFAuto = AL_DIRECT_FILTER_GAINHF_AUTO,
  856. srcAuxSendFilterGainAuto = AL_AUXILIARY_SEND_FILTER_GAIN_AUTO,
  857. srcAuxSendFilterGainHFAuto = AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO,
  858. srcDirectFilter = AL_DIRECT_FILTER,
  859. srcAuxSendFilter = AL_AUXILIARY_SEND_FILTER,
  860. /* AL_SOFT_direct_channels */
  861. srcDirectChannelsSOFT = AL_DIRECT_CHANNELS_SOFT,
  862. /* AL_EXT_source_distance_model */
  863. srcDistanceModel = AL_DISTANCE_MODEL,
  864. /* AL_SOFT_source_latency */
  865. srcSampleOffsetLatencySOFT = AL_SAMPLE_OFFSET_LATENCY_SOFT,
  866. srcSecOffsetLatencySOFT = AL_SEC_OFFSET_LATENCY_SOFT,
  867. /* AL_EXT_STEREO_ANGLES */
  868. srcAngles = AL_STEREO_ANGLES,
  869. /* AL_EXT_SOURCE_RADIUS */
  870. srcRadius = AL_SOURCE_RADIUS,
  871. /* AL_EXT_BFORMAT */
  872. srcOrientation = AL_ORIENTATION,
  873. /* AL_SOFT_source_length */
  874. srcByteLength = AL_BYTE_LENGTH_SOFT,
  875. srcSampleLength = AL_SAMPLE_LENGTH_SOFT,
  876. srcSecLength = AL_SEC_LENGTH_SOFT,
  877. /* AL_SOFT_source_resampler */
  878. srcResampler = AL_SOURCE_RESAMPLER_SOFT,
  879. /* AL_SOFT_source_spatialize */
  880. srcSpatialize = AL_SOURCE_SPATIALIZE_SOFT,
  881. /* ALC_SOFT_device_clock */
  882. srcSampleOffsetClockSOFT = AL_SAMPLE_OFFSET_CLOCK_SOFT,
  883. srcSecOffsetClockSOFT = AL_SEC_OFFSET_CLOCK_SOFT,
  884. /* AL_SOFT_UHJ */
  885. srcStereoMode = AL_STEREO_MODE_SOFT,
  886. srcSuperStereoWidth = AL_SUPER_STEREO_WIDTH_SOFT,
  887. /* AL_SOFT_buffer_sub_data */
  888. srcByteRWOffsetsSOFT = AL_BYTE_RW_OFFSETS_SOFT,
  889. srcSampleRWOffsetsSOFT = AL_SAMPLE_RW_OFFSETS_SOFT,
  890. /* AL_SOFT_source_panning */
  891. srcPanningEnabledSOFT = AL_PANNING_ENABLED_SOFT,
  892. srcPanSOFT = AL_PAN_SOFT,
  893. };
  894. constexpr ALuint IntValsByProp(ALenum prop)
  895. {
  896. switch(static_cast<SourceProp>(prop))
  897. {
  898. case AL_SOURCE_STATE:
  899. case AL_SOURCE_TYPE:
  900. case AL_BUFFERS_QUEUED:
  901. case AL_BUFFERS_PROCESSED:
  902. case AL_BYTE_LENGTH_SOFT:
  903. case AL_SAMPLE_LENGTH_SOFT:
  904. case AL_SOURCE_RELATIVE:
  905. case AL_LOOPING:
  906. case AL_BUFFER:
  907. case AL_SAMPLE_OFFSET:
  908. case AL_BYTE_OFFSET:
  909. case AL_DIRECT_FILTER:
  910. case AL_DIRECT_FILTER_GAINHF_AUTO:
  911. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  912. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  913. case AL_DIRECT_CHANNELS_SOFT:
  914. case AL_DISTANCE_MODEL:
  915. case AL_SOURCE_RESAMPLER_SOFT:
  916. case AL_SOURCE_SPATIALIZE_SOFT:
  917. case AL_STEREO_MODE_SOFT:
  918. case AL_PANNING_ENABLED_SOFT:
  919. case AL_PAN_SOFT:
  920. return 1;
  921. case AL_SOURCE_RADIUS: /*AL_BYTE_RW_OFFSETS_SOFT:*/
  922. if(sBufferSubDataCompat)
  923. return 2;
  924. /*fall-through*/
  925. case AL_CONE_INNER_ANGLE:
  926. case AL_CONE_OUTER_ANGLE:
  927. case AL_PITCH:
  928. case AL_GAIN:
  929. case AL_MIN_GAIN:
  930. case AL_MAX_GAIN:
  931. case AL_REFERENCE_DISTANCE:
  932. case AL_ROLLOFF_FACTOR:
  933. case AL_CONE_OUTER_GAIN:
  934. case AL_MAX_DISTANCE:
  935. case AL_SEC_OFFSET:
  936. case AL_DOPPLER_FACTOR:
  937. case AL_CONE_OUTER_GAINHF:
  938. case AL_AIR_ABSORPTION_FACTOR:
  939. case AL_ROOM_ROLLOFF_FACTOR:
  940. case AL_SEC_LENGTH_SOFT:
  941. case AL_SUPER_STEREO_WIDTH_SOFT:
  942. return 1; /* 1x float */
  943. case AL_SAMPLE_RW_OFFSETS_SOFT:
  944. if(sBufferSubDataCompat)
  945. return 2;
  946. break;
  947. case AL_AUXILIARY_SEND_FILTER:
  948. return 3;
  949. case AL_POSITION:
  950. case AL_VELOCITY:
  951. case AL_DIRECTION:
  952. return 3; /* 3x float */
  953. case AL_ORIENTATION:
  954. return 6; /* 6x float */
  955. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  956. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  957. case AL_STEREO_ANGLES:
  958. break; /* i64 only */
  959. case AL_SEC_OFFSET_LATENCY_SOFT:
  960. case AL_SEC_OFFSET_CLOCK_SOFT:
  961. break; /* double only */
  962. }
  963. return 0;
  964. }
  965. constexpr ALuint Int64ValsByProp(ALenum prop)
  966. {
  967. switch(static_cast<SourceProp>(prop))
  968. {
  969. case AL_SOURCE_STATE:
  970. case AL_SOURCE_TYPE:
  971. case AL_BUFFERS_QUEUED:
  972. case AL_BUFFERS_PROCESSED:
  973. case AL_BYTE_LENGTH_SOFT:
  974. case AL_SAMPLE_LENGTH_SOFT:
  975. case AL_SOURCE_RELATIVE:
  976. case AL_LOOPING:
  977. case AL_BUFFER:
  978. case AL_SAMPLE_OFFSET:
  979. case AL_BYTE_OFFSET:
  980. case AL_DIRECT_FILTER:
  981. case AL_DIRECT_FILTER_GAINHF_AUTO:
  982. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  983. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  984. case AL_DIRECT_CHANNELS_SOFT:
  985. case AL_DISTANCE_MODEL:
  986. case AL_SOURCE_RESAMPLER_SOFT:
  987. case AL_SOURCE_SPATIALIZE_SOFT:
  988. case AL_STEREO_MODE_SOFT:
  989. case AL_PANNING_ENABLED_SOFT:
  990. case AL_PAN_SOFT:
  991. return 1;
  992. case AL_SOURCE_RADIUS: /*AL_BYTE_RW_OFFSETS_SOFT:*/
  993. if(sBufferSubDataCompat)
  994. return 2;
  995. /*fall-through*/
  996. case AL_CONE_INNER_ANGLE:
  997. case AL_CONE_OUTER_ANGLE:
  998. case AL_PITCH:
  999. case AL_GAIN:
  1000. case AL_MIN_GAIN:
  1001. case AL_MAX_GAIN:
  1002. case AL_REFERENCE_DISTANCE:
  1003. case AL_ROLLOFF_FACTOR:
  1004. case AL_CONE_OUTER_GAIN:
  1005. case AL_MAX_DISTANCE:
  1006. case AL_SEC_OFFSET:
  1007. case AL_DOPPLER_FACTOR:
  1008. case AL_CONE_OUTER_GAINHF:
  1009. case AL_AIR_ABSORPTION_FACTOR:
  1010. case AL_ROOM_ROLLOFF_FACTOR:
  1011. case AL_SEC_LENGTH_SOFT:
  1012. case AL_SUPER_STEREO_WIDTH_SOFT:
  1013. return 1; /* 1x float */
  1014. case AL_SAMPLE_RW_OFFSETS_SOFT:
  1015. if(sBufferSubDataCompat)
  1016. return 2;
  1017. break;
  1018. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1019. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1020. case AL_STEREO_ANGLES:
  1021. return 2;
  1022. case AL_AUXILIARY_SEND_FILTER:
  1023. return 3;
  1024. case AL_POSITION:
  1025. case AL_VELOCITY:
  1026. case AL_DIRECTION:
  1027. return 3; /* 3x float */
  1028. case AL_ORIENTATION:
  1029. return 6; /* 6x float */
  1030. case AL_SEC_OFFSET_LATENCY_SOFT:
  1031. case AL_SEC_OFFSET_CLOCK_SOFT:
  1032. break; /* double only */
  1033. }
  1034. return 0;
  1035. }
  1036. constexpr ALuint FloatValsByProp(ALenum prop)
  1037. {
  1038. switch(static_cast<SourceProp>(prop))
  1039. {
  1040. case AL_PITCH:
  1041. case AL_GAIN:
  1042. case AL_MIN_GAIN:
  1043. case AL_MAX_GAIN:
  1044. case AL_MAX_DISTANCE:
  1045. case AL_ROLLOFF_FACTOR:
  1046. case AL_DOPPLER_FACTOR:
  1047. case AL_CONE_OUTER_GAIN:
  1048. case AL_SEC_OFFSET:
  1049. case AL_SAMPLE_OFFSET:
  1050. case AL_BYTE_OFFSET:
  1051. case AL_CONE_INNER_ANGLE:
  1052. case AL_CONE_OUTER_ANGLE:
  1053. case AL_REFERENCE_DISTANCE:
  1054. case AL_CONE_OUTER_GAINHF:
  1055. case AL_AIR_ABSORPTION_FACTOR:
  1056. case AL_ROOM_ROLLOFF_FACTOR:
  1057. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1058. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1059. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1060. case AL_DIRECT_CHANNELS_SOFT:
  1061. case AL_DISTANCE_MODEL:
  1062. case AL_SOURCE_RELATIVE:
  1063. case AL_LOOPING:
  1064. case AL_SOURCE_STATE:
  1065. case AL_BUFFERS_QUEUED:
  1066. case AL_BUFFERS_PROCESSED:
  1067. case AL_SOURCE_TYPE:
  1068. case AL_SOURCE_RESAMPLER_SOFT:
  1069. case AL_SOURCE_SPATIALIZE_SOFT:
  1070. case AL_BYTE_LENGTH_SOFT:
  1071. case AL_SAMPLE_LENGTH_SOFT:
  1072. case AL_SEC_LENGTH_SOFT:
  1073. case AL_STEREO_MODE_SOFT:
  1074. case AL_SUPER_STEREO_WIDTH_SOFT:
  1075. case AL_PANNING_ENABLED_SOFT:
  1076. case AL_PAN_SOFT:
  1077. return 1;
  1078. case AL_SOURCE_RADIUS: /*AL_BYTE_RW_OFFSETS_SOFT:*/
  1079. if(!sBufferSubDataCompat)
  1080. return 1;
  1081. /*fall-through*/
  1082. case AL_SAMPLE_RW_OFFSETS_SOFT:
  1083. break;
  1084. case AL_STEREO_ANGLES:
  1085. return 2;
  1086. case AL_POSITION:
  1087. case AL_VELOCITY:
  1088. case AL_DIRECTION:
  1089. return 3;
  1090. case AL_ORIENTATION:
  1091. return 6;
  1092. case AL_SEC_OFFSET_LATENCY_SOFT:
  1093. case AL_SEC_OFFSET_CLOCK_SOFT:
  1094. break; /* Double only */
  1095. case AL_BUFFER:
  1096. case AL_DIRECT_FILTER:
  1097. case AL_AUXILIARY_SEND_FILTER:
  1098. break; /* i/i64 only */
  1099. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1100. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1101. break; /* i64 only */
  1102. }
  1103. return 0;
  1104. }
  1105. constexpr ALuint DoubleValsByProp(ALenum prop)
  1106. {
  1107. switch(static_cast<SourceProp>(prop))
  1108. {
  1109. case AL_PITCH:
  1110. case AL_GAIN:
  1111. case AL_MIN_GAIN:
  1112. case AL_MAX_GAIN:
  1113. case AL_MAX_DISTANCE:
  1114. case AL_ROLLOFF_FACTOR:
  1115. case AL_DOPPLER_FACTOR:
  1116. case AL_CONE_OUTER_GAIN:
  1117. case AL_SEC_OFFSET:
  1118. case AL_SAMPLE_OFFSET:
  1119. case AL_BYTE_OFFSET:
  1120. case AL_CONE_INNER_ANGLE:
  1121. case AL_CONE_OUTER_ANGLE:
  1122. case AL_REFERENCE_DISTANCE:
  1123. case AL_CONE_OUTER_GAINHF:
  1124. case AL_AIR_ABSORPTION_FACTOR:
  1125. case AL_ROOM_ROLLOFF_FACTOR:
  1126. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1127. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1128. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1129. case AL_DIRECT_CHANNELS_SOFT:
  1130. case AL_DISTANCE_MODEL:
  1131. case AL_SOURCE_RELATIVE:
  1132. case AL_LOOPING:
  1133. case AL_SOURCE_STATE:
  1134. case AL_BUFFERS_QUEUED:
  1135. case AL_BUFFERS_PROCESSED:
  1136. case AL_SOURCE_TYPE:
  1137. case AL_SOURCE_RESAMPLER_SOFT:
  1138. case AL_SOURCE_SPATIALIZE_SOFT:
  1139. case AL_BYTE_LENGTH_SOFT:
  1140. case AL_SAMPLE_LENGTH_SOFT:
  1141. case AL_SEC_LENGTH_SOFT:
  1142. case AL_STEREO_MODE_SOFT:
  1143. case AL_SUPER_STEREO_WIDTH_SOFT:
  1144. case AL_PANNING_ENABLED_SOFT:
  1145. case AL_PAN_SOFT:
  1146. return 1;
  1147. case AL_SOURCE_RADIUS: /*AL_BYTE_RW_OFFSETS_SOFT:*/
  1148. if(!sBufferSubDataCompat)
  1149. return 1;
  1150. /*fall-through*/
  1151. case AL_SAMPLE_RW_OFFSETS_SOFT:
  1152. break;
  1153. case AL_SEC_OFFSET_LATENCY_SOFT:
  1154. case AL_SEC_OFFSET_CLOCK_SOFT:
  1155. case AL_STEREO_ANGLES:
  1156. return 2;
  1157. case AL_POSITION:
  1158. case AL_VELOCITY:
  1159. case AL_DIRECTION:
  1160. return 3;
  1161. case AL_ORIENTATION:
  1162. return 6;
  1163. case AL_BUFFER:
  1164. case AL_DIRECT_FILTER:
  1165. case AL_AUXILIARY_SEND_FILTER:
  1166. break; /* i/i64 only */
  1167. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1168. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1169. break; /* i64 only */
  1170. }
  1171. return 0;
  1172. }
  1173. void UpdateSourceProps(ALsource *source, ALCcontext *context)
  1174. {
  1175. if(!context->mDeferUpdates)
  1176. {
  1177. if(Voice *voice{GetSourceVoice(source, context)})
  1178. {
  1179. UpdateSourceProps(source, voice, context);
  1180. return;
  1181. }
  1182. }
  1183. source->mPropsDirty = true;
  1184. }
  1185. #if ALSOFT_EAX
  1186. void CommitAndUpdateSourceProps(ALsource *source, ALCcontext *context)
  1187. {
  1188. if(!context->mDeferUpdates)
  1189. {
  1190. if(context->hasEax())
  1191. source->eaxCommit();
  1192. if(Voice *voice{GetSourceVoice(source, context)})
  1193. {
  1194. UpdateSourceProps(source, voice, context);
  1195. return;
  1196. }
  1197. }
  1198. source->mPropsDirty = true;
  1199. }
  1200. #else
  1201. inline void CommitAndUpdateSourceProps(ALsource *source, ALCcontext *context)
  1202. { UpdateSourceProps(source, context); }
  1203. #endif
  1204. template<typename T>
  1205. auto PropTypeName() -> std::string_view = delete;
  1206. template<>
  1207. auto PropTypeName<ALint>() -> std::string_view { return "integer"sv; }
  1208. template<>
  1209. auto PropTypeName<ALint64SOFT>() -> std::string_view { return "int64"sv; }
  1210. template<>
  1211. auto PropTypeName<ALfloat>() -> std::string_view { return "float"sv; }
  1212. template<>
  1213. auto PropTypeName<ALdouble>() -> std::string_view { return "double"sv; }
  1214. /**
  1215. * Returns a pair of lambdas to check the following setter.
  1216. *
  1217. * The first lambda checks the size of the span is valid for the required size,
  1218. * throwing a context error if it fails.
  1219. *
  1220. * The second lambda tests the validity of the value check, throwing a context
  1221. * error if it failed.
  1222. */
  1223. template<typename T, typename U>
  1224. struct PairStruct { T First; U Second; };
  1225. template<typename T, typename U>
  1226. PairStruct(T,U) -> PairStruct<T,U>;
  1227. template<typename T, size_t N>
  1228. auto GetCheckers(ALCcontext *context, const SourceProp prop, const al::span<T,N> values)
  1229. {
  1230. return PairStruct{
  1231. [=](size_t expect) -> void
  1232. {
  1233. if(values.size() == expect) return;
  1234. context->throw_error(AL_INVALID_ENUM, "Property {:#04x} expects {} value{}, got {}",
  1235. as_unsigned(al::to_underlying(prop)), expect, (expect==1) ? "" : "s",
  1236. values.size());
  1237. },
  1238. [context](bool passed) -> void
  1239. {
  1240. if(passed) return;
  1241. context->throw_error(AL_INVALID_VALUE, "Value out of range");
  1242. }
  1243. };
  1244. }
  1245. template<typename T>
  1246. NOINLINE void SetProperty(ALsource *const Source, ALCcontext *const Context, const SourceProp prop,
  1247. const al::span<const T> values)
  1248. {
  1249. auto [CheckSize, CheckValue] = GetCheckers(Context, prop, values);
  1250. auto *device = Context->mALDevice.get();
  1251. switch(prop)
  1252. {
  1253. case AL_SOURCE_STATE:
  1254. case AL_SOURCE_TYPE:
  1255. case AL_BUFFERS_QUEUED:
  1256. case AL_BUFFERS_PROCESSED:
  1257. if constexpr(std::is_integral_v<T>)
  1258. {
  1259. /* Query only */
  1260. Context->throw_error(AL_INVALID_OPERATION,
  1261. "Setting read-only source property {:#04x}", as_unsigned(al::to_underlying(prop)));
  1262. }
  1263. break;
  1264. case AL_BYTE_LENGTH_SOFT:
  1265. case AL_SAMPLE_LENGTH_SOFT:
  1266. case AL_SEC_LENGTH_SOFT:
  1267. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1268. case AL_SEC_OFFSET_LATENCY_SOFT:
  1269. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1270. case AL_SEC_OFFSET_CLOCK_SOFT:
  1271. /* Query only */
  1272. Context->throw_error(AL_INVALID_OPERATION, "Setting read-only source property {:#04x}",
  1273. as_unsigned(al::to_underlying(prop)));
  1274. case AL_PITCH:
  1275. CheckSize(1);
  1276. if constexpr(std::is_floating_point_v<T>)
  1277. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1278. else
  1279. CheckValue(values[0] >= T{0});
  1280. Source->Pitch = static_cast<float>(values[0]);
  1281. return UpdateSourceProps(Source, Context);
  1282. case AL_CONE_INNER_ANGLE:
  1283. CheckSize(1);
  1284. CheckValue(values[0] >= T{0} && values[0] <= T{360});
  1285. Source->InnerAngle = static_cast<float>(values[0]);
  1286. return CommitAndUpdateSourceProps(Source, Context);
  1287. case AL_CONE_OUTER_ANGLE:
  1288. CheckSize(1);
  1289. CheckValue(values[0] >= T{0} && values[0] <= T{360});
  1290. Source->OuterAngle = static_cast<float>(values[0]);
  1291. return CommitAndUpdateSourceProps(Source, Context);
  1292. case AL_GAIN:
  1293. CheckSize(1);
  1294. if constexpr(std::is_floating_point_v<T>)
  1295. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1296. else
  1297. CheckValue(values[0] >= T{0});
  1298. Source->Gain = static_cast<float>(values[0]);
  1299. return UpdateSourceProps(Source, Context);
  1300. case AL_MAX_DISTANCE:
  1301. CheckSize(1);
  1302. if constexpr(std::is_floating_point_v<T>)
  1303. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1304. else
  1305. CheckValue(values[0] >= T{0});
  1306. Source->MaxDistance = static_cast<float>(values[0]);
  1307. return CommitAndUpdateSourceProps(Source, Context);
  1308. case AL_ROLLOFF_FACTOR:
  1309. CheckSize(1);
  1310. if constexpr(std::is_floating_point_v<T>)
  1311. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1312. else
  1313. CheckValue(values[0] >= T{0});
  1314. Source->RolloffFactor = static_cast<float>(values[0]);
  1315. return CommitAndUpdateSourceProps(Source, Context);
  1316. case AL_REFERENCE_DISTANCE:
  1317. CheckSize(1);
  1318. if constexpr(std::is_floating_point_v<T>)
  1319. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1320. else
  1321. CheckValue(values[0] >= T{0});
  1322. Source->RefDistance = static_cast<float>(values[0]);
  1323. return CommitAndUpdateSourceProps(Source, Context);
  1324. case AL_MIN_GAIN:
  1325. CheckSize(1);
  1326. if constexpr(std::is_floating_point_v<T>)
  1327. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1328. else
  1329. CheckValue(values[0] >= T{0});
  1330. Source->MinGain = static_cast<float>(values[0]);
  1331. return UpdateSourceProps(Source, Context);
  1332. case AL_MAX_GAIN:
  1333. CheckSize(1);
  1334. if constexpr(std::is_floating_point_v<T>)
  1335. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1336. else
  1337. CheckValue(values[0] >= T{0});
  1338. Source->MaxGain = static_cast<float>(values[0]);
  1339. return UpdateSourceProps(Source, Context);
  1340. case AL_CONE_OUTER_GAIN:
  1341. CheckSize(1);
  1342. CheckValue(values[0] >= T{0} && values[0] <= T{1});
  1343. Source->OuterGain = static_cast<float>(values[0]);
  1344. return UpdateSourceProps(Source, Context);
  1345. case AL_CONE_OUTER_GAINHF:
  1346. CheckSize(1);
  1347. CheckValue(values[0] >= T{0} && values[0] <= T{1});
  1348. Source->OuterGainHF = static_cast<float>(values[0]);
  1349. return UpdateSourceProps(Source, Context);
  1350. case AL_AIR_ABSORPTION_FACTOR:
  1351. CheckSize(1);
  1352. CheckValue(values[0] >= T{0} && values[0] <= T{10});
  1353. Source->AirAbsorptionFactor = static_cast<float>(values[0]);
  1354. return UpdateSourceProps(Source, Context);
  1355. case AL_ROOM_ROLLOFF_FACTOR:
  1356. CheckSize(1);
  1357. CheckValue(values[0] >= T{0} && values[0] <= T{1});
  1358. Source->RoomRolloffFactor = static_cast<float>(values[0]);
  1359. return UpdateSourceProps(Source, Context);
  1360. case AL_DOPPLER_FACTOR:
  1361. CheckSize(1);
  1362. CheckValue(values[0] >= T{0} && values[0] <= T{1});
  1363. Source->DopplerFactor = static_cast<float>(values[0]);
  1364. return UpdateSourceProps(Source, Context);
  1365. case AL_SOURCE_RELATIVE:
  1366. if constexpr(std::is_integral_v<T>)
  1367. {
  1368. CheckSize(1);
  1369. CheckValue(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1370. Source->HeadRelative = values[0] != AL_FALSE;
  1371. return CommitAndUpdateSourceProps(Source, Context);
  1372. }
  1373. break;
  1374. case AL_LOOPING:
  1375. if constexpr(std::is_integral_v<T>)
  1376. {
  1377. CheckSize(1);
  1378. CheckValue(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1379. Source->Looping = values[0] != AL_FALSE;
  1380. if(Voice *voice{GetSourceVoice(Source, Context)})
  1381. {
  1382. if(Source->Looping)
  1383. voice->mLoopBuffer.store(&Source->mQueue.front(), std::memory_order_release);
  1384. else
  1385. voice->mLoopBuffer.store(nullptr, std::memory_order_release);
  1386. /* If the source is playing, wait for the current mix to finish
  1387. * to ensure it isn't currently looping back or reaching the
  1388. * end.
  1389. */
  1390. std::ignore = device->waitForMix();
  1391. }
  1392. return;
  1393. }
  1394. break;
  1395. case AL_BUFFER:
  1396. if constexpr(std::is_integral_v<T>)
  1397. {
  1398. CheckSize(1);
  1399. if(const ALenum state{GetSourceState(Source, GetSourceVoice(Source, Context))};
  1400. state == AL_PLAYING || state == AL_PAUSED)
  1401. Context->throw_error(AL_INVALID_OPERATION,
  1402. "Setting buffer on playing or paused source {}", Source->id);
  1403. std::deque<ALbufferQueueItem> oldlist;
  1404. if(values[0])
  1405. {
  1406. using UT = std::make_unsigned_t<T>;
  1407. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1408. ALbuffer *buffer{LookupBuffer(device, static_cast<UT>(values[0]))};
  1409. if(!buffer)
  1410. Context->throw_error(AL_INVALID_VALUE, "Invalid buffer ID {}", values[0]);
  1411. if(buffer->MappedAccess && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT))
  1412. Context->throw_error(AL_INVALID_OPERATION,
  1413. "Setting non-persistently mapped buffer {}", buffer->id);
  1414. if(buffer->mCallback && buffer->ref.load(std::memory_order_relaxed) != 0)
  1415. Context->throw_error(AL_INVALID_OPERATION,
  1416. "Setting already-set callback buffer {}", buffer->id);
  1417. /* Add the selected buffer to a one-item queue */
  1418. std::deque<ALbufferQueueItem> newlist;
  1419. newlist.emplace_back();
  1420. newlist.back().mCallback = buffer->mCallback;
  1421. newlist.back().mUserData = buffer->mUserData;
  1422. newlist.back().mBlockAlign = buffer->mBlockAlign;
  1423. newlist.back().mSampleLen = buffer->mSampleLen;
  1424. newlist.back().mLoopStart = buffer->mLoopStart;
  1425. newlist.back().mLoopEnd = buffer->mLoopEnd;
  1426. newlist.back().mSamples = buffer->mData;
  1427. newlist.back().mBuffer = buffer;
  1428. IncrementRef(buffer->ref);
  1429. /* Source is now Static */
  1430. Source->SourceType = AL_STATIC;
  1431. Source->mQueue.swap(oldlist);
  1432. Source->mQueue.swap(newlist);
  1433. }
  1434. else
  1435. {
  1436. /* Source is now Undetermined */
  1437. Source->SourceType = AL_UNDETERMINED;
  1438. Source->mQueue.swap(oldlist);
  1439. }
  1440. /* Delete all elements in the previous queue */
  1441. for(auto &item : oldlist)
  1442. {
  1443. if(ALbuffer *buffer{item.mBuffer})
  1444. DecrementRef(buffer->ref);
  1445. }
  1446. return;
  1447. }
  1448. break;
  1449. case AL_SEC_OFFSET:
  1450. case AL_SAMPLE_OFFSET:
  1451. case AL_BYTE_OFFSET:
  1452. CheckSize(1);
  1453. if constexpr(std::is_floating_point_v<T>)
  1454. CheckValue(std::isfinite(values[0]));
  1455. if(Voice *voice{GetSourceVoice(Source, Context)})
  1456. {
  1457. auto vpos = GetSampleOffset(Source->mQueue, prop, static_cast<double>(values[0]));
  1458. if(!vpos) Context->throw_error(AL_INVALID_VALUE, "Invalid offset");
  1459. if(SetVoiceOffset(voice, *vpos, Source, Context, Context->mALDevice.get()))
  1460. return;
  1461. }
  1462. Source->OffsetType = prop;
  1463. Source->Offset = static_cast<double>(values[0]);
  1464. return;
  1465. case AL_SAMPLE_RW_OFFSETS_SOFT:
  1466. if(sBufferSubDataCompat)
  1467. {
  1468. if constexpr(std::is_integral_v<T>)
  1469. {
  1470. /* Query only */
  1471. Context->throw_error(AL_INVALID_OPERATION,
  1472. "Setting read-only source property {:#04x}",
  1473. as_unsigned(al::to_underlying(prop)));
  1474. }
  1475. }
  1476. break;
  1477. case AL_SOURCE_RADIUS: /*AL_BYTE_RW_OFFSETS_SOFT:*/
  1478. if(sBufferSubDataCompat)
  1479. {
  1480. if constexpr(std::is_integral_v<T>)
  1481. {
  1482. /* Query only */
  1483. Context->throw_error(AL_INVALID_OPERATION,
  1484. "Setting read-only source property {:#04x}",
  1485. as_unsigned(al::to_underlying(prop)));
  1486. }
  1487. break;
  1488. }
  1489. CheckSize(1);
  1490. if constexpr(std::is_floating_point_v<T>)
  1491. CheckValue(values[0] >= T{0} && std::isfinite(static_cast<float>(values[0])));
  1492. else
  1493. CheckValue(values[0] >= T{0});
  1494. Source->Radius = static_cast<float>(values[0]);
  1495. return UpdateSourceProps(Source, Context);
  1496. case AL_SUPER_STEREO_WIDTH_SOFT:
  1497. CheckSize(1);
  1498. CheckValue(values[0] >= T{0} && values[0] <= T{1});
  1499. Source->EnhWidth = static_cast<float>(values[0]);
  1500. return UpdateSourceProps(Source, Context);
  1501. case AL_PANNING_ENABLED_SOFT:
  1502. CheckSize(1);
  1503. if(const ALenum state{GetSourceState(Source, GetSourceVoice(Source, Context))};
  1504. state == AL_PLAYING || state == AL_PAUSED)
  1505. Context->throw_error(AL_INVALID_OPERATION,
  1506. "Modifying panning enabled on playing or paused source {}", Source->id);
  1507. CheckValue(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1508. Source->mPanningEnabled = values[0] != AL_FALSE;
  1509. return UpdateSourceProps(Source, Context);
  1510. case AL_PAN_SOFT:
  1511. CheckSize(1);
  1512. CheckValue(values[0] >= T{-1} && values[0] <= T{1});
  1513. Source->mPan = static_cast<float>(values[0]);
  1514. return UpdateSourceProps(Source, Context);
  1515. case AL_STEREO_ANGLES:
  1516. CheckSize(2);
  1517. if constexpr(std::is_floating_point_v<T>)
  1518. CheckValue(std::isfinite(static_cast<float>(values[0]))
  1519. && std::isfinite(static_cast<float>(values[1])));
  1520. Source->StereoPan[0] = static_cast<float>(values[0]);
  1521. Source->StereoPan[1] = static_cast<float>(values[1]);
  1522. return UpdateSourceProps(Source, Context);
  1523. case AL_POSITION:
  1524. CheckSize(3);
  1525. if constexpr(std::is_floating_point_v<T>)
  1526. CheckValue(std::isfinite(static_cast<float>(values[0]))
  1527. && std::isfinite(static_cast<float>(values[1]))
  1528. && std::isfinite(static_cast<float>(values[2])));
  1529. Source->Position[0] = static_cast<float>(values[0]);
  1530. Source->Position[1] = static_cast<float>(values[1]);
  1531. Source->Position[2] = static_cast<float>(values[2]);
  1532. return CommitAndUpdateSourceProps(Source, Context);
  1533. case AL_VELOCITY:
  1534. CheckSize(3);
  1535. if constexpr(std::is_floating_point_v<T>)
  1536. CheckValue(std::isfinite(static_cast<float>(values[0]))
  1537. && std::isfinite(static_cast<float>(values[1]))
  1538. && std::isfinite(static_cast<float>(values[2])));
  1539. Source->Velocity[0] = static_cast<float>(values[0]);
  1540. Source->Velocity[1] = static_cast<float>(values[1]);
  1541. Source->Velocity[2] = static_cast<float>(values[2]);
  1542. return CommitAndUpdateSourceProps(Source, Context);
  1543. case AL_DIRECTION:
  1544. CheckSize(3);
  1545. if constexpr(std::is_floating_point_v<T>)
  1546. CheckValue(std::isfinite(static_cast<float>(values[0]))
  1547. && std::isfinite(static_cast<float>(values[1]))
  1548. && std::isfinite(static_cast<float>(values[2])));
  1549. Source->Direction[0] = static_cast<float>(values[0]);
  1550. Source->Direction[1] = static_cast<float>(values[1]);
  1551. Source->Direction[2] = static_cast<float>(values[2]);
  1552. return CommitAndUpdateSourceProps(Source, Context);
  1553. case AL_ORIENTATION:
  1554. CheckSize(6);
  1555. if constexpr(std::is_floating_point_v<T>)
  1556. CheckValue(std::isfinite(static_cast<float>(values[0]))
  1557. && std::isfinite(static_cast<float>(values[1]))
  1558. && std::isfinite(static_cast<float>(values[2]))
  1559. && std::isfinite(static_cast<float>(values[3]))
  1560. && std::isfinite(static_cast<float>(values[4]))
  1561. && std::isfinite(static_cast<float>(values[5])));
  1562. Source->OrientAt[0] = static_cast<float>(values[0]);
  1563. Source->OrientAt[1] = static_cast<float>(values[1]);
  1564. Source->OrientAt[2] = static_cast<float>(values[2]);
  1565. Source->OrientUp[0] = static_cast<float>(values[3]);
  1566. Source->OrientUp[1] = static_cast<float>(values[4]);
  1567. Source->OrientUp[2] = static_cast<float>(values[5]);
  1568. return UpdateSourceProps(Source, Context);
  1569. case AL_DIRECT_FILTER:
  1570. if constexpr(std::is_integral_v<T>)
  1571. {
  1572. CheckSize(1);
  1573. const auto filterid = static_cast<std::make_unsigned_t<T>>(values[0]);
  1574. if(values[0])
  1575. {
  1576. std::lock_guard<std::mutex> filterlock{device->FilterLock};
  1577. ALfilter *filter{LookupFilter(device, filterid)};
  1578. if(!filter)
  1579. Context->throw_error(AL_INVALID_VALUE, "Invalid filter ID {}", filterid);
  1580. Source->Direct.Gain = filter->Gain;
  1581. Source->Direct.GainHF = filter->GainHF;
  1582. Source->Direct.HFReference = filter->HFReference;
  1583. Source->Direct.GainLF = filter->GainLF;
  1584. Source->Direct.LFReference = filter->LFReference;
  1585. }
  1586. else
  1587. {
  1588. Source->Direct.Gain = 1.0f;
  1589. Source->Direct.GainHF = 1.0f;
  1590. Source->Direct.HFReference = LowPassFreqRef;
  1591. Source->Direct.GainLF = 1.0f;
  1592. Source->Direct.LFReference = HighPassFreqRef;
  1593. }
  1594. return UpdateSourceProps(Source, Context);
  1595. }
  1596. break;
  1597. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1598. if constexpr(std::is_integral_v<T>)
  1599. {
  1600. CheckSize(1);
  1601. CheckValue(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1602. Source->DryGainHFAuto = values[0] != AL_FALSE;
  1603. return UpdateSourceProps(Source, Context);
  1604. }
  1605. break;
  1606. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1607. if constexpr(std::is_integral_v<T>)
  1608. {
  1609. CheckSize(1);
  1610. CheckValue(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1611. Source->WetGainAuto = values[0] != AL_FALSE;
  1612. return UpdateSourceProps(Source, Context);
  1613. }
  1614. break;
  1615. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1616. if constexpr(std::is_integral_v<T>)
  1617. {
  1618. CheckSize(1);
  1619. CheckValue(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1620. Source->WetGainHFAuto = values[0] != AL_FALSE;
  1621. return UpdateSourceProps(Source, Context);
  1622. }
  1623. break;
  1624. case AL_DIRECT_CHANNELS_SOFT:
  1625. if constexpr(std::is_integral_v<T>)
  1626. {
  1627. CheckSize(1);
  1628. if(auto mode = DirectModeFromEnum(values[0]))
  1629. {
  1630. Source->DirectChannels = *mode;
  1631. return UpdateSourceProps(Source, Context);
  1632. }
  1633. Context->throw_error(AL_INVALID_VALUE, "Invalid direct channels mode: {:#x}",
  1634. as_unsigned(values[0]));
  1635. }
  1636. break;
  1637. case AL_DISTANCE_MODEL:
  1638. if constexpr(std::is_integral_v<T>)
  1639. {
  1640. CheckSize(1);
  1641. if(auto model = DistanceModelFromALenum(values[0]))
  1642. {
  1643. Source->mDistanceModel = *model;
  1644. if(Context->mSourceDistanceModel)
  1645. UpdateSourceProps(Source, Context);
  1646. return;
  1647. }
  1648. Context->throw_error(AL_INVALID_VALUE, "Invalid distance model: {:#x}",
  1649. as_unsigned(values[0]));
  1650. }
  1651. break;
  1652. case AL_SOURCE_RESAMPLER_SOFT:
  1653. if constexpr(std::is_integral_v<T>)
  1654. {
  1655. CheckSize(1);
  1656. CheckValue(values[0] >= 0 && values[0] <= al::to_underlying(Resampler::Max));
  1657. Source->mResampler = static_cast<Resampler>(values[0]);
  1658. return UpdateSourceProps(Source, Context);
  1659. }
  1660. break;
  1661. case AL_SOURCE_SPATIALIZE_SOFT:
  1662. if constexpr(std::is_integral_v<T>)
  1663. {
  1664. CheckSize(1);
  1665. if(auto mode = SpatializeModeFromEnum(values[0]))
  1666. {
  1667. Source->mSpatialize = *mode;
  1668. return UpdateSourceProps(Source, Context);
  1669. }
  1670. Context->throw_error(AL_INVALID_VALUE, "Invalid source spatialize mode: {}",
  1671. values[0]);
  1672. }
  1673. break;
  1674. case AL_STEREO_MODE_SOFT:
  1675. if constexpr(std::is_integral_v<T>)
  1676. {
  1677. CheckSize(1);
  1678. if(const ALenum state{GetSourceState(Source, GetSourceVoice(Source, Context))};
  1679. state == AL_PLAYING || state == AL_PAUSED)
  1680. Context->throw_error(AL_INVALID_OPERATION,
  1681. "Modifying stereo mode on playing or paused source {}", Source->id);
  1682. if(auto mode = StereoModeFromEnum(values[0]))
  1683. {
  1684. Source->mStereoMode = *mode;
  1685. return;
  1686. }
  1687. Context->throw_error(AL_INVALID_VALUE, "Invalid stereo mode: {:#x}",
  1688. as_unsigned(values[0]));
  1689. }
  1690. break;
  1691. case AL_AUXILIARY_SEND_FILTER:
  1692. if constexpr(std::is_integral_v<T>)
  1693. {
  1694. CheckSize(3);
  1695. const auto slotid = static_cast<std::make_unsigned_t<T>>(values[0]);
  1696. const auto sendidx = static_cast<std::make_unsigned_t<T>>(values[1]);
  1697. const auto filterid = static_cast<std::make_unsigned_t<T>>(values[2]);
  1698. std::unique_lock slotlock{Context->mEffectSlotLock};
  1699. ALeffectslot *slot{};
  1700. if(values[0])
  1701. {
  1702. slot = LookupEffectSlot(Context, slotid);
  1703. if(!slot)
  1704. Context->throw_error(AL_INVALID_VALUE, "Invalid effect ID {}", slotid);
  1705. }
  1706. if(sendidx >= device->NumAuxSends)
  1707. Context->throw_error(AL_INVALID_VALUE, "Invalid send {}", sendidx);
  1708. auto &send = Source->Send[static_cast<size_t>(sendidx)];
  1709. if(values[2])
  1710. {
  1711. std::lock_guard<std::mutex> filterlock{device->FilterLock};
  1712. ALfilter *filter{LookupFilter(device, filterid)};
  1713. if(!filter)
  1714. Context->throw_error(AL_INVALID_VALUE, "Invalid filter ID {}", filterid);
  1715. send.Gain = filter->Gain;
  1716. send.GainHF = filter->GainHF;
  1717. send.HFReference = filter->HFReference;
  1718. send.GainLF = filter->GainLF;
  1719. send.LFReference = filter->LFReference;
  1720. }
  1721. else
  1722. {
  1723. /* Disable filter */
  1724. send.Gain = 1.0f;
  1725. send.GainHF = 1.0f;
  1726. send.HFReference = LowPassFreqRef;
  1727. send.GainLF = 1.0f;
  1728. send.LFReference = HighPassFreqRef;
  1729. }
  1730. /* We must force an update if the current auxiliary slot is valid
  1731. * and about to be changed on an active source, in case the old
  1732. * slot is about to be deleted.
  1733. */
  1734. if(send.Slot && slot != send.Slot && IsPlayingOrPaused(Source))
  1735. {
  1736. /* Add refcount on the new slot, and release the previous slot */
  1737. if(slot) IncrementRef(slot->ref);
  1738. if(auto *oldslot = send.Slot)
  1739. DecrementRef(oldslot->ref);
  1740. send.Slot = slot;
  1741. Voice *voice{GetSourceVoice(Source, Context)};
  1742. if(voice) UpdateSourceProps(Source, voice, Context);
  1743. else Source->mPropsDirty = true;
  1744. }
  1745. else
  1746. {
  1747. if(slot) IncrementRef(slot->ref);
  1748. if(auto *oldslot = send.Slot)
  1749. DecrementRef(oldslot->ref);
  1750. send.Slot = slot;
  1751. UpdateSourceProps(Source, Context);
  1752. }
  1753. return;
  1754. }
  1755. break;
  1756. }
  1757. Context->throw_error(AL_INVALID_ENUM, "Invalid source {} property {:#04x}", PropTypeName<T>(),
  1758. as_unsigned(al::to_underlying(prop)));
  1759. }
  1760. template<typename T, size_t N>
  1761. auto GetSizeChecker(ALCcontext *context, const SourceProp prop, const al::span<T,N> values)
  1762. {
  1763. return [=](size_t expect) -> void
  1764. {
  1765. if(values.size() == expect) LIKELY return;
  1766. context->throw_error(AL_INVALID_ENUM, "Property {:#04x} expects {} value{}, got {}",
  1767. as_unsigned(al::to_underlying(prop)), expect, (expect==1) ? "" : "s", values.size());
  1768. };
  1769. }
  1770. template<typename T>
  1771. NOINLINE void GetProperty(ALsource *const Source, ALCcontext *const Context, const SourceProp prop,
  1772. const al::span<T> values)
  1773. {
  1774. using std::chrono::duration_cast;
  1775. auto CheckSize = GetSizeChecker(Context, prop, values);
  1776. auto *device = Context->mALDevice.get();
  1777. switch(prop)
  1778. {
  1779. case AL_GAIN:
  1780. CheckSize(1);
  1781. values[0] = static_cast<T>(Source->Gain);
  1782. return;
  1783. case AL_PITCH:
  1784. CheckSize(1);
  1785. values[0] = static_cast<T>(Source->Pitch);
  1786. return;
  1787. case AL_MAX_DISTANCE:
  1788. CheckSize(1);
  1789. values[0] = static_cast<T>(Source->MaxDistance);
  1790. return;
  1791. case AL_ROLLOFF_FACTOR:
  1792. CheckSize(1);
  1793. values[0] = static_cast<T>(Source->RolloffFactor);
  1794. return;
  1795. case AL_REFERENCE_DISTANCE:
  1796. CheckSize(1);
  1797. values[0] = static_cast<T>(Source->RefDistance);
  1798. return;
  1799. case AL_CONE_INNER_ANGLE:
  1800. CheckSize(1);
  1801. values[0] = static_cast<T>(Source->InnerAngle);
  1802. return;
  1803. case AL_CONE_OUTER_ANGLE:
  1804. CheckSize(1);
  1805. values[0] = static_cast<T>(Source->OuterAngle);
  1806. return;
  1807. case AL_MIN_GAIN:
  1808. CheckSize(1);
  1809. values[0] = static_cast<T>(Source->MinGain);
  1810. return;
  1811. case AL_MAX_GAIN:
  1812. CheckSize(1);
  1813. values[0] = static_cast<T>(Source->MaxGain);
  1814. return;
  1815. case AL_CONE_OUTER_GAIN:
  1816. CheckSize(1);
  1817. values[0] = static_cast<T>(Source->OuterGain);
  1818. return;
  1819. case AL_SEC_OFFSET:
  1820. case AL_SAMPLE_OFFSET:
  1821. case AL_BYTE_OFFSET:
  1822. CheckSize(1);
  1823. values[0] = GetSourceOffset<T>(Source, prop, Context);
  1824. return;
  1825. case AL_CONE_OUTER_GAINHF:
  1826. CheckSize(1);
  1827. values[0] = static_cast<T>(Source->OuterGainHF);
  1828. return;
  1829. case AL_AIR_ABSORPTION_FACTOR:
  1830. CheckSize(1);
  1831. values[0] = static_cast<T>(Source->AirAbsorptionFactor);
  1832. return;
  1833. case AL_ROOM_ROLLOFF_FACTOR:
  1834. CheckSize(1);
  1835. values[0] = static_cast<T>(Source->RoomRolloffFactor);
  1836. return;
  1837. case AL_DOPPLER_FACTOR:
  1838. CheckSize(1);
  1839. values[0] = static_cast<T>(Source->DopplerFactor);
  1840. return;
  1841. case AL_SAMPLE_RW_OFFSETS_SOFT:
  1842. if constexpr(std::is_integral_v<T>)
  1843. {
  1844. if(sBufferSubDataCompat)
  1845. {
  1846. CheckSize(2);
  1847. values[0] = GetSourceOffset<T>(Source, AL_SAMPLE_OFFSET, Context);
  1848. /* FIXME: values[1] should be ahead of values[0] by the device
  1849. * update time. It needs to clamp or wrap the length of the
  1850. * buffer queue.
  1851. */
  1852. values[1] = values[0];
  1853. return;
  1854. }
  1855. }
  1856. break;
  1857. case AL_SOURCE_RADIUS: /*AL_BYTE_RW_OFFSETS_SOFT:*/
  1858. if constexpr(std::is_floating_point_v<T>)
  1859. {
  1860. if(sBufferSubDataCompat)
  1861. break;
  1862. CheckSize(1);
  1863. values[0] = static_cast<T>(Source->Radius);
  1864. return;
  1865. }
  1866. else
  1867. {
  1868. if(sBufferSubDataCompat)
  1869. {
  1870. CheckSize(2);
  1871. values[0] = GetSourceOffset<T>(Source, AL_BYTE_OFFSET, Context);
  1872. /* FIXME: values[1] should be ahead of values[0] by the device
  1873. * update time. It needs to clamp or wrap the length of the
  1874. * buffer queue.
  1875. */
  1876. values[1] = values[0];
  1877. return;
  1878. }
  1879. break;
  1880. }
  1881. case AL_SUPER_STEREO_WIDTH_SOFT:
  1882. CheckSize(1);
  1883. values[0] = static_cast<T>(Source->EnhWidth);
  1884. return;
  1885. case AL_BYTE_LENGTH_SOFT:
  1886. case AL_SAMPLE_LENGTH_SOFT:
  1887. case AL_SEC_LENGTH_SOFT:
  1888. CheckSize(1);
  1889. values[0] = GetSourceLength<T>(Source, prop);
  1890. return;
  1891. case AL_PANNING_ENABLED_SOFT:
  1892. CheckSize(1);
  1893. values[0] = Source->mPanningEnabled;
  1894. return;
  1895. case AL_PAN_SOFT:
  1896. CheckSize(1);
  1897. values[0] = static_cast<T>(Source->mPan);
  1898. return;
  1899. case AL_STEREO_ANGLES:
  1900. if constexpr(std::is_floating_point_v<T>)
  1901. {
  1902. CheckSize(2);
  1903. values[0] = static_cast<T>(Source->StereoPan[0]);
  1904. values[1] = static_cast<T>(Source->StereoPan[1]);
  1905. return;
  1906. }
  1907. break;
  1908. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1909. if constexpr(std::is_same_v<T,int64_t>)
  1910. {
  1911. CheckSize(2);
  1912. /* Get the source offset with the clock time first. Then get the
  1913. * clock time with the device latency. Order is important.
  1914. */
  1915. ClockLatency clocktime{};
  1916. nanoseconds srcclock{};
  1917. values[0] = GetSourceSampleOffset(Source, Context, &srcclock);
  1918. {
  1919. std::lock_guard<std::mutex> statelock{device->StateLock};
  1920. clocktime = GetClockLatency(device, device->Backend.get());
  1921. }
  1922. if(srcclock == clocktime.ClockTime)
  1923. values[1] = nanoseconds{clocktime.Latency}.count();
  1924. else
  1925. {
  1926. /* If the clock time incremented, reduce the latency by that
  1927. * much since it's that much closer to the source offset it got
  1928. * earlier.
  1929. */
  1930. const auto diff = std::min(clocktime.Latency, clocktime.ClockTime-srcclock);
  1931. values[1] = nanoseconds{clocktime.Latency - diff}.count();
  1932. }
  1933. return;
  1934. }
  1935. break;
  1936. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1937. if constexpr(std::is_same_v<T,int64_t>)
  1938. {
  1939. CheckSize(2);
  1940. nanoseconds srcclock{};
  1941. values[0] = GetSourceSampleOffset(Source, Context, &srcclock);
  1942. values[1] = srcclock.count();
  1943. return;
  1944. }
  1945. break;
  1946. case AL_SEC_OFFSET_LATENCY_SOFT:
  1947. if constexpr(std::is_same_v<T,double>)
  1948. {
  1949. CheckSize(2);
  1950. /* Get the source offset with the clock time first. Then get the
  1951. * clock time with the device latency. Order is important.
  1952. */
  1953. ClockLatency clocktime{};
  1954. nanoseconds srcclock{};
  1955. values[0] = GetSourceSecOffset(Source, Context, &srcclock);
  1956. {
  1957. std::lock_guard<std::mutex> statelock{device->StateLock};
  1958. clocktime = GetClockLatency(device, device->Backend.get());
  1959. }
  1960. if(srcclock == clocktime.ClockTime)
  1961. values[1] = duration_cast<seconds_d>(clocktime.Latency).count();
  1962. else
  1963. {
  1964. /* If the clock time incremented, reduce the latency by that
  1965. * much since it's that much closer to the source offset it got
  1966. * earlier.
  1967. */
  1968. const auto diff = std::min(clocktime.Latency, clocktime.ClockTime-srcclock);
  1969. values[1] = duration_cast<seconds_d>(clocktime.Latency - diff).count();
  1970. }
  1971. return;
  1972. }
  1973. break;
  1974. case AL_SEC_OFFSET_CLOCK_SOFT:
  1975. if constexpr(std::is_same_v<T,double>)
  1976. {
  1977. CheckSize(2);
  1978. nanoseconds srcclock{};
  1979. values[0] = GetSourceSecOffset(Source, Context, &srcclock);
  1980. values[1] = duration_cast<seconds_d>(srcclock).count();
  1981. return;
  1982. }
  1983. break;
  1984. case AL_POSITION:
  1985. CheckSize(3);
  1986. values[0] = static_cast<T>(Source->Position[0]);
  1987. values[1] = static_cast<T>(Source->Position[1]);
  1988. values[2] = static_cast<T>(Source->Position[2]);
  1989. return;
  1990. case AL_VELOCITY:
  1991. CheckSize(3);
  1992. values[0] = static_cast<T>(Source->Velocity[0]);
  1993. values[1] = static_cast<T>(Source->Velocity[1]);
  1994. values[2] = static_cast<T>(Source->Velocity[2]);
  1995. return;
  1996. case AL_DIRECTION:
  1997. CheckSize(3);
  1998. values[0] = static_cast<T>(Source->Direction[0]);
  1999. values[1] = static_cast<T>(Source->Direction[1]);
  2000. values[2] = static_cast<T>(Source->Direction[2]);
  2001. return;
  2002. case AL_ORIENTATION:
  2003. CheckSize(6);
  2004. values[0] = static_cast<T>(Source->OrientAt[0]);
  2005. values[1] = static_cast<T>(Source->OrientAt[1]);
  2006. values[2] = static_cast<T>(Source->OrientAt[2]);
  2007. values[3] = static_cast<T>(Source->OrientUp[0]);
  2008. values[4] = static_cast<T>(Source->OrientUp[1]);
  2009. values[5] = static_cast<T>(Source->OrientUp[2]);
  2010. return;
  2011. case AL_SOURCE_RELATIVE:
  2012. if constexpr(std::is_integral_v<T>)
  2013. {
  2014. CheckSize(1);
  2015. values[0] = Source->HeadRelative;
  2016. return;
  2017. }
  2018. break;
  2019. case AL_LOOPING:
  2020. if constexpr(std::is_integral_v<T>)
  2021. {
  2022. CheckSize(1);
  2023. values[0] = Source->Looping;
  2024. return;
  2025. }
  2026. break;
  2027. case AL_BUFFER:
  2028. if constexpr(std::is_integral_v<T>)
  2029. {
  2030. CheckSize(1);
  2031. const ALbufferQueueItem *BufferList{};
  2032. /* HACK: This query should technically only return the buffer set
  2033. * on a static source. However, some apps had used it to detect
  2034. * when a streaming source changed buffers, so report the current
  2035. * buffer's ID when playing.
  2036. */
  2037. if(Source->SourceType == AL_STATIC || Source->state == AL_INITIAL)
  2038. {
  2039. if(!Source->mQueue.empty())
  2040. BufferList = &Source->mQueue.front();
  2041. }
  2042. else if(Voice *voice{GetSourceVoice(Source, Context)})
  2043. {
  2044. VoiceBufferItem *Current{voice->mCurrentBuffer.load(std::memory_order_relaxed)};
  2045. const auto iter = std::find_if(Source->mQueue.cbegin(), Source->mQueue.cend(),
  2046. [Current](const ALbufferQueueItem &item) noexcept -> bool
  2047. { return &item == Current; });
  2048. BufferList = (iter != Source->mQueue.cend()) ? al::to_address(iter) : nullptr;
  2049. }
  2050. ALbuffer *buffer{BufferList ? BufferList->mBuffer : nullptr};
  2051. values[0] = buffer ? static_cast<T>(buffer->id) : T{0};
  2052. return;
  2053. }
  2054. break;
  2055. case AL_SOURCE_STATE:
  2056. if constexpr(std::is_integral_v<T>)
  2057. {
  2058. CheckSize(1);
  2059. values[0] = GetSourceState(Source, GetSourceVoice(Source, Context));
  2060. return;
  2061. }
  2062. break;
  2063. case AL_BUFFERS_QUEUED:
  2064. if constexpr(std::is_integral_v<T>)
  2065. {
  2066. CheckSize(1);
  2067. values[0] = static_cast<T>(Source->mQueue.size());
  2068. return;
  2069. }
  2070. break;
  2071. case AL_BUFFERS_PROCESSED:
  2072. if constexpr(std::is_integral_v<T>)
  2073. {
  2074. CheckSize(1);
  2075. if(Source->Looping || Source->SourceType != AL_STREAMING)
  2076. {
  2077. /* Buffers on a looping source are in a perpetual state of
  2078. * PENDING, so don't report any as PROCESSED
  2079. */
  2080. values[0] = 0;
  2081. }
  2082. else
  2083. {
  2084. int played{0};
  2085. if(Source->state != AL_INITIAL)
  2086. {
  2087. const VoiceBufferItem *Current{nullptr};
  2088. if(Voice *voice{GetSourceVoice(Source, Context)})
  2089. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  2090. for(auto &item : Source->mQueue)
  2091. {
  2092. if(&item == Current)
  2093. break;
  2094. ++played;
  2095. }
  2096. }
  2097. values[0] = played;
  2098. }
  2099. return;
  2100. }
  2101. break;
  2102. case AL_SOURCE_TYPE:
  2103. if constexpr(std::is_integral_v<T>)
  2104. {
  2105. CheckSize(1);
  2106. values[0] = Source->SourceType;
  2107. return;
  2108. }
  2109. break;
  2110. case AL_DIRECT_FILTER_GAINHF_AUTO:
  2111. if constexpr(std::is_integral_v<T>)
  2112. {
  2113. CheckSize(1);
  2114. values[0] = Source->DryGainHFAuto;
  2115. return;
  2116. }
  2117. break;
  2118. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  2119. if constexpr(std::is_integral_v<T>)
  2120. {
  2121. CheckSize(1);
  2122. values[0] = Source->WetGainAuto;
  2123. return;
  2124. }
  2125. break;
  2126. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  2127. if constexpr(std::is_integral_v<T>)
  2128. {
  2129. CheckSize(1);
  2130. values[0] = Source->WetGainHFAuto;
  2131. return;
  2132. }
  2133. break;
  2134. case AL_DIRECT_CHANNELS_SOFT:
  2135. if constexpr(std::is_integral_v<T>)
  2136. {
  2137. CheckSize(1);
  2138. values[0] = EnumFromDirectMode(Source->DirectChannels);
  2139. return;
  2140. }
  2141. break;
  2142. case AL_DISTANCE_MODEL:
  2143. if constexpr(std::is_integral_v<T>)
  2144. {
  2145. CheckSize(1);
  2146. values[0] = ALenumFromDistanceModel(Source->mDistanceModel);
  2147. return;
  2148. }
  2149. break;
  2150. case AL_SOURCE_RESAMPLER_SOFT:
  2151. if constexpr(std::is_integral_v<T>)
  2152. {
  2153. CheckSize(1);
  2154. values[0] = static_cast<T>(Source->mResampler);
  2155. return;
  2156. }
  2157. break;
  2158. case AL_SOURCE_SPATIALIZE_SOFT:
  2159. if constexpr(std::is_integral_v<T>)
  2160. {
  2161. CheckSize(1);
  2162. values[0] = EnumFromSpatializeMode(Source->mSpatialize);
  2163. return;
  2164. }
  2165. break;
  2166. case AL_STEREO_MODE_SOFT:
  2167. if constexpr(std::is_integral_v<T>)
  2168. {
  2169. CheckSize(1);
  2170. values[0] = EnumFromStereoMode(Source->mStereoMode);
  2171. return;
  2172. }
  2173. break;
  2174. case AL_DIRECT_FILTER:
  2175. case AL_AUXILIARY_SEND_FILTER:
  2176. break;
  2177. }
  2178. Context->throw_error(AL_INVALID_ENUM, "Invalid source {} query property {:#04x}",
  2179. PropTypeName<T>(), as_unsigned(al::to_underlying(prop)));
  2180. }
  2181. void StartSources(ALCcontext *const context, const al::span<ALsource*> srchandles,
  2182. const nanoseconds start_time=nanoseconds::min())
  2183. {
  2184. auto *device = context->mALDevice.get();
  2185. /* If the device is disconnected, and voices stop on disconnect, go right
  2186. * to stopped.
  2187. */
  2188. if(!device->Connected.load(std::memory_order_acquire)) UNLIKELY
  2189. {
  2190. if(context->mStopVoicesOnDisconnect.load(std::memory_order_acquire))
  2191. {
  2192. for(ALsource *source : srchandles)
  2193. {
  2194. /* TODO: Send state change event? */
  2195. source->Offset = 0.0;
  2196. source->OffsetType = AL_NONE;
  2197. source->state = AL_STOPPED;
  2198. }
  2199. return;
  2200. }
  2201. }
  2202. /* Count the number of reusable voices. */
  2203. auto voicelist = context->getVoicesSpan();
  2204. size_t free_voices{0};
  2205. for(const Voice *voice : voicelist)
  2206. {
  2207. free_voices += (voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  2208. && voice->mSourceID.load(std::memory_order_relaxed) == 0u
  2209. && voice->mPendingChange.load(std::memory_order_relaxed) == false);
  2210. if(free_voices == srchandles.size())
  2211. break;
  2212. }
  2213. if(srchandles.size() != free_voices) UNLIKELY
  2214. {
  2215. const size_t inc_amount{srchandles.size() - free_voices};
  2216. auto &allvoices = *context->mVoices.load(std::memory_order_relaxed);
  2217. if(inc_amount > allvoices.size() - voicelist.size())
  2218. {
  2219. /* Increase the number of voices to handle the request. */
  2220. context->allocVoices(inc_amount - (allvoices.size() - voicelist.size()));
  2221. }
  2222. context->mActiveVoiceCount.fetch_add(inc_amount, std::memory_order_release);
  2223. voicelist = context->getVoicesSpan();
  2224. }
  2225. auto voiceiter = voicelist.begin();
  2226. ALuint vidx{0};
  2227. VoiceChange *tail{}, *cur{};
  2228. for(ALsource *source : srchandles)
  2229. {
  2230. /* Check that there is a queue containing at least one valid, non zero
  2231. * length buffer.
  2232. */
  2233. auto find_buffer = [](ALbufferQueueItem &entry) noexcept
  2234. { return entry.mSampleLen != 0 || entry.mCallback != nullptr; };
  2235. auto BufferList = std::find_if(source->mQueue.begin(), source->mQueue.end(), find_buffer);
  2236. /* If there's nothing to play, go right to stopped. */
  2237. if(BufferList == source->mQueue.end()) UNLIKELY
  2238. {
  2239. /* NOTE: A source without any playable buffers should not have a
  2240. * Voice since it shouldn't be in a playing or paused state. So
  2241. * there's no need to look up its voice and clear the source.
  2242. */
  2243. source->Offset = 0.0;
  2244. source->OffsetType = AL_NONE;
  2245. source->state = AL_STOPPED;
  2246. continue;
  2247. }
  2248. if(!cur)
  2249. cur = tail = GetVoiceChanger(context);
  2250. else
  2251. {
  2252. cur->mNext.store(GetVoiceChanger(context), std::memory_order_relaxed);
  2253. cur = cur->mNext.load(std::memory_order_relaxed);
  2254. }
  2255. Voice *voice{GetSourceVoice(source, context)};
  2256. switch(GetSourceState(source, voice))
  2257. {
  2258. case AL_PAUSED:
  2259. /* A source that's paused simply resumes. If there's no voice, it
  2260. * was lost from a disconnect, so just start over with a new one.
  2261. */
  2262. cur->mOldVoice = nullptr;
  2263. if(!voice) break;
  2264. cur->mVoice = voice;
  2265. cur->mSourceID = source->id;
  2266. cur->mState = VChangeState::Play;
  2267. source->state = AL_PLAYING;
  2268. #if ALSOFT_EAX
  2269. if(context->hasEax())
  2270. source->eaxCommit();
  2271. #endif // ALSOFT_EAX
  2272. continue;
  2273. case AL_PLAYING:
  2274. /* A source that's already playing is restarted from the beginning.
  2275. * Stop the current voice and start a new one so it properly cross-
  2276. * fades back to the beginning.
  2277. */
  2278. if(voice)
  2279. voice->mPendingChange.store(true, std::memory_order_relaxed);
  2280. cur->mOldVoice = voice;
  2281. voice = nullptr;
  2282. break;
  2283. default:
  2284. assert(voice == nullptr);
  2285. cur->mOldVoice = nullptr;
  2286. #if ALSOFT_EAX
  2287. if(context->hasEax())
  2288. source->eaxCommit();
  2289. #endif // ALSOFT_EAX
  2290. break;
  2291. }
  2292. /* Find the next unused voice to play this source with. */
  2293. for(;voiceiter != voicelist.end();++voiceiter,++vidx)
  2294. {
  2295. Voice *v{*voiceiter};
  2296. if(v->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  2297. && v->mSourceID.load(std::memory_order_relaxed) == 0u
  2298. && v->mPendingChange.load(std::memory_order_relaxed) == false)
  2299. {
  2300. voice = v;
  2301. break;
  2302. }
  2303. }
  2304. ASSUME(voice != nullptr);
  2305. voice->mPosition.store(0, std::memory_order_relaxed);
  2306. voice->mPositionFrac.store(0, std::memory_order_relaxed);
  2307. voice->mCurrentBuffer.store(&source->mQueue.front(), std::memory_order_relaxed);
  2308. voice->mStartTime = start_time;
  2309. voice->mFlags.reset();
  2310. /* A source that's not playing or paused has any offset applied when it
  2311. * starts playing.
  2312. */
  2313. if(const ALenum offsettype{source->OffsetType})
  2314. {
  2315. const double offset{source->Offset};
  2316. source->OffsetType = AL_NONE;
  2317. source->Offset = 0.0;
  2318. if(auto vpos = GetSampleOffset(source->mQueue, offsettype, offset))
  2319. {
  2320. voice->mPosition.store(vpos->pos, std::memory_order_relaxed);
  2321. voice->mPositionFrac.store(vpos->frac, std::memory_order_relaxed);
  2322. voice->mCurrentBuffer.store(vpos->bufferitem, std::memory_order_relaxed);
  2323. if(vpos->pos > 0 || (vpos->pos == 0 && vpos->frac > 0)
  2324. || vpos->bufferitem != &source->mQueue.front())
  2325. voice->mFlags.set(VoiceIsFading);
  2326. }
  2327. }
  2328. InitVoice(voice, source, al::to_address(BufferList), context, device);
  2329. source->VoiceIdx = vidx;
  2330. source->state = AL_PLAYING;
  2331. cur->mVoice = voice;
  2332. cur->mSourceID = source->id;
  2333. cur->mState = VChangeState::Play;
  2334. }
  2335. if(tail) LIKELY
  2336. SendVoiceChanges(context, tail);
  2337. }
  2338. } // namespace
  2339. AL_API DECL_FUNC2(void, alGenSources, ALsizei,n, ALuint*,sources)
  2340. FORCE_ALIGN void AL_APIENTRY alGenSourcesDirect(ALCcontext *context, ALsizei n, ALuint *sources) noexcept
  2341. try {
  2342. if(n < 0)
  2343. context->throw_error(AL_INVALID_VALUE, "Generating {} sources", n);
  2344. if(n <= 0) UNLIKELY return;
  2345. auto srclock = std::unique_lock{context->mSourceLock};
  2346. auto *device = context->mALDevice.get();
  2347. const al::span sids{sources, static_cast<ALuint>(n)};
  2348. if(context->mNumSources > device->SourcesMax
  2349. || sids.size() > device->SourcesMax-context->mNumSources)
  2350. context->throw_error(AL_OUT_OF_MEMORY, "Exceeding {} source limit ({} + {})",
  2351. device->SourcesMax, context->mNumSources, n);
  2352. if(!EnsureSources(context, sids.size()))
  2353. context->throw_error(AL_OUT_OF_MEMORY, "Failed to allocate {} source{}", n,
  2354. (n==1) ? "" : "s");
  2355. std::generate(sids.begin(), sids.end(), [context]{ return AllocSource(context)->id; });
  2356. }
  2357. catch(al::base_exception&) {
  2358. }
  2359. catch(std::exception &e) {
  2360. ERR("Caught exception: {}", e.what());
  2361. }
  2362. AL_API DECL_FUNC2(void, alDeleteSources, ALsizei,n, const ALuint*,sources)
  2363. FORCE_ALIGN void AL_APIENTRY alDeleteSourcesDirect(ALCcontext *context, ALsizei n,
  2364. const ALuint *sources) noexcept
  2365. try {
  2366. if(n < 0)
  2367. context->throw_error(AL_INVALID_VALUE, "Deleting {} sources", n);
  2368. if(n <= 0) UNLIKELY return;
  2369. std::lock_guard<std::mutex> srclock{context->mSourceLock};
  2370. /* Check that all Sources are valid */
  2371. auto validate_source = [context](const ALuint sid) -> bool
  2372. { return LookupSource(context, sid) != nullptr; };
  2373. const al::span sids{sources, static_cast<ALuint>(n)};
  2374. auto invsrc = std::find_if_not(sids.begin(), sids.end(), validate_source);
  2375. if(invsrc != sids.end())
  2376. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", *invsrc);
  2377. /* All good. Delete source IDs. */
  2378. auto delete_source = [&context](const ALuint sid) -> void
  2379. {
  2380. if(ALsource *src{LookupSource(context, sid)})
  2381. FreeSource(context, src);
  2382. };
  2383. std::for_each(sids.begin(), sids.end(), delete_source);
  2384. }
  2385. catch(al::base_exception&) {
  2386. }
  2387. catch(std::exception &e) {
  2388. ERR("Caught exception: {}", e.what());
  2389. }
  2390. AL_API DECL_FUNC1(ALboolean, alIsSource, ALuint,source)
  2391. FORCE_ALIGN ALboolean AL_APIENTRY alIsSourceDirect(ALCcontext *context, ALuint source) noexcept
  2392. {
  2393. std::lock_guard<std::mutex> srclock{context->mSourceLock};
  2394. if(LookupSource(context, source) != nullptr)
  2395. return AL_TRUE;
  2396. return AL_FALSE;
  2397. }
  2398. AL_API DECL_FUNC3(void, alSourcef, ALuint,source, ALenum,param, ALfloat,value)
  2399. FORCE_ALIGN void AL_APIENTRY alSourcefDirect(ALCcontext *context, ALuint source, ALenum param,
  2400. ALfloat value) noexcept
  2401. try {
  2402. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2403. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2404. ALsource *Source{LookupSource(context, source)};
  2405. if(!Source)
  2406. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2407. SetProperty<float>(Source, context, static_cast<SourceProp>(param), {&value, 1u});
  2408. }
  2409. catch(al::base_exception&) {
  2410. }
  2411. catch(std::exception &e) {
  2412. ERR("Caught exception: {}", e.what());
  2413. }
  2414. AL_API DECL_FUNC5(void, alSource3f, ALuint,source, ALenum,param, ALfloat,value1, ALfloat,value2, ALfloat,value3)
  2415. FORCE_ALIGN void AL_APIENTRY alSource3fDirect(ALCcontext *context, ALuint source, ALenum param,
  2416. ALfloat value1, ALfloat value2, ALfloat value3) noexcept
  2417. try {
  2418. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2419. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2420. ALsource *Source{LookupSource(context, source)};
  2421. if(!Source)
  2422. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2423. const std::array fvals{value1, value2, value3};
  2424. SetProperty<float>(Source, context, static_cast<SourceProp>(param), fvals);
  2425. }
  2426. catch(al::base_exception&) {
  2427. }
  2428. catch(std::exception &e) {
  2429. ERR("Caught exception: {}", e.what());
  2430. }
  2431. AL_API DECL_FUNC3(void, alSourcefv, ALuint,source, ALenum,param, const ALfloat*,values)
  2432. FORCE_ALIGN void AL_APIENTRY alSourcefvDirect(ALCcontext *context, ALuint source, ALenum param,
  2433. const ALfloat *values) noexcept
  2434. try {
  2435. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2436. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2437. ALsource *Source{LookupSource(context, source)};
  2438. if(!Source)
  2439. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2440. if(!values)
  2441. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2442. const ALuint count{FloatValsByProp(param)};
  2443. SetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2444. }
  2445. catch(al::base_exception&) {
  2446. }
  2447. catch(std::exception &e) {
  2448. ERR("Caught exception: {}", e.what());
  2449. }
  2450. AL_API DECL_FUNCEXT3(void, alSourced,SOFT, ALuint,source, ALenum,param, ALdouble,value)
  2451. FORCE_ALIGN void AL_APIENTRY alSourcedDirectSOFT(ALCcontext *context, ALuint source, ALenum param,
  2452. ALdouble value) noexcept
  2453. try {
  2454. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2455. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2456. ALsource *Source{LookupSource(context, source)};
  2457. if(!Source)
  2458. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2459. SetProperty<double>(Source, context, static_cast<SourceProp>(param), {&value, 1});
  2460. }
  2461. catch(al::base_exception&) {
  2462. }
  2463. catch(std::exception &e) {
  2464. ERR("Caught exception: {}", e.what());
  2465. }
  2466. AL_API DECL_FUNCEXT5(void, alSource3d,SOFT, ALuint,source, ALenum,param, ALdouble,value1, ALdouble,value2, ALdouble,value3)
  2467. FORCE_ALIGN void AL_APIENTRY alSource3dDirectSOFT(ALCcontext *context, ALuint source, ALenum param,
  2468. ALdouble value1, ALdouble value2, ALdouble value3) noexcept
  2469. try {
  2470. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2471. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2472. ALsource *Source{LookupSource(context, source)};
  2473. if(!Source)
  2474. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2475. const std::array dvals{value1, value2, value3};
  2476. SetProperty<double>(Source, context, static_cast<SourceProp>(param), dvals);
  2477. }
  2478. catch(al::base_exception&) {
  2479. }
  2480. catch(std::exception &e) {
  2481. ERR("Caught exception: {}", e.what());
  2482. }
  2483. AL_API DECL_FUNCEXT3(void, alSourcedv,SOFT, ALuint,source, ALenum,param, const ALdouble*,values)
  2484. FORCE_ALIGN void AL_APIENTRY alSourcedvDirectSOFT(ALCcontext *context, ALuint source, ALenum param,
  2485. const ALdouble *values) noexcept
  2486. try {
  2487. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2488. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2489. ALsource *Source{LookupSource(context, source)};
  2490. if(!Source)
  2491. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2492. if(!values)
  2493. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2494. const ALuint count{DoubleValsByProp(param)};
  2495. SetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2496. }
  2497. catch(al::base_exception&) {
  2498. }
  2499. catch(std::exception &e) {
  2500. ERR("Caught exception: {}", e.what());
  2501. }
  2502. AL_API DECL_FUNC3(void, alSourcei, ALuint,source, ALenum,param, ALint,value)
  2503. FORCE_ALIGN void AL_APIENTRY alSourceiDirect(ALCcontext *context, ALuint source, ALenum param,
  2504. ALint value) noexcept
  2505. try {
  2506. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2507. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2508. ALsource *Source{LookupSource(context, source)};
  2509. if(!Source)
  2510. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2511. SetProperty<int>(Source, context, static_cast<SourceProp>(param), {&value, 1u});
  2512. }
  2513. catch(al::base_exception&) {
  2514. }
  2515. catch(std::exception &e) {
  2516. ERR("Caught exception: {}", e.what());
  2517. }
  2518. AL_API DECL_FUNC5(void, alSource3i, ALuint,buffer, ALenum,param, ALint,value1, ALint,value2, ALint,value3)
  2519. FORCE_ALIGN void AL_APIENTRY alSource3iDirect(ALCcontext *context, ALuint source, ALenum param,
  2520. ALint value1, ALint value2, ALint value3) noexcept
  2521. try {
  2522. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2523. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2524. ALsource *Source{LookupSource(context, source)};
  2525. if(!Source)
  2526. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2527. const std::array ivals{value1, value2, value3};
  2528. SetProperty<int>(Source, context, static_cast<SourceProp>(param), ivals);
  2529. }
  2530. catch(al::base_exception&) {
  2531. }
  2532. catch(std::exception &e) {
  2533. ERR("Caught exception: {}", e.what());
  2534. }
  2535. AL_API DECL_FUNC3(void, alSourceiv, ALuint,source, ALenum,param, const ALint*,values)
  2536. FORCE_ALIGN void AL_APIENTRY alSourceivDirect(ALCcontext *context, ALuint source, ALenum param,
  2537. const ALint *values) noexcept
  2538. try {
  2539. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2540. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2541. ALsource *Source{LookupSource(context, source)};
  2542. if(!Source)
  2543. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2544. if(!values)
  2545. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2546. const ALuint count{IntValsByProp(param)};
  2547. SetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2548. }
  2549. catch(al::base_exception&) {
  2550. }
  2551. catch(std::exception &e) {
  2552. ERR("Caught exception: {}", e.what());
  2553. }
  2554. AL_API DECL_FUNCEXT3(void, alSourcei64,SOFT, ALuint,source, ALenum,param, ALint64SOFT,value)
  2555. FORCE_ALIGN void AL_APIENTRY alSourcei64DirectSOFT(ALCcontext *context, ALuint source,
  2556. ALenum param, ALint64SOFT value) noexcept
  2557. try {
  2558. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2559. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2560. ALsource *Source{LookupSource(context, source)};
  2561. if(!Source)
  2562. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2563. SetProperty<int64_t>(Source, context, static_cast<SourceProp>(param), {&value, 1u});
  2564. }
  2565. catch(al::base_exception&) {
  2566. }
  2567. catch(std::exception &e) {
  2568. ERR("Caught exception: {}", e.what());
  2569. }
  2570. AL_API DECL_FUNCEXT5(void, alSource3i64,SOFT, ALuint,source, ALenum,param, ALint64SOFT,value1, ALint64SOFT,value2, ALint64SOFT,value3)
  2571. FORCE_ALIGN void AL_APIENTRY alSource3i64DirectSOFT(ALCcontext *context, ALuint source,
  2572. ALenum param, ALint64SOFT value1, ALint64SOFT value2, ALint64SOFT value3) noexcept
  2573. try {
  2574. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2575. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2576. ALsource *Source{LookupSource(context, source)};
  2577. if(!Source)
  2578. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2579. const std::array i64vals{value1, value2, value3};
  2580. SetProperty<int64_t>(Source, context, static_cast<SourceProp>(param), i64vals);
  2581. }
  2582. catch(al::base_exception&) {
  2583. }
  2584. catch(std::exception &e) {
  2585. ERR("Caught exception: {}", e.what());
  2586. }
  2587. AL_API DECL_FUNCEXT3(void, alSourcei64v,SOFT, ALuint,source, ALenum,param, const ALint64SOFT*,values)
  2588. FORCE_ALIGN void AL_APIENTRY alSourcei64vDirectSOFT(ALCcontext *context, ALuint source,
  2589. ALenum param, const ALint64SOFT *values) noexcept
  2590. try {
  2591. std::lock_guard<std::mutex> proplock{context->mPropLock};
  2592. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2593. ALsource *Source{LookupSource(context, source)};
  2594. if(!Source)
  2595. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2596. if(!values)
  2597. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2598. const ALuint count{Int64ValsByProp(param)};
  2599. SetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2600. }
  2601. catch(al::base_exception&) {
  2602. }
  2603. catch(std::exception &e) {
  2604. ERR("Caught exception: {}", e.what());
  2605. }
  2606. AL_API DECL_FUNC3(void, alGetSourcef, ALuint,source, ALenum,param, ALfloat*,value)
  2607. FORCE_ALIGN void AL_APIENTRY alGetSourcefDirect(ALCcontext *context, ALuint source, ALenum param,
  2608. ALfloat *value) noexcept
  2609. try {
  2610. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2611. ALsource *Source{LookupSource(context, source)};
  2612. if(!Source)
  2613. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2614. if(!value)
  2615. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2616. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{value, 1u});
  2617. }
  2618. catch(al::base_exception&) {
  2619. }
  2620. catch(std::exception &e) {
  2621. ERR("Caught exception: {}", e.what());
  2622. }
  2623. AL_API DECL_FUNC5(void, alGetSource3f, ALuint,source, ALenum,param, ALfloat*,value1, ALfloat*,value2, ALfloat*,value3)
  2624. FORCE_ALIGN void AL_APIENTRY alGetSource3fDirect(ALCcontext *context, ALuint source, ALenum param,
  2625. ALfloat *value1, ALfloat *value2, ALfloat *value3) noexcept
  2626. try {
  2627. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2628. ALsource *Source{LookupSource(context, source)};
  2629. if(!Source)
  2630. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2631. if(!(value1 && value2 && value3))
  2632. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2633. std::array<float,3> fvals{};
  2634. GetProperty<float>(Source, context, static_cast<SourceProp>(param), fvals);
  2635. *value1 = fvals[0];
  2636. *value2 = fvals[1];
  2637. *value3 = fvals[2];
  2638. }
  2639. catch(al::base_exception&) {
  2640. }
  2641. catch(std::exception &e) {
  2642. ERR("Caught exception: {}", e.what());
  2643. }
  2644. AL_API DECL_FUNC3(void, alGetSourcefv, ALuint,source, ALenum,param, ALfloat*,values)
  2645. FORCE_ALIGN void AL_APIENTRY alGetSourcefvDirect(ALCcontext *context, ALuint source, ALenum param,
  2646. ALfloat *values) noexcept
  2647. try {
  2648. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2649. ALsource *Source{LookupSource(context, source)};
  2650. if(!Source)
  2651. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2652. if(!values)
  2653. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2654. const ALuint count{FloatValsByProp(param)};
  2655. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2656. }
  2657. catch(al::base_exception&) {
  2658. }
  2659. catch(std::exception &e) {
  2660. ERR("Caught exception: {}", e.what());
  2661. }
  2662. AL_API DECL_FUNCEXT3(void, alGetSourced,SOFT, ALuint,source, ALenum,param, ALdouble*,value)
  2663. FORCE_ALIGN void AL_APIENTRY alGetSourcedDirectSOFT(ALCcontext *context, ALuint source,
  2664. ALenum param, ALdouble *value) noexcept
  2665. try {
  2666. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2667. ALsource *Source{LookupSource(context, source)};
  2668. if(!Source)
  2669. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2670. if(!value)
  2671. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2672. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{value, 1u});
  2673. }
  2674. catch(al::base_exception&) {
  2675. }
  2676. catch(std::exception &e) {
  2677. ERR("Caught exception: {}", e.what());
  2678. }
  2679. AL_API DECL_FUNCEXT5(void, alGetSource3d,SOFT, ALuint,source, ALenum,param, ALdouble*,value1, ALdouble*,value2, ALdouble*,value3)
  2680. FORCE_ALIGN void AL_APIENTRY alGetSource3dDirectSOFT(ALCcontext *context, ALuint source,
  2681. ALenum param, ALdouble *value1, ALdouble *value2, ALdouble *value3) noexcept
  2682. try {
  2683. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2684. ALsource *Source{LookupSource(context, source)};
  2685. if(!Source)
  2686. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2687. if(!(value1 && value2 && value3))
  2688. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2689. std::array<double,3> dvals{};
  2690. GetProperty<double>(Source, context, static_cast<SourceProp>(param), dvals);
  2691. *value1 = dvals[0];
  2692. *value2 = dvals[1];
  2693. *value3 = dvals[2];
  2694. }
  2695. catch(al::base_exception&) {
  2696. }
  2697. catch(std::exception &e) {
  2698. ERR("Caught exception: {}", e.what());
  2699. }
  2700. AL_API DECL_FUNCEXT3(void, alGetSourcedv,SOFT, ALuint,source, ALenum,param, ALdouble*,values)
  2701. FORCE_ALIGN void AL_APIENTRY alGetSourcedvDirectSOFT(ALCcontext *context, ALuint source,
  2702. ALenum param, ALdouble *values) noexcept
  2703. try {
  2704. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2705. ALsource *Source{LookupSource(context, source)};
  2706. if(!Source)
  2707. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2708. if(!values)
  2709. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2710. const ALuint count{DoubleValsByProp(param)};
  2711. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2712. }
  2713. catch(al::base_exception&) {
  2714. }
  2715. catch(std::exception &e) {
  2716. ERR("Caught exception: {}", e.what());
  2717. }
  2718. AL_API DECL_FUNC3(void, alGetSourcei, ALuint,source, ALenum,param, ALint*,value)
  2719. FORCE_ALIGN void AL_APIENTRY alGetSourceiDirect(ALCcontext *context, ALuint source, ALenum param,
  2720. ALint *value) noexcept
  2721. try {
  2722. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2723. ALsource *Source{LookupSource(context, source)};
  2724. if(!Source)
  2725. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2726. if(!value)
  2727. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2728. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{value, 1u});
  2729. }
  2730. catch(al::base_exception&) {
  2731. }
  2732. catch(std::exception &e) {
  2733. ERR("Caught exception: {}", e.what());
  2734. }
  2735. AL_API DECL_FUNC5(void, alGetSource3i, ALuint,source, ALenum,param, ALint*,value1, ALint*,value2, ALint*,value3)
  2736. FORCE_ALIGN void AL_APIENTRY alGetSource3iDirect(ALCcontext *context, ALuint source, ALenum param,
  2737. ALint *value1, ALint *value2, ALint *value3) noexcept
  2738. try {
  2739. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2740. ALsource *Source{LookupSource(context, source)};
  2741. if(!Source)
  2742. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2743. if(!(value1 && value2 && value3))
  2744. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2745. std::array<int,3> ivals{};
  2746. GetProperty<int>(Source, context, static_cast<SourceProp>(param), ivals);
  2747. *value1 = ivals[0];
  2748. *value2 = ivals[1];
  2749. *value3 = ivals[2];
  2750. }
  2751. catch(al::base_exception&) {
  2752. }
  2753. catch(std::exception &e) {
  2754. ERR("Caught exception: {}", e.what());
  2755. }
  2756. AL_API DECL_FUNC3(void, alGetSourceiv, ALuint,source, ALenum,param, ALint*,values)
  2757. FORCE_ALIGN void AL_APIENTRY alGetSourceivDirect(ALCcontext *context, ALuint source, ALenum param,
  2758. ALint *values) noexcept
  2759. try {
  2760. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2761. ALsource *Source{LookupSource(context, source)};
  2762. if(!Source)
  2763. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2764. if(!values)
  2765. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2766. const ALuint count{IntValsByProp(param)};
  2767. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2768. }
  2769. catch(al::base_exception&) {
  2770. }
  2771. catch(std::exception &e) {
  2772. ERR("Caught exception: {}", e.what());
  2773. }
  2774. AL_API DECL_FUNCEXT3(void, alGetSourcei64,SOFT, ALuint,source, ALenum,param, ALint64SOFT*,value)
  2775. FORCE_ALIGN void AL_APIENTRY alGetSourcei64DirectSOFT(ALCcontext *context, ALuint source, ALenum param, ALint64SOFT *value) noexcept
  2776. try {
  2777. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2778. ALsource *Source{LookupSource(context, source)};
  2779. if(!Source)
  2780. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2781. if(!value)
  2782. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2783. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{value, 1u});
  2784. }
  2785. catch(al::base_exception&) {
  2786. }
  2787. catch(std::exception &e) {
  2788. ERR("Caught exception: {}", e.what());
  2789. }
  2790. AL_API DECL_FUNCEXT5(void, alGetSource3i64,SOFT, ALuint,source, ALenum,param, ALint64SOFT*,value1, ALint64SOFT*,value2, ALint64SOFT*,value3)
  2791. FORCE_ALIGN void AL_APIENTRY alGetSource3i64DirectSOFT(ALCcontext *context, ALuint source,
  2792. ALenum param, ALint64SOFT *value1, ALint64SOFT *value2, ALint64SOFT *value3) noexcept
  2793. try {
  2794. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2795. ALsource *Source{LookupSource(context, source)};
  2796. if(!Source)
  2797. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2798. if(!(value1 && value2 && value3))
  2799. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2800. std::array<int64_t,3> i64vals{};
  2801. GetProperty<int64_t>(Source, context, static_cast<SourceProp>(param), i64vals);
  2802. *value1 = i64vals[0];
  2803. *value2 = i64vals[1];
  2804. *value3 = i64vals[2];
  2805. }
  2806. catch(al::base_exception&) {
  2807. }
  2808. catch(std::exception &e) {
  2809. ERR("Caught exception: {}", e.what());
  2810. }
  2811. AL_API DECL_FUNCEXT3(void, alGetSourcei64v,SOFT, ALuint,source, ALenum,param, ALint64SOFT*,values)
  2812. FORCE_ALIGN void AL_APIENTRY alGetSourcei64vDirectSOFT(ALCcontext *context, ALuint source,
  2813. ALenum param, ALint64SOFT *values) noexcept
  2814. try {
  2815. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2816. ALsource *Source{LookupSource(context, source)};
  2817. if(!Source)
  2818. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2819. if(!values)
  2820. context->throw_error(AL_INVALID_VALUE, "NULL pointer");
  2821. const ALuint count{Int64ValsByProp(param)};
  2822. GetProperty(Source, context, static_cast<SourceProp>(param), al::span{values, count});
  2823. }
  2824. catch(al::base_exception&) {
  2825. }
  2826. catch(std::exception &e) {
  2827. ERR("Caught exception: {}", e.what());
  2828. }
  2829. AL_API DECL_FUNC1(void, alSourcePlay, ALuint,source)
  2830. FORCE_ALIGN void AL_APIENTRY alSourcePlayDirect(ALCcontext *context, ALuint source) noexcept
  2831. try {
  2832. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2833. ALsource *Source{LookupSource(context, source)};
  2834. if(!Source)
  2835. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2836. StartSources(context, {&Source, 1});
  2837. }
  2838. catch(al::base_exception&) {
  2839. }
  2840. catch(std::exception &e) {
  2841. ERR("Caught exception: {}", e.what());
  2842. }
  2843. FORCE_ALIGN DECL_FUNCEXT2(void, alSourcePlayAtTime,SOFT, ALuint,source, ALint64SOFT,start_time)
  2844. FORCE_ALIGN void AL_APIENTRY alSourcePlayAtTimeDirectSOFT(ALCcontext *context, ALuint source,
  2845. ALint64SOFT start_time) noexcept
  2846. try {
  2847. if(start_time < 0)
  2848. context->throw_error(AL_INVALID_VALUE, "Invalid time point {}", start_time);
  2849. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2850. ALsource *Source{LookupSource(context, source)};
  2851. if(!Source)
  2852. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", source);
  2853. StartSources(context, {&Source, 1}, nanoseconds{start_time});
  2854. }
  2855. catch(al::base_exception&) {
  2856. }
  2857. catch(std::exception &e) {
  2858. ERR("Caught exception: {}", e.what());
  2859. }
  2860. AL_API DECL_FUNC2(void, alSourcePlayv, ALsizei,n, const ALuint*,sources)
  2861. FORCE_ALIGN void AL_APIENTRY alSourcePlayvDirect(ALCcontext *context, ALsizei n,
  2862. const ALuint *sources) noexcept
  2863. try {
  2864. if(n < 0)
  2865. context->throw_error(AL_INVALID_VALUE, "Playing {} sources", n);
  2866. if(n <= 0) UNLIKELY return;
  2867. al::span sids{sources, static_cast<ALuint>(n)};
  2868. source_store_variant source_store;
  2869. const auto srchandles = [&source_store](size_t count) -> al::span<ALsource*>
  2870. {
  2871. if(count > std::tuple_size_v<source_store_array>)
  2872. return al::span{source_store.emplace<source_store_vector>(count)};
  2873. return al::span{source_store.emplace<source_store_array>()}.first(count);
  2874. }(sids.size());
  2875. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2876. auto lookup_src = [context](const ALuint sid) -> ALsource*
  2877. {
  2878. if(ALsource *src{LookupSource(context, sid)})
  2879. return src;
  2880. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", sid);
  2881. };
  2882. std::transform(sids.cbegin(), sids.cend(), srchandles.begin(), lookup_src);
  2883. StartSources(context, srchandles);
  2884. }
  2885. catch(al::base_exception&) {
  2886. }
  2887. catch(std::exception &e) {
  2888. ERR("Caught exception: {}", e.what());
  2889. }
  2890. FORCE_ALIGN DECL_FUNCEXT3(void, alSourcePlayAtTimev,SOFT, ALsizei,n, const ALuint*,sources, ALint64SOFT,start_time)
  2891. FORCE_ALIGN void AL_APIENTRY alSourcePlayAtTimevDirectSOFT(ALCcontext *context, ALsizei n,
  2892. const ALuint *sources, ALint64SOFT start_time) noexcept
  2893. try {
  2894. if(n < 0)
  2895. context->throw_error(AL_INVALID_VALUE, "Playing {} sources", n);
  2896. if(n <= 0) UNLIKELY return;
  2897. if(start_time < 0)
  2898. context->throw_error(AL_INVALID_VALUE, "Invalid time point {}", start_time);
  2899. al::span sids{sources, static_cast<ALuint>(n)};
  2900. source_store_variant source_store;
  2901. const auto srchandles = [&source_store](size_t count) -> al::span<ALsource*>
  2902. {
  2903. if(count > std::tuple_size_v<source_store_array>)
  2904. return al::span{source_store.emplace<source_store_vector>(count)};
  2905. return al::span{source_store.emplace<source_store_array>()}.first(count);
  2906. }(sids.size());
  2907. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2908. auto lookup_src = [context](const ALuint sid) -> ALsource*
  2909. {
  2910. if(ALsource *src{LookupSource(context, sid)})
  2911. return src;
  2912. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", sid);
  2913. };
  2914. std::transform(sids.cbegin(), sids.cend(), srchandles.begin(), lookup_src);
  2915. StartSources(context, srchandles, nanoseconds{start_time});
  2916. }
  2917. catch(al::base_exception&) {
  2918. }
  2919. catch(std::exception &e) {
  2920. ERR("Caught exception: {}", e.what());
  2921. }
  2922. AL_API DECL_FUNC1(void, alSourcePause, ALuint,source)
  2923. FORCE_ALIGN void AL_APIENTRY alSourcePauseDirect(ALCcontext *context, ALuint source) noexcept
  2924. { alSourcePausevDirect(context, 1, &source); }
  2925. AL_API DECL_FUNC2(void, alSourcePausev, ALsizei,n, const ALuint*,sources)
  2926. FORCE_ALIGN void AL_APIENTRY alSourcePausevDirect(ALCcontext *context, ALsizei n,
  2927. const ALuint *sources) noexcept
  2928. try {
  2929. if(n < 0)
  2930. context->throw_error(AL_INVALID_VALUE, "Pausing {} sources", n);
  2931. if(n <= 0) UNLIKELY return;
  2932. al::span sids{sources, static_cast<ALuint>(n)};
  2933. source_store_variant source_store;
  2934. const auto srchandles = [&source_store](size_t count) -> al::span<ALsource*>
  2935. {
  2936. if(count > std::tuple_size_v<source_store_array>)
  2937. return al::span{source_store.emplace<source_store_vector>(count)};
  2938. return al::span{source_store.emplace<source_store_array>()}.first(count);
  2939. }(sids.size());
  2940. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  2941. auto lookup_src = [context](const ALuint sid) -> ALsource*
  2942. {
  2943. if(ALsource *src{LookupSource(context, sid)})
  2944. return src;
  2945. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", sid);
  2946. };
  2947. std::transform(sids.cbegin(), sids.cend(), srchandles.begin(), lookup_src);
  2948. /* Pausing has to be done in two steps. First, for each source that's
  2949. * detected to be playing, chamge the voice (asynchronously) to
  2950. * stopping/paused.
  2951. */
  2952. VoiceChange *tail{}, *cur{};
  2953. for(ALsource *source : srchandles)
  2954. {
  2955. Voice *voice{GetSourceVoice(source, context)};
  2956. if(GetSourceState(source, voice) == AL_PLAYING)
  2957. {
  2958. if(!cur)
  2959. cur = tail = GetVoiceChanger(context);
  2960. else
  2961. {
  2962. cur->mNext.store(GetVoiceChanger(context), std::memory_order_relaxed);
  2963. cur = cur->mNext.load(std::memory_order_relaxed);
  2964. }
  2965. cur->mVoice = voice;
  2966. cur->mSourceID = source->id;
  2967. cur->mState = VChangeState::Pause;
  2968. }
  2969. }
  2970. if(tail) LIKELY
  2971. {
  2972. SendVoiceChanges(context, tail);
  2973. /* Second, now that the voice changes have been sent, because it's
  2974. * possible that the voice stopped after it was detected playing and
  2975. * before the voice got paused, recheck that the source is still
  2976. * considered playing and set it to paused if so.
  2977. */
  2978. for(ALsource *source : srchandles)
  2979. {
  2980. Voice *voice{GetSourceVoice(source, context)};
  2981. if(GetSourceState(source, voice) == AL_PLAYING)
  2982. source->state = AL_PAUSED;
  2983. }
  2984. }
  2985. }
  2986. catch(al::base_exception&) {
  2987. }
  2988. catch(std::exception &e) {
  2989. ERR("Caught exception: {}", e.what());
  2990. }
  2991. AL_API DECL_FUNC1(void, alSourceStop, ALuint,source)
  2992. FORCE_ALIGN void AL_APIENTRY alSourceStopDirect(ALCcontext *context, ALuint source) noexcept
  2993. { alSourceStopvDirect(context, 1, &source); }
  2994. AL_API DECL_FUNC2(void, alSourceStopv, ALsizei,n, const ALuint*,sources)
  2995. FORCE_ALIGN void AL_APIENTRY alSourceStopvDirect(ALCcontext *context, ALsizei n,
  2996. const ALuint *sources) noexcept
  2997. try {
  2998. if(n < 0)
  2999. context->throw_error(AL_INVALID_VALUE, "Stopping {} sources", n);
  3000. if(n <= 0) UNLIKELY return;
  3001. al::span sids{sources, static_cast<ALuint>(n)};
  3002. source_store_variant source_store;
  3003. const auto srchandles = [&source_store](size_t count) -> al::span<ALsource*>
  3004. {
  3005. if(count > std::tuple_size_v<source_store_array>)
  3006. return al::span{source_store.emplace<source_store_vector>(count)};
  3007. return al::span{source_store.emplace<source_store_array>()}.first(count);
  3008. }(sids.size());
  3009. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  3010. auto lookup_src = [context](const ALuint sid) -> ALsource*
  3011. {
  3012. if(ALsource *src{LookupSource(context, sid)})
  3013. return src;
  3014. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", sid);
  3015. };
  3016. std::transform(sids.cbegin(), sids.cend(), srchandles.begin(), lookup_src);
  3017. VoiceChange *tail{}, *cur{};
  3018. for(ALsource *source : srchandles)
  3019. {
  3020. if(Voice *voice{GetSourceVoice(source, context)})
  3021. {
  3022. if(!cur)
  3023. cur = tail = GetVoiceChanger(context);
  3024. else
  3025. {
  3026. cur->mNext.store(GetVoiceChanger(context), std::memory_order_relaxed);
  3027. cur = cur->mNext.load(std::memory_order_relaxed);
  3028. }
  3029. voice->mPendingChange.store(true, std::memory_order_relaxed);
  3030. cur->mVoice = voice;
  3031. cur->mSourceID = source->id;
  3032. cur->mState = VChangeState::Stop;
  3033. source->state = AL_STOPPED;
  3034. }
  3035. source->Offset = 0.0;
  3036. source->OffsetType = AL_NONE;
  3037. source->VoiceIdx = InvalidVoiceIndex;
  3038. }
  3039. if(tail) LIKELY
  3040. SendVoiceChanges(context, tail);
  3041. }
  3042. catch(al::base_exception&) {
  3043. }
  3044. catch(std::exception &e) {
  3045. ERR("Caught exception: {}", e.what());
  3046. }
  3047. AL_API DECL_FUNC1(void, alSourceRewind, ALuint,source)
  3048. FORCE_ALIGN void AL_APIENTRY alSourceRewindDirect(ALCcontext *context, ALuint source) noexcept
  3049. { alSourceRewindvDirect(context, 1, &source); }
  3050. AL_API DECL_FUNC2(void, alSourceRewindv, ALsizei,n, const ALuint*,sources)
  3051. FORCE_ALIGN void AL_APIENTRY alSourceRewindvDirect(ALCcontext *context, ALsizei n,
  3052. const ALuint *sources) noexcept
  3053. try {
  3054. if(n < 0)
  3055. context->throw_error(AL_INVALID_VALUE, "Rewinding {} sources", n);
  3056. if(n <= 0) UNLIKELY return;
  3057. al::span sids{sources, static_cast<ALuint>(n)};
  3058. source_store_variant source_store;
  3059. const auto srchandles = [&source_store](size_t count) -> al::span<ALsource*>
  3060. {
  3061. if(count > std::tuple_size_v<source_store_array>)
  3062. return al::span{source_store.emplace<source_store_vector>(count)};
  3063. return al::span{source_store.emplace<source_store_array>()}.first(count);
  3064. }(sids.size());
  3065. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  3066. auto lookup_src = [context](const ALuint sid) -> ALsource*
  3067. {
  3068. if(ALsource *src{LookupSource(context, sid)})
  3069. return src;
  3070. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", sid);
  3071. };
  3072. std::transform(sids.cbegin(), sids.cend(), srchandles.begin(), lookup_src);
  3073. VoiceChange *tail{}, *cur{};
  3074. for(ALsource *source : srchandles)
  3075. {
  3076. Voice *voice{GetSourceVoice(source, context)};
  3077. if(source->state != AL_INITIAL)
  3078. {
  3079. if(!cur)
  3080. cur = tail = GetVoiceChanger(context);
  3081. else
  3082. {
  3083. cur->mNext.store(GetVoiceChanger(context), std::memory_order_relaxed);
  3084. cur = cur->mNext.load(std::memory_order_relaxed);
  3085. }
  3086. if(voice)
  3087. voice->mPendingChange.store(true, std::memory_order_relaxed);
  3088. cur->mVoice = voice;
  3089. cur->mSourceID = source->id;
  3090. cur->mState = VChangeState::Reset;
  3091. source->state = AL_INITIAL;
  3092. }
  3093. source->Offset = 0.0;
  3094. source->OffsetType = AL_NONE;
  3095. source->VoiceIdx = InvalidVoiceIndex;
  3096. }
  3097. if(tail) LIKELY
  3098. SendVoiceChanges(context, tail);
  3099. }
  3100. catch(al::base_exception&) {
  3101. }
  3102. catch(std::exception &e) {
  3103. ERR("Caught exception: {}", e.what());
  3104. }
  3105. AL_API DECL_FUNC3(void, alSourceQueueBuffers, ALuint,source, ALsizei,nb, const ALuint*,buffers)
  3106. FORCE_ALIGN void AL_APIENTRY alSourceQueueBuffersDirect(ALCcontext *context, ALuint src,
  3107. ALsizei nb, const ALuint *buffers) noexcept
  3108. try {
  3109. if(nb < 0)
  3110. context->throw_error(AL_INVALID_VALUE, "Queueing {} buffers", nb);
  3111. if(nb <= 0) UNLIKELY return;
  3112. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  3113. ALsource *source{LookupSource(context,src)};
  3114. if(!source)
  3115. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", src);
  3116. /* Can't queue on a Static Source */
  3117. if(source->SourceType == AL_STATIC)
  3118. context->throw_error(AL_INVALID_OPERATION, "Queueing onto static source {}", src);
  3119. /* Check for a valid Buffer, for its frequency and format */
  3120. auto *device = context->mALDevice.get();
  3121. ALbuffer *BufferFmt{nullptr};
  3122. for(auto &item : source->mQueue)
  3123. {
  3124. BufferFmt = item.mBuffer;
  3125. if(BufferFmt) break;
  3126. }
  3127. std::unique_lock<std::mutex> buflock{device->BufferLock};
  3128. const auto bids = al::span{buffers, static_cast<ALuint>(nb)};
  3129. const size_t NewListStart{source->mQueue.size()};
  3130. try {
  3131. ALbufferQueueItem *BufferList{nullptr};
  3132. auto append_buffer = [context,source,device,&BufferFmt,&BufferList](const ALuint bid)
  3133. {
  3134. ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr};
  3135. if(bid && !buffer)
  3136. context->throw_error(AL_INVALID_NAME, "Queueing invalid buffer ID {}", bid);
  3137. if(buffer)
  3138. {
  3139. if(buffer->mSampleRate < 1)
  3140. context->throw_error(AL_INVALID_OPERATION,
  3141. "Queueing buffer {} with no format", buffer->id);
  3142. if(buffer->mCallback)
  3143. context->throw_error(AL_INVALID_OPERATION, "Queueing callback buffer {}",
  3144. buffer->id);
  3145. if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT))
  3146. context->throw_error(AL_INVALID_OPERATION,
  3147. "Queueing non-persistently mapped buffer {}", buffer->id);
  3148. }
  3149. source->mQueue.emplace_back();
  3150. if(!BufferList)
  3151. BufferList = &source->mQueue.back();
  3152. else
  3153. {
  3154. auto &item = source->mQueue.back();
  3155. BufferList->mNext.store(&item, std::memory_order_relaxed);
  3156. BufferList = &item;
  3157. }
  3158. if(!buffer) return;
  3159. BufferList->mBlockAlign = buffer->mBlockAlign;
  3160. BufferList->mSampleLen = buffer->mSampleLen;
  3161. BufferList->mLoopEnd = buffer->mSampleLen;
  3162. BufferList->mSamples = buffer->mData;
  3163. BufferList->mBuffer = buffer;
  3164. IncrementRef(buffer->ref);
  3165. if(BufferFmt == nullptr)
  3166. BufferFmt = buffer;
  3167. else
  3168. {
  3169. auto fmt_mismatch = false;
  3170. fmt_mismatch |= BufferFmt->mSampleRate != buffer->mSampleRate;
  3171. fmt_mismatch |= BufferFmt->mChannels != buffer->mChannels;
  3172. fmt_mismatch |= BufferFmt->mType != buffer->mType;
  3173. if(BufferFmt->isBFormat())
  3174. {
  3175. fmt_mismatch |= BufferFmt->mAmbiLayout != buffer->mAmbiLayout;
  3176. fmt_mismatch |= BufferFmt->mAmbiScaling != buffer->mAmbiScaling;
  3177. }
  3178. fmt_mismatch |= BufferFmt->mAmbiOrder != buffer->mAmbiOrder;
  3179. if(fmt_mismatch)
  3180. context->throw_error(AL_INVALID_OPERATION,
  3181. "Queueing buffer with mismatched format\n"
  3182. " Expected: {}hz, {}, {} ; Got: {}hz, {}, {}\n", BufferFmt->mSampleRate,
  3183. NameFromFormat(BufferFmt->mType), NameFromFormat(BufferFmt->mChannels),
  3184. buffer->mSampleRate, NameFromFormat(buffer->mType),
  3185. NameFromFormat(buffer->mChannels));
  3186. }
  3187. };
  3188. std::for_each(bids.cbegin(), bids.cend(), append_buffer);
  3189. }
  3190. catch(...) {
  3191. /* A buffer failed (invalid ID or format), or there was some other
  3192. * unexpected error, so unlock and release each buffer we had.
  3193. */
  3194. auto iter = source->mQueue.begin() + ptrdiff_t(NewListStart);
  3195. for(;iter != source->mQueue.end();++iter)
  3196. {
  3197. if(ALbuffer *buf{iter->mBuffer})
  3198. DecrementRef(buf->ref);
  3199. }
  3200. source->mQueue.resize(NewListStart);
  3201. throw;
  3202. }
  3203. /* All buffers good. */
  3204. buflock.unlock();
  3205. /* Source is now streaming */
  3206. source->SourceType = AL_STREAMING;
  3207. if(NewListStart != 0)
  3208. {
  3209. auto iter = source->mQueue.begin() + ptrdiff_t(NewListStart);
  3210. (iter-1)->mNext.store(al::to_address(iter), std::memory_order_release);
  3211. }
  3212. }
  3213. catch(al::base_exception&) {
  3214. }
  3215. catch(std::exception &e) {
  3216. ERR("Caught exception: {}", e.what());
  3217. }
  3218. AL_API DECL_FUNC3(void, alSourceUnqueueBuffers, ALuint,source, ALsizei,nb, ALuint*,buffers)
  3219. FORCE_ALIGN void AL_APIENTRY alSourceUnqueueBuffersDirect(ALCcontext *context, ALuint src,
  3220. ALsizei nb, ALuint *buffers) noexcept
  3221. try {
  3222. if(nb < 0)
  3223. context->throw_error(AL_INVALID_VALUE, "Unqueueing {} buffers", nb);
  3224. if(nb <= 0) UNLIKELY return;
  3225. std::lock_guard<std::mutex> sourcelock{context->mSourceLock};
  3226. ALsource *source{LookupSource(context,src)};
  3227. if(!source)
  3228. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", src);
  3229. if(source->SourceType != AL_STREAMING)
  3230. context->throw_error(AL_INVALID_VALUE, "Unqueueing from a non-streaming source {}", src);
  3231. if(source->Looping)
  3232. context->throw_error(AL_INVALID_VALUE, "Unqueueing from looping source {}", src);
  3233. /* Make sure enough buffers have been processed to unqueue. */
  3234. const al::span bids{buffers, static_cast<ALuint>(nb)};
  3235. size_t processed{0};
  3236. if(source->state != AL_INITIAL) LIKELY
  3237. {
  3238. VoiceBufferItem *Current{nullptr};
  3239. if(Voice *voice{GetSourceVoice(source, context)})
  3240. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  3241. for(auto &item : source->mQueue)
  3242. {
  3243. if(&item == Current)
  3244. break;
  3245. ++processed;
  3246. }
  3247. }
  3248. if(processed < bids.size())
  3249. context->throw_error(AL_INVALID_VALUE, "Unqueueing {} buffer{} (only {} processed)",
  3250. nb, (nb==1) ? "" : "s", processed);
  3251. std::generate(bids.begin(), bids.end(), [source]() noexcept -> ALuint
  3252. {
  3253. auto &head = source->mQueue.front();
  3254. ALuint bid{0};
  3255. if(ALbuffer *buffer{head.mBuffer})
  3256. {
  3257. bid = buffer->id;
  3258. DecrementRef(buffer->ref);
  3259. }
  3260. source->mQueue.pop_front();
  3261. return bid;
  3262. });
  3263. }
  3264. catch(al::base_exception&) {
  3265. }
  3266. catch(std::exception &e) {
  3267. ERR("Caught exception: {}", e.what());
  3268. }
  3269. AL_API void AL_APIENTRY alSourceQueueBufferLayersSOFT(ALuint, ALsizei, const ALuint*) noexcept
  3270. {
  3271. ContextRef context{GetContextRef()};
  3272. if(!context) UNLIKELY return;
  3273. context->setError(AL_INVALID_OPERATION, "alSourceQueueBufferLayersSOFT not supported");
  3274. }
  3275. ALsource::ALsource() noexcept
  3276. {
  3277. Direct.Gain = 1.0f;
  3278. Direct.GainHF = 1.0f;
  3279. Direct.HFReference = LowPassFreqRef;
  3280. Direct.GainLF = 1.0f;
  3281. Direct.LFReference = HighPassFreqRef;
  3282. for(auto &send : Send)
  3283. {
  3284. send.Slot = nullptr;
  3285. send.Gain = 1.0f;
  3286. send.GainHF = 1.0f;
  3287. send.HFReference = LowPassFreqRef;
  3288. send.GainLF = 1.0f;
  3289. send.LFReference = HighPassFreqRef;
  3290. }
  3291. }
  3292. ALsource::~ALsource()
  3293. {
  3294. for(auto &item : mQueue)
  3295. {
  3296. if(ALbuffer *buffer{item.mBuffer})
  3297. DecrementRef(buffer->ref);
  3298. }
  3299. auto clear_send = [](ALsource::SendData &send) -> void
  3300. { if(send.Slot) DecrementRef(send.Slot->ref); };
  3301. std::for_each(Send.begin(), Send.end(), clear_send);
  3302. }
  3303. void UpdateAllSourceProps(ALCcontext *context)
  3304. {
  3305. std::lock_guard<std::mutex> srclock{context->mSourceLock};
  3306. auto voicelist = context->getVoicesSpan();
  3307. ALuint vidx{0u};
  3308. for(Voice *voice : voicelist)
  3309. {
  3310. ALuint sid{voice->mSourceID.load(std::memory_order_acquire)};
  3311. ALsource *source{sid ? LookupSource(context, sid) : nullptr};
  3312. if(source && source->VoiceIdx == vidx)
  3313. {
  3314. if(std::exchange(source->mPropsDirty, false))
  3315. UpdateSourceProps(source, voice, context);
  3316. }
  3317. ++vidx;
  3318. }
  3319. }
  3320. void ALsource::SetName(ALCcontext *context, ALuint id, std::string_view name)
  3321. {
  3322. std::lock_guard<std::mutex> srclock{context->mSourceLock};
  3323. auto source = LookupSource(context, id);
  3324. if(!source)
  3325. context->throw_error(AL_INVALID_NAME, "Invalid source ID {}", id);
  3326. context->mSourceNames.insert_or_assign(id, name);
  3327. }
  3328. SourceSubList::~SourceSubList()
  3329. {
  3330. if(!Sources)
  3331. return;
  3332. uint64_t usemask{~FreeMask};
  3333. while(usemask)
  3334. {
  3335. const int idx{al::countr_zero(usemask)};
  3336. usemask &= ~(1_u64 << idx);
  3337. std::destroy_at(al::to_address(Sources->begin() + idx));
  3338. }
  3339. FreeMask = ~usemask;
  3340. SubListAllocator{}.deallocate(Sources, 1);
  3341. Sources = nullptr;
  3342. }
  3343. #if ALSOFT_EAX
  3344. void ALsource::eaxInitialize(ALCcontext *context) noexcept
  3345. {
  3346. assert(context != nullptr);
  3347. mEaxAlContext = context;
  3348. mEaxPrimaryFxSlotId = context->eaxGetPrimaryFxSlotIndex();
  3349. eax_set_defaults();
  3350. eax1_translate(mEax1.i, mEax);
  3351. mEaxVersion = 1;
  3352. mEaxChanged = true;
  3353. }
  3354. ALsource* ALsource::EaxLookupSource(ALCcontext& al_context, ALuint source_id) noexcept
  3355. {
  3356. return LookupSource(&al_context, source_id);
  3357. }
  3358. [[noreturn]] void ALsource::eax_fail(const char* message)
  3359. {
  3360. throw Exception{message};
  3361. }
  3362. [[noreturn]] void ALsource::eax_fail_unknown_property_id()
  3363. {
  3364. eax_fail("Unknown property id.");
  3365. }
  3366. [[noreturn]] void ALsource::eax_fail_unknown_version()
  3367. {
  3368. eax_fail("Unknown version.");
  3369. }
  3370. [[noreturn]] void ALsource::eax_fail_unknown_active_fx_slot_id()
  3371. {
  3372. eax_fail("Unknown active FX slot ID.");
  3373. }
  3374. [[noreturn]] void ALsource::eax_fail_unknown_receiving_fx_slot_id()
  3375. {
  3376. eax_fail("Unknown receiving FX slot ID.");
  3377. }
  3378. void ALsource::eax_set_sends_defaults(EaxSends& sends, const EaxFxSlotIds& ids) noexcept
  3379. {
  3380. for(size_t i{0};i < EAX_MAX_FXSLOTS;++i)
  3381. {
  3382. auto& send = sends[i];
  3383. send.guidReceivingFXSlotID = *(ids[i]);
  3384. send.lSend = EAXSOURCE_DEFAULTSEND;
  3385. send.lSendHF = EAXSOURCE_DEFAULTSENDHF;
  3386. send.lOcclusion = EAXSOURCE_DEFAULTOCCLUSION;
  3387. send.flOcclusionLFRatio = EAXSOURCE_DEFAULTOCCLUSIONLFRATIO;
  3388. send.flOcclusionRoomRatio = EAXSOURCE_DEFAULTOCCLUSIONROOMRATIO;
  3389. send.flOcclusionDirectRatio = EAXSOURCE_DEFAULTOCCLUSIONDIRECTRATIO;
  3390. send.lExclusion = EAXSOURCE_DEFAULTEXCLUSION;
  3391. send.flExclusionLFRatio = EAXSOURCE_DEFAULTEXCLUSIONLFRATIO;
  3392. }
  3393. }
  3394. void ALsource::eax1_set_defaults(EAXBUFFER_REVERBPROPERTIES& props) noexcept
  3395. {
  3396. props.fMix = EAX_REVERBMIX_USEDISTANCE;
  3397. }
  3398. void ALsource::eax1_set_defaults() noexcept
  3399. {
  3400. eax1_set_defaults(mEax1.i);
  3401. mEax1.d = mEax1.i;
  3402. }
  3403. void ALsource::eax2_set_defaults(EAX20BUFFERPROPERTIES& props) noexcept
  3404. {
  3405. props.lDirect = EAXSOURCE_DEFAULTDIRECT;
  3406. props.lDirectHF = EAXSOURCE_DEFAULTDIRECTHF;
  3407. props.lRoom = EAXSOURCE_DEFAULTROOM;
  3408. props.lRoomHF = EAXSOURCE_DEFAULTROOMHF;
  3409. props.flRoomRolloffFactor = EAXSOURCE_DEFAULTROOMROLLOFFFACTOR;
  3410. props.lObstruction = EAXSOURCE_DEFAULTOBSTRUCTION;
  3411. props.flObstructionLFRatio = EAXSOURCE_DEFAULTOBSTRUCTIONLFRATIO;
  3412. props.lOcclusion = EAXSOURCE_DEFAULTOCCLUSION;
  3413. props.flOcclusionLFRatio = EAXSOURCE_DEFAULTOCCLUSIONLFRATIO;
  3414. props.flOcclusionRoomRatio = EAXSOURCE_DEFAULTOCCLUSIONROOMRATIO;
  3415. props.lOutsideVolumeHF = EAXSOURCE_DEFAULTOUTSIDEVOLUMEHF;
  3416. props.flAirAbsorptionFactor = EAXSOURCE_DEFAULTAIRABSORPTIONFACTOR;
  3417. props.dwFlags = EAXSOURCE_DEFAULTFLAGS;
  3418. }
  3419. void ALsource::eax2_set_defaults() noexcept
  3420. {
  3421. eax2_set_defaults(mEax2.i);
  3422. mEax2.d = mEax2.i;
  3423. }
  3424. void ALsource::eax3_set_defaults(EAX30SOURCEPROPERTIES& props) noexcept
  3425. {
  3426. props.lDirect = EAXSOURCE_DEFAULTDIRECT;
  3427. props.lDirectHF = EAXSOURCE_DEFAULTDIRECTHF;
  3428. props.lRoom = EAXSOURCE_DEFAULTROOM;
  3429. props.lRoomHF = EAXSOURCE_DEFAULTROOMHF;
  3430. props.lObstruction = EAXSOURCE_DEFAULTOBSTRUCTION;
  3431. props.flObstructionLFRatio = EAXSOURCE_DEFAULTOBSTRUCTIONLFRATIO;
  3432. props.lOcclusion = EAXSOURCE_DEFAULTOCCLUSION;
  3433. props.flOcclusionLFRatio = EAXSOURCE_DEFAULTOCCLUSIONLFRATIO;
  3434. props.flOcclusionRoomRatio = EAXSOURCE_DEFAULTOCCLUSIONROOMRATIO;
  3435. props.flOcclusionDirectRatio = EAXSOURCE_DEFAULTOCCLUSIONDIRECTRATIO;
  3436. props.lExclusion = EAXSOURCE_DEFAULTEXCLUSION;
  3437. props.flExclusionLFRatio = EAXSOURCE_DEFAULTEXCLUSIONLFRATIO;
  3438. props.lOutsideVolumeHF = EAXSOURCE_DEFAULTOUTSIDEVOLUMEHF;
  3439. props.flDopplerFactor = EAXSOURCE_DEFAULTDOPPLERFACTOR;
  3440. props.flRolloffFactor = EAXSOURCE_DEFAULTROLLOFFFACTOR;
  3441. props.flRoomRolloffFactor = EAXSOURCE_DEFAULTROOMROLLOFFFACTOR;
  3442. props.flAirAbsorptionFactor = EAXSOURCE_DEFAULTAIRABSORPTIONFACTOR;
  3443. props.ulFlags = EAXSOURCE_DEFAULTFLAGS;
  3444. }
  3445. void ALsource::eax3_set_defaults() noexcept
  3446. {
  3447. eax3_set_defaults(mEax3.i);
  3448. mEax3.d = mEax3.i;
  3449. }
  3450. void ALsource::eax4_set_sends_defaults(EaxSends& sends) noexcept
  3451. {
  3452. eax_set_sends_defaults(sends, eax4_fx_slot_ids);
  3453. }
  3454. void ALsource::eax4_set_active_fx_slots_defaults(EAX40ACTIVEFXSLOTS& slots) noexcept
  3455. {
  3456. slots = EAX40SOURCE_DEFAULTACTIVEFXSLOTID;
  3457. }
  3458. void ALsource::eax4_set_defaults() noexcept
  3459. {
  3460. eax3_set_defaults(mEax4.i.source);
  3461. eax4_set_sends_defaults(mEax4.i.sends);
  3462. eax4_set_active_fx_slots_defaults(mEax4.i.active_fx_slots);
  3463. mEax4.d = mEax4.i;
  3464. }
  3465. void ALsource::eax5_set_source_defaults(EAX50SOURCEPROPERTIES& props) noexcept
  3466. {
  3467. eax3_set_defaults(static_cast<EAX30SOURCEPROPERTIES&>(props));
  3468. props.flMacroFXFactor = EAXSOURCE_DEFAULTMACROFXFACTOR;
  3469. }
  3470. void ALsource::eax5_set_sends_defaults(EaxSends& sends) noexcept
  3471. {
  3472. eax_set_sends_defaults(sends, eax5_fx_slot_ids);
  3473. }
  3474. void ALsource::eax5_set_active_fx_slots_defaults(EAX50ACTIVEFXSLOTS& slots) noexcept
  3475. {
  3476. slots = EAX50SOURCE_3DDEFAULTACTIVEFXSLOTID;
  3477. }
  3478. void ALsource::eax5_set_speaker_levels_defaults(EaxSpeakerLevels& speaker_levels) noexcept
  3479. {
  3480. for(size_t i{0};i < eax_max_speakers;++i)
  3481. {
  3482. auto& speaker_level = speaker_levels[i];
  3483. speaker_level.lSpeakerID = static_cast<long>(EAXSPEAKER_FRONT_LEFT + i);
  3484. speaker_level.lLevel = EAXSOURCE_DEFAULTSPEAKERLEVEL;
  3485. }
  3486. }
  3487. void ALsource::eax5_set_defaults(Eax5Props& props) noexcept
  3488. {
  3489. eax5_set_source_defaults(props.source);
  3490. eax5_set_sends_defaults(props.sends);
  3491. eax5_set_active_fx_slots_defaults(props.active_fx_slots);
  3492. eax5_set_speaker_levels_defaults(props.speaker_levels);
  3493. }
  3494. void ALsource::eax5_set_defaults() noexcept
  3495. {
  3496. eax5_set_defaults(mEax5.i);
  3497. mEax5.d = mEax5.i;
  3498. }
  3499. void ALsource::eax_set_defaults() noexcept
  3500. {
  3501. eax1_set_defaults();
  3502. eax2_set_defaults();
  3503. eax3_set_defaults();
  3504. eax4_set_defaults();
  3505. eax5_set_defaults();
  3506. }
  3507. void ALsource::eax1_translate(const EAXBUFFER_REVERBPROPERTIES& src, Eax5Props& dst) noexcept
  3508. {
  3509. eax5_set_defaults(dst);
  3510. if (src.fMix == EAX_REVERBMIX_USEDISTANCE)
  3511. {
  3512. dst.source.ulFlags |= EAXSOURCEFLAGS_ROOMAUTO;
  3513. dst.sends[0].lSend = 0;
  3514. }
  3515. else
  3516. {
  3517. dst.source.ulFlags &= ~EAXSOURCEFLAGS_ROOMAUTO;
  3518. dst.sends[0].lSend = std::clamp(static_cast<long>(gain_to_level_mb(src.fMix)),
  3519. EAXSOURCE_MINSEND, EAXSOURCE_MAXSEND);
  3520. }
  3521. }
  3522. void ALsource::eax2_translate(const EAX20BUFFERPROPERTIES& src, Eax5Props& dst) noexcept
  3523. {
  3524. // Source.
  3525. //
  3526. dst.source.lDirect = src.lDirect;
  3527. dst.source.lDirectHF = src.lDirectHF;
  3528. dst.source.lRoom = src.lRoom;
  3529. dst.source.lRoomHF = src.lRoomHF;
  3530. dst.source.lObstruction = src.lObstruction;
  3531. dst.source.flObstructionLFRatio = src.flObstructionLFRatio;
  3532. dst.source.lOcclusion = src.lOcclusion;
  3533. dst.source.flOcclusionLFRatio = src.flOcclusionLFRatio;
  3534. dst.source.flOcclusionRoomRatio = src.flOcclusionRoomRatio;
  3535. dst.source.flOcclusionDirectRatio = EAXSOURCE_DEFAULTOCCLUSIONDIRECTRATIO;
  3536. dst.source.lExclusion = EAXSOURCE_DEFAULTEXCLUSION;
  3537. dst.source.flExclusionLFRatio = EAXSOURCE_DEFAULTEXCLUSIONLFRATIO;
  3538. dst.source.lOutsideVolumeHF = src.lOutsideVolumeHF;
  3539. dst.source.flDopplerFactor = EAXSOURCE_DEFAULTDOPPLERFACTOR;
  3540. dst.source.flRolloffFactor = EAXSOURCE_DEFAULTROLLOFFFACTOR;
  3541. dst.source.flRoomRolloffFactor = src.flRoomRolloffFactor;
  3542. dst.source.flAirAbsorptionFactor = src.flAirAbsorptionFactor;
  3543. dst.source.ulFlags = src.dwFlags;
  3544. dst.source.flMacroFXFactor = EAXSOURCE_DEFAULTMACROFXFACTOR;
  3545. // Set everything else to defaults.
  3546. //
  3547. eax5_set_sends_defaults(dst.sends);
  3548. eax5_set_active_fx_slots_defaults(dst.active_fx_slots);
  3549. eax5_set_speaker_levels_defaults(dst.speaker_levels);
  3550. }
  3551. void ALsource::eax3_translate(const EAX30SOURCEPROPERTIES& src, Eax5Props& dst) noexcept
  3552. {
  3553. // Source.
  3554. //
  3555. static_cast<EAX30SOURCEPROPERTIES&>(dst.source) = src;
  3556. dst.source.flMacroFXFactor = EAXSOURCE_DEFAULTMACROFXFACTOR;
  3557. // Set everything else to defaults.
  3558. //
  3559. eax5_set_sends_defaults(dst.sends);
  3560. eax5_set_active_fx_slots_defaults(dst.active_fx_slots);
  3561. eax5_set_speaker_levels_defaults(dst.speaker_levels);
  3562. }
  3563. void ALsource::eax4_translate(const Eax4Props& src, Eax5Props& dst) noexcept
  3564. {
  3565. // Source.
  3566. //
  3567. static_cast<EAX30SOURCEPROPERTIES&>(dst.source) = src.source;
  3568. dst.source.flMacroFXFactor = EAXSOURCE_DEFAULTMACROFXFACTOR;
  3569. // Sends.
  3570. //
  3571. dst.sends = src.sends;
  3572. for(size_t i{0};i < EAX_MAX_FXSLOTS;++i)
  3573. dst.sends[i].guidReceivingFXSlotID = *(eax5_fx_slot_ids[i]);
  3574. // Active FX slots.
  3575. //
  3576. auto translate_slotid = [](const GUID &src_id) -> GUID
  3577. {
  3578. if(src_id == EAX_NULL_GUID)
  3579. return EAX_NULL_GUID;
  3580. if(src_id == EAX_PrimaryFXSlotID)
  3581. return EAX_PrimaryFXSlotID;
  3582. if(src_id == EAXPROPERTYID_EAX40_FXSlot0)
  3583. return EAXPROPERTYID_EAX50_FXSlot0;
  3584. if(src_id == EAXPROPERTYID_EAX40_FXSlot1)
  3585. return EAXPROPERTYID_EAX50_FXSlot1;
  3586. if(src_id == EAXPROPERTYID_EAX40_FXSlot2)
  3587. return EAXPROPERTYID_EAX50_FXSlot2;
  3588. if(src_id == EAXPROPERTYID_EAX40_FXSlot3)
  3589. return EAXPROPERTYID_EAX50_FXSlot3;
  3590. UNLIKELY
  3591. ERR("Unexpected active FX slot ID");
  3592. return EAX_NULL_GUID;
  3593. };
  3594. const auto src_slots = al::span{src.active_fx_slots.guidActiveFXSlots};
  3595. const auto dst_slots = al::span{dst.active_fx_slots.guidActiveFXSlots};
  3596. auto dstiter = std::transform(src_slots.cbegin(), src_slots.cend(), dst_slots.begin(),
  3597. translate_slotid);
  3598. std::fill(dstiter, dst_slots.end(), EAX_NULL_GUID);
  3599. // Speaker levels.
  3600. //
  3601. eax5_set_speaker_levels_defaults(dst.speaker_levels);
  3602. }
  3603. float ALsource::eax_calculate_dst_occlusion_mb(
  3604. long src_occlusion_mb,
  3605. float path_ratio,
  3606. float lf_ratio) noexcept
  3607. {
  3608. const auto ratio_1 = path_ratio + lf_ratio - 1.0F;
  3609. const auto ratio_2 = path_ratio * lf_ratio;
  3610. const auto ratio = (ratio_2 > ratio_1) ? ratio_2 : ratio_1;
  3611. const auto dst_occlustion_mb = static_cast<float>(src_occlusion_mb) * ratio;
  3612. return dst_occlustion_mb;
  3613. }
  3614. EaxAlLowPassParam ALsource::eax_create_direct_filter_param() const noexcept
  3615. {
  3616. const auto &source = mEax.source;
  3617. auto gain_mb = static_cast<float>(source.lObstruction) * source.flObstructionLFRatio;
  3618. auto gainhf_mb = static_cast<float>(source.lObstruction);
  3619. for(size_t i{0};i < EAX_MAX_FXSLOTS;++i)
  3620. {
  3621. if(!mEaxActiveFxSlots[i])
  3622. continue;
  3623. if(source.lOcclusion != 0)
  3624. {
  3625. const auto& fx_slot = mEaxAlContext->eaxGetFxSlot(i);
  3626. const auto& fx_slot_eax = fx_slot.eax_get_eax_fx_slot();
  3627. const auto is_environmental_fx = ((fx_slot_eax.ulFlags&EAXFXSLOTFLAGS_ENVIRONMENT) != 0);
  3628. const auto is_primary = (mEaxPrimaryFxSlotId.value_or(-1) == fx_slot.eax_get_index());
  3629. if(is_environmental_fx && is_primary)
  3630. {
  3631. gain_mb += eax_calculate_dst_occlusion_mb(source.lOcclusion,
  3632. source.flOcclusionDirectRatio, source.flOcclusionLFRatio);
  3633. gainhf_mb += static_cast<float>(source.lOcclusion) * source.flOcclusionDirectRatio;
  3634. }
  3635. }
  3636. const auto& send = mEax.sends[i];
  3637. if(send.lOcclusion != 0)
  3638. {
  3639. gain_mb += eax_calculate_dst_occlusion_mb(send.lOcclusion, send.flOcclusionDirectRatio,
  3640. send.flOcclusionLFRatio);
  3641. gainhf_mb += static_cast<float>(send.lOcclusion) * send.flOcclusionDirectRatio;
  3642. }
  3643. }
  3644. /* gainhf_mb is the absolute mBFS of the filter's high-frequency volume,
  3645. * and gain_mb is the absolute mBFS of the filter's low-frequency volume.
  3646. * Adjust the HF volume to be relative to the LF volume, to make the
  3647. * appropriate main and relative HF filter volumes.
  3648. *
  3649. * Also add the Direct and DirectHF properties to the filter, which are
  3650. * already the main and relative HF volumes.
  3651. */
  3652. gainhf_mb -= gain_mb - static_cast<float>(source.lDirectHF);
  3653. gain_mb += static_cast<float>(source.lDirect);
  3654. return EaxAlLowPassParam{level_mb_to_gain(gain_mb),
  3655. std::min(level_mb_to_gain(gainhf_mb), 1.0f)};
  3656. }
  3657. EaxAlLowPassParam ALsource::eax_create_room_filter_param(
  3658. const ALeffectslot& fx_slot,
  3659. const EAXSOURCEALLSENDPROPERTIES& send) const noexcept
  3660. {
  3661. const auto& fx_slot_eax = fx_slot.eax_get_eax_fx_slot();
  3662. const auto is_environmental_fx = bool{(fx_slot_eax.ulFlags & EAXFXSLOTFLAGS_ENVIRONMENT) != 0};
  3663. const auto is_primary = bool{mEaxPrimaryFxSlotId.value_or(-1) == fx_slot.eax_get_index()};
  3664. auto gain_mb = (static_cast<float>(fx_slot_eax.lOcclusion) * fx_slot_eax.flOcclusionLFRatio)
  3665. + eax_calculate_dst_occlusion_mb(send.lOcclusion, send.flOcclusionRoomRatio,
  3666. send.flOcclusionLFRatio)
  3667. + (static_cast<float>(send.lExclusion) * send.flExclusionLFRatio);
  3668. auto gainhf_mb = static_cast<float>(fx_slot_eax.lOcclusion)
  3669. + (static_cast<float>(send.lOcclusion) * send.flOcclusionRoomRatio);
  3670. if(is_environmental_fx && is_primary)
  3671. {
  3672. const auto &source = mEax.source;
  3673. gain_mb += eax_calculate_dst_occlusion_mb(source.lOcclusion, source.flOcclusionRoomRatio,
  3674. source.flOcclusionLFRatio);
  3675. gain_mb += static_cast<float>(source.lExclusion) * source.flExclusionLFRatio;
  3676. gainhf_mb += static_cast<float>(source.lOcclusion) * source.flOcclusionRoomRatio;
  3677. gainhf_mb += static_cast<float>(source.lExclusion + send.lExclusion);
  3678. }
  3679. gainhf_mb -= gain_mb - static_cast<float>(send.lSendHF);
  3680. gain_mb += static_cast<float>(send.lSend);
  3681. if(is_environmental_fx)
  3682. {
  3683. const auto &source = mEax.source;
  3684. gain_mb += static_cast<float>(source.lRoom);
  3685. gainhf_mb += static_cast<float>(source.lRoomHF);
  3686. }
  3687. return EaxAlLowPassParam{level_mb_to_gain(gain_mb),
  3688. std::min(level_mb_to_gain(gainhf_mb), 1.0f)};
  3689. }
  3690. void ALsource::eax_update_direct_filter()
  3691. {
  3692. const auto& direct_param = eax_create_direct_filter_param();
  3693. Direct.Gain = direct_param.gain;
  3694. Direct.GainHF = direct_param.gain_hf;
  3695. Direct.HFReference = LowPassFreqRef;
  3696. Direct.GainLF = 1.0f;
  3697. Direct.LFReference = HighPassFreqRef;
  3698. mPropsDirty = true;
  3699. }
  3700. void ALsource::eax_update_room_filters()
  3701. {
  3702. for(size_t i{0};i < EAX_MAX_FXSLOTS;++i)
  3703. {
  3704. if(!mEaxActiveFxSlots[i])
  3705. continue;
  3706. auto& fx_slot = mEaxAlContext->eaxGetFxSlot(i);
  3707. const auto& send = mEax.sends[i];
  3708. const auto& room_param = eax_create_room_filter_param(fx_slot, send);
  3709. eax_set_al_source_send(&fx_slot, i, room_param);
  3710. }
  3711. }
  3712. void ALsource::eax_set_efx_outer_gain_hf()
  3713. {
  3714. OuterGainHF = std::clamp(
  3715. level_mb_to_gain(static_cast<float>(mEax.source.lOutsideVolumeHF)),
  3716. AL_MIN_CONE_OUTER_GAINHF,
  3717. AL_MAX_CONE_OUTER_GAINHF);
  3718. }
  3719. void ALsource::eax_set_efx_doppler_factor()
  3720. {
  3721. DopplerFactor = mEax.source.flDopplerFactor;
  3722. }
  3723. void ALsource::eax_set_efx_rolloff_factor()
  3724. {
  3725. RolloffFactor2 = mEax.source.flRolloffFactor;
  3726. }
  3727. void ALsource::eax_set_efx_room_rolloff_factor()
  3728. {
  3729. RoomRolloffFactor = mEax.source.flRoomRolloffFactor;
  3730. }
  3731. void ALsource::eax_set_efx_air_absorption_factor()
  3732. {
  3733. AirAbsorptionFactor = mEax.source.flAirAbsorptionFactor;
  3734. }
  3735. void ALsource::eax_set_efx_dry_gain_hf_auto()
  3736. {
  3737. DryGainHFAuto = ((mEax.source.ulFlags & EAXSOURCEFLAGS_DIRECTHFAUTO) != 0);
  3738. }
  3739. void ALsource::eax_set_efx_wet_gain_auto()
  3740. {
  3741. WetGainAuto = ((mEax.source.ulFlags & EAXSOURCEFLAGS_ROOMAUTO) != 0);
  3742. }
  3743. void ALsource::eax_set_efx_wet_gain_hf_auto()
  3744. {
  3745. WetGainHFAuto = ((mEax.source.ulFlags & EAXSOURCEFLAGS_ROOMHFAUTO) != 0);
  3746. }
  3747. void ALsource::eax1_set(const EaxCall& call, EAXBUFFER_REVERBPROPERTIES& props)
  3748. {
  3749. switch (call.get_property_id()) {
  3750. case DSPROPERTY_EAXBUFFER_ALL:
  3751. eax_defer<Eax1SourceAllValidator>(call, props);
  3752. break;
  3753. case DSPROPERTY_EAXBUFFER_REVERBMIX:
  3754. eax_defer<Eax1SourceReverbMixValidator>(call, props.fMix);
  3755. break;
  3756. default:
  3757. eax_fail_unknown_property_id();
  3758. }
  3759. }
  3760. void ALsource::eax2_set(const EaxCall& call, EAX20BUFFERPROPERTIES& props)
  3761. {
  3762. switch (call.get_property_id()) {
  3763. case DSPROPERTY_EAX20BUFFER_NONE:
  3764. break;
  3765. case DSPROPERTY_EAX20BUFFER_ALLPARAMETERS:
  3766. eax_defer<Eax2SourceAllValidator>(call, props);
  3767. break;
  3768. case DSPROPERTY_EAX20BUFFER_DIRECT:
  3769. eax_defer<Eax2SourceDirectValidator>(call, props.lDirect);
  3770. break;
  3771. case DSPROPERTY_EAX20BUFFER_DIRECTHF:
  3772. eax_defer<Eax2SourceDirectHfValidator>(call, props.lDirectHF);
  3773. break;
  3774. case DSPROPERTY_EAX20BUFFER_ROOM:
  3775. eax_defer<Eax2SourceRoomValidator>(call, props.lRoom);
  3776. break;
  3777. case DSPROPERTY_EAX20BUFFER_ROOMHF:
  3778. eax_defer<Eax2SourceRoomHfValidator>(call, props.lRoomHF);
  3779. break;
  3780. case DSPROPERTY_EAX20BUFFER_ROOMROLLOFFFACTOR:
  3781. eax_defer<Eax2SourceRoomRolloffFactorValidator>(call, props.flRoomRolloffFactor);
  3782. break;
  3783. case DSPROPERTY_EAX20BUFFER_OBSTRUCTION:
  3784. eax_defer<Eax2SourceObstructionValidator>(call, props.lObstruction);
  3785. break;
  3786. case DSPROPERTY_EAX20BUFFER_OBSTRUCTIONLFRATIO:
  3787. eax_defer<Eax2SourceObstructionLfRatioValidator>(call, props.flObstructionLFRatio);
  3788. break;
  3789. case DSPROPERTY_EAX20BUFFER_OCCLUSION:
  3790. eax_defer<Eax2SourceOcclusionValidator>(call, props.lOcclusion);
  3791. break;
  3792. case DSPROPERTY_EAX20BUFFER_OCCLUSIONLFRATIO:
  3793. eax_defer<Eax2SourceOcclusionLfRatioValidator>(call, props.flOcclusionLFRatio);
  3794. break;
  3795. case DSPROPERTY_EAX20BUFFER_OCCLUSIONROOMRATIO:
  3796. eax_defer<Eax2SourceOcclusionRoomRatioValidator>(call, props.flOcclusionRoomRatio);
  3797. break;
  3798. case DSPROPERTY_EAX20BUFFER_OUTSIDEVOLUMEHF:
  3799. eax_defer<Eax2SourceOutsideVolumeHfValidator>(call, props.lOutsideVolumeHF);
  3800. break;
  3801. case DSPROPERTY_EAX20BUFFER_AIRABSORPTIONFACTOR:
  3802. eax_defer<Eax2SourceAirAbsorptionFactorValidator>(call, props.flAirAbsorptionFactor);
  3803. break;
  3804. case DSPROPERTY_EAX20BUFFER_FLAGS:
  3805. eax_defer<Eax2SourceFlagsValidator>(call, props.dwFlags);
  3806. break;
  3807. default:
  3808. eax_fail_unknown_property_id();
  3809. }
  3810. }
  3811. void ALsource::eax3_set(const EaxCall& call, EAX30SOURCEPROPERTIES& props)
  3812. {
  3813. switch (call.get_property_id()) {
  3814. case EAXSOURCE_NONE:
  3815. break;
  3816. case EAXSOURCE_ALLPARAMETERS:
  3817. eax_defer<Eax3SourceAllValidator>(call, props);
  3818. break;
  3819. case EAXSOURCE_OBSTRUCTIONPARAMETERS:
  3820. eax_defer_sub<Eax4ObstructionValidator, EAXOBSTRUCTIONPROPERTIES>(call, props.lObstruction);
  3821. break;
  3822. case EAXSOURCE_OCCLUSIONPARAMETERS:
  3823. eax_defer_sub<Eax4OcclusionValidator, EAXOCCLUSIONPROPERTIES>(call, props.lOcclusion);
  3824. break;
  3825. case EAXSOURCE_EXCLUSIONPARAMETERS:
  3826. eax_defer_sub<Eax4ExclusionValidator, EAXEXCLUSIONPROPERTIES>(call, props.lExclusion);
  3827. break;
  3828. case EAXSOURCE_DIRECT:
  3829. eax_defer<Eax2SourceDirectValidator>(call, props.lDirect);
  3830. break;
  3831. case EAXSOURCE_DIRECTHF:
  3832. eax_defer<Eax2SourceDirectHfValidator>(call, props.lDirectHF);
  3833. break;
  3834. case EAXSOURCE_ROOM:
  3835. eax_defer<Eax2SourceRoomValidator>(call, props.lRoom);
  3836. break;
  3837. case EAXSOURCE_ROOMHF:
  3838. eax_defer<Eax2SourceRoomHfValidator>(call, props.lRoomHF);
  3839. break;
  3840. case EAXSOURCE_OBSTRUCTION:
  3841. eax_defer<Eax2SourceObstructionValidator>(call, props.lObstruction);
  3842. break;
  3843. case EAXSOURCE_OBSTRUCTIONLFRATIO:
  3844. eax_defer<Eax2SourceObstructionLfRatioValidator>(call, props.flObstructionLFRatio);
  3845. break;
  3846. case EAXSOURCE_OCCLUSION:
  3847. eax_defer<Eax2SourceOcclusionValidator>(call, props.lOcclusion);
  3848. break;
  3849. case EAXSOURCE_OCCLUSIONLFRATIO:
  3850. eax_defer<Eax2SourceOcclusionLfRatioValidator>(call, props.flOcclusionLFRatio);
  3851. break;
  3852. case EAXSOURCE_OCCLUSIONROOMRATIO:
  3853. eax_defer<Eax2SourceOcclusionRoomRatioValidator>(call, props.flOcclusionRoomRatio);
  3854. break;
  3855. case EAXSOURCE_OCCLUSIONDIRECTRATIO:
  3856. eax_defer<Eax3SourceOcclusionDirectRatioValidator>(call, props.flOcclusionDirectRatio);
  3857. break;
  3858. case EAXSOURCE_EXCLUSION:
  3859. eax_defer<Eax3SourceExclusionValidator>(call, props.lExclusion);
  3860. break;
  3861. case EAXSOURCE_EXCLUSIONLFRATIO:
  3862. eax_defer<Eax3SourceExclusionLfRatioValidator>(call, props.flExclusionLFRatio);
  3863. break;
  3864. case EAXSOURCE_OUTSIDEVOLUMEHF:
  3865. eax_defer<Eax2SourceOutsideVolumeHfValidator>(call, props.lOutsideVolumeHF);
  3866. break;
  3867. case EAXSOURCE_DOPPLERFACTOR:
  3868. eax_defer<Eax3SourceDopplerFactorValidator>(call, props.flDopplerFactor);
  3869. break;
  3870. case EAXSOURCE_ROLLOFFFACTOR:
  3871. eax_defer<Eax3SourceRolloffFactorValidator>(call, props.flRolloffFactor);
  3872. break;
  3873. case EAXSOURCE_ROOMROLLOFFFACTOR:
  3874. eax_defer<Eax2SourceRoomRolloffFactorValidator>(call, props.flRoomRolloffFactor);
  3875. break;
  3876. case EAXSOURCE_AIRABSORPTIONFACTOR:
  3877. eax_defer<Eax2SourceAirAbsorptionFactorValidator>(call, props.flAirAbsorptionFactor);
  3878. break;
  3879. case EAXSOURCE_FLAGS:
  3880. eax_defer<Eax2SourceFlagsValidator>(call, props.ulFlags);
  3881. break;
  3882. default:
  3883. eax_fail_unknown_property_id();
  3884. }
  3885. }
  3886. void ALsource::eax4_set(const EaxCall& call, Eax4Props& props)
  3887. {
  3888. switch (call.get_property_id()) {
  3889. case EAXSOURCE_NONE:
  3890. case EAXSOURCE_ALLPARAMETERS:
  3891. case EAXSOURCE_OBSTRUCTIONPARAMETERS:
  3892. case EAXSOURCE_OCCLUSIONPARAMETERS:
  3893. case EAXSOURCE_EXCLUSIONPARAMETERS:
  3894. case EAXSOURCE_DIRECT:
  3895. case EAXSOURCE_DIRECTHF:
  3896. case EAXSOURCE_ROOM:
  3897. case EAXSOURCE_ROOMHF:
  3898. case EAXSOURCE_OBSTRUCTION:
  3899. case EAXSOURCE_OBSTRUCTIONLFRATIO:
  3900. case EAXSOURCE_OCCLUSION:
  3901. case EAXSOURCE_OCCLUSIONLFRATIO:
  3902. case EAXSOURCE_OCCLUSIONROOMRATIO:
  3903. case EAXSOURCE_OCCLUSIONDIRECTRATIO:
  3904. case EAXSOURCE_EXCLUSION:
  3905. case EAXSOURCE_EXCLUSIONLFRATIO:
  3906. case EAXSOURCE_OUTSIDEVOLUMEHF:
  3907. case EAXSOURCE_DOPPLERFACTOR:
  3908. case EAXSOURCE_ROLLOFFFACTOR:
  3909. case EAXSOURCE_ROOMROLLOFFFACTOR:
  3910. case EAXSOURCE_AIRABSORPTIONFACTOR:
  3911. case EAXSOURCE_FLAGS:
  3912. eax3_set(call, props.source);
  3913. break;
  3914. case EAXSOURCE_SENDPARAMETERS:
  3915. eax4_defer_sends<Eax4SendValidator, EAXSOURCESENDPROPERTIES>(call, props.sends);
  3916. break;
  3917. case EAXSOURCE_ALLSENDPARAMETERS:
  3918. eax4_defer_sends<Eax4AllSendValidator, EAXSOURCEALLSENDPROPERTIES>(call, props.sends);
  3919. break;
  3920. case EAXSOURCE_OCCLUSIONSENDPARAMETERS:
  3921. eax4_defer_sends<Eax4OcclusionSendValidator, EAXSOURCEOCCLUSIONSENDPROPERTIES>(call, props.sends);
  3922. break;
  3923. case EAXSOURCE_EXCLUSIONSENDPARAMETERS:
  3924. eax4_defer_sends<Eax4ExclusionSendValidator, EAXSOURCEEXCLUSIONSENDPROPERTIES>(call, props.sends);
  3925. break;
  3926. case EAXSOURCE_ACTIVEFXSLOTID:
  3927. eax4_defer_active_fx_slot_id(call, al::span{props.active_fx_slots.guidActiveFXSlots});
  3928. break;
  3929. default:
  3930. eax_fail_unknown_property_id();
  3931. }
  3932. }
  3933. void ALsource::eax5_defer_all_2d(const EaxCall& call, EAX50SOURCEPROPERTIES& props)
  3934. {
  3935. const auto& src_props = call.get_value<Exception, const EAXSOURCE2DPROPERTIES>();
  3936. Eax5SourceAll2dValidator{}(src_props);
  3937. props.lDirect = src_props.lDirect;
  3938. props.lDirectHF = src_props.lDirectHF;
  3939. props.lRoom = src_props.lRoom;
  3940. props.lRoomHF = src_props.lRoomHF;
  3941. props.ulFlags = src_props.ulFlags;
  3942. }
  3943. void ALsource::eax5_defer_speaker_levels(const EaxCall& call, EaxSpeakerLevels& props)
  3944. {
  3945. const auto values = call.get_values<const EAXSPEAKERLEVELPROPERTIES>(eax_max_speakers);
  3946. std::for_each(values.cbegin(), values.cend(), Eax5SpeakerAllValidator{});
  3947. for (const auto& value : values) {
  3948. const auto index = static_cast<size_t>(value.lSpeakerID - EAXSPEAKER_FRONT_LEFT);
  3949. props[index].lLevel = value.lLevel;
  3950. }
  3951. }
  3952. void ALsource::eax5_set(const EaxCall& call, Eax5Props& props)
  3953. {
  3954. switch (call.get_property_id()) {
  3955. case EAXSOURCE_NONE:
  3956. break;
  3957. case EAXSOURCE_ALLPARAMETERS:
  3958. eax_defer<Eax5SourceAllValidator>(call, props.source);
  3959. break;
  3960. case EAXSOURCE_OBSTRUCTIONPARAMETERS:
  3961. case EAXSOURCE_OCCLUSIONPARAMETERS:
  3962. case EAXSOURCE_EXCLUSIONPARAMETERS:
  3963. case EAXSOURCE_DIRECT:
  3964. case EAXSOURCE_DIRECTHF:
  3965. case EAXSOURCE_ROOM:
  3966. case EAXSOURCE_ROOMHF:
  3967. case EAXSOURCE_OBSTRUCTION:
  3968. case EAXSOURCE_OBSTRUCTIONLFRATIO:
  3969. case EAXSOURCE_OCCLUSION:
  3970. case EAXSOURCE_OCCLUSIONLFRATIO:
  3971. case EAXSOURCE_OCCLUSIONROOMRATIO:
  3972. case EAXSOURCE_OCCLUSIONDIRECTRATIO:
  3973. case EAXSOURCE_EXCLUSION:
  3974. case EAXSOURCE_EXCLUSIONLFRATIO:
  3975. case EAXSOURCE_OUTSIDEVOLUMEHF:
  3976. case EAXSOURCE_DOPPLERFACTOR:
  3977. case EAXSOURCE_ROLLOFFFACTOR:
  3978. case EAXSOURCE_ROOMROLLOFFFACTOR:
  3979. case EAXSOURCE_AIRABSORPTIONFACTOR:
  3980. eax3_set(call, props.source);
  3981. break;
  3982. case EAXSOURCE_FLAGS:
  3983. eax_defer<Eax5SourceFlagsValidator>(call, props.source.ulFlags);
  3984. break;
  3985. case EAXSOURCE_SENDPARAMETERS:
  3986. eax5_defer_sends<Eax5SendValidator, EAXSOURCESENDPROPERTIES>(call, props.sends);
  3987. break;
  3988. case EAXSOURCE_ALLSENDPARAMETERS:
  3989. eax5_defer_sends<Eax5AllSendValidator, EAXSOURCEALLSENDPROPERTIES>(call, props.sends);
  3990. break;
  3991. case EAXSOURCE_OCCLUSIONSENDPARAMETERS:
  3992. eax5_defer_sends<Eax5OcclusionSendValidator, EAXSOURCEOCCLUSIONSENDPROPERTIES>(call, props.sends);
  3993. break;
  3994. case EAXSOURCE_EXCLUSIONSENDPARAMETERS:
  3995. eax5_defer_sends<Eax5ExclusionSendValidator, EAXSOURCEEXCLUSIONSENDPROPERTIES>(call, props.sends);
  3996. break;
  3997. case EAXSOURCE_ACTIVEFXSLOTID:
  3998. eax5_defer_active_fx_slot_id(call, al::span{props.active_fx_slots.guidActiveFXSlots});
  3999. break;
  4000. case EAXSOURCE_MACROFXFACTOR:
  4001. eax_defer<Eax5SourceMacroFXFactorValidator>(call, props.source.flMacroFXFactor);
  4002. break;
  4003. case EAXSOURCE_SPEAKERLEVELS:
  4004. eax5_defer_speaker_levels(call, props.speaker_levels);
  4005. break;
  4006. case EAXSOURCE_ALL2DPARAMETERS:
  4007. eax5_defer_all_2d(call, props.source);
  4008. break;
  4009. default:
  4010. eax_fail_unknown_property_id();
  4011. }
  4012. }
  4013. void ALsource::eax_set(const EaxCall& call)
  4014. {
  4015. const auto eax_version = call.get_version();
  4016. switch(eax_version)
  4017. {
  4018. case 1: eax1_set(call, mEax1.d); break;
  4019. case 2: eax2_set(call, mEax2.d); break;
  4020. case 3: eax3_set(call, mEax3.d); break;
  4021. case 4: eax4_set(call, mEax4.d); break;
  4022. case 5: eax5_set(call, mEax5.d); break;
  4023. default: eax_fail_unknown_property_id();
  4024. }
  4025. mEaxChanged = true;
  4026. mEaxVersion = eax_version;
  4027. }
  4028. void ALsource::eax_get_active_fx_slot_id(const EaxCall& call, const al::span<const GUID> src_ids)
  4029. {
  4030. assert(src_ids.size()==EAX40_MAX_ACTIVE_FXSLOTS || src_ids.size()==EAX50_MAX_ACTIVE_FXSLOTS);
  4031. const auto dst_ids = call.get_values<GUID>(src_ids.size());
  4032. std::uninitialized_copy_n(src_ids.begin(), dst_ids.size(), dst_ids.begin());
  4033. }
  4034. void ALsource::eax1_get(const EaxCall& call, const EAXBUFFER_REVERBPROPERTIES& props)
  4035. {
  4036. switch (call.get_property_id()) {
  4037. case DSPROPERTY_EAXBUFFER_ALL:
  4038. case DSPROPERTY_EAXBUFFER_REVERBMIX:
  4039. call.set_value<Exception>(props.fMix);
  4040. break;
  4041. default:
  4042. eax_fail_unknown_property_id();
  4043. }
  4044. }
  4045. void ALsource::eax2_get(const EaxCall& call, const EAX20BUFFERPROPERTIES& props)
  4046. {
  4047. switch (call.get_property_id()) {
  4048. case DSPROPERTY_EAX20BUFFER_NONE:
  4049. break;
  4050. case DSPROPERTY_EAX20BUFFER_ALLPARAMETERS:
  4051. call.set_value<Exception>(props);
  4052. break;
  4053. case DSPROPERTY_EAX20BUFFER_DIRECT:
  4054. call.set_value<Exception>(props.lDirect);
  4055. break;
  4056. case DSPROPERTY_EAX20BUFFER_DIRECTHF:
  4057. call.set_value<Exception>(props.lDirectHF);
  4058. break;
  4059. case DSPROPERTY_EAX20BUFFER_ROOM:
  4060. call.set_value<Exception>(props.lRoom);
  4061. break;
  4062. case DSPROPERTY_EAX20BUFFER_ROOMHF:
  4063. call.set_value<Exception>(props.lRoomHF);
  4064. break;
  4065. case DSPROPERTY_EAX20BUFFER_ROOMROLLOFFFACTOR:
  4066. call.set_value<Exception>(props.flRoomRolloffFactor);
  4067. break;
  4068. case DSPROPERTY_EAX20BUFFER_OBSTRUCTION:
  4069. call.set_value<Exception>(props.lObstruction);
  4070. break;
  4071. case DSPROPERTY_EAX20BUFFER_OBSTRUCTIONLFRATIO:
  4072. call.set_value<Exception>(props.flObstructionLFRatio);
  4073. break;
  4074. case DSPROPERTY_EAX20BUFFER_OCCLUSION:
  4075. call.set_value<Exception>(props.lOcclusion);
  4076. break;
  4077. case DSPROPERTY_EAX20BUFFER_OCCLUSIONLFRATIO:
  4078. call.set_value<Exception>(props.flOcclusionLFRatio);
  4079. break;
  4080. case DSPROPERTY_EAX20BUFFER_OCCLUSIONROOMRATIO:
  4081. call.set_value<Exception>(props.flOcclusionRoomRatio);
  4082. break;
  4083. case DSPROPERTY_EAX20BUFFER_OUTSIDEVOLUMEHF:
  4084. call.set_value<Exception>(props.lOutsideVolumeHF);
  4085. break;
  4086. case DSPROPERTY_EAX20BUFFER_AIRABSORPTIONFACTOR:
  4087. call.set_value<Exception>(props.flAirAbsorptionFactor);
  4088. break;
  4089. case DSPROPERTY_EAX20BUFFER_FLAGS:
  4090. call.set_value<Exception>(props.dwFlags);
  4091. break;
  4092. default:
  4093. eax_fail_unknown_property_id();
  4094. }
  4095. }
  4096. void ALsource::eax3_get_obstruction(const EaxCall& call, const EAX30SOURCEPROPERTIES& props)
  4097. {
  4098. const auto& subprops = reinterpret_cast<const EAXOBSTRUCTIONPROPERTIES&>(props.lObstruction);
  4099. call.set_value<Exception>(subprops);
  4100. }
  4101. void ALsource::eax3_get_occlusion(const EaxCall& call, const EAX30SOURCEPROPERTIES& props)
  4102. {
  4103. const auto& subprops = reinterpret_cast<const EAXOCCLUSIONPROPERTIES&>(props.lOcclusion);
  4104. call.set_value<Exception>(subprops);
  4105. }
  4106. void ALsource::eax3_get_exclusion(const EaxCall& call, const EAX30SOURCEPROPERTIES& props)
  4107. {
  4108. const auto& subprops = reinterpret_cast<const EAXEXCLUSIONPROPERTIES&>(props.lExclusion);
  4109. call.set_value<Exception>(subprops);
  4110. }
  4111. void ALsource::eax3_get(const EaxCall& call, const EAX30SOURCEPROPERTIES& props)
  4112. {
  4113. switch (call.get_property_id()) {
  4114. case EAXSOURCE_NONE:
  4115. break;
  4116. case EAXSOURCE_ALLPARAMETERS:
  4117. call.set_value<Exception>(props);
  4118. break;
  4119. case EAXSOURCE_OBSTRUCTIONPARAMETERS:
  4120. eax3_get_obstruction(call, props);
  4121. break;
  4122. case EAXSOURCE_OCCLUSIONPARAMETERS:
  4123. eax3_get_occlusion(call, props);
  4124. break;
  4125. case EAXSOURCE_EXCLUSIONPARAMETERS:
  4126. eax3_get_exclusion(call, props);
  4127. break;
  4128. case EAXSOURCE_DIRECT:
  4129. call.set_value<Exception>(props.lDirect);
  4130. break;
  4131. case EAXSOURCE_DIRECTHF:
  4132. call.set_value<Exception>(props.lDirectHF);
  4133. break;
  4134. case EAXSOURCE_ROOM:
  4135. call.set_value<Exception>(props.lRoom);
  4136. break;
  4137. case EAXSOURCE_ROOMHF:
  4138. call.set_value<Exception>(props.lRoomHF);
  4139. break;
  4140. case EAXSOURCE_OBSTRUCTION:
  4141. call.set_value<Exception>(props.lObstruction);
  4142. break;
  4143. case EAXSOURCE_OBSTRUCTIONLFRATIO:
  4144. call.set_value<Exception>(props.flObstructionLFRatio);
  4145. break;
  4146. case EAXSOURCE_OCCLUSION:
  4147. call.set_value<Exception>(props.lOcclusion);
  4148. break;
  4149. case EAXSOURCE_OCCLUSIONLFRATIO:
  4150. call.set_value<Exception>(props.flOcclusionLFRatio);
  4151. break;
  4152. case EAXSOURCE_OCCLUSIONROOMRATIO:
  4153. call.set_value<Exception>(props.flOcclusionRoomRatio);
  4154. break;
  4155. case EAXSOURCE_OCCLUSIONDIRECTRATIO:
  4156. call.set_value<Exception>(props.flOcclusionDirectRatio);
  4157. break;
  4158. case EAXSOURCE_EXCLUSION:
  4159. call.set_value<Exception>(props.lExclusion);
  4160. break;
  4161. case EAXSOURCE_EXCLUSIONLFRATIO:
  4162. call.set_value<Exception>(props.flExclusionLFRatio);
  4163. break;
  4164. case EAXSOURCE_OUTSIDEVOLUMEHF:
  4165. call.set_value<Exception>(props.lOutsideVolumeHF);
  4166. break;
  4167. case EAXSOURCE_DOPPLERFACTOR:
  4168. call.set_value<Exception>(props.flDopplerFactor);
  4169. break;
  4170. case EAXSOURCE_ROLLOFFFACTOR:
  4171. call.set_value<Exception>(props.flRolloffFactor);
  4172. break;
  4173. case EAXSOURCE_ROOMROLLOFFFACTOR:
  4174. call.set_value<Exception>(props.flRoomRolloffFactor);
  4175. break;
  4176. case EAXSOURCE_AIRABSORPTIONFACTOR:
  4177. call.set_value<Exception>(props.flAirAbsorptionFactor);
  4178. break;
  4179. case EAXSOURCE_FLAGS:
  4180. call.set_value<Exception>(props.ulFlags);
  4181. break;
  4182. default:
  4183. eax_fail_unknown_property_id();
  4184. }
  4185. }
  4186. void ALsource::eax4_get(const EaxCall& call, const Eax4Props& props)
  4187. {
  4188. switch (call.get_property_id()) {
  4189. case EAXSOURCE_NONE:
  4190. break;
  4191. case EAXSOURCE_ALLPARAMETERS:
  4192. case EAXSOURCE_OBSTRUCTIONPARAMETERS:
  4193. case EAXSOURCE_OCCLUSIONPARAMETERS:
  4194. case EAXSOURCE_EXCLUSIONPARAMETERS:
  4195. case EAXSOURCE_DIRECT:
  4196. case EAXSOURCE_DIRECTHF:
  4197. case EAXSOURCE_ROOM:
  4198. case EAXSOURCE_ROOMHF:
  4199. case EAXSOURCE_OBSTRUCTION:
  4200. case EAXSOURCE_OBSTRUCTIONLFRATIO:
  4201. case EAXSOURCE_OCCLUSION:
  4202. case EAXSOURCE_OCCLUSIONLFRATIO:
  4203. case EAXSOURCE_OCCLUSIONROOMRATIO:
  4204. case EAXSOURCE_OCCLUSIONDIRECTRATIO:
  4205. case EAXSOURCE_EXCLUSION:
  4206. case EAXSOURCE_EXCLUSIONLFRATIO:
  4207. case EAXSOURCE_OUTSIDEVOLUMEHF:
  4208. case EAXSOURCE_DOPPLERFACTOR:
  4209. case EAXSOURCE_ROLLOFFFACTOR:
  4210. case EAXSOURCE_ROOMROLLOFFFACTOR:
  4211. case EAXSOURCE_AIRABSORPTIONFACTOR:
  4212. case EAXSOURCE_FLAGS:
  4213. eax3_get(call, props.source);
  4214. break;
  4215. case EAXSOURCE_SENDPARAMETERS:
  4216. eax_get_sends<EAXSOURCESENDPROPERTIES>(call, props.sends);
  4217. break;
  4218. case EAXSOURCE_ALLSENDPARAMETERS:
  4219. eax_get_sends<EAXSOURCEALLSENDPROPERTIES>(call, props.sends);
  4220. break;
  4221. case EAXSOURCE_OCCLUSIONSENDPARAMETERS:
  4222. eax_get_sends<EAXSOURCEOCCLUSIONSENDPROPERTIES>(call, props.sends);
  4223. break;
  4224. case EAXSOURCE_EXCLUSIONSENDPARAMETERS:
  4225. eax_get_sends<EAXSOURCEEXCLUSIONSENDPROPERTIES>(call, props.sends);
  4226. break;
  4227. case EAXSOURCE_ACTIVEFXSLOTID:
  4228. eax_get_active_fx_slot_id(call, props.active_fx_slots.guidActiveFXSlots);
  4229. break;
  4230. default:
  4231. eax_fail_unknown_property_id();
  4232. }
  4233. }
  4234. void ALsource::eax5_get_all_2d(const EaxCall& call, const EAX50SOURCEPROPERTIES& props)
  4235. {
  4236. auto& subprops = call.get_value<Exception, EAXSOURCE2DPROPERTIES>();
  4237. subprops.lDirect = props.lDirect;
  4238. subprops.lDirectHF = props.lDirectHF;
  4239. subprops.lRoom = props.lRoom;
  4240. subprops.lRoomHF = props.lRoomHF;
  4241. subprops.ulFlags = props.ulFlags;
  4242. }
  4243. void ALsource::eax5_get_speaker_levels(const EaxCall& call, const EaxSpeakerLevels& props)
  4244. {
  4245. const auto subprops = call.get_values<EAXSPEAKERLEVELPROPERTIES>(eax_max_speakers);
  4246. std::uninitialized_copy_n(props.cbegin(), subprops.size(), subprops.begin());
  4247. }
  4248. void ALsource::eax5_get(const EaxCall& call, const Eax5Props& props)
  4249. {
  4250. switch (call.get_property_id()) {
  4251. case EAXSOURCE_NONE:
  4252. break;
  4253. case EAXSOURCE_ALLPARAMETERS:
  4254. case EAXSOURCE_OBSTRUCTIONPARAMETERS:
  4255. case EAXSOURCE_OCCLUSIONPARAMETERS:
  4256. case EAXSOURCE_EXCLUSIONPARAMETERS:
  4257. case EAXSOURCE_DIRECT:
  4258. case EAXSOURCE_DIRECTHF:
  4259. case EAXSOURCE_ROOM:
  4260. case EAXSOURCE_ROOMHF:
  4261. case EAXSOURCE_OBSTRUCTION:
  4262. case EAXSOURCE_OBSTRUCTIONLFRATIO:
  4263. case EAXSOURCE_OCCLUSION:
  4264. case EAXSOURCE_OCCLUSIONLFRATIO:
  4265. case EAXSOURCE_OCCLUSIONROOMRATIO:
  4266. case EAXSOURCE_OCCLUSIONDIRECTRATIO:
  4267. case EAXSOURCE_EXCLUSION:
  4268. case EAXSOURCE_EXCLUSIONLFRATIO:
  4269. case EAXSOURCE_OUTSIDEVOLUMEHF:
  4270. case EAXSOURCE_DOPPLERFACTOR:
  4271. case EAXSOURCE_ROLLOFFFACTOR:
  4272. case EAXSOURCE_ROOMROLLOFFFACTOR:
  4273. case EAXSOURCE_AIRABSORPTIONFACTOR:
  4274. case EAXSOURCE_FLAGS:
  4275. eax3_get(call, props.source);
  4276. break;
  4277. case EAXSOURCE_SENDPARAMETERS:
  4278. eax_get_sends<EAXSOURCESENDPROPERTIES>(call, props.sends);
  4279. break;
  4280. case EAXSOURCE_ALLSENDPARAMETERS:
  4281. eax_get_sends<EAXSOURCEALLSENDPROPERTIES>(call, props.sends);
  4282. break;
  4283. case EAXSOURCE_OCCLUSIONSENDPARAMETERS:
  4284. eax_get_sends<EAXSOURCEOCCLUSIONSENDPROPERTIES>(call, props.sends);
  4285. break;
  4286. case EAXSOURCE_EXCLUSIONSENDPARAMETERS:
  4287. eax_get_sends<EAXSOURCEEXCLUSIONSENDPROPERTIES>(call, props.sends);
  4288. break;
  4289. case EAXSOURCE_ACTIVEFXSLOTID:
  4290. eax_get_active_fx_slot_id(call, props.active_fx_slots.guidActiveFXSlots);
  4291. break;
  4292. case EAXSOURCE_MACROFXFACTOR:
  4293. call.set_value<Exception>(props.source.flMacroFXFactor);
  4294. break;
  4295. case EAXSOURCE_SPEAKERLEVELS:
  4296. call.set_value<Exception>(props.speaker_levels);
  4297. break;
  4298. case EAXSOURCE_ALL2DPARAMETERS:
  4299. eax5_get_all_2d(call, props.source);
  4300. break;
  4301. default:
  4302. eax_fail_unknown_property_id();
  4303. }
  4304. }
  4305. void ALsource::eax_get(const EaxCall& call)
  4306. {
  4307. switch (call.get_version()) {
  4308. case 1: eax1_get(call, mEax1.i); break;
  4309. case 2: eax2_get(call, mEax2.i); break;
  4310. case 3: eax3_get(call, mEax3.i); break;
  4311. case 4: eax4_get(call, mEax4.i); break;
  4312. case 5: eax5_get(call, mEax5.i); break;
  4313. default: eax_fail_unknown_version();
  4314. }
  4315. }
  4316. void ALsource::eax_set_al_source_send(ALeffectslot *slot, size_t sendidx, const EaxAlLowPassParam &filter)
  4317. {
  4318. if(sendidx >= EAX_MAX_FXSLOTS)
  4319. return;
  4320. auto &send = Send[sendidx];
  4321. send.Gain = filter.gain;
  4322. send.GainHF = filter.gain_hf;
  4323. send.HFReference = LowPassFreqRef;
  4324. send.GainLF = 1.0f;
  4325. send.LFReference = HighPassFreqRef;
  4326. if(slot != nullptr)
  4327. IncrementRef(slot->ref);
  4328. if(auto *oldslot = send.Slot)
  4329. DecrementRef(oldslot->ref);
  4330. send.Slot = slot;
  4331. mPropsDirty = true;
  4332. }
  4333. void ALsource::eax_commit_active_fx_slots()
  4334. {
  4335. // Clear all slots to an inactive state.
  4336. mEaxActiveFxSlots.fill(false);
  4337. // Mark the set slots as active.
  4338. for(const auto& slot_id : mEax.active_fx_slots.guidActiveFXSlots)
  4339. {
  4340. if(slot_id == EAX_NULL_GUID)
  4341. {
  4342. }
  4343. else if(slot_id == EAX_PrimaryFXSlotID)
  4344. {
  4345. // Mark primary FX slot as active.
  4346. if(mEaxPrimaryFxSlotId.has_value())
  4347. mEaxActiveFxSlots[*mEaxPrimaryFxSlotId] = true;
  4348. }
  4349. else if(slot_id == EAXPROPERTYID_EAX50_FXSlot0)
  4350. mEaxActiveFxSlots[0] = true;
  4351. else if(slot_id == EAXPROPERTYID_EAX50_FXSlot1)
  4352. mEaxActiveFxSlots[1] = true;
  4353. else if(slot_id == EAXPROPERTYID_EAX50_FXSlot2)
  4354. mEaxActiveFxSlots[2] = true;
  4355. else if(slot_id == EAXPROPERTYID_EAX50_FXSlot3)
  4356. mEaxActiveFxSlots[3] = true;
  4357. }
  4358. // Deactivate EFX auxiliary effect slots for inactive slots. Active slots
  4359. // will be updated with the room filters.
  4360. for(size_t i{0};i < EAX_MAX_FXSLOTS;++i)
  4361. {
  4362. if(!mEaxActiveFxSlots[i])
  4363. eax_set_al_source_send(nullptr, i, EaxAlLowPassParam{1.0f, 1.0f});
  4364. }
  4365. }
  4366. void ALsource::eax_commit_filters()
  4367. {
  4368. eax_update_direct_filter();
  4369. eax_update_room_filters();
  4370. }
  4371. void ALsource::eaxCommit()
  4372. {
  4373. const auto primary_fx_slot_id = mEaxAlContext->eaxGetPrimaryFxSlotIndex();
  4374. const auto is_primary_fx_slot_id_changed = (mEaxPrimaryFxSlotId != primary_fx_slot_id);
  4375. if(!mEaxChanged && !is_primary_fx_slot_id_changed)
  4376. return;
  4377. mEaxPrimaryFxSlotId = primary_fx_slot_id;
  4378. mEaxChanged = false;
  4379. switch(mEaxVersion)
  4380. {
  4381. case 1:
  4382. mEax1.i = mEax1.d;
  4383. eax1_translate(mEax1.i, mEax);
  4384. break;
  4385. case 2:
  4386. mEax2.i = mEax2.d;
  4387. eax2_translate(mEax2.i, mEax);
  4388. break;
  4389. case 3:
  4390. mEax3.i = mEax3.d;
  4391. eax3_translate(mEax3.i, mEax);
  4392. break;
  4393. case 4:
  4394. mEax4.i = mEax4.d;
  4395. eax4_translate(mEax4.i, mEax);
  4396. break;
  4397. case 5:
  4398. mEax5.i = mEax5.d;
  4399. mEax = mEax5.d;
  4400. break;
  4401. }
  4402. eax_set_efx_outer_gain_hf();
  4403. eax_set_efx_doppler_factor();
  4404. eax_set_efx_rolloff_factor();
  4405. eax_set_efx_room_rolloff_factor();
  4406. eax_set_efx_air_absorption_factor();
  4407. eax_set_efx_dry_gain_hf_auto();
  4408. eax_set_efx_wet_gain_auto();
  4409. eax_set_efx_wet_gain_hf_auto();
  4410. eax_commit_active_fx_slots();
  4411. eax_commit_filters();
  4412. }
  4413. #endif // ALSOFT_EAX