source.cpp 112 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462
  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 <cassert>
  26. #include <chrono>
  27. #include <climits>
  28. #include <cmath>
  29. #include <cstdint>
  30. #include <functional>
  31. #include <iterator>
  32. #include <limits>
  33. #include <memory>
  34. #include <mutex>
  35. #include <new>
  36. #include <numeric>
  37. #include <thread>
  38. #include <utility>
  39. #include "AL/al.h"
  40. #include "AL/alc.h"
  41. #include "AL/alext.h"
  42. #include "AL/efx.h"
  43. #include "albit.h"
  44. #include "alcmain.h"
  45. #include "alcontext.h"
  46. #include "almalloc.h"
  47. #include "alnumeric.h"
  48. #include "aloptional.h"
  49. #include "alspan.h"
  50. #include "alu.h"
  51. #include "atomic.h"
  52. #include "auxeffectslot.h"
  53. #include "backends/base.h"
  54. #include "bformatdec.h"
  55. #include "buffer.h"
  56. #include "core/ambidefs.h"
  57. #include "core/except.h"
  58. #include "core/filters/nfc.h"
  59. #include "core/filters/splitter.h"
  60. #include "core/logging.h"
  61. #include "event.h"
  62. #include "filter.h"
  63. #include "inprogext.h"
  64. #include "math_defs.h"
  65. #include "opthelpers.h"
  66. #include "ringbuffer.h"
  67. #include "threads.h"
  68. #include "voice_change.h"
  69. namespace {
  70. using namespace std::placeholders;
  71. using std::chrono::nanoseconds;
  72. Voice *GetSourceVoice(ALsource *source, ALCcontext *context)
  73. {
  74. auto voicelist = context->getVoicesSpan();
  75. ALuint idx{source->VoiceIdx};
  76. if(idx < voicelist.size())
  77. {
  78. ALuint sid{source->id};
  79. Voice *voice = voicelist[idx];
  80. if(voice->mSourceID.load(std::memory_order_acquire) == sid)
  81. return voice;
  82. }
  83. source->VoiceIdx = INVALID_VOICE_IDX;
  84. return nullptr;
  85. }
  86. void UpdateSourceProps(const ALsource *source, Voice *voice, ALCcontext *context)
  87. {
  88. /* Get an unused property container, or allocate a new one as needed. */
  89. VoicePropsItem *props{context->mFreeVoiceProps.load(std::memory_order_acquire)};
  90. if(!props)
  91. props = new VoicePropsItem{};
  92. else
  93. {
  94. VoicePropsItem *next;
  95. do {
  96. next = props->next.load(std::memory_order_relaxed);
  97. } while(context->mFreeVoiceProps.compare_exchange_weak(props, next,
  98. std::memory_order_acq_rel, std::memory_order_acquire) == 0);
  99. }
  100. props->Pitch = source->Pitch;
  101. props->Gain = source->Gain;
  102. props->OuterGain = source->OuterGain;
  103. props->MinGain = source->MinGain;
  104. props->MaxGain = source->MaxGain;
  105. props->InnerAngle = source->InnerAngle;
  106. props->OuterAngle = source->OuterAngle;
  107. props->RefDistance = source->RefDistance;
  108. props->MaxDistance = source->MaxDistance;
  109. props->RolloffFactor = source->RolloffFactor;
  110. props->Position = source->Position;
  111. props->Velocity = source->Velocity;
  112. props->Direction = source->Direction;
  113. props->OrientAt = source->OrientAt;
  114. props->OrientUp = source->OrientUp;
  115. props->HeadRelative = source->HeadRelative;
  116. props->mDistanceModel = source->mDistanceModel;
  117. props->mResampler = source->mResampler;
  118. props->DirectChannels = source->DirectChannels;
  119. props->mSpatializeMode = source->mSpatialize;
  120. props->DryGainHFAuto = source->DryGainHFAuto;
  121. props->WetGainAuto = source->WetGainAuto;
  122. props->WetGainHFAuto = source->WetGainHFAuto;
  123. props->OuterGainHF = source->OuterGainHF;
  124. props->AirAbsorptionFactor = source->AirAbsorptionFactor;
  125. props->RoomRolloffFactor = source->RoomRolloffFactor;
  126. props->DopplerFactor = source->DopplerFactor;
  127. props->StereoPan = source->StereoPan;
  128. props->Radius = source->Radius;
  129. props->Direct.Gain = source->Direct.Gain;
  130. props->Direct.GainHF = source->Direct.GainHF;
  131. props->Direct.HFReference = source->Direct.HFReference;
  132. props->Direct.GainLF = source->Direct.GainLF;
  133. props->Direct.LFReference = source->Direct.LFReference;
  134. auto copy_send = [](const ALsource::SendData &srcsend) noexcept -> VoiceProps::SendData
  135. {
  136. VoiceProps::SendData ret{};
  137. ret.Slot = srcsend.Slot ? &srcsend.Slot->mSlot : nullptr;
  138. ret.Gain = srcsend.Gain;
  139. ret.GainHF = srcsend.GainHF;
  140. ret.HFReference = srcsend.HFReference;
  141. ret.GainLF = srcsend.GainLF;
  142. ret.LFReference = srcsend.LFReference;
  143. return ret;
  144. };
  145. std::transform(source->Send.cbegin(), source->Send.cend(), props->Send, copy_send);
  146. if(!props->Send[0].Slot && context->mDefaultSlot)
  147. props->Send[0].Slot = &context->mDefaultSlot->mSlot;
  148. /* Set the new container for updating internal parameters. */
  149. props = voice->mUpdate.exchange(props, std::memory_order_acq_rel);
  150. if(props)
  151. {
  152. /* If there was an unused update container, put it back in the
  153. * freelist.
  154. */
  155. AtomicReplaceHead(context->mFreeVoiceProps, props);
  156. }
  157. }
  158. /* GetSourceSampleOffset
  159. *
  160. * Gets the current read offset for the given Source, in 32.32 fixed-point
  161. * samples. The offset is relative to the start of the queue (not the start of
  162. * the current buffer).
  163. */
  164. int64_t GetSourceSampleOffset(ALsource *Source, ALCcontext *context, nanoseconds *clocktime)
  165. {
  166. ALCdevice *device{context->mDevice.get()};
  167. const VoiceBufferItem *Current{};
  168. uint64_t readPos{};
  169. ALuint refcount;
  170. Voice *voice;
  171. do {
  172. refcount = device->waitForMix();
  173. *clocktime = GetDeviceClockTime(device);
  174. voice = GetSourceVoice(Source, context);
  175. if(voice)
  176. {
  177. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  178. readPos = uint64_t{voice->mPosition.load(std::memory_order_relaxed)} << 32;
  179. readPos |= uint64_t{voice->mPositionFrac.load(std::memory_order_relaxed)} <<
  180. (32-MixerFracBits);
  181. }
  182. std::atomic_thread_fence(std::memory_order_acquire);
  183. } while(refcount != device->MixCount.load(std::memory_order_relaxed));
  184. if(!voice)
  185. return 0;
  186. for(auto &item : Source->mQueue)
  187. {
  188. if(&item == Current) break;
  189. readPos += uint64_t{item.mSampleLen} << 32;
  190. }
  191. return static_cast<int64_t>(minu64(readPos, 0x7fffffffffffffff_u64));
  192. }
  193. /* GetSourceSecOffset
  194. *
  195. * Gets the current read offset for the given Source, in seconds. The offset is
  196. * relative to the start of the queue (not the start of the current buffer).
  197. */
  198. double GetSourceSecOffset(ALsource *Source, ALCcontext *context, nanoseconds *clocktime)
  199. {
  200. ALCdevice *device{context->mDevice.get()};
  201. const VoiceBufferItem *Current{};
  202. uint64_t readPos{};
  203. ALuint refcount;
  204. Voice *voice;
  205. do {
  206. refcount = device->waitForMix();
  207. *clocktime = GetDeviceClockTime(device);
  208. voice = GetSourceVoice(Source, context);
  209. if(voice)
  210. {
  211. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  212. readPos = uint64_t{voice->mPosition.load(std::memory_order_relaxed)} << MixerFracBits;
  213. readPos |= voice->mPositionFrac.load(std::memory_order_relaxed);
  214. }
  215. std::atomic_thread_fence(std::memory_order_acquire);
  216. } while(refcount != device->MixCount.load(std::memory_order_relaxed));
  217. if(!voice)
  218. return 0.0f;
  219. const ALbuffer *BufferFmt{nullptr};
  220. auto BufferList = Source->mQueue.cbegin();
  221. while(BufferList != Source->mQueue.cend() && std::addressof(*BufferList) != Current)
  222. {
  223. if(!BufferFmt) BufferFmt = BufferList->mBuffer;
  224. readPos += uint64_t{BufferList->mSampleLen} << MixerFracBits;
  225. ++BufferList;
  226. }
  227. while(BufferList != Source->mQueue.cend() && !BufferFmt)
  228. {
  229. BufferFmt = BufferList->mBuffer;
  230. ++BufferList;
  231. }
  232. assert(BufferFmt != nullptr);
  233. return static_cast<double>(readPos) / double{MixerFracOne} / BufferFmt->mSampleRate;
  234. }
  235. /* GetSourceOffset
  236. *
  237. * Gets the current read offset for the given Source, in the appropriate format
  238. * (Bytes, Samples or Seconds). The offset is relative to the start of the
  239. * queue (not the start of the current buffer).
  240. */
  241. double GetSourceOffset(ALsource *Source, ALenum name, ALCcontext *context)
  242. {
  243. ALCdevice *device{context->mDevice.get()};
  244. const VoiceBufferItem *Current{};
  245. ALuint readPos{};
  246. ALuint readPosFrac{};
  247. ALuint refcount;
  248. Voice *voice;
  249. do {
  250. refcount = device->waitForMix();
  251. voice = GetSourceVoice(Source, context);
  252. if(voice)
  253. {
  254. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  255. readPos = voice->mPosition.load(std::memory_order_relaxed);
  256. readPosFrac = voice->mPositionFrac.load(std::memory_order_relaxed);
  257. }
  258. std::atomic_thread_fence(std::memory_order_acquire);
  259. } while(refcount != device->MixCount.load(std::memory_order_relaxed));
  260. if(!voice)
  261. return 0.0;
  262. const ALbuffer *BufferFmt{nullptr};
  263. auto BufferList = Source->mQueue.cbegin();
  264. while(BufferList != Source->mQueue.cend() && std::addressof(*BufferList) != Current)
  265. {
  266. if(!BufferFmt) BufferFmt = BufferList->mBuffer;
  267. readPos += BufferList->mSampleLen;
  268. ++BufferList;
  269. }
  270. while(BufferList != Source->mQueue.cend() && !BufferFmt)
  271. {
  272. BufferFmt = BufferList->mBuffer;
  273. ++BufferList;
  274. }
  275. assert(BufferFmt != nullptr);
  276. double offset{};
  277. switch(name)
  278. {
  279. case AL_SEC_OFFSET:
  280. offset = (readPos + readPosFrac/double{MixerFracOne}) / BufferFmt->mSampleRate;
  281. break;
  282. case AL_SAMPLE_OFFSET:
  283. offset = readPos + readPosFrac/double{MixerFracOne};
  284. break;
  285. case AL_BYTE_OFFSET:
  286. if(BufferFmt->OriginalType == UserFmtIMA4)
  287. {
  288. ALuint FrameBlockSize{BufferFmt->OriginalAlign};
  289. ALuint align{(BufferFmt->OriginalAlign-1)/2 + 4};
  290. ALuint BlockSize{align * BufferFmt->channelsFromFmt()};
  291. /* Round down to nearest ADPCM block */
  292. offset = static_cast<double>(readPos / FrameBlockSize * BlockSize);
  293. }
  294. else if(BufferFmt->OriginalType == UserFmtMSADPCM)
  295. {
  296. ALuint FrameBlockSize{BufferFmt->OriginalAlign};
  297. ALuint align{(FrameBlockSize-2)/2 + 7};
  298. ALuint BlockSize{align * BufferFmt->channelsFromFmt()};
  299. /* Round down to nearest ADPCM block */
  300. offset = static_cast<double>(readPos / FrameBlockSize * BlockSize);
  301. }
  302. else
  303. {
  304. const ALuint FrameSize{BufferFmt->frameSizeFromFmt()};
  305. offset = static_cast<double>(readPos * FrameSize);
  306. }
  307. break;
  308. }
  309. return offset;
  310. }
  311. struct VoicePos {
  312. ALuint pos, frac;
  313. VoiceBufferItem *bufferitem;
  314. };
  315. /**
  316. * GetSampleOffset
  317. *
  318. * Retrieves the voice position, fixed-point fraction, and bufferlist item
  319. * using the givem offset type and offset. If the offset is out of range,
  320. * returns an empty optional.
  321. */
  322. al::optional<VoicePos> GetSampleOffset(al::deque<ALbufferQueueItem> &BufferList, ALenum OffsetType,
  323. double Offset)
  324. {
  325. /* Find the first valid Buffer in the Queue */
  326. const ALbuffer *BufferFmt{nullptr};
  327. for(auto &item : BufferList)
  328. {
  329. BufferFmt = item.mBuffer;
  330. if(BufferFmt) break;
  331. }
  332. if(!BufferFmt)
  333. return al::nullopt;
  334. /* Get sample frame offset */
  335. ALuint offset{0u}, frac{0u};
  336. double dbloff, dblfrac;
  337. switch(OffsetType)
  338. {
  339. case AL_SEC_OFFSET:
  340. dblfrac = std::modf(Offset*BufferFmt->mSampleRate, &dbloff);
  341. offset = static_cast<ALuint>(mind(dbloff, std::numeric_limits<ALuint>::max()));
  342. frac = static_cast<ALuint>(mind(dblfrac*MixerFracOne, MixerFracOne-1.0));
  343. break;
  344. case AL_SAMPLE_OFFSET:
  345. dblfrac = std::modf(Offset, &dbloff);
  346. offset = static_cast<ALuint>(mind(dbloff, std::numeric_limits<ALuint>::max()));
  347. frac = static_cast<ALuint>(mind(dblfrac*MixerFracOne, MixerFracOne-1.0));
  348. break;
  349. case AL_BYTE_OFFSET:
  350. /* Determine the ByteOffset (and ensure it is block aligned) */
  351. offset = static_cast<ALuint>(Offset);
  352. if(BufferFmt->OriginalType == UserFmtIMA4)
  353. {
  354. const ALuint align{(BufferFmt->OriginalAlign-1)/2 + 4};
  355. offset /= align * BufferFmt->channelsFromFmt();
  356. offset *= BufferFmt->OriginalAlign;
  357. }
  358. else if(BufferFmt->OriginalType == UserFmtMSADPCM)
  359. {
  360. const ALuint align{(BufferFmt->OriginalAlign-2)/2 + 7};
  361. offset /= align * BufferFmt->channelsFromFmt();
  362. offset *= BufferFmt->OriginalAlign;
  363. }
  364. else
  365. offset /= BufferFmt->frameSizeFromFmt();
  366. frac = 0;
  367. break;
  368. }
  369. /* Find the bufferlist item this offset belongs to. */
  370. ALuint totalBufferLen{0u};
  371. for(auto &item : BufferList)
  372. {
  373. if(totalBufferLen > offset)
  374. break;
  375. if(item.mSampleLen > offset-totalBufferLen)
  376. {
  377. /* Offset is in this buffer */
  378. return al::make_optional(VoicePos{offset-totalBufferLen, frac, &item});
  379. }
  380. totalBufferLen += item.mSampleLen;
  381. }
  382. /* Offset is out of range of the queue */
  383. return al::nullopt;
  384. }
  385. void InitVoice(Voice *voice, ALsource *source, ALbufferQueueItem *BufferList, ALCcontext *context,
  386. ALCdevice *device)
  387. {
  388. voice->mLoopBuffer.store(source->Looping ? &source->mQueue.front() : nullptr,
  389. std::memory_order_relaxed);
  390. ALbuffer *buffer{BufferList->mBuffer};
  391. ALuint num_channels{buffer->channelsFromFmt()};
  392. voice->mFrequency = buffer->mSampleRate;
  393. voice->mFmtChannels = buffer->mChannels;
  394. voice->mFmtType = buffer->mType;
  395. voice->mSampleSize = buffer->bytesFromFmt();
  396. voice->mAmbiLayout = buffer->mAmbiLayout;
  397. voice->mAmbiScaling = buffer->mAmbiScaling;
  398. voice->mAmbiOrder = buffer->mAmbiOrder;
  399. if(buffer->mCallback) voice->mFlags |= VoiceIsCallback;
  400. else if(source->SourceType == AL_STATIC) voice->mFlags |= VoiceIsStatic;
  401. voice->mNumCallbackSamples = 0;
  402. /* Clear the stepping value explicitly so the mixer knows not to mix this
  403. * until the update gets applied.
  404. */
  405. voice->mStep = 0;
  406. if(voice->mChans.capacity() > 2 && num_channels < voice->mChans.capacity())
  407. al::vector<Voice::ChannelData>{}.swap(voice->mChans);
  408. voice->mChans.reserve(maxu(2, num_channels));
  409. voice->mChans.resize(num_channels);
  410. /* Don't need to set the VOICE_IS_AMBISONIC flag if the device is not
  411. * higher order than the voice. No HF scaling is necessary to mix it.
  412. */
  413. if(voice->mAmbiOrder && device->mAmbiOrder > voice->mAmbiOrder)
  414. {
  415. const uint8_t *OrderFromChan{(voice->mFmtChannels == FmtBFormat2D) ?
  416. AmbiIndex::OrderFrom2DChannel().data() :
  417. AmbiIndex::OrderFromChannel().data()};
  418. const auto scales = BFormatDec::GetHFOrderScales(voice->mAmbiOrder, device->mAmbiOrder);
  419. const BandSplitter splitter{device->mXOverFreq / static_cast<float>(device->Frequency)};
  420. for(auto &chandata : voice->mChans)
  421. {
  422. chandata.mPrevSamples.fill(0.0f);
  423. chandata.mAmbiScale = scales[*(OrderFromChan++)];
  424. chandata.mAmbiSplitter = splitter;
  425. chandata.mDryParams = DirectParams{};
  426. std::fill_n(chandata.mWetParams.begin(), device->NumAuxSends, SendParams{});
  427. }
  428. voice->mFlags |= VoiceIsAmbisonic;
  429. }
  430. else
  431. {
  432. /* Clear previous samples. */
  433. for(auto &chandata : voice->mChans)
  434. {
  435. chandata.mPrevSamples.fill(0.0f);
  436. chandata.mDryParams = DirectParams{};
  437. std::fill_n(chandata.mWetParams.begin(), device->NumAuxSends, SendParams{});
  438. }
  439. }
  440. if(device->AvgSpeakerDist > 0.0f)
  441. {
  442. const float w1{SpeedOfSoundMetersPerSec /
  443. (device->AvgSpeakerDist * static_cast<float>(device->Frequency))};
  444. for(auto &chandata : voice->mChans)
  445. chandata.mDryParams.NFCtrlFilter.init(w1);
  446. }
  447. source->PropsClean.test_and_set(std::memory_order_acq_rel);
  448. UpdateSourceProps(source, voice, context);
  449. voice->mSourceID.store(source->id, std::memory_order_release);
  450. }
  451. VoiceChange *GetVoiceChanger(ALCcontext *ctx)
  452. {
  453. VoiceChange *vchg{ctx->mVoiceChangeTail};
  454. if UNLIKELY(vchg == ctx->mCurrentVoiceChange.load(std::memory_order_acquire))
  455. {
  456. ctx->allocVoiceChanges(1);
  457. vchg = ctx->mVoiceChangeTail;
  458. }
  459. ctx->mVoiceChangeTail = vchg->mNext.exchange(nullptr, std::memory_order_relaxed);
  460. return vchg;
  461. }
  462. void SendVoiceChanges(ALCcontext *ctx, VoiceChange *tail)
  463. {
  464. ALCdevice *device{ctx->mDevice.get()};
  465. VoiceChange *oldhead{ctx->mCurrentVoiceChange.load(std::memory_order_acquire)};
  466. while(VoiceChange *next{oldhead->mNext.load(std::memory_order_relaxed)})
  467. oldhead = next;
  468. oldhead->mNext.store(tail, std::memory_order_release);
  469. const bool connected{device->Connected.load(std::memory_order_acquire)};
  470. device->waitForMix();
  471. if UNLIKELY(!connected)
  472. {
  473. /* If the device is disconnected, just ignore all pending changes. */
  474. VoiceChange *cur{ctx->mCurrentVoiceChange.load(std::memory_order_acquire)};
  475. while(VoiceChange *next{cur->mNext.load(std::memory_order_acquire)})
  476. {
  477. cur = next;
  478. if(Voice *voice{cur->mVoice})
  479. voice->mSourceID.store(0, std::memory_order_relaxed);
  480. }
  481. ctx->mCurrentVoiceChange.store(cur, std::memory_order_release);
  482. }
  483. }
  484. bool SetVoiceOffset(Voice *oldvoice, const VoicePos &vpos, ALsource *source, ALCcontext *context,
  485. ALCdevice *device)
  486. {
  487. /* First, get a free voice to start at the new offset. */
  488. auto voicelist = context->getVoicesSpan();
  489. Voice *newvoice{};
  490. ALuint vidx{0};
  491. for(Voice *voice : voicelist)
  492. {
  493. if(voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  494. && voice->mSourceID.load(std::memory_order_relaxed) == 0u
  495. && voice->mPendingChange.load(std::memory_order_relaxed) == false)
  496. {
  497. newvoice = voice;
  498. break;
  499. }
  500. ++vidx;
  501. }
  502. if UNLIKELY(!newvoice)
  503. {
  504. auto &allvoices = *context->mVoices.load(std::memory_order_relaxed);
  505. if(allvoices.size() == voicelist.size())
  506. context->allocVoices(1);
  507. context->mActiveVoiceCount.fetch_add(1, std::memory_order_release);
  508. voicelist = context->getVoicesSpan();
  509. vidx = 0;
  510. for(Voice *voice : voicelist)
  511. {
  512. if(voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  513. && voice->mSourceID.load(std::memory_order_relaxed) == 0u
  514. && voice->mPendingChange.load(std::memory_order_relaxed) == false)
  515. {
  516. newvoice = voice;
  517. break;
  518. }
  519. ++vidx;
  520. }
  521. }
  522. /* Initialize the new voice and set its starting offset.
  523. * TODO: It might be better to have the VoiceChange processing copy the old
  524. * voice's mixing parameters (and pending update) insead of initializing it
  525. * all here. This would just need to set the minimum properties to link the
  526. * voice to the source and its position-dependent properties (including the
  527. * fading flag).
  528. */
  529. newvoice->mPlayState.store(Voice::Pending, std::memory_order_relaxed);
  530. newvoice->mPosition.store(vpos.pos, std::memory_order_relaxed);
  531. newvoice->mPositionFrac.store(vpos.frac, std::memory_order_relaxed);
  532. newvoice->mCurrentBuffer.store(vpos.bufferitem, std::memory_order_relaxed);
  533. newvoice->mFlags = 0u;
  534. if(vpos.pos > 0 || vpos.frac > 0 || vpos.bufferitem != &source->mQueue.front())
  535. newvoice->mFlags |= VoiceIsFading;
  536. InitVoice(newvoice, source, &source->mQueue.front(), context, device);
  537. source->VoiceIdx = vidx;
  538. /* Set the old voice as having a pending change, and send it off with the
  539. * new one with a new offset voice change.
  540. */
  541. oldvoice->mPendingChange.store(true, std::memory_order_relaxed);
  542. VoiceChange *vchg{GetVoiceChanger(context)};
  543. vchg->mOldVoice = oldvoice;
  544. vchg->mVoice = newvoice;
  545. vchg->mSourceID = source->id;
  546. vchg->mState = VChangeState::Restart;
  547. SendVoiceChanges(context, vchg);
  548. /* If the old voice still has a sourceID, it's still active and the change-
  549. * over will work on the next update.
  550. */
  551. if LIKELY(oldvoice->mSourceID.load(std::memory_order_acquire) != 0u)
  552. return true;
  553. /* Otherwise, if the new voice's state is not pending, the change-over
  554. * already happened.
  555. */
  556. if(newvoice->mPlayState.load(std::memory_order_acquire) != Voice::Pending)
  557. return true;
  558. /* Otherwise, wait for any current mix to finish and check one last time. */
  559. device->waitForMix();
  560. if(newvoice->mPlayState.load(std::memory_order_acquire) != Voice::Pending)
  561. return true;
  562. /* The change-over failed because the old voice stopped before the new
  563. * voice could start at the new offset. Let go of the new voice and have
  564. * the caller store the source offset since it's stopped.
  565. */
  566. newvoice->mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
  567. newvoice->mLoopBuffer.store(nullptr, std::memory_order_relaxed);
  568. newvoice->mSourceID.store(0u, std::memory_order_relaxed);
  569. newvoice->mPlayState.store(Voice::Stopped, std::memory_order_relaxed);
  570. return false;
  571. }
  572. /**
  573. * Returns if the last known state for the source was playing or paused. Does
  574. * not sync with the mixer voice.
  575. */
  576. inline bool IsPlayingOrPaused(ALsource *source)
  577. { return source->state == AL_PLAYING || source->state == AL_PAUSED; }
  578. /**
  579. * Returns an updated source state using the matching voice's status (or lack
  580. * thereof).
  581. */
  582. inline ALenum GetSourceState(ALsource *source, Voice *voice)
  583. {
  584. if(!voice && source->state == AL_PLAYING)
  585. source->state = AL_STOPPED;
  586. return source->state;
  587. }
  588. /**
  589. * Returns if the source should specify an update, given the context's
  590. * deferring state and the source's last known state.
  591. */
  592. inline bool SourceShouldUpdate(ALsource *source, ALCcontext *context)
  593. {
  594. return !context->mDeferUpdates.load(std::memory_order_acquire) &&
  595. IsPlayingOrPaused(source);
  596. }
  597. bool EnsureSources(ALCcontext *context, size_t needed)
  598. {
  599. size_t count{std::accumulate(context->mSourceList.cbegin(), context->mSourceList.cend(),
  600. size_t{0},
  601. [](size_t cur, const SourceSubList &sublist) noexcept -> size_t
  602. { return cur + static_cast<ALuint>(al::popcount(sublist.FreeMask)); })};
  603. while(needed > count)
  604. {
  605. if UNLIKELY(context->mSourceList.size() >= 1<<25)
  606. return false;
  607. context->mSourceList.emplace_back();
  608. auto sublist = context->mSourceList.end() - 1;
  609. sublist->FreeMask = ~0_u64;
  610. sublist->Sources = static_cast<ALsource*>(al_calloc(alignof(ALsource), sizeof(ALsource)*64));
  611. if UNLIKELY(!sublist->Sources)
  612. {
  613. context->mSourceList.pop_back();
  614. return false;
  615. }
  616. count += 64;
  617. }
  618. return true;
  619. }
  620. ALsource *AllocSource(ALCcontext *context)
  621. {
  622. auto sublist = std::find_if(context->mSourceList.begin(), context->mSourceList.end(),
  623. [](const SourceSubList &entry) noexcept -> bool
  624. { return entry.FreeMask != 0; }
  625. );
  626. auto lidx = static_cast<ALuint>(std::distance(context->mSourceList.begin(), sublist));
  627. auto slidx = static_cast<ALuint>(al::countr_zero(sublist->FreeMask));
  628. ALsource *source{::new(sublist->Sources + slidx) ALsource{}};
  629. /* Add 1 to avoid source ID 0. */
  630. source->id = ((lidx<<6) | slidx) + 1;
  631. context->mNumSources += 1;
  632. sublist->FreeMask &= ~(1_u64 << slidx);
  633. return source;
  634. }
  635. void FreeSource(ALCcontext *context, ALsource *source)
  636. {
  637. const ALuint id{source->id - 1};
  638. const size_t lidx{id >> 6};
  639. const ALuint slidx{id & 0x3f};
  640. if(IsPlayingOrPaused(source))
  641. {
  642. if(Voice *voice{GetSourceVoice(source, context)})
  643. {
  644. VoiceChange *vchg{GetVoiceChanger(context)};
  645. voice->mPendingChange.store(true, std::memory_order_relaxed);
  646. vchg->mVoice = voice;
  647. vchg->mSourceID = source->id;
  648. vchg->mState = VChangeState::Stop;
  649. SendVoiceChanges(context, vchg);
  650. }
  651. }
  652. al::destroy_at(source);
  653. context->mSourceList[lidx].FreeMask |= 1_u64 << slidx;
  654. context->mNumSources--;
  655. }
  656. inline ALsource *LookupSource(ALCcontext *context, ALuint id) noexcept
  657. {
  658. const size_t lidx{(id-1) >> 6};
  659. const ALuint slidx{(id-1) & 0x3f};
  660. if UNLIKELY(lidx >= context->mSourceList.size())
  661. return nullptr;
  662. SourceSubList &sublist{context->mSourceList[lidx]};
  663. if UNLIKELY(sublist.FreeMask & (1_u64 << slidx))
  664. return nullptr;
  665. return sublist.Sources + slidx;
  666. }
  667. inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id) noexcept
  668. {
  669. const size_t lidx{(id-1) >> 6};
  670. const ALuint slidx{(id-1) & 0x3f};
  671. if UNLIKELY(lidx >= device->BufferList.size())
  672. return nullptr;
  673. BufferSubList &sublist = device->BufferList[lidx];
  674. if UNLIKELY(sublist.FreeMask & (1_u64 << slidx))
  675. return nullptr;
  676. return sublist.Buffers + slidx;
  677. }
  678. inline ALfilter *LookupFilter(ALCdevice *device, ALuint id) noexcept
  679. {
  680. const size_t lidx{(id-1) >> 6};
  681. const ALuint slidx{(id-1) & 0x3f};
  682. if UNLIKELY(lidx >= device->FilterList.size())
  683. return nullptr;
  684. FilterSubList &sublist = device->FilterList[lidx];
  685. if UNLIKELY(sublist.FreeMask & (1_u64 << slidx))
  686. return nullptr;
  687. return sublist.Filters + slidx;
  688. }
  689. inline ALeffectslot *LookupEffectSlot(ALCcontext *context, ALuint id) noexcept
  690. {
  691. const size_t lidx{(id-1) >> 6};
  692. const ALuint slidx{(id-1) & 0x3f};
  693. if UNLIKELY(lidx >= context->mEffectSlotList.size())
  694. return nullptr;
  695. EffectSlotSubList &sublist{context->mEffectSlotList[lidx]};
  696. if UNLIKELY(sublist.FreeMask & (1_u64 << slidx))
  697. return nullptr;
  698. return sublist.EffectSlots + slidx;
  699. }
  700. al::optional<SpatializeMode> SpatializeModeFromEnum(ALenum mode)
  701. {
  702. switch(mode)
  703. {
  704. case AL_FALSE: return al::make_optional(SpatializeMode::Off);
  705. case AL_TRUE: return al::make_optional(SpatializeMode::On);
  706. case AL_AUTO_SOFT: return al::make_optional(SpatializeMode::Auto);
  707. }
  708. WARN("Unsupported spatialize mode: 0x%04x\n", mode);
  709. return al::nullopt;
  710. }
  711. ALenum EnumFromSpatializeMode(SpatializeMode mode)
  712. {
  713. switch(mode)
  714. {
  715. case SpatializeMode::Off: return AL_FALSE;
  716. case SpatializeMode::On: return AL_TRUE;
  717. case SpatializeMode::Auto: return AL_AUTO_SOFT;
  718. }
  719. throw std::runtime_error{"Invalid SpatializeMode: "+std::to_string(int(mode))};
  720. }
  721. al::optional<DirectMode> DirectModeFromEnum(ALenum mode)
  722. {
  723. switch(mode)
  724. {
  725. case AL_FALSE: return al::make_optional(DirectMode::Off);
  726. case AL_DROP_UNMATCHED_SOFT: return al::make_optional(DirectMode::DropMismatch);
  727. case AL_REMIX_UNMATCHED_SOFT: return al::make_optional(DirectMode::RemixMismatch);
  728. }
  729. WARN("Unsupported direct mode: 0x%04x\n", mode);
  730. return al::nullopt;
  731. }
  732. ALenum EnumFromDirectMode(DirectMode mode)
  733. {
  734. switch(mode)
  735. {
  736. case DirectMode::Off: return AL_FALSE;
  737. case DirectMode::DropMismatch: return AL_DROP_UNMATCHED_SOFT;
  738. case DirectMode::RemixMismatch: return AL_REMIX_UNMATCHED_SOFT;
  739. }
  740. throw std::runtime_error{"Invalid DirectMode: "+std::to_string(int(mode))};
  741. }
  742. al::optional<DistanceModel> DistanceModelFromALenum(ALenum model)
  743. {
  744. switch(model)
  745. {
  746. case AL_NONE: return al::make_optional(DistanceModel::Disable);
  747. case AL_INVERSE_DISTANCE: return al::make_optional(DistanceModel::Inverse);
  748. case AL_INVERSE_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::InverseClamped);
  749. case AL_LINEAR_DISTANCE: return al::make_optional(DistanceModel::Linear);
  750. case AL_LINEAR_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::LinearClamped);
  751. case AL_EXPONENT_DISTANCE: return al::make_optional(DistanceModel::Exponent);
  752. case AL_EXPONENT_DISTANCE_CLAMPED: return al::make_optional(DistanceModel::ExponentClamped);
  753. }
  754. return al::nullopt;
  755. }
  756. ALenum ALenumFromDistanceModel(DistanceModel model)
  757. {
  758. switch(model)
  759. {
  760. case DistanceModel::Disable: return AL_NONE;
  761. case DistanceModel::Inverse: return AL_INVERSE_DISTANCE;
  762. case DistanceModel::InverseClamped: return AL_INVERSE_DISTANCE_CLAMPED;
  763. case DistanceModel::Linear: return AL_LINEAR_DISTANCE;
  764. case DistanceModel::LinearClamped: return AL_LINEAR_DISTANCE_CLAMPED;
  765. case DistanceModel::Exponent: return AL_EXPONENT_DISTANCE;
  766. case DistanceModel::ExponentClamped: return AL_EXPONENT_DISTANCE_CLAMPED;
  767. }
  768. throw std::runtime_error{"Unexpected distance model "+std::to_string(static_cast<int>(model))};
  769. }
  770. enum SourceProp : ALenum {
  771. srcPitch = AL_PITCH,
  772. srcGain = AL_GAIN,
  773. srcMinGain = AL_MIN_GAIN,
  774. srcMaxGain = AL_MAX_GAIN,
  775. srcMaxDistance = AL_MAX_DISTANCE,
  776. srcRolloffFactor = AL_ROLLOFF_FACTOR,
  777. srcDopplerFactor = AL_DOPPLER_FACTOR,
  778. srcConeOuterGain = AL_CONE_OUTER_GAIN,
  779. srcSecOffset = AL_SEC_OFFSET,
  780. srcSampleOffset = AL_SAMPLE_OFFSET,
  781. srcByteOffset = AL_BYTE_OFFSET,
  782. srcConeInnerAngle = AL_CONE_INNER_ANGLE,
  783. srcConeOuterAngle = AL_CONE_OUTER_ANGLE,
  784. srcRefDistance = AL_REFERENCE_DISTANCE,
  785. srcPosition = AL_POSITION,
  786. srcVelocity = AL_VELOCITY,
  787. srcDirection = AL_DIRECTION,
  788. srcSourceRelative = AL_SOURCE_RELATIVE,
  789. srcLooping = AL_LOOPING,
  790. srcBuffer = AL_BUFFER,
  791. srcSourceState = AL_SOURCE_STATE,
  792. srcBuffersQueued = AL_BUFFERS_QUEUED,
  793. srcBuffersProcessed = AL_BUFFERS_PROCESSED,
  794. srcSourceType = AL_SOURCE_TYPE,
  795. /* ALC_EXT_EFX */
  796. srcConeOuterGainHF = AL_CONE_OUTER_GAINHF,
  797. srcAirAbsorptionFactor = AL_AIR_ABSORPTION_FACTOR,
  798. srcRoomRolloffFactor = AL_ROOM_ROLLOFF_FACTOR,
  799. srcDirectFilterGainHFAuto = AL_DIRECT_FILTER_GAINHF_AUTO,
  800. srcAuxSendFilterGainAuto = AL_AUXILIARY_SEND_FILTER_GAIN_AUTO,
  801. srcAuxSendFilterGainHFAuto = AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO,
  802. srcDirectFilter = AL_DIRECT_FILTER,
  803. srcAuxSendFilter = AL_AUXILIARY_SEND_FILTER,
  804. /* AL_SOFT_direct_channels */
  805. srcDirectChannelsSOFT = AL_DIRECT_CHANNELS_SOFT,
  806. /* AL_EXT_source_distance_model */
  807. srcDistanceModel = AL_DISTANCE_MODEL,
  808. /* AL_SOFT_source_latency */
  809. srcSampleOffsetLatencySOFT = AL_SAMPLE_OFFSET_LATENCY_SOFT,
  810. srcSecOffsetLatencySOFT = AL_SEC_OFFSET_LATENCY_SOFT,
  811. /* AL_EXT_STEREO_ANGLES */
  812. srcAngles = AL_STEREO_ANGLES,
  813. /* AL_EXT_SOURCE_RADIUS */
  814. srcRadius = AL_SOURCE_RADIUS,
  815. /* AL_EXT_BFORMAT */
  816. srcOrientation = AL_ORIENTATION,
  817. /* AL_SOFT_source_resampler */
  818. srcResampler = AL_SOURCE_RESAMPLER_SOFT,
  819. /* AL_SOFT_source_spatialize */
  820. srcSpatialize = AL_SOURCE_SPATIALIZE_SOFT,
  821. /* ALC_SOFT_device_clock */
  822. srcSampleOffsetClockSOFT = AL_SAMPLE_OFFSET_CLOCK_SOFT,
  823. srcSecOffsetClockSOFT = AL_SEC_OFFSET_CLOCK_SOFT,
  824. };
  825. constexpr size_t MaxValues{6u};
  826. ALuint FloatValsByProp(ALenum prop)
  827. {
  828. switch(static_cast<SourceProp>(prop))
  829. {
  830. case AL_PITCH:
  831. case AL_GAIN:
  832. case AL_MIN_GAIN:
  833. case AL_MAX_GAIN:
  834. case AL_MAX_DISTANCE:
  835. case AL_ROLLOFF_FACTOR:
  836. case AL_DOPPLER_FACTOR:
  837. case AL_CONE_OUTER_GAIN:
  838. case AL_SEC_OFFSET:
  839. case AL_SAMPLE_OFFSET:
  840. case AL_BYTE_OFFSET:
  841. case AL_CONE_INNER_ANGLE:
  842. case AL_CONE_OUTER_ANGLE:
  843. case AL_REFERENCE_DISTANCE:
  844. case AL_CONE_OUTER_GAINHF:
  845. case AL_AIR_ABSORPTION_FACTOR:
  846. case AL_ROOM_ROLLOFF_FACTOR:
  847. case AL_DIRECT_FILTER_GAINHF_AUTO:
  848. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  849. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  850. case AL_DIRECT_CHANNELS_SOFT:
  851. case AL_DISTANCE_MODEL:
  852. case AL_SOURCE_RELATIVE:
  853. case AL_LOOPING:
  854. case AL_SOURCE_STATE:
  855. case AL_BUFFERS_QUEUED:
  856. case AL_BUFFERS_PROCESSED:
  857. case AL_SOURCE_TYPE:
  858. case AL_SOURCE_RADIUS:
  859. case AL_SOURCE_RESAMPLER_SOFT:
  860. case AL_SOURCE_SPATIALIZE_SOFT:
  861. return 1;
  862. case AL_STEREO_ANGLES:
  863. return 2;
  864. case AL_POSITION:
  865. case AL_VELOCITY:
  866. case AL_DIRECTION:
  867. return 3;
  868. case AL_ORIENTATION:
  869. return 6;
  870. case AL_SEC_OFFSET_LATENCY_SOFT:
  871. case AL_SEC_OFFSET_CLOCK_SOFT:
  872. break; /* Double only */
  873. case AL_BUFFER:
  874. case AL_DIRECT_FILTER:
  875. case AL_AUXILIARY_SEND_FILTER:
  876. break; /* i/i64 only */
  877. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  878. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  879. break; /* i64 only */
  880. }
  881. return 0;
  882. }
  883. ALuint DoubleValsByProp(ALenum prop)
  884. {
  885. switch(static_cast<SourceProp>(prop))
  886. {
  887. case AL_PITCH:
  888. case AL_GAIN:
  889. case AL_MIN_GAIN:
  890. case AL_MAX_GAIN:
  891. case AL_MAX_DISTANCE:
  892. case AL_ROLLOFF_FACTOR:
  893. case AL_DOPPLER_FACTOR:
  894. case AL_CONE_OUTER_GAIN:
  895. case AL_SEC_OFFSET:
  896. case AL_SAMPLE_OFFSET:
  897. case AL_BYTE_OFFSET:
  898. case AL_CONE_INNER_ANGLE:
  899. case AL_CONE_OUTER_ANGLE:
  900. case AL_REFERENCE_DISTANCE:
  901. case AL_CONE_OUTER_GAINHF:
  902. case AL_AIR_ABSORPTION_FACTOR:
  903. case AL_ROOM_ROLLOFF_FACTOR:
  904. case AL_DIRECT_FILTER_GAINHF_AUTO:
  905. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  906. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  907. case AL_DIRECT_CHANNELS_SOFT:
  908. case AL_DISTANCE_MODEL:
  909. case AL_SOURCE_RELATIVE:
  910. case AL_LOOPING:
  911. case AL_SOURCE_STATE:
  912. case AL_BUFFERS_QUEUED:
  913. case AL_BUFFERS_PROCESSED:
  914. case AL_SOURCE_TYPE:
  915. case AL_SOURCE_RADIUS:
  916. case AL_SOURCE_RESAMPLER_SOFT:
  917. case AL_SOURCE_SPATIALIZE_SOFT:
  918. return 1;
  919. case AL_SEC_OFFSET_LATENCY_SOFT:
  920. case AL_SEC_OFFSET_CLOCK_SOFT:
  921. case AL_STEREO_ANGLES:
  922. return 2;
  923. case AL_POSITION:
  924. case AL_VELOCITY:
  925. case AL_DIRECTION:
  926. return 3;
  927. case AL_ORIENTATION:
  928. return 6;
  929. case AL_BUFFER:
  930. case AL_DIRECT_FILTER:
  931. case AL_AUXILIARY_SEND_FILTER:
  932. break; /* i/i64 only */
  933. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  934. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  935. break; /* i64 only */
  936. }
  937. return 0;
  938. }
  939. bool SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const float> values);
  940. bool SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const int> values);
  941. bool SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const int64_t> values);
  942. #define CHECKSIZE(v, s) do { \
  943. if LIKELY((v).size() == (s) || (v).size() == MaxValues) break; \
  944. Context->setError(AL_INVALID_ENUM, \
  945. "Property 0x%04x expects %d value(s), got %zu", prop, (s), \
  946. (v).size()); \
  947. return false; \
  948. } while(0)
  949. #define CHECKVAL(x) do { \
  950. if LIKELY(x) break; \
  951. Context->setError(AL_INVALID_VALUE, "Value out of range"); \
  952. return false; \
  953. } while(0)
  954. bool UpdateSourceProps(ALsource *source, ALCcontext *context)
  955. {
  956. Voice *voice;
  957. if(SourceShouldUpdate(source, context) && (voice=GetSourceVoice(source, context)) != nullptr)
  958. UpdateSourceProps(source, voice, context);
  959. else
  960. source->PropsClean.clear(std::memory_order_release);
  961. return true;
  962. }
  963. bool SetSourcefv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const float> values)
  964. {
  965. int ival;
  966. switch(prop)
  967. {
  968. case AL_SEC_OFFSET_LATENCY_SOFT:
  969. case AL_SEC_OFFSET_CLOCK_SOFT:
  970. /* Query only */
  971. SETERR_RETURN(Context, AL_INVALID_OPERATION, false,
  972. "Setting read-only source property 0x%04x", prop);
  973. case AL_PITCH:
  974. CHECKSIZE(values, 1);
  975. CHECKVAL(values[0] >= 0.0f);
  976. Source->Pitch = values[0];
  977. return UpdateSourceProps(Source, Context);
  978. case AL_CONE_INNER_ANGLE:
  979. CHECKSIZE(values, 1);
  980. CHECKVAL(values[0] >= 0.0f && values[0] <= 360.0f);
  981. Source->InnerAngle = values[0];
  982. return UpdateSourceProps(Source, Context);
  983. case AL_CONE_OUTER_ANGLE:
  984. CHECKSIZE(values, 1);
  985. CHECKVAL(values[0] >= 0.0f && values[0] <= 360.0f);
  986. Source->OuterAngle = values[0];
  987. return UpdateSourceProps(Source, Context);
  988. case AL_GAIN:
  989. CHECKSIZE(values, 1);
  990. CHECKVAL(values[0] >= 0.0f);
  991. Source->Gain = values[0];
  992. return UpdateSourceProps(Source, Context);
  993. case AL_MAX_DISTANCE:
  994. CHECKSIZE(values, 1);
  995. CHECKVAL(values[0] >= 0.0f);
  996. Source->MaxDistance = values[0];
  997. return UpdateSourceProps(Source, Context);
  998. case AL_ROLLOFF_FACTOR:
  999. CHECKSIZE(values, 1);
  1000. CHECKVAL(values[0] >= 0.0f);
  1001. Source->RolloffFactor = values[0];
  1002. return UpdateSourceProps(Source, Context);
  1003. case AL_REFERENCE_DISTANCE:
  1004. CHECKSIZE(values, 1);
  1005. CHECKVAL(values[0] >= 0.0f);
  1006. Source->RefDistance = values[0];
  1007. return UpdateSourceProps(Source, Context);
  1008. case AL_MIN_GAIN:
  1009. CHECKSIZE(values, 1);
  1010. CHECKVAL(values[0] >= 0.0f);
  1011. Source->MinGain = values[0];
  1012. return UpdateSourceProps(Source, Context);
  1013. case AL_MAX_GAIN:
  1014. CHECKSIZE(values, 1);
  1015. CHECKVAL(values[0] >= 0.0f);
  1016. Source->MaxGain = values[0];
  1017. return UpdateSourceProps(Source, Context);
  1018. case AL_CONE_OUTER_GAIN:
  1019. CHECKSIZE(values, 1);
  1020. CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f);
  1021. Source->OuterGain = values[0];
  1022. return UpdateSourceProps(Source, Context);
  1023. case AL_CONE_OUTER_GAINHF:
  1024. CHECKSIZE(values, 1);
  1025. CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f);
  1026. Source->OuterGainHF = values[0];
  1027. return UpdateSourceProps(Source, Context);
  1028. case AL_AIR_ABSORPTION_FACTOR:
  1029. CHECKSIZE(values, 1);
  1030. CHECKVAL(values[0] >= 0.0f && values[0] <= 10.0f);
  1031. Source->AirAbsorptionFactor = values[0];
  1032. return UpdateSourceProps(Source, Context);
  1033. case AL_ROOM_ROLLOFF_FACTOR:
  1034. CHECKSIZE(values, 1);
  1035. CHECKVAL(values[0] >= 0.0f && values[0] <= 10.0f);
  1036. Source->RoomRolloffFactor = values[0];
  1037. return UpdateSourceProps(Source, Context);
  1038. case AL_DOPPLER_FACTOR:
  1039. CHECKSIZE(values, 1);
  1040. CHECKVAL(values[0] >= 0.0f && values[0] <= 1.0f);
  1041. Source->DopplerFactor = values[0];
  1042. return UpdateSourceProps(Source, Context);
  1043. case AL_SEC_OFFSET:
  1044. case AL_SAMPLE_OFFSET:
  1045. case AL_BYTE_OFFSET:
  1046. CHECKSIZE(values, 1);
  1047. CHECKVAL(values[0] >= 0.0f);
  1048. if(Voice *voice{GetSourceVoice(Source, Context)})
  1049. {
  1050. if((voice->mFlags&VoiceIsCallback))
  1051. SETERR_RETURN(Context, AL_INVALID_VALUE, false,
  1052. "Source offset for callback is invalid");
  1053. auto vpos = GetSampleOffset(Source->mQueue, prop, values[0]);
  1054. if(!vpos) SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid offset");
  1055. if(SetVoiceOffset(voice, *vpos, Source, Context, Context->mDevice.get()))
  1056. return true;
  1057. }
  1058. Source->OffsetType = prop;
  1059. Source->Offset = values[0];
  1060. return true;
  1061. case AL_SOURCE_RADIUS:
  1062. CHECKSIZE(values, 1);
  1063. CHECKVAL(values[0] >= 0.0f && std::isfinite(values[0]));
  1064. Source->Radius = values[0];
  1065. return UpdateSourceProps(Source, Context);
  1066. case AL_STEREO_ANGLES:
  1067. CHECKSIZE(values, 2);
  1068. CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]));
  1069. Source->StereoPan[0] = values[0];
  1070. Source->StereoPan[1] = values[1];
  1071. return UpdateSourceProps(Source, Context);
  1072. case AL_POSITION:
  1073. CHECKSIZE(values, 3);
  1074. CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]));
  1075. Source->Position[0] = values[0];
  1076. Source->Position[1] = values[1];
  1077. Source->Position[2] = values[2];
  1078. return UpdateSourceProps(Source, Context);
  1079. case AL_VELOCITY:
  1080. CHECKSIZE(values, 3);
  1081. CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]));
  1082. Source->Velocity[0] = values[0];
  1083. Source->Velocity[1] = values[1];
  1084. Source->Velocity[2] = values[2];
  1085. return UpdateSourceProps(Source, Context);
  1086. case AL_DIRECTION:
  1087. CHECKSIZE(values, 3);
  1088. CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2]));
  1089. Source->Direction[0] = values[0];
  1090. Source->Direction[1] = values[1];
  1091. Source->Direction[2] = values[2];
  1092. return UpdateSourceProps(Source, Context);
  1093. case AL_ORIENTATION:
  1094. CHECKSIZE(values, 6);
  1095. CHECKVAL(std::isfinite(values[0]) && std::isfinite(values[1]) && std::isfinite(values[2])
  1096. && std::isfinite(values[3]) && std::isfinite(values[4]) && std::isfinite(values[5]));
  1097. Source->OrientAt[0] = values[0];
  1098. Source->OrientAt[1] = values[1];
  1099. Source->OrientAt[2] = values[2];
  1100. Source->OrientUp[0] = values[3];
  1101. Source->OrientUp[1] = values[4];
  1102. Source->OrientUp[2] = values[5];
  1103. return UpdateSourceProps(Source, Context);
  1104. case AL_SOURCE_RELATIVE:
  1105. case AL_LOOPING:
  1106. case AL_SOURCE_STATE:
  1107. case AL_SOURCE_TYPE:
  1108. case AL_DISTANCE_MODEL:
  1109. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1110. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1111. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1112. case AL_DIRECT_CHANNELS_SOFT:
  1113. case AL_SOURCE_RESAMPLER_SOFT:
  1114. case AL_SOURCE_SPATIALIZE_SOFT:
  1115. CHECKSIZE(values, 1);
  1116. ival = static_cast<int>(values[0]);
  1117. return SetSourceiv(Source, Context, prop, {&ival, 1u});
  1118. case AL_BUFFERS_QUEUED:
  1119. case AL_BUFFERS_PROCESSED:
  1120. CHECKSIZE(values, 1);
  1121. ival = static_cast<int>(static_cast<ALuint>(values[0]));
  1122. return SetSourceiv(Source, Context, prop, {&ival, 1u});
  1123. case AL_BUFFER:
  1124. case AL_DIRECT_FILTER:
  1125. case AL_AUXILIARY_SEND_FILTER:
  1126. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1127. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1128. break;
  1129. }
  1130. ERR("Unexpected property: 0x%04x\n", prop);
  1131. Context->setError(AL_INVALID_ENUM, "Invalid source float property 0x%04x", prop);
  1132. return false;
  1133. }
  1134. bool SetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const int> values)
  1135. {
  1136. ALCdevice *device{Context->mDevice.get()};
  1137. ALeffectslot *slot{nullptr};
  1138. al::deque<ALbufferQueueItem> oldlist;
  1139. std::unique_lock<std::mutex> slotlock;
  1140. float fvals[6];
  1141. switch(prop)
  1142. {
  1143. case AL_SOURCE_STATE:
  1144. case AL_SOURCE_TYPE:
  1145. case AL_BUFFERS_QUEUED:
  1146. case AL_BUFFERS_PROCESSED:
  1147. /* Query only */
  1148. SETERR_RETURN(Context, AL_INVALID_OPERATION, false,
  1149. "Setting read-only source property 0x%04x", prop);
  1150. case AL_SOURCE_RELATIVE:
  1151. CHECKSIZE(values, 1);
  1152. CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1153. Source->HeadRelative = values[0] != AL_FALSE;
  1154. return UpdateSourceProps(Source, Context);
  1155. case AL_LOOPING:
  1156. CHECKSIZE(values, 1);
  1157. CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1158. Source->Looping = values[0] != AL_FALSE;
  1159. if(IsPlayingOrPaused(Source))
  1160. {
  1161. if(Voice *voice{GetSourceVoice(Source, Context)})
  1162. {
  1163. if(Source->Looping)
  1164. voice->mLoopBuffer.store(&Source->mQueue.front(), std::memory_order_release);
  1165. else
  1166. voice->mLoopBuffer.store(nullptr, std::memory_order_release);
  1167. /* If the source is playing, wait for the current mix to finish
  1168. * to ensure it isn't currently looping back or reaching the
  1169. * end.
  1170. */
  1171. device->waitForMix();
  1172. }
  1173. }
  1174. return true;
  1175. case AL_BUFFER:
  1176. CHECKSIZE(values, 1);
  1177. {
  1178. const ALenum state{GetSourceState(Source, GetSourceVoice(Source, Context))};
  1179. if(state == AL_PLAYING || state == AL_PAUSED)
  1180. SETERR_RETURN(Context, AL_INVALID_OPERATION, false,
  1181. "Setting buffer on playing or paused source %u", Source->id);
  1182. }
  1183. if(values[0])
  1184. {
  1185. std::lock_guard<std::mutex> _{device->BufferLock};
  1186. ALbuffer *buffer{LookupBuffer(device, static_cast<ALuint>(values[0]))};
  1187. if(!buffer)
  1188. SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid buffer ID %u",
  1189. static_cast<ALuint>(values[0]));
  1190. if(buffer->MappedAccess && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT))
  1191. SETERR_RETURN(Context, AL_INVALID_OPERATION, false,
  1192. "Setting non-persistently mapped buffer %u", buffer->id);
  1193. if(buffer->mCallback && ReadRef(buffer->ref) != 0)
  1194. SETERR_RETURN(Context, AL_INVALID_OPERATION, false,
  1195. "Setting already-set callback buffer %u", buffer->id);
  1196. /* Add the selected buffer to a one-item queue */
  1197. al::deque<ALbufferQueueItem> newlist;
  1198. newlist.emplace_back();
  1199. newlist.back().mCallback = buffer->mCallback;
  1200. newlist.back().mUserData = buffer->mUserData;
  1201. newlist.back().mSampleLen = buffer->mSampleLen;
  1202. newlist.back().mLoopStart = buffer->mLoopStart;
  1203. newlist.back().mLoopEnd = buffer->mLoopEnd;
  1204. newlist.back().mSamples = buffer->mData.data();
  1205. newlist.back().mBuffer = buffer;
  1206. IncrementRef(buffer->ref);
  1207. /* Source is now Static */
  1208. Source->SourceType = AL_STATIC;
  1209. Source->mQueue.swap(oldlist);
  1210. Source->mQueue.swap(newlist);
  1211. }
  1212. else
  1213. {
  1214. /* Source is now Undetermined */
  1215. Source->SourceType = AL_UNDETERMINED;
  1216. Source->mQueue.swap(oldlist);
  1217. }
  1218. /* Delete all elements in the previous queue */
  1219. for(auto &item : oldlist)
  1220. {
  1221. if(ALbuffer *buffer{item.mBuffer})
  1222. DecrementRef(buffer->ref);
  1223. }
  1224. return true;
  1225. case AL_SEC_OFFSET:
  1226. case AL_SAMPLE_OFFSET:
  1227. case AL_BYTE_OFFSET:
  1228. CHECKSIZE(values, 1);
  1229. CHECKVAL(values[0] >= 0);
  1230. if(Voice *voice{GetSourceVoice(Source, Context)})
  1231. {
  1232. if((voice->mFlags&VoiceIsCallback))
  1233. SETERR_RETURN(Context, AL_INVALID_VALUE, false,
  1234. "Source offset for callback is invalid");
  1235. auto vpos = GetSampleOffset(Source->mQueue, prop, values[0]);
  1236. if(!vpos) SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid source offset");
  1237. if(SetVoiceOffset(voice, *vpos, Source, Context, device))
  1238. return true;
  1239. }
  1240. Source->OffsetType = prop;
  1241. Source->Offset = values[0];
  1242. return true;
  1243. case AL_DIRECT_FILTER:
  1244. CHECKSIZE(values, 1);
  1245. if(values[0])
  1246. {
  1247. std::lock_guard<std::mutex> _{device->FilterLock};
  1248. ALfilter *filter{LookupFilter(device, static_cast<ALuint>(values[0]))};
  1249. if(!filter)
  1250. SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid filter ID %u",
  1251. static_cast<ALuint>(values[0]));
  1252. Source->Direct.Gain = filter->Gain;
  1253. Source->Direct.GainHF = filter->GainHF;
  1254. Source->Direct.HFReference = filter->HFReference;
  1255. Source->Direct.GainLF = filter->GainLF;
  1256. Source->Direct.LFReference = filter->LFReference;
  1257. }
  1258. else
  1259. {
  1260. Source->Direct.Gain = 1.0f;
  1261. Source->Direct.GainHF = 1.0f;
  1262. Source->Direct.HFReference = LOWPASSFREQREF;
  1263. Source->Direct.GainLF = 1.0f;
  1264. Source->Direct.LFReference = HIGHPASSFREQREF;
  1265. }
  1266. return UpdateSourceProps(Source, Context);
  1267. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1268. CHECKSIZE(values, 1);
  1269. CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1270. Source->DryGainHFAuto = values[0] != AL_FALSE;
  1271. return UpdateSourceProps(Source, Context);
  1272. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1273. CHECKSIZE(values, 1);
  1274. CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1275. Source->WetGainAuto = values[0] != AL_FALSE;
  1276. return UpdateSourceProps(Source, Context);
  1277. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1278. CHECKSIZE(values, 1);
  1279. CHECKVAL(values[0] == AL_FALSE || values[0] == AL_TRUE);
  1280. Source->WetGainHFAuto = values[0] != AL_FALSE;
  1281. return UpdateSourceProps(Source, Context);
  1282. case AL_DIRECT_CHANNELS_SOFT:
  1283. CHECKSIZE(values, 1);
  1284. if(auto mode = DirectModeFromEnum(values[0]))
  1285. {
  1286. Source->DirectChannels = *mode;
  1287. return UpdateSourceProps(Source, Context);
  1288. }
  1289. Context->setError(AL_INVALID_VALUE, "Unsupported AL_DIRECT_CHANNELS_SOFT: 0x%04x\n",
  1290. values[0]);
  1291. return false;
  1292. case AL_DISTANCE_MODEL:
  1293. CHECKSIZE(values, 1);
  1294. if(auto model = DistanceModelFromALenum(values[0]))
  1295. {
  1296. Source->mDistanceModel = *model;
  1297. if(Context->mSourceDistanceModel)
  1298. return UpdateSourceProps(Source, Context);
  1299. return true;
  1300. }
  1301. Context->setError(AL_INVALID_VALUE, "Distance model out of range: 0x%04x", values[0]);
  1302. return false;
  1303. case AL_SOURCE_RESAMPLER_SOFT:
  1304. CHECKSIZE(values, 1);
  1305. CHECKVAL(values[0] >= 0 && values[0] <= static_cast<int>(Resampler::Max));
  1306. Source->mResampler = static_cast<Resampler>(values[0]);
  1307. return UpdateSourceProps(Source, Context);
  1308. case AL_SOURCE_SPATIALIZE_SOFT:
  1309. CHECKSIZE(values, 1);
  1310. if(auto mode = SpatializeModeFromEnum(values[0]))
  1311. {
  1312. Source->mSpatialize = *mode;
  1313. return UpdateSourceProps(Source, Context);
  1314. }
  1315. Context->setError(AL_INVALID_VALUE, "Unsupported AL_SOURCE_SPATIALIZE_SOFT: 0x%04x\n",
  1316. values[0]);
  1317. return false;
  1318. case AL_AUXILIARY_SEND_FILTER:
  1319. CHECKSIZE(values, 3);
  1320. slotlock = std::unique_lock<std::mutex>{Context->mEffectSlotLock};
  1321. if(values[0] && (slot=LookupEffectSlot(Context, static_cast<ALuint>(values[0]))) == nullptr)
  1322. SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid effect ID %u", values[0]);
  1323. if(static_cast<ALuint>(values[1]) >= device->NumAuxSends)
  1324. SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid send %u", values[1]);
  1325. if(values[2])
  1326. {
  1327. std::lock_guard<std::mutex> _{device->FilterLock};
  1328. ALfilter *filter{LookupFilter(device, static_cast<ALuint>(values[2]))};
  1329. if(!filter)
  1330. SETERR_RETURN(Context, AL_INVALID_VALUE, false, "Invalid filter ID %u", values[2]);
  1331. auto &send = Source->Send[static_cast<ALuint>(values[1])];
  1332. send.Gain = filter->Gain;
  1333. send.GainHF = filter->GainHF;
  1334. send.HFReference = filter->HFReference;
  1335. send.GainLF = filter->GainLF;
  1336. send.LFReference = filter->LFReference;
  1337. }
  1338. else
  1339. {
  1340. /* Disable filter */
  1341. auto &send = Source->Send[static_cast<ALuint>(values[1])];
  1342. send.Gain = 1.0f;
  1343. send.GainHF = 1.0f;
  1344. send.HFReference = LOWPASSFREQREF;
  1345. send.GainLF = 1.0f;
  1346. send.LFReference = HIGHPASSFREQREF;
  1347. }
  1348. if(slot != Source->Send[static_cast<ALuint>(values[1])].Slot && IsPlayingOrPaused(Source))
  1349. {
  1350. /* Add refcount on the new slot, and release the previous slot */
  1351. if(slot) IncrementRef(slot->ref);
  1352. if(auto *oldslot = Source->Send[static_cast<ALuint>(values[1])].Slot)
  1353. DecrementRef(oldslot->ref);
  1354. Source->Send[static_cast<ALuint>(values[1])].Slot = slot;
  1355. /* We must force an update if the auxiliary slot changed on an
  1356. * active source, in case the slot is about to be deleted.
  1357. */
  1358. Voice *voice{GetSourceVoice(Source, Context)};
  1359. if(voice) UpdateSourceProps(Source, voice, Context);
  1360. else Source->PropsClean.clear(std::memory_order_release);
  1361. }
  1362. else
  1363. {
  1364. if(slot) IncrementRef(slot->ref);
  1365. if(auto *oldslot = Source->Send[static_cast<ALuint>(values[1])].Slot)
  1366. DecrementRef(oldslot->ref);
  1367. Source->Send[static_cast<ALuint>(values[1])].Slot = slot;
  1368. UpdateSourceProps(Source, Context);
  1369. }
  1370. return true;
  1371. /* 1x float */
  1372. case AL_CONE_INNER_ANGLE:
  1373. case AL_CONE_OUTER_ANGLE:
  1374. case AL_PITCH:
  1375. case AL_GAIN:
  1376. case AL_MIN_GAIN:
  1377. case AL_MAX_GAIN:
  1378. case AL_REFERENCE_DISTANCE:
  1379. case AL_ROLLOFF_FACTOR:
  1380. case AL_CONE_OUTER_GAIN:
  1381. case AL_MAX_DISTANCE:
  1382. case AL_DOPPLER_FACTOR:
  1383. case AL_CONE_OUTER_GAINHF:
  1384. case AL_AIR_ABSORPTION_FACTOR:
  1385. case AL_ROOM_ROLLOFF_FACTOR:
  1386. case AL_SOURCE_RADIUS:
  1387. CHECKSIZE(values, 1);
  1388. fvals[0] = static_cast<float>(values[0]);
  1389. return SetSourcefv(Source, Context, prop, {fvals, 1u});
  1390. /* 3x float */
  1391. case AL_POSITION:
  1392. case AL_VELOCITY:
  1393. case AL_DIRECTION:
  1394. CHECKSIZE(values, 3);
  1395. fvals[0] = static_cast<float>(values[0]);
  1396. fvals[1] = static_cast<float>(values[1]);
  1397. fvals[2] = static_cast<float>(values[2]);
  1398. return SetSourcefv(Source, Context, prop, {fvals, 3u});
  1399. /* 6x float */
  1400. case AL_ORIENTATION:
  1401. CHECKSIZE(values, 6);
  1402. fvals[0] = static_cast<float>(values[0]);
  1403. fvals[1] = static_cast<float>(values[1]);
  1404. fvals[2] = static_cast<float>(values[2]);
  1405. fvals[3] = static_cast<float>(values[3]);
  1406. fvals[4] = static_cast<float>(values[4]);
  1407. fvals[5] = static_cast<float>(values[5]);
  1408. return SetSourcefv(Source, Context, prop, {fvals, 6u});
  1409. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1410. case AL_SEC_OFFSET_LATENCY_SOFT:
  1411. case AL_SEC_OFFSET_CLOCK_SOFT:
  1412. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1413. case AL_STEREO_ANGLES:
  1414. break;
  1415. }
  1416. ERR("Unexpected property: 0x%04x\n", prop);
  1417. Context->setError(AL_INVALID_ENUM, "Invalid source integer property 0x%04x", prop);
  1418. return false;
  1419. }
  1420. bool SetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<const int64_t> values)
  1421. {
  1422. float fvals[MaxValues];
  1423. int ivals[MaxValues];
  1424. switch(prop)
  1425. {
  1426. case AL_SOURCE_TYPE:
  1427. case AL_BUFFERS_QUEUED:
  1428. case AL_BUFFERS_PROCESSED:
  1429. case AL_SOURCE_STATE:
  1430. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1431. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1432. /* Query only */
  1433. SETERR_RETURN(Context, AL_INVALID_OPERATION, false,
  1434. "Setting read-only source property 0x%04x", prop);
  1435. /* 1x int */
  1436. case AL_SOURCE_RELATIVE:
  1437. case AL_LOOPING:
  1438. case AL_SEC_OFFSET:
  1439. case AL_SAMPLE_OFFSET:
  1440. case AL_BYTE_OFFSET:
  1441. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1442. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1443. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1444. case AL_DIRECT_CHANNELS_SOFT:
  1445. case AL_DISTANCE_MODEL:
  1446. case AL_SOURCE_RESAMPLER_SOFT:
  1447. case AL_SOURCE_SPATIALIZE_SOFT:
  1448. CHECKSIZE(values, 1);
  1449. CHECKVAL(values[0] <= INT_MAX && values[0] >= INT_MIN);
  1450. ivals[0] = static_cast<int>(values[0]);
  1451. return SetSourceiv(Source, Context, prop, {ivals, 1u});
  1452. /* 1x uint */
  1453. case AL_BUFFER:
  1454. case AL_DIRECT_FILTER:
  1455. CHECKSIZE(values, 1);
  1456. CHECKVAL(values[0] <= UINT_MAX && values[0] >= 0);
  1457. ivals[0] = static_cast<int>(values[0]);
  1458. return SetSourceiv(Source, Context, prop, {ivals, 1u});
  1459. /* 3x uint */
  1460. case AL_AUXILIARY_SEND_FILTER:
  1461. CHECKSIZE(values, 3);
  1462. CHECKVAL(values[0] <= UINT_MAX && values[0] >= 0 && values[1] <= UINT_MAX && values[1] >= 0
  1463. && values[2] <= UINT_MAX && values[2] >= 0);
  1464. ivals[0] = static_cast<int>(values[0]);
  1465. ivals[1] = static_cast<int>(values[1]);
  1466. ivals[2] = static_cast<int>(values[2]);
  1467. return SetSourceiv(Source, Context, prop, {ivals, 3u});
  1468. /* 1x float */
  1469. case AL_CONE_INNER_ANGLE:
  1470. case AL_CONE_OUTER_ANGLE:
  1471. case AL_PITCH:
  1472. case AL_GAIN:
  1473. case AL_MIN_GAIN:
  1474. case AL_MAX_GAIN:
  1475. case AL_REFERENCE_DISTANCE:
  1476. case AL_ROLLOFF_FACTOR:
  1477. case AL_CONE_OUTER_GAIN:
  1478. case AL_MAX_DISTANCE:
  1479. case AL_DOPPLER_FACTOR:
  1480. case AL_CONE_OUTER_GAINHF:
  1481. case AL_AIR_ABSORPTION_FACTOR:
  1482. case AL_ROOM_ROLLOFF_FACTOR:
  1483. case AL_SOURCE_RADIUS:
  1484. CHECKSIZE(values, 1);
  1485. fvals[0] = static_cast<float>(values[0]);
  1486. return SetSourcefv(Source, Context, prop, {fvals, 1u});
  1487. /* 3x float */
  1488. case AL_POSITION:
  1489. case AL_VELOCITY:
  1490. case AL_DIRECTION:
  1491. CHECKSIZE(values, 3);
  1492. fvals[0] = static_cast<float>(values[0]);
  1493. fvals[1] = static_cast<float>(values[1]);
  1494. fvals[2] = static_cast<float>(values[2]);
  1495. return SetSourcefv(Source, Context, prop, {fvals, 3u});
  1496. /* 6x float */
  1497. case AL_ORIENTATION:
  1498. CHECKSIZE(values, 6);
  1499. fvals[0] = static_cast<float>(values[0]);
  1500. fvals[1] = static_cast<float>(values[1]);
  1501. fvals[2] = static_cast<float>(values[2]);
  1502. fvals[3] = static_cast<float>(values[3]);
  1503. fvals[4] = static_cast<float>(values[4]);
  1504. fvals[5] = static_cast<float>(values[5]);
  1505. return SetSourcefv(Source, Context, prop, {fvals, 6u});
  1506. case AL_SEC_OFFSET_LATENCY_SOFT:
  1507. case AL_SEC_OFFSET_CLOCK_SOFT:
  1508. case AL_STEREO_ANGLES:
  1509. break;
  1510. }
  1511. ERR("Unexpected property: 0x%04x\n", prop);
  1512. Context->setError(AL_INVALID_ENUM, "Invalid source integer64 property 0x%04x", prop);
  1513. return false;
  1514. }
  1515. #undef CHECKVAL
  1516. bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<double> values);
  1517. bool GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<int> values);
  1518. bool GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<int64_t> values);
  1519. bool GetSourcedv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<double> values)
  1520. {
  1521. ALCdevice *device{Context->mDevice.get()};
  1522. ClockLatency clocktime;
  1523. nanoseconds srcclock;
  1524. int ivals[MaxValues];
  1525. bool err;
  1526. switch(prop)
  1527. {
  1528. case AL_GAIN:
  1529. CHECKSIZE(values, 1);
  1530. values[0] = Source->Gain;
  1531. return true;
  1532. case AL_PITCH:
  1533. CHECKSIZE(values, 1);
  1534. values[0] = Source->Pitch;
  1535. return true;
  1536. case AL_MAX_DISTANCE:
  1537. CHECKSIZE(values, 1);
  1538. values[0] = Source->MaxDistance;
  1539. return true;
  1540. case AL_ROLLOFF_FACTOR:
  1541. CHECKSIZE(values, 1);
  1542. values[0] = Source->RolloffFactor;
  1543. return true;
  1544. case AL_REFERENCE_DISTANCE:
  1545. CHECKSIZE(values, 1);
  1546. values[0] = Source->RefDistance;
  1547. return true;
  1548. case AL_CONE_INNER_ANGLE:
  1549. CHECKSIZE(values, 1);
  1550. values[0] = Source->InnerAngle;
  1551. return true;
  1552. case AL_CONE_OUTER_ANGLE:
  1553. CHECKSIZE(values, 1);
  1554. values[0] = Source->OuterAngle;
  1555. return true;
  1556. case AL_MIN_GAIN:
  1557. CHECKSIZE(values, 1);
  1558. values[0] = Source->MinGain;
  1559. return true;
  1560. case AL_MAX_GAIN:
  1561. CHECKSIZE(values, 1);
  1562. values[0] = Source->MaxGain;
  1563. return true;
  1564. case AL_CONE_OUTER_GAIN:
  1565. CHECKSIZE(values, 1);
  1566. values[0] = Source->OuterGain;
  1567. return true;
  1568. case AL_SEC_OFFSET:
  1569. case AL_SAMPLE_OFFSET:
  1570. case AL_BYTE_OFFSET:
  1571. CHECKSIZE(values, 1);
  1572. values[0] = GetSourceOffset(Source, prop, Context);
  1573. return true;
  1574. case AL_CONE_OUTER_GAINHF:
  1575. CHECKSIZE(values, 1);
  1576. values[0] = Source->OuterGainHF;
  1577. return true;
  1578. case AL_AIR_ABSORPTION_FACTOR:
  1579. CHECKSIZE(values, 1);
  1580. values[0] = Source->AirAbsorptionFactor;
  1581. return true;
  1582. case AL_ROOM_ROLLOFF_FACTOR:
  1583. CHECKSIZE(values, 1);
  1584. values[0] = Source->RoomRolloffFactor;
  1585. return true;
  1586. case AL_DOPPLER_FACTOR:
  1587. CHECKSIZE(values, 1);
  1588. values[0] = Source->DopplerFactor;
  1589. return true;
  1590. case AL_SOURCE_RADIUS:
  1591. CHECKSIZE(values, 1);
  1592. values[0] = Source->Radius;
  1593. return true;
  1594. case AL_STEREO_ANGLES:
  1595. CHECKSIZE(values, 2);
  1596. values[0] = Source->StereoPan[0];
  1597. values[1] = Source->StereoPan[1];
  1598. return true;
  1599. case AL_SEC_OFFSET_LATENCY_SOFT:
  1600. CHECKSIZE(values, 2);
  1601. /* Get the source offset with the clock time first. Then get the clock
  1602. * time with the device latency. Order is important.
  1603. */
  1604. values[0] = GetSourceSecOffset(Source, Context, &srcclock);
  1605. {
  1606. std::lock_guard<std::mutex> _{device->StateLock};
  1607. clocktime = GetClockLatency(device);
  1608. }
  1609. if(srcclock == clocktime.ClockTime)
  1610. values[1] = static_cast<double>(clocktime.Latency.count()) / 1000000000.0;
  1611. else
  1612. {
  1613. /* If the clock time incremented, reduce the latency by that much
  1614. * since it's that much closer to the source offset it got earlier.
  1615. */
  1616. const nanoseconds diff{clocktime.ClockTime - srcclock};
  1617. const nanoseconds latency{clocktime.Latency - std::min(clocktime.Latency, diff)};
  1618. values[1] = static_cast<double>(latency.count()) / 1000000000.0;
  1619. }
  1620. return true;
  1621. case AL_SEC_OFFSET_CLOCK_SOFT:
  1622. CHECKSIZE(values, 2);
  1623. values[0] = GetSourceSecOffset(Source, Context, &srcclock);
  1624. values[1] = static_cast<double>(srcclock.count()) / 1000000000.0;
  1625. return true;
  1626. case AL_POSITION:
  1627. CHECKSIZE(values, 3);
  1628. values[0] = Source->Position[0];
  1629. values[1] = Source->Position[1];
  1630. values[2] = Source->Position[2];
  1631. return true;
  1632. case AL_VELOCITY:
  1633. CHECKSIZE(values, 3);
  1634. values[0] = Source->Velocity[0];
  1635. values[1] = Source->Velocity[1];
  1636. values[2] = Source->Velocity[2];
  1637. return true;
  1638. case AL_DIRECTION:
  1639. CHECKSIZE(values, 3);
  1640. values[0] = Source->Direction[0];
  1641. values[1] = Source->Direction[1];
  1642. values[2] = Source->Direction[2];
  1643. return true;
  1644. case AL_ORIENTATION:
  1645. CHECKSIZE(values, 6);
  1646. values[0] = Source->OrientAt[0];
  1647. values[1] = Source->OrientAt[1];
  1648. values[2] = Source->OrientAt[2];
  1649. values[3] = Source->OrientUp[0];
  1650. values[4] = Source->OrientUp[1];
  1651. values[5] = Source->OrientUp[2];
  1652. return true;
  1653. /* 1x int */
  1654. case AL_SOURCE_RELATIVE:
  1655. case AL_LOOPING:
  1656. case AL_SOURCE_STATE:
  1657. case AL_BUFFERS_QUEUED:
  1658. case AL_BUFFERS_PROCESSED:
  1659. case AL_SOURCE_TYPE:
  1660. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1661. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1662. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1663. case AL_DIRECT_CHANNELS_SOFT:
  1664. case AL_DISTANCE_MODEL:
  1665. case AL_SOURCE_RESAMPLER_SOFT:
  1666. case AL_SOURCE_SPATIALIZE_SOFT:
  1667. CHECKSIZE(values, 1);
  1668. if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false)
  1669. values[0] = static_cast<double>(ivals[0]);
  1670. return err;
  1671. case AL_BUFFER:
  1672. case AL_DIRECT_FILTER:
  1673. case AL_AUXILIARY_SEND_FILTER:
  1674. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1675. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1676. break;
  1677. }
  1678. ERR("Unexpected property: 0x%04x\n", prop);
  1679. Context->setError(AL_INVALID_ENUM, "Invalid source double property 0x%04x", prop);
  1680. return false;
  1681. }
  1682. bool GetSourceiv(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<int> values)
  1683. {
  1684. double dvals[MaxValues];
  1685. bool err;
  1686. switch(prop)
  1687. {
  1688. case AL_SOURCE_RELATIVE:
  1689. CHECKSIZE(values, 1);
  1690. values[0] = Source->HeadRelative;
  1691. return true;
  1692. case AL_LOOPING:
  1693. CHECKSIZE(values, 1);
  1694. values[0] = Source->Looping;
  1695. return true;
  1696. case AL_BUFFER:
  1697. CHECKSIZE(values, 1);
  1698. {
  1699. ALbufferQueueItem *BufferList{(Source->SourceType == AL_STATIC)
  1700. ? &Source->mQueue.front() : nullptr};
  1701. ALbuffer *buffer{BufferList ? BufferList->mBuffer : nullptr};
  1702. values[0] = buffer ? static_cast<int>(buffer->id) : 0;
  1703. }
  1704. return true;
  1705. case AL_SOURCE_STATE:
  1706. CHECKSIZE(values, 1);
  1707. values[0] = GetSourceState(Source, GetSourceVoice(Source, Context));
  1708. return true;
  1709. case AL_BUFFERS_QUEUED:
  1710. CHECKSIZE(values, 1);
  1711. values[0] = static_cast<int>(Source->mQueue.size());
  1712. return true;
  1713. case AL_BUFFERS_PROCESSED:
  1714. CHECKSIZE(values, 1);
  1715. if(Source->Looping || Source->SourceType != AL_STREAMING)
  1716. {
  1717. /* Buffers on a looping source are in a perpetual state of PENDING,
  1718. * so don't report any as PROCESSED
  1719. */
  1720. values[0] = 0;
  1721. }
  1722. else
  1723. {
  1724. int played{0};
  1725. if(Source->state != AL_INITIAL)
  1726. {
  1727. const VoiceBufferItem *Current{nullptr};
  1728. if(Voice *voice{GetSourceVoice(Source, Context)})
  1729. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  1730. for(auto &item : Source->mQueue)
  1731. {
  1732. if(&item == Current)
  1733. break;
  1734. ++played;
  1735. }
  1736. }
  1737. values[0] = played;
  1738. }
  1739. return true;
  1740. case AL_SOURCE_TYPE:
  1741. CHECKSIZE(values, 1);
  1742. values[0] = Source->SourceType;
  1743. return true;
  1744. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1745. CHECKSIZE(values, 1);
  1746. values[0] = Source->DryGainHFAuto;
  1747. return true;
  1748. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1749. CHECKSIZE(values, 1);
  1750. values[0] = Source->WetGainAuto;
  1751. return true;
  1752. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1753. CHECKSIZE(values, 1);
  1754. values[0] = Source->WetGainHFAuto;
  1755. return true;
  1756. case AL_DIRECT_CHANNELS_SOFT:
  1757. CHECKSIZE(values, 1);
  1758. values[0] = EnumFromDirectMode(Source->DirectChannels);
  1759. return true;
  1760. case AL_DISTANCE_MODEL:
  1761. CHECKSIZE(values, 1);
  1762. values[0] = ALenumFromDistanceModel(Source->mDistanceModel);
  1763. return true;
  1764. case AL_SOURCE_RESAMPLER_SOFT:
  1765. CHECKSIZE(values, 1);
  1766. values[0] = static_cast<int>(Source->mResampler);
  1767. return true;
  1768. case AL_SOURCE_SPATIALIZE_SOFT:
  1769. CHECKSIZE(values, 1);
  1770. values[0] = EnumFromSpatializeMode(Source->mSpatialize);
  1771. return true;
  1772. /* 1x float/double */
  1773. case AL_CONE_INNER_ANGLE:
  1774. case AL_CONE_OUTER_ANGLE:
  1775. case AL_PITCH:
  1776. case AL_GAIN:
  1777. case AL_MIN_GAIN:
  1778. case AL_MAX_GAIN:
  1779. case AL_REFERENCE_DISTANCE:
  1780. case AL_ROLLOFF_FACTOR:
  1781. case AL_CONE_OUTER_GAIN:
  1782. case AL_MAX_DISTANCE:
  1783. case AL_SEC_OFFSET:
  1784. case AL_SAMPLE_OFFSET:
  1785. case AL_BYTE_OFFSET:
  1786. case AL_DOPPLER_FACTOR:
  1787. case AL_AIR_ABSORPTION_FACTOR:
  1788. case AL_ROOM_ROLLOFF_FACTOR:
  1789. case AL_CONE_OUTER_GAINHF:
  1790. case AL_SOURCE_RADIUS:
  1791. CHECKSIZE(values, 1);
  1792. if((err=GetSourcedv(Source, Context, prop, {dvals, 1u})) != false)
  1793. values[0] = static_cast<int>(dvals[0]);
  1794. return err;
  1795. /* 3x float/double */
  1796. case AL_POSITION:
  1797. case AL_VELOCITY:
  1798. case AL_DIRECTION:
  1799. CHECKSIZE(values, 3);
  1800. if((err=GetSourcedv(Source, Context, prop, {dvals, 3u})) != false)
  1801. {
  1802. values[0] = static_cast<int>(dvals[0]);
  1803. values[1] = static_cast<int>(dvals[1]);
  1804. values[2] = static_cast<int>(dvals[2]);
  1805. }
  1806. return err;
  1807. /* 6x float/double */
  1808. case AL_ORIENTATION:
  1809. CHECKSIZE(values, 6);
  1810. if((err=GetSourcedv(Source, Context, prop, {dvals, 6u})) != false)
  1811. {
  1812. values[0] = static_cast<int>(dvals[0]);
  1813. values[1] = static_cast<int>(dvals[1]);
  1814. values[2] = static_cast<int>(dvals[2]);
  1815. values[3] = static_cast<int>(dvals[3]);
  1816. values[4] = static_cast<int>(dvals[4]);
  1817. values[5] = static_cast<int>(dvals[5]);
  1818. }
  1819. return err;
  1820. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1821. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1822. break; /* i64 only */
  1823. case AL_SEC_OFFSET_LATENCY_SOFT:
  1824. case AL_SEC_OFFSET_CLOCK_SOFT:
  1825. break; /* Double only */
  1826. case AL_STEREO_ANGLES:
  1827. break; /* Float/double only */
  1828. case AL_DIRECT_FILTER:
  1829. case AL_AUXILIARY_SEND_FILTER:
  1830. break; /* ??? */
  1831. }
  1832. ERR("Unexpected property: 0x%04x\n", prop);
  1833. Context->setError(AL_INVALID_ENUM, "Invalid source integer property 0x%04x", prop);
  1834. return false;
  1835. }
  1836. bool GetSourcei64v(ALsource *Source, ALCcontext *Context, SourceProp prop, const al::span<int64_t> values)
  1837. {
  1838. ALCdevice *device = Context->mDevice.get();
  1839. ClockLatency clocktime;
  1840. nanoseconds srcclock;
  1841. double dvals[MaxValues];
  1842. int ivals[MaxValues];
  1843. bool err;
  1844. switch(prop)
  1845. {
  1846. case AL_SAMPLE_OFFSET_LATENCY_SOFT:
  1847. CHECKSIZE(values, 2);
  1848. /* Get the source offset with the clock time first. Then get the clock
  1849. * time with the device latency. Order is important.
  1850. */
  1851. values[0] = GetSourceSampleOffset(Source, Context, &srcclock);
  1852. {
  1853. std::lock_guard<std::mutex> _{device->StateLock};
  1854. clocktime = GetClockLatency(device);
  1855. }
  1856. if(srcclock == clocktime.ClockTime)
  1857. values[1] = clocktime.Latency.count();
  1858. else
  1859. {
  1860. /* If the clock time incremented, reduce the latency by that much
  1861. * since it's that much closer to the source offset it got earlier.
  1862. */
  1863. const nanoseconds diff{clocktime.ClockTime - srcclock};
  1864. values[1] = nanoseconds{clocktime.Latency - std::min(clocktime.Latency, diff)}.count();
  1865. }
  1866. return true;
  1867. case AL_SAMPLE_OFFSET_CLOCK_SOFT:
  1868. CHECKSIZE(values, 2);
  1869. values[0] = GetSourceSampleOffset(Source, Context, &srcclock);
  1870. values[1] = srcclock.count();
  1871. return true;
  1872. /* 1x float/double */
  1873. case AL_CONE_INNER_ANGLE:
  1874. case AL_CONE_OUTER_ANGLE:
  1875. case AL_PITCH:
  1876. case AL_GAIN:
  1877. case AL_MIN_GAIN:
  1878. case AL_MAX_GAIN:
  1879. case AL_REFERENCE_DISTANCE:
  1880. case AL_ROLLOFF_FACTOR:
  1881. case AL_CONE_OUTER_GAIN:
  1882. case AL_MAX_DISTANCE:
  1883. case AL_SEC_OFFSET:
  1884. case AL_SAMPLE_OFFSET:
  1885. case AL_BYTE_OFFSET:
  1886. case AL_DOPPLER_FACTOR:
  1887. case AL_AIR_ABSORPTION_FACTOR:
  1888. case AL_ROOM_ROLLOFF_FACTOR:
  1889. case AL_CONE_OUTER_GAINHF:
  1890. case AL_SOURCE_RADIUS:
  1891. CHECKSIZE(values, 1);
  1892. if((err=GetSourcedv(Source, Context, prop, {dvals, 1u})) != false)
  1893. values[0] = static_cast<int64_t>(dvals[0]);
  1894. return err;
  1895. /* 3x float/double */
  1896. case AL_POSITION:
  1897. case AL_VELOCITY:
  1898. case AL_DIRECTION:
  1899. CHECKSIZE(values, 3);
  1900. if((err=GetSourcedv(Source, Context, prop, {dvals, 3u})) != false)
  1901. {
  1902. values[0] = static_cast<int64_t>(dvals[0]);
  1903. values[1] = static_cast<int64_t>(dvals[1]);
  1904. values[2] = static_cast<int64_t>(dvals[2]);
  1905. }
  1906. return err;
  1907. /* 6x float/double */
  1908. case AL_ORIENTATION:
  1909. CHECKSIZE(values, 6);
  1910. if((err=GetSourcedv(Source, Context, prop, {dvals, 6u})) != false)
  1911. {
  1912. values[0] = static_cast<int64_t>(dvals[0]);
  1913. values[1] = static_cast<int64_t>(dvals[1]);
  1914. values[2] = static_cast<int64_t>(dvals[2]);
  1915. values[3] = static_cast<int64_t>(dvals[3]);
  1916. values[4] = static_cast<int64_t>(dvals[4]);
  1917. values[5] = static_cast<int64_t>(dvals[5]);
  1918. }
  1919. return err;
  1920. /* 1x int */
  1921. case AL_SOURCE_RELATIVE:
  1922. case AL_LOOPING:
  1923. case AL_SOURCE_STATE:
  1924. case AL_BUFFERS_QUEUED:
  1925. case AL_BUFFERS_PROCESSED:
  1926. case AL_SOURCE_TYPE:
  1927. case AL_DIRECT_FILTER_GAINHF_AUTO:
  1928. case AL_AUXILIARY_SEND_FILTER_GAIN_AUTO:
  1929. case AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO:
  1930. case AL_DIRECT_CHANNELS_SOFT:
  1931. case AL_DISTANCE_MODEL:
  1932. case AL_SOURCE_RESAMPLER_SOFT:
  1933. case AL_SOURCE_SPATIALIZE_SOFT:
  1934. CHECKSIZE(values, 1);
  1935. if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false)
  1936. values[0] = ivals[0];
  1937. return err;
  1938. /* 1x uint */
  1939. case AL_BUFFER:
  1940. case AL_DIRECT_FILTER:
  1941. CHECKSIZE(values, 1);
  1942. if((err=GetSourceiv(Source, Context, prop, {ivals, 1u})) != false)
  1943. values[0] = static_cast<ALuint>(ivals[0]);
  1944. return err;
  1945. /* 3x uint */
  1946. case AL_AUXILIARY_SEND_FILTER:
  1947. CHECKSIZE(values, 3);
  1948. if((err=GetSourceiv(Source, Context, prop, {ivals, 3u})) != false)
  1949. {
  1950. values[0] = static_cast<ALuint>(ivals[0]);
  1951. values[1] = static_cast<ALuint>(ivals[1]);
  1952. values[2] = static_cast<ALuint>(ivals[2]);
  1953. }
  1954. return err;
  1955. case AL_SEC_OFFSET_LATENCY_SOFT:
  1956. case AL_SEC_OFFSET_CLOCK_SOFT:
  1957. break; /* Double only */
  1958. case AL_STEREO_ANGLES:
  1959. break; /* Float/double only */
  1960. }
  1961. ERR("Unexpected property: 0x%04x\n", prop);
  1962. Context->setError(AL_INVALID_ENUM, "Invalid source integer64 property 0x%04x", prop);
  1963. return false;
  1964. }
  1965. } // namespace
  1966. AL_API void AL_APIENTRY alGenSources(ALsizei n, ALuint *sources)
  1967. START_API_FUNC
  1968. {
  1969. ContextRef context{GetContextRef()};
  1970. if UNLIKELY(!context) return;
  1971. if UNLIKELY(n < 0)
  1972. context->setError(AL_INVALID_VALUE, "Generating %d sources", n);
  1973. if UNLIKELY(n <= 0) return;
  1974. std::unique_lock<std::mutex> srclock{context->mSourceLock};
  1975. ALCdevice *device{context->mDevice.get()};
  1976. if(static_cast<ALuint>(n) > device->SourcesMax-context->mNumSources)
  1977. {
  1978. context->setError(AL_OUT_OF_MEMORY, "Exceeding %u source limit (%u + %d)",
  1979. device->SourcesMax, context->mNumSources, n);
  1980. return;
  1981. }
  1982. if(!EnsureSources(context.get(), static_cast<ALuint>(n)))
  1983. {
  1984. context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d source%s", n, (n==1)?"":"s");
  1985. return;
  1986. }
  1987. if(n == 1)
  1988. {
  1989. ALsource *source{AllocSource(context.get())};
  1990. sources[0] = source->id;
  1991. }
  1992. else
  1993. {
  1994. al::vector<ALuint> ids;
  1995. ids.reserve(static_cast<ALuint>(n));
  1996. do {
  1997. ALsource *source{AllocSource(context.get())};
  1998. ids.emplace_back(source->id);
  1999. } while(--n);
  2000. std::copy(ids.cbegin(), ids.cend(), sources);
  2001. }
  2002. }
  2003. END_API_FUNC
  2004. AL_API void AL_APIENTRY alDeleteSources(ALsizei n, const ALuint *sources)
  2005. START_API_FUNC
  2006. {
  2007. ContextRef context{GetContextRef()};
  2008. if UNLIKELY(!context) return;
  2009. if UNLIKELY(n < 0)
  2010. SETERR_RETURN(context, AL_INVALID_VALUE,, "Deleting %d sources", n);
  2011. std::lock_guard<std::mutex> _{context->mSourceLock};
  2012. /* Check that all Sources are valid */
  2013. auto validate_source = [&context](const ALuint sid) -> bool
  2014. { return LookupSource(context.get(), sid) != nullptr; };
  2015. const ALuint *sources_end = sources + n;
  2016. auto invsrc = std::find_if_not(sources, sources_end, validate_source);
  2017. if UNLIKELY(invsrc != sources_end)
  2018. {
  2019. context->setError(AL_INVALID_NAME, "Invalid source ID %u", *invsrc);
  2020. return;
  2021. }
  2022. /* All good. Delete source IDs. */
  2023. auto delete_source = [&context](const ALuint sid) -> void
  2024. {
  2025. ALsource *src{LookupSource(context.get(), sid)};
  2026. if(src) FreeSource(context.get(), src);
  2027. };
  2028. std::for_each(sources, sources_end, delete_source);
  2029. }
  2030. END_API_FUNC
  2031. AL_API ALboolean AL_APIENTRY alIsSource(ALuint source)
  2032. START_API_FUNC
  2033. {
  2034. ContextRef context{GetContextRef()};
  2035. if LIKELY(context)
  2036. {
  2037. std::lock_guard<std::mutex> _{context->mSourceLock};
  2038. if(LookupSource(context.get(), source) != nullptr)
  2039. return AL_TRUE;
  2040. }
  2041. return AL_FALSE;
  2042. }
  2043. END_API_FUNC
  2044. AL_API void AL_APIENTRY alSourcef(ALuint source, ALenum param, ALfloat value)
  2045. START_API_FUNC
  2046. {
  2047. ContextRef context{GetContextRef()};
  2048. if UNLIKELY(!context) return;
  2049. std::lock_guard<std::mutex> _{context->mPropLock};
  2050. std::lock_guard<std::mutex> __{context->mSourceLock};
  2051. ALsource *Source = LookupSource(context.get(), source);
  2052. if UNLIKELY(!Source)
  2053. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2054. else
  2055. SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), {&value, 1u});
  2056. }
  2057. END_API_FUNC
  2058. AL_API void AL_APIENTRY alSource3f(ALuint source, ALenum param, ALfloat value1, ALfloat value2, ALfloat value3)
  2059. START_API_FUNC
  2060. {
  2061. ContextRef context{GetContextRef()};
  2062. if UNLIKELY(!context) return;
  2063. std::lock_guard<std::mutex> _{context->mPropLock};
  2064. std::lock_guard<std::mutex> __{context->mSourceLock};
  2065. ALsource *Source = LookupSource(context.get(), source);
  2066. if UNLIKELY(!Source)
  2067. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2068. else
  2069. {
  2070. const float fvals[3]{ value1, value2, value3 };
  2071. SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), fvals);
  2072. }
  2073. }
  2074. END_API_FUNC
  2075. AL_API void AL_APIENTRY alSourcefv(ALuint source, ALenum param, const ALfloat *values)
  2076. START_API_FUNC
  2077. {
  2078. ContextRef context{GetContextRef()};
  2079. if UNLIKELY(!context) return;
  2080. std::lock_guard<std::mutex> _{context->mPropLock};
  2081. std::lock_guard<std::mutex> __{context->mSourceLock};
  2082. ALsource *Source = LookupSource(context.get(), source);
  2083. if UNLIKELY(!Source)
  2084. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2085. else if UNLIKELY(!values)
  2086. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2087. else
  2088. SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues});
  2089. }
  2090. END_API_FUNC
  2091. AL_API void AL_APIENTRY alSourcedSOFT(ALuint source, ALenum param, ALdouble value)
  2092. START_API_FUNC
  2093. {
  2094. ContextRef context{GetContextRef()};
  2095. if UNLIKELY(!context) return;
  2096. std::lock_guard<std::mutex> _{context->mPropLock};
  2097. std::lock_guard<std::mutex> __{context->mSourceLock};
  2098. ALsource *Source = LookupSource(context.get(), source);
  2099. if UNLIKELY(!Source)
  2100. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2101. else
  2102. {
  2103. const float fval[1]{static_cast<float>(value)};
  2104. SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), fval);
  2105. }
  2106. }
  2107. END_API_FUNC
  2108. AL_API void AL_APIENTRY alSource3dSOFT(ALuint source, ALenum param, ALdouble value1, ALdouble value2, ALdouble value3)
  2109. START_API_FUNC
  2110. {
  2111. ContextRef context{GetContextRef()};
  2112. if UNLIKELY(!context) return;
  2113. std::lock_guard<std::mutex> _{context->mPropLock};
  2114. std::lock_guard<std::mutex> __{context->mSourceLock};
  2115. ALsource *Source = LookupSource(context.get(), source);
  2116. if UNLIKELY(!Source)
  2117. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2118. else
  2119. {
  2120. const float fvals[3]{static_cast<float>(value1), static_cast<float>(value2),
  2121. static_cast<float>(value3)};
  2122. SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), fvals);
  2123. }
  2124. }
  2125. END_API_FUNC
  2126. AL_API void AL_APIENTRY alSourcedvSOFT(ALuint source, ALenum param, const ALdouble *values)
  2127. START_API_FUNC
  2128. {
  2129. ContextRef context{GetContextRef()};
  2130. if UNLIKELY(!context) return;
  2131. std::lock_guard<std::mutex> _{context->mPropLock};
  2132. std::lock_guard<std::mutex> __{context->mSourceLock};
  2133. ALsource *Source = LookupSource(context.get(), source);
  2134. if UNLIKELY(!Source)
  2135. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2136. else if UNLIKELY(!values)
  2137. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2138. else
  2139. {
  2140. const ALuint count{DoubleValsByProp(param)};
  2141. float fvals[MaxValues];
  2142. for(ALuint i{0};i < count;i++)
  2143. fvals[i] = static_cast<float>(values[i]);
  2144. SetSourcefv(Source, context.get(), static_cast<SourceProp>(param), {fvals, count});
  2145. }
  2146. }
  2147. END_API_FUNC
  2148. AL_API void AL_APIENTRY alSourcei(ALuint source, ALenum param, ALint value)
  2149. START_API_FUNC
  2150. {
  2151. ContextRef context{GetContextRef()};
  2152. if UNLIKELY(!context) return;
  2153. std::lock_guard<std::mutex> _{context->mPropLock};
  2154. std::lock_guard<std::mutex> __{context->mSourceLock};
  2155. ALsource *Source = LookupSource(context.get(), source);
  2156. if UNLIKELY(!Source)
  2157. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2158. else
  2159. SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {&value, 1u});
  2160. }
  2161. END_API_FUNC
  2162. AL_API void AL_APIENTRY alSource3i(ALuint source, ALenum param, ALint value1, ALint value2, ALint value3)
  2163. START_API_FUNC
  2164. {
  2165. ContextRef context{GetContextRef()};
  2166. if UNLIKELY(!context) return;
  2167. std::lock_guard<std::mutex> _{context->mPropLock};
  2168. std::lock_guard<std::mutex> __{context->mSourceLock};
  2169. ALsource *Source = LookupSource(context.get(), source);
  2170. if UNLIKELY(!Source)
  2171. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2172. else
  2173. {
  2174. const int ivals[3]{ value1, value2, value3 };
  2175. SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), ivals);
  2176. }
  2177. }
  2178. END_API_FUNC
  2179. AL_API void AL_APIENTRY alSourceiv(ALuint source, ALenum param, const ALint *values)
  2180. START_API_FUNC
  2181. {
  2182. ContextRef context{GetContextRef()};
  2183. if UNLIKELY(!context) return;
  2184. std::lock_guard<std::mutex> _{context->mPropLock};
  2185. std::lock_guard<std::mutex> __{context->mSourceLock};
  2186. ALsource *Source = LookupSource(context.get(), source);
  2187. if UNLIKELY(!Source)
  2188. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2189. else if UNLIKELY(!values)
  2190. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2191. else
  2192. SetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues});
  2193. }
  2194. END_API_FUNC
  2195. AL_API void AL_APIENTRY alSourcei64SOFT(ALuint source, ALenum param, ALint64SOFT value)
  2196. START_API_FUNC
  2197. {
  2198. ContextRef context{GetContextRef()};
  2199. if UNLIKELY(!context) return;
  2200. std::lock_guard<std::mutex> _{context->mPropLock};
  2201. std::lock_guard<std::mutex> __{context->mSourceLock};
  2202. ALsource *Source{LookupSource(context.get(), source)};
  2203. if UNLIKELY(!Source)
  2204. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2205. else
  2206. SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {&value, 1u});
  2207. }
  2208. END_API_FUNC
  2209. AL_API void AL_APIENTRY alSource3i64SOFT(ALuint source, ALenum param, ALint64SOFT value1, ALint64SOFT value2, ALint64SOFT value3)
  2210. START_API_FUNC
  2211. {
  2212. ContextRef context{GetContextRef()};
  2213. if UNLIKELY(!context) return;
  2214. std::lock_guard<std::mutex> _{context->mPropLock};
  2215. std::lock_guard<std::mutex> __{context->mSourceLock};
  2216. ALsource *Source{LookupSource(context.get(), source)};
  2217. if UNLIKELY(!Source)
  2218. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2219. else
  2220. {
  2221. const int64_t i64vals[3]{ value1, value2, value3 };
  2222. SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), i64vals);
  2223. }
  2224. }
  2225. END_API_FUNC
  2226. AL_API void AL_APIENTRY alSourcei64vSOFT(ALuint source, ALenum param, const ALint64SOFT *values)
  2227. START_API_FUNC
  2228. {
  2229. ContextRef context{GetContextRef()};
  2230. if UNLIKELY(!context) return;
  2231. std::lock_guard<std::mutex> _{context->mPropLock};
  2232. std::lock_guard<std::mutex> __{context->mSourceLock};
  2233. ALsource *Source{LookupSource(context.get(), source)};
  2234. if UNLIKELY(!Source)
  2235. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2236. else if UNLIKELY(!values)
  2237. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2238. else
  2239. SetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues});
  2240. }
  2241. END_API_FUNC
  2242. AL_API void AL_APIENTRY alGetSourcef(ALuint source, ALenum param, ALfloat *value)
  2243. START_API_FUNC
  2244. {
  2245. ContextRef context{GetContextRef()};
  2246. if UNLIKELY(!context) return;
  2247. std::lock_guard<std::mutex> _{context->mSourceLock};
  2248. ALsource *Source{LookupSource(context.get(), source)};
  2249. if UNLIKELY(!Source)
  2250. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2251. else if UNLIKELY(!value)
  2252. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2253. else
  2254. {
  2255. double dval[1];
  2256. if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), dval))
  2257. *value = static_cast<float>(dval[0]);
  2258. }
  2259. }
  2260. END_API_FUNC
  2261. AL_API void AL_APIENTRY alGetSource3f(ALuint source, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
  2262. START_API_FUNC
  2263. {
  2264. ContextRef context{GetContextRef()};
  2265. if UNLIKELY(!context) return;
  2266. std::lock_guard<std::mutex> _{context->mSourceLock};
  2267. ALsource *Source{LookupSource(context.get(), source)};
  2268. if UNLIKELY(!Source)
  2269. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2270. else if UNLIKELY(!(value1 && value2 && value3))
  2271. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2272. else
  2273. {
  2274. double dvals[3];
  2275. if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), dvals))
  2276. {
  2277. *value1 = static_cast<float>(dvals[0]);
  2278. *value2 = static_cast<float>(dvals[1]);
  2279. *value3 = static_cast<float>(dvals[2]);
  2280. }
  2281. }
  2282. }
  2283. END_API_FUNC
  2284. AL_API void AL_APIENTRY alGetSourcefv(ALuint source, ALenum param, ALfloat *values)
  2285. START_API_FUNC
  2286. {
  2287. ContextRef context{GetContextRef()};
  2288. if UNLIKELY(!context) return;
  2289. std::lock_guard<std::mutex> _{context->mSourceLock};
  2290. ALsource *Source{LookupSource(context.get(), source)};
  2291. if UNLIKELY(!Source)
  2292. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2293. else if UNLIKELY(!values)
  2294. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2295. else
  2296. {
  2297. const ALuint count{FloatValsByProp(param)};
  2298. double dvals[MaxValues];
  2299. if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), {dvals, count}))
  2300. {
  2301. for(ALuint i{0};i < count;i++)
  2302. values[i] = static_cast<float>(dvals[i]);
  2303. }
  2304. }
  2305. }
  2306. END_API_FUNC
  2307. AL_API void AL_APIENTRY alGetSourcedSOFT(ALuint source, ALenum param, ALdouble *value)
  2308. START_API_FUNC
  2309. {
  2310. ContextRef context{GetContextRef()};
  2311. if UNLIKELY(!context) return;
  2312. std::lock_guard<std::mutex> _{context->mSourceLock};
  2313. ALsource *Source{LookupSource(context.get(), source)};
  2314. if UNLIKELY(!Source)
  2315. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2316. else if UNLIKELY(!value)
  2317. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2318. else
  2319. GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), {value, 1u});
  2320. }
  2321. END_API_FUNC
  2322. AL_API void AL_APIENTRY alGetSource3dSOFT(ALuint source, ALenum param, ALdouble *value1, ALdouble *value2, ALdouble *value3)
  2323. START_API_FUNC
  2324. {
  2325. ContextRef context{GetContextRef()};
  2326. if UNLIKELY(!context) return;
  2327. std::lock_guard<std::mutex> _{context->mSourceLock};
  2328. ALsource *Source{LookupSource(context.get(), source)};
  2329. if UNLIKELY(!Source)
  2330. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2331. else if UNLIKELY(!(value1 && value2 && value3))
  2332. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2333. else
  2334. {
  2335. double dvals[3];
  2336. if(GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), dvals))
  2337. {
  2338. *value1 = dvals[0];
  2339. *value2 = dvals[1];
  2340. *value3 = dvals[2];
  2341. }
  2342. }
  2343. }
  2344. END_API_FUNC
  2345. AL_API void AL_APIENTRY alGetSourcedvSOFT(ALuint source, ALenum param, ALdouble *values)
  2346. START_API_FUNC
  2347. {
  2348. ContextRef context{GetContextRef()};
  2349. if UNLIKELY(!context) return;
  2350. std::lock_guard<std::mutex> _{context->mSourceLock};
  2351. ALsource *Source{LookupSource(context.get(), source)};
  2352. if UNLIKELY(!Source)
  2353. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2354. else if UNLIKELY(!values)
  2355. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2356. else
  2357. GetSourcedv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues});
  2358. }
  2359. END_API_FUNC
  2360. AL_API void AL_APIENTRY alGetSourcei(ALuint source, ALenum param, ALint *value)
  2361. START_API_FUNC
  2362. {
  2363. ContextRef context{GetContextRef()};
  2364. if UNLIKELY(!context) return;
  2365. std::lock_guard<std::mutex> _{context->mSourceLock};
  2366. ALsource *Source{LookupSource(context.get(), source)};
  2367. if UNLIKELY(!Source)
  2368. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2369. else if UNLIKELY(!value)
  2370. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2371. else
  2372. GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {value, 1u});
  2373. }
  2374. END_API_FUNC
  2375. AL_API void AL_APIENTRY alGetSource3i(ALuint source, ALenum param, ALint *value1, ALint *value2, ALint *value3)
  2376. START_API_FUNC
  2377. {
  2378. ContextRef context{GetContextRef()};
  2379. if UNLIKELY(!context) return;
  2380. std::lock_guard<std::mutex> _{context->mSourceLock};
  2381. ALsource *Source{LookupSource(context.get(), source)};
  2382. if UNLIKELY(!Source)
  2383. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2384. else if UNLIKELY(!(value1 && value2 && value3))
  2385. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2386. else
  2387. {
  2388. int ivals[3];
  2389. if(GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), ivals))
  2390. {
  2391. *value1 = ivals[0];
  2392. *value2 = ivals[1];
  2393. *value3 = ivals[2];
  2394. }
  2395. }
  2396. }
  2397. END_API_FUNC
  2398. AL_API void AL_APIENTRY alGetSourceiv(ALuint source, ALenum param, ALint *values)
  2399. START_API_FUNC
  2400. {
  2401. ContextRef context{GetContextRef()};
  2402. if UNLIKELY(!context) return;
  2403. std::lock_guard<std::mutex> _{context->mSourceLock};
  2404. ALsource *Source{LookupSource(context.get(), source)};
  2405. if UNLIKELY(!Source)
  2406. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2407. else if UNLIKELY(!values)
  2408. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2409. else
  2410. GetSourceiv(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues});
  2411. }
  2412. END_API_FUNC
  2413. AL_API void AL_APIENTRY alGetSourcei64SOFT(ALuint source, ALenum param, ALint64SOFT *value)
  2414. START_API_FUNC
  2415. {
  2416. ContextRef context{GetContextRef()};
  2417. if UNLIKELY(!context) return;
  2418. std::lock_guard<std::mutex> _{context->mSourceLock};
  2419. ALsource *Source{LookupSource(context.get(), source)};
  2420. if UNLIKELY(!Source)
  2421. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2422. else if UNLIKELY(!value)
  2423. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2424. else
  2425. GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {value, 1u});
  2426. }
  2427. END_API_FUNC
  2428. AL_API void AL_APIENTRY alGetSource3i64SOFT(ALuint source, ALenum param, ALint64SOFT *value1, ALint64SOFT *value2, ALint64SOFT *value3)
  2429. START_API_FUNC
  2430. {
  2431. ContextRef context{GetContextRef()};
  2432. if UNLIKELY(!context) return;
  2433. std::lock_guard<std::mutex> _{context->mSourceLock};
  2434. ALsource *Source{LookupSource(context.get(), source)};
  2435. if UNLIKELY(!Source)
  2436. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2437. else if UNLIKELY(!(value1 && value2 && value3))
  2438. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2439. else
  2440. {
  2441. int64_t i64vals[3];
  2442. if(GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), i64vals))
  2443. {
  2444. *value1 = i64vals[0];
  2445. *value2 = i64vals[1];
  2446. *value3 = i64vals[2];
  2447. }
  2448. }
  2449. }
  2450. END_API_FUNC
  2451. AL_API void AL_APIENTRY alGetSourcei64vSOFT(ALuint source, ALenum param, ALint64SOFT *values)
  2452. START_API_FUNC
  2453. {
  2454. ContextRef context{GetContextRef()};
  2455. if UNLIKELY(!context) return;
  2456. std::lock_guard<std::mutex> _{context->mSourceLock};
  2457. ALsource *Source{LookupSource(context.get(), source)};
  2458. if UNLIKELY(!Source)
  2459. context->setError(AL_INVALID_NAME, "Invalid source ID %u", source);
  2460. else if UNLIKELY(!values)
  2461. context->setError(AL_INVALID_VALUE, "NULL pointer");
  2462. else
  2463. GetSourcei64v(Source, context.get(), static_cast<SourceProp>(param), {values, MaxValues});
  2464. }
  2465. END_API_FUNC
  2466. AL_API void AL_APIENTRY alSourcePlay(ALuint source)
  2467. START_API_FUNC
  2468. { alSourcePlayv(1, &source); }
  2469. END_API_FUNC
  2470. AL_API void AL_APIENTRY alSourcePlayv(ALsizei n, const ALuint *sources)
  2471. START_API_FUNC
  2472. {
  2473. ContextRef context{GetContextRef()};
  2474. if UNLIKELY(!context) return;
  2475. if UNLIKELY(n < 0)
  2476. context->setError(AL_INVALID_VALUE, "Playing %d sources", n);
  2477. if UNLIKELY(n <= 0) return;
  2478. al::vector<ALsource*> extra_sources;
  2479. std::array<ALsource*,8> source_storage;
  2480. al::span<ALsource*> srchandles;
  2481. if LIKELY(static_cast<ALuint>(n) <= source_storage.size())
  2482. srchandles = {source_storage.data(), static_cast<ALuint>(n)};
  2483. else
  2484. {
  2485. extra_sources.resize(static_cast<ALuint>(n));
  2486. srchandles = {extra_sources.data(), extra_sources.size()};
  2487. }
  2488. std::lock_guard<std::mutex> _{context->mSourceLock};
  2489. for(auto &srchdl : srchandles)
  2490. {
  2491. srchdl = LookupSource(context.get(), *sources);
  2492. if(!srchdl)
  2493. SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources);
  2494. ++sources;
  2495. }
  2496. ALCdevice *device{context->mDevice.get()};
  2497. /* If the device is disconnected, go right to stopped. */
  2498. if UNLIKELY(!device->Connected.load(std::memory_order_acquire))
  2499. {
  2500. /* TODO: Send state change event? */
  2501. for(ALsource *source : srchandles)
  2502. {
  2503. source->Offset = 0.0;
  2504. source->OffsetType = AL_NONE;
  2505. source->state = AL_STOPPED;
  2506. }
  2507. return;
  2508. }
  2509. /* Count the number of reusable voices. */
  2510. auto voicelist = context->getVoicesSpan();
  2511. size_t free_voices{0};
  2512. for(const Voice *voice : voicelist)
  2513. {
  2514. free_voices += (voice->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  2515. && voice->mSourceID.load(std::memory_order_relaxed) == 0u
  2516. && voice->mPendingChange.load(std::memory_order_relaxed) == false);
  2517. if(free_voices == srchandles.size())
  2518. break;
  2519. }
  2520. if UNLIKELY(srchandles.size() != free_voices)
  2521. {
  2522. const size_t inc_amount{srchandles.size() - free_voices};
  2523. auto &allvoices = *context->mVoices.load(std::memory_order_relaxed);
  2524. if(inc_amount > allvoices.size() - voicelist.size())
  2525. {
  2526. /* Increase the number of voices to handle the request. */
  2527. context->allocVoices(inc_amount - (allvoices.size() - voicelist.size()));
  2528. }
  2529. context->mActiveVoiceCount.fetch_add(inc_amount, std::memory_order_release);
  2530. voicelist = context->getVoicesSpan();
  2531. }
  2532. auto voiceiter = voicelist.begin();
  2533. ALuint vidx{0};
  2534. VoiceChange *tail{}, *cur{};
  2535. for(ALsource *source : srchandles)
  2536. {
  2537. /* Check that there is a queue containing at least one valid, non zero
  2538. * length buffer.
  2539. */
  2540. auto BufferList = source->mQueue.begin();
  2541. for(;BufferList != source->mQueue.end();++BufferList)
  2542. {
  2543. if(BufferList->mSampleLen != 0 || BufferList->mCallback)
  2544. break;
  2545. }
  2546. /* If there's nothing to play, go right to stopped. */
  2547. if UNLIKELY(BufferList == source->mQueue.end())
  2548. {
  2549. /* NOTE: A source without any playable buffers should not have a
  2550. * Voice since it shouldn't be in a playing or paused state. So
  2551. * there's no need to look up its voice and clear the source.
  2552. */
  2553. source->Offset = 0.0;
  2554. source->OffsetType = AL_NONE;
  2555. source->state = AL_STOPPED;
  2556. continue;
  2557. }
  2558. if(!cur)
  2559. cur = tail = GetVoiceChanger(context.get());
  2560. else
  2561. {
  2562. cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed);
  2563. cur = cur->mNext.load(std::memory_order_relaxed);
  2564. }
  2565. Voice *voice{GetSourceVoice(source, context.get())};
  2566. switch(GetSourceState(source, voice))
  2567. {
  2568. case AL_PAUSED:
  2569. /* A source that's paused simply resumes. If there's no voice, it
  2570. * was lost from a disconnect, so just start over with a new one.
  2571. */
  2572. cur->mOldVoice = nullptr;
  2573. if(!voice) break;
  2574. cur->mVoice = voice;
  2575. cur->mSourceID = source->id;
  2576. cur->mState = VChangeState::Play;
  2577. source->state = AL_PLAYING;
  2578. continue;
  2579. case AL_PLAYING:
  2580. /* A source that's already playing is restarted from the beginning.
  2581. * Stop the current voice and start a new one so it properly cross-
  2582. * fades back to the beginning.
  2583. */
  2584. if(voice)
  2585. voice->mPendingChange.store(true, std::memory_order_relaxed);
  2586. cur->mOldVoice = voice;
  2587. voice = nullptr;
  2588. break;
  2589. default:
  2590. assert(voice == nullptr);
  2591. cur->mOldVoice = nullptr;
  2592. break;
  2593. }
  2594. /* Find the next unused voice to play this source with. */
  2595. for(;voiceiter != voicelist.end();++voiceiter,++vidx)
  2596. {
  2597. Voice *v{*voiceiter};
  2598. if(v->mPlayState.load(std::memory_order_acquire) == Voice::Stopped
  2599. && v->mSourceID.load(std::memory_order_relaxed) == 0u
  2600. && v->mPendingChange.load(std::memory_order_relaxed) == false)
  2601. {
  2602. voice = v;
  2603. break;
  2604. }
  2605. }
  2606. voice->mPosition.store(0u, std::memory_order_relaxed);
  2607. voice->mPositionFrac.store(0, std::memory_order_relaxed);
  2608. voice->mCurrentBuffer.store(&source->mQueue.front(), std::memory_order_relaxed);
  2609. voice->mFlags = 0;
  2610. /* A source that's not playing or paused has any offset applied when it
  2611. * starts playing.
  2612. */
  2613. if(const ALenum offsettype{source->OffsetType})
  2614. {
  2615. const double offset{source->Offset};
  2616. source->OffsetType = AL_NONE;
  2617. source->Offset = 0.0;
  2618. if(auto vpos = GetSampleOffset(source->mQueue, offsettype, offset))
  2619. {
  2620. voice->mPosition.store(vpos->pos, std::memory_order_relaxed);
  2621. voice->mPositionFrac.store(vpos->frac, std::memory_order_relaxed);
  2622. voice->mCurrentBuffer.store(vpos->bufferitem, std::memory_order_relaxed);
  2623. if(vpos->pos!=0 || vpos->frac!=0 || vpos->bufferitem!=&source->mQueue.front())
  2624. voice->mFlags |= VoiceIsFading;
  2625. }
  2626. }
  2627. InitVoice(voice, source, std::addressof(*BufferList), context.get(), device);
  2628. source->VoiceIdx = vidx;
  2629. source->state = AL_PLAYING;
  2630. cur->mVoice = voice;
  2631. cur->mSourceID = source->id;
  2632. cur->mState = VChangeState::Play;
  2633. }
  2634. if LIKELY(tail)
  2635. SendVoiceChanges(context.get(), tail);
  2636. }
  2637. END_API_FUNC
  2638. AL_API void AL_APIENTRY alSourcePause(ALuint source)
  2639. START_API_FUNC
  2640. { alSourcePausev(1, &source); }
  2641. END_API_FUNC
  2642. AL_API void AL_APIENTRY alSourcePausev(ALsizei n, const ALuint *sources)
  2643. START_API_FUNC
  2644. {
  2645. ContextRef context{GetContextRef()};
  2646. if UNLIKELY(!context) return;
  2647. if UNLIKELY(n < 0)
  2648. context->setError(AL_INVALID_VALUE, "Pausing %d sources", n);
  2649. if UNLIKELY(n <= 0) return;
  2650. al::vector<ALsource*> extra_sources;
  2651. std::array<ALsource*,8> source_storage;
  2652. al::span<ALsource*> srchandles;
  2653. if LIKELY(static_cast<ALuint>(n) <= source_storage.size())
  2654. srchandles = {source_storage.data(), static_cast<ALuint>(n)};
  2655. else
  2656. {
  2657. extra_sources.resize(static_cast<ALuint>(n));
  2658. srchandles = {extra_sources.data(), extra_sources.size()};
  2659. }
  2660. std::lock_guard<std::mutex> _{context->mSourceLock};
  2661. for(auto &srchdl : srchandles)
  2662. {
  2663. srchdl = LookupSource(context.get(), *sources);
  2664. if(!srchdl)
  2665. SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources);
  2666. ++sources;
  2667. }
  2668. /* Pausing has to be done in two steps. First, for each source that's
  2669. * detected to be playing, chamge the voice (asynchronously) to
  2670. * stopping/paused.
  2671. */
  2672. VoiceChange *tail{}, *cur{};
  2673. for(ALsource *source : srchandles)
  2674. {
  2675. Voice *voice{GetSourceVoice(source, context.get())};
  2676. if(GetSourceState(source, voice) == AL_PLAYING)
  2677. {
  2678. if(!cur)
  2679. cur = tail = GetVoiceChanger(context.get());
  2680. else
  2681. {
  2682. cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed);
  2683. cur = cur->mNext.load(std::memory_order_relaxed);
  2684. }
  2685. cur->mVoice = voice;
  2686. cur->mSourceID = source->id;
  2687. cur->mState = VChangeState::Pause;
  2688. }
  2689. }
  2690. if LIKELY(tail)
  2691. {
  2692. SendVoiceChanges(context.get(), tail);
  2693. /* Second, now that the voice changes have been sent, because it's
  2694. * possible that the voice stopped after it was detected playing and
  2695. * before the voice got paused, recheck that the source is still
  2696. * considered playing and set it to paused if so.
  2697. */
  2698. for(ALsource *source : srchandles)
  2699. {
  2700. Voice *voice{GetSourceVoice(source, context.get())};
  2701. if(GetSourceState(source, voice) == AL_PLAYING)
  2702. source->state = AL_PAUSED;
  2703. }
  2704. }
  2705. }
  2706. END_API_FUNC
  2707. AL_API void AL_APIENTRY alSourceStop(ALuint source)
  2708. START_API_FUNC
  2709. { alSourceStopv(1, &source); }
  2710. END_API_FUNC
  2711. AL_API void AL_APIENTRY alSourceStopv(ALsizei n, const ALuint *sources)
  2712. START_API_FUNC
  2713. {
  2714. ContextRef context{GetContextRef()};
  2715. if UNLIKELY(!context) return;
  2716. if UNLIKELY(n < 0)
  2717. context->setError(AL_INVALID_VALUE, "Stopping %d sources", n);
  2718. if UNLIKELY(n <= 0) return;
  2719. al::vector<ALsource*> extra_sources;
  2720. std::array<ALsource*,8> source_storage;
  2721. al::span<ALsource*> srchandles;
  2722. if LIKELY(static_cast<ALuint>(n) <= source_storage.size())
  2723. srchandles = {source_storage.data(), static_cast<ALuint>(n)};
  2724. else
  2725. {
  2726. extra_sources.resize(static_cast<ALuint>(n));
  2727. srchandles = {extra_sources.data(), extra_sources.size()};
  2728. }
  2729. std::lock_guard<std::mutex> _{context->mSourceLock};
  2730. for(auto &srchdl : srchandles)
  2731. {
  2732. srchdl = LookupSource(context.get(), *sources);
  2733. if(!srchdl)
  2734. SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources);
  2735. ++sources;
  2736. }
  2737. VoiceChange *tail{}, *cur{};
  2738. for(ALsource *source : srchandles)
  2739. {
  2740. if(Voice *voice{GetSourceVoice(source, context.get())})
  2741. {
  2742. if(!cur)
  2743. cur = tail = GetVoiceChanger(context.get());
  2744. else
  2745. {
  2746. cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed);
  2747. cur = cur->mNext.load(std::memory_order_relaxed);
  2748. }
  2749. voice->mPendingChange.store(true, std::memory_order_relaxed);
  2750. cur->mVoice = voice;
  2751. cur->mSourceID = source->id;
  2752. cur->mState = VChangeState::Stop;
  2753. source->state = AL_STOPPED;
  2754. }
  2755. source->Offset = 0.0;
  2756. source->OffsetType = AL_NONE;
  2757. source->VoiceIdx = INVALID_VOICE_IDX;
  2758. }
  2759. if LIKELY(tail)
  2760. SendVoiceChanges(context.get(), tail);
  2761. }
  2762. END_API_FUNC
  2763. AL_API void AL_APIENTRY alSourceRewind(ALuint source)
  2764. START_API_FUNC
  2765. { alSourceRewindv(1, &source); }
  2766. END_API_FUNC
  2767. AL_API void AL_APIENTRY alSourceRewindv(ALsizei n, const ALuint *sources)
  2768. START_API_FUNC
  2769. {
  2770. ContextRef context{GetContextRef()};
  2771. if UNLIKELY(!context) return;
  2772. if UNLIKELY(n < 0)
  2773. context->setError(AL_INVALID_VALUE, "Rewinding %d sources", n);
  2774. if UNLIKELY(n <= 0) return;
  2775. al::vector<ALsource*> extra_sources;
  2776. std::array<ALsource*,8> source_storage;
  2777. al::span<ALsource*> srchandles;
  2778. if LIKELY(static_cast<ALuint>(n) <= source_storage.size())
  2779. srchandles = {source_storage.data(), static_cast<ALuint>(n)};
  2780. else
  2781. {
  2782. extra_sources.resize(static_cast<ALuint>(n));
  2783. srchandles = {extra_sources.data(), extra_sources.size()};
  2784. }
  2785. std::lock_guard<std::mutex> _{context->mSourceLock};
  2786. for(auto &srchdl : srchandles)
  2787. {
  2788. srchdl = LookupSource(context.get(), *sources);
  2789. if(!srchdl)
  2790. SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", *sources);
  2791. ++sources;
  2792. }
  2793. VoiceChange *tail{}, *cur{};
  2794. for(ALsource *source : srchandles)
  2795. {
  2796. Voice *voice{GetSourceVoice(source, context.get())};
  2797. if(source->state != AL_INITIAL)
  2798. {
  2799. if(!cur)
  2800. cur = tail = GetVoiceChanger(context.get());
  2801. else
  2802. {
  2803. cur->mNext.store(GetVoiceChanger(context.get()), std::memory_order_relaxed);
  2804. cur = cur->mNext.load(std::memory_order_relaxed);
  2805. }
  2806. if(voice)
  2807. voice->mPendingChange.store(true, std::memory_order_relaxed);
  2808. cur->mVoice = voice;
  2809. cur->mSourceID = source->id;
  2810. cur->mState = VChangeState::Reset;
  2811. source->state = AL_INITIAL;
  2812. }
  2813. source->Offset = 0.0;
  2814. source->OffsetType = AL_NONE;
  2815. source->VoiceIdx = INVALID_VOICE_IDX;
  2816. }
  2817. if LIKELY(tail)
  2818. SendVoiceChanges(context.get(), tail);
  2819. }
  2820. END_API_FUNC
  2821. AL_API void AL_APIENTRY alSourceQueueBuffers(ALuint src, ALsizei nb, const ALuint *buffers)
  2822. START_API_FUNC
  2823. {
  2824. ContextRef context{GetContextRef()};
  2825. if UNLIKELY(!context) return;
  2826. if UNLIKELY(nb < 0)
  2827. context->setError(AL_INVALID_VALUE, "Queueing %d buffers", nb);
  2828. if UNLIKELY(nb <= 0) return;
  2829. std::lock_guard<std::mutex> _{context->mSourceLock};
  2830. ALsource *source{LookupSource(context.get(),src)};
  2831. if UNLIKELY(!source)
  2832. SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", src);
  2833. /* Can't queue on a Static Source */
  2834. if UNLIKELY(source->SourceType == AL_STATIC)
  2835. SETERR_RETURN(context, AL_INVALID_OPERATION,, "Queueing onto static source %u", src);
  2836. /* Check for a valid Buffer, for its frequency and format */
  2837. ALCdevice *device{context->mDevice.get()};
  2838. ALbuffer *BufferFmt{nullptr};
  2839. for(auto &item : source->mQueue)
  2840. {
  2841. BufferFmt = item.mBuffer;
  2842. if(BufferFmt) break;
  2843. }
  2844. std::unique_lock<std::mutex> buflock{device->BufferLock};
  2845. const size_t NewListStart{source->mQueue.size()};
  2846. ALbufferQueueItem *BufferList{nullptr};
  2847. for(ALsizei i{0};i < nb;i++)
  2848. {
  2849. bool fmt_mismatch{false};
  2850. ALbuffer *buffer{nullptr};
  2851. if(buffers[i] && (buffer=LookupBuffer(device, buffers[i])) == nullptr)
  2852. {
  2853. context->setError(AL_INVALID_NAME, "Queueing invalid buffer ID %u", buffers[i]);
  2854. goto buffer_error;
  2855. }
  2856. if(buffer && buffer->mCallback)
  2857. {
  2858. context->setError(AL_INVALID_OPERATION, "Queueing callback buffer %u", buffers[i]);
  2859. goto buffer_error;
  2860. }
  2861. source->mQueue.emplace_back();
  2862. if(!BufferList)
  2863. BufferList = &source->mQueue.back();
  2864. else
  2865. {
  2866. auto &item = source->mQueue.back();
  2867. BufferList->mNext.store(&item, std::memory_order_relaxed);
  2868. BufferList = &item;
  2869. }
  2870. if(!buffer) continue;
  2871. BufferList->mSampleLen = buffer->mSampleLen;
  2872. BufferList->mLoopEnd = buffer->mSampleLen;
  2873. BufferList->mSamples = buffer->mData.data();
  2874. BufferList->mBuffer = buffer;
  2875. IncrementRef(buffer->ref);
  2876. if(buffer->MappedAccess != 0 && !(buffer->MappedAccess&AL_MAP_PERSISTENT_BIT_SOFT))
  2877. {
  2878. context->setError(AL_INVALID_OPERATION, "Queueing non-persistently mapped buffer %u",
  2879. buffer->id);
  2880. goto buffer_error;
  2881. }
  2882. if(BufferFmt == nullptr)
  2883. BufferFmt = buffer;
  2884. else
  2885. {
  2886. fmt_mismatch |= BufferFmt->mSampleRate != buffer->mSampleRate;
  2887. fmt_mismatch |= BufferFmt->mChannels != buffer->mChannels;
  2888. if(BufferFmt->isBFormat())
  2889. {
  2890. fmt_mismatch |= BufferFmt->mAmbiLayout != buffer->mAmbiLayout;
  2891. fmt_mismatch |= BufferFmt->mAmbiScaling != buffer->mAmbiScaling;
  2892. }
  2893. fmt_mismatch |= BufferFmt->mAmbiOrder != buffer->mAmbiOrder;
  2894. fmt_mismatch |= BufferFmt->OriginalType != buffer->OriginalType;
  2895. }
  2896. if UNLIKELY(fmt_mismatch)
  2897. {
  2898. context->setError(AL_INVALID_OPERATION, "Queueing buffer with mismatched format");
  2899. buffer_error:
  2900. /* A buffer failed (invalid ID or format), so unlock and release
  2901. * each buffer we had.
  2902. */
  2903. auto iter = source->mQueue.begin() + ptrdiff_t(NewListStart);
  2904. for(;iter != source->mQueue.end();++iter)
  2905. {
  2906. if(ALbuffer *buf{iter->mBuffer})
  2907. DecrementRef(buf->ref);
  2908. }
  2909. source->mQueue.resize(NewListStart);
  2910. return;
  2911. }
  2912. }
  2913. /* All buffers good. */
  2914. buflock.unlock();
  2915. /* Source is now streaming */
  2916. source->SourceType = AL_STREAMING;
  2917. if(NewListStart != 0)
  2918. {
  2919. auto iter = source->mQueue.begin() + ptrdiff_t(NewListStart);
  2920. (iter-1)->mNext.store(std::addressof(*iter), std::memory_order_release);
  2921. }
  2922. }
  2923. END_API_FUNC
  2924. AL_API void AL_APIENTRY alSourceUnqueueBuffers(ALuint src, ALsizei nb, ALuint *buffers)
  2925. START_API_FUNC
  2926. {
  2927. ContextRef context{GetContextRef()};
  2928. if UNLIKELY(!context) return;
  2929. if UNLIKELY(nb < 0)
  2930. context->setError(AL_INVALID_VALUE, "Unqueueing %d buffers", nb);
  2931. if UNLIKELY(nb <= 0) return;
  2932. std::lock_guard<std::mutex> _{context->mSourceLock};
  2933. ALsource *source{LookupSource(context.get(),src)};
  2934. if UNLIKELY(!source)
  2935. SETERR_RETURN(context, AL_INVALID_NAME,, "Invalid source ID %u", src);
  2936. if UNLIKELY(source->SourceType != AL_STREAMING)
  2937. SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing from a non-streaming source %u",
  2938. src);
  2939. if UNLIKELY(source->Looping)
  2940. SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing from looping source %u", src);
  2941. /* Make sure enough buffers have been processed to unqueue. */
  2942. uint processed{0u};
  2943. if LIKELY(source->state != AL_INITIAL)
  2944. {
  2945. VoiceBufferItem *Current{nullptr};
  2946. if(Voice *voice{GetSourceVoice(source, context.get())})
  2947. Current = voice->mCurrentBuffer.load(std::memory_order_relaxed);
  2948. for(auto &item : source->mQueue)
  2949. {
  2950. if(&item == Current)
  2951. break;
  2952. ++processed;
  2953. }
  2954. }
  2955. if UNLIKELY(processed < static_cast<ALuint>(nb))
  2956. SETERR_RETURN(context, AL_INVALID_VALUE,, "Unqueueing %d buffer%s (only %u processed)",
  2957. nb, (nb==1)?"":"s", processed);
  2958. do {
  2959. auto &head = source->mQueue.front();
  2960. if(ALbuffer *buffer{head.mBuffer})
  2961. {
  2962. *(buffers++) = buffer->id;
  2963. DecrementRef(buffer->ref);
  2964. }
  2965. else
  2966. *(buffers++) = 0;
  2967. source->mQueue.pop_front();
  2968. } while(--nb);
  2969. }
  2970. END_API_FUNC
  2971. ALsource::ALsource()
  2972. {
  2973. Direct.Gain = 1.0f;
  2974. Direct.GainHF = 1.0f;
  2975. Direct.HFReference = LOWPASSFREQREF;
  2976. Direct.GainLF = 1.0f;
  2977. Direct.LFReference = HIGHPASSFREQREF;
  2978. for(auto &send : Send)
  2979. {
  2980. send.Slot = nullptr;
  2981. send.Gain = 1.0f;
  2982. send.GainHF = 1.0f;
  2983. send.HFReference = LOWPASSFREQREF;
  2984. send.GainLF = 1.0f;
  2985. send.LFReference = HIGHPASSFREQREF;
  2986. }
  2987. PropsClean.test_and_set(std::memory_order_relaxed);
  2988. }
  2989. ALsource::~ALsource()
  2990. {
  2991. for(auto &item : mQueue)
  2992. {
  2993. if(ALbuffer *buffer{item.mBuffer})
  2994. DecrementRef(buffer->ref);
  2995. }
  2996. auto clear_send = [](ALsource::SendData &send) -> void
  2997. { if(send.Slot) DecrementRef(send.Slot->ref); };
  2998. std::for_each(Send.begin(), Send.end(), clear_send);
  2999. }
  3000. void UpdateAllSourceProps(ALCcontext *context)
  3001. {
  3002. std::lock_guard<std::mutex> _{context->mSourceLock};
  3003. auto voicelist = context->getVoicesSpan();
  3004. ALuint vidx{0u};
  3005. for(Voice *voice : voicelist)
  3006. {
  3007. ALuint sid{voice->mSourceID.load(std::memory_order_acquire)};
  3008. ALsource *source = sid ? LookupSource(context, sid) : nullptr;
  3009. if(source && source->VoiceIdx == vidx)
  3010. {
  3011. if(!source->PropsClean.test_and_set(std::memory_order_acq_rel))
  3012. UpdateSourceProps(source, voice, context);
  3013. }
  3014. ++vidx;
  3015. }
  3016. }
  3017. SourceSubList::~SourceSubList()
  3018. {
  3019. uint64_t usemask{~FreeMask};
  3020. while(usemask)
  3021. {
  3022. const int idx{al::countr_zero(usemask)};
  3023. al::destroy_at(Sources+idx);
  3024. usemask &= ~(1_u64 << idx);
  3025. }
  3026. FreeMask = ~usemask;
  3027. al_free(Sources);
  3028. Sources = nullptr;
  3029. }