alu.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  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 "alu.h"
  22. #include <algorithm>
  23. #include <array>
  24. #include <atomic>
  25. #include <chrono>
  26. #include <climits>
  27. #include <cmath>
  28. #include <cstdarg>
  29. #include <cstdio>
  30. #include <cstdlib>
  31. #include <functional>
  32. #include <iterator>
  33. #include <limits>
  34. #include <memory>
  35. #include <new>
  36. #include <numeric>
  37. #include <utility>
  38. #include "AL/al.h"
  39. #include "AL/alc.h"
  40. #include "AL/efx.h"
  41. #include "al/auxeffectslot.h"
  42. #include "al/buffer.h"
  43. #include "al/effect.h"
  44. #include "al/event.h"
  45. #include "al/listener.h"
  46. #include "alcmain.h"
  47. #include "alcontext.h"
  48. #include "almalloc.h"
  49. #include "alnumeric.h"
  50. #include "alspan.h"
  51. #include "alstring.h"
  52. #include "ambidefs.h"
  53. #include "atomic.h"
  54. #include "bformatdec.h"
  55. #include "bs2b.h"
  56. #include "cpu_caps.h"
  57. #include "devformat.h"
  58. #include "effects/base.h"
  59. #include "filters/biquad.h"
  60. #include "filters/nfc.h"
  61. #include "filters/splitter.h"
  62. #include "fpu_modes.h"
  63. #include "hrtf.h"
  64. #include "inprogext.h"
  65. #include "mastering.h"
  66. #include "math_defs.h"
  67. #include "mixer/defs.h"
  68. #include "opthelpers.h"
  69. #include "ringbuffer.h"
  70. #include "strutils.h"
  71. #include "threads.h"
  72. #include "uhjfilter.h"
  73. #include "vecmat.h"
  74. #include "voice.h"
  75. #include "bsinc_inc.h"
  76. static_assert(!(MAX_RESAMPLER_PADDING&1) && MAX_RESAMPLER_PADDING >= bsinc24.m[0],
  77. "MAX_RESAMPLER_PADDING is not a multiple of two, or is too small");
  78. namespace {
  79. using namespace std::placeholders;
  80. ALfloat InitConeScale()
  81. {
  82. ALfloat ret{1.0f};
  83. if(auto optval = al::getenv("__ALSOFT_HALF_ANGLE_CONES"))
  84. {
  85. if(al::strcasecmp(optval->c_str(), "true") == 0
  86. || strtol(optval->c_str(), nullptr, 0) == 1)
  87. ret *= 0.5f;
  88. }
  89. return ret;
  90. }
  91. ALfloat InitZScale()
  92. {
  93. ALfloat ret{1.0f};
  94. if(auto optval = al::getenv("__ALSOFT_REVERSE_Z"))
  95. {
  96. if(al::strcasecmp(optval->c_str(), "true") == 0
  97. || strtol(optval->c_str(), nullptr, 0) == 1)
  98. ret *= -1.0f;
  99. }
  100. return ret;
  101. }
  102. } // namespace
  103. /* Cone scalar */
  104. const ALfloat ConeScale{InitConeScale()};
  105. /* Localized Z scalar for mono sources */
  106. const ALfloat ZScale{InitZScale()};
  107. MixerFunc MixSamples{Mix_<CTag>};
  108. RowMixerFunc MixRowSamples{MixRow_<CTag>};
  109. namespace {
  110. struct ChanMap {
  111. Channel channel;
  112. ALfloat angle;
  113. ALfloat elevation;
  114. };
  115. HrtfDirectMixerFunc MixDirectHrtf = MixDirectHrtf_<CTag>;
  116. inline MixerFunc SelectMixer()
  117. {
  118. #ifdef HAVE_NEON
  119. if((CPUCapFlags&CPU_CAP_NEON))
  120. return Mix_<NEONTag>;
  121. #endif
  122. #ifdef HAVE_SSE
  123. if((CPUCapFlags&CPU_CAP_SSE))
  124. return Mix_<SSETag>;
  125. #endif
  126. return Mix_<CTag>;
  127. }
  128. inline RowMixerFunc SelectRowMixer()
  129. {
  130. #ifdef HAVE_NEON
  131. if((CPUCapFlags&CPU_CAP_NEON))
  132. return MixRow_<NEONTag>;
  133. #endif
  134. #ifdef HAVE_SSE
  135. if((CPUCapFlags&CPU_CAP_SSE))
  136. return MixRow_<SSETag>;
  137. #endif
  138. return MixRow_<CTag>;
  139. }
  140. inline HrtfDirectMixerFunc SelectHrtfMixer(void)
  141. {
  142. #ifdef HAVE_NEON
  143. if((CPUCapFlags&CPU_CAP_NEON))
  144. return MixDirectHrtf_<NEONTag>;
  145. #endif
  146. #ifdef HAVE_SSE
  147. if((CPUCapFlags&CPU_CAP_SSE))
  148. return MixDirectHrtf_<SSETag>;
  149. #endif
  150. return MixDirectHrtf_<CTag>;
  151. }
  152. inline void BsincPrepare(const ALuint increment, BsincState *state, const BSincTable *table)
  153. {
  154. size_t si{BSINC_SCALE_COUNT - 1};
  155. float sf{0.0f};
  156. if(increment > FRACTIONONE)
  157. {
  158. sf = FRACTIONONE / static_cast<float>(increment);
  159. sf = maxf(0.0f, (BSINC_SCALE_COUNT-1) * (sf-table->scaleBase) * table->scaleRange);
  160. si = float2uint(sf);
  161. /* The interpolation factor is fit to this diagonally-symmetric curve
  162. * to reduce the transition ripple caused by interpolating different
  163. * scales of the sinc function.
  164. */
  165. sf = 1.0f - std::cos(std::asin(sf - static_cast<float>(si)));
  166. }
  167. state->sf = sf;
  168. state->m = table->m[si];
  169. state->l = (state->m/2) - 1;
  170. state->filter = table->Tab + table->filterOffset[si];
  171. }
  172. inline ResamplerFunc SelectResampler(Resampler resampler, ALuint increment)
  173. {
  174. switch(resampler)
  175. {
  176. case Resampler::Point:
  177. return Resample_<PointTag,CTag>;
  178. case Resampler::Linear:
  179. #ifdef HAVE_NEON
  180. if((CPUCapFlags&CPU_CAP_NEON))
  181. return Resample_<LerpTag,NEONTag>;
  182. #endif
  183. #ifdef HAVE_SSE4_1
  184. if((CPUCapFlags&CPU_CAP_SSE4_1))
  185. return Resample_<LerpTag,SSE4Tag>;
  186. #endif
  187. #ifdef HAVE_SSE2
  188. if((CPUCapFlags&CPU_CAP_SSE2))
  189. return Resample_<LerpTag,SSE2Tag>;
  190. #endif
  191. return Resample_<LerpTag,CTag>;
  192. case Resampler::Cubic:
  193. return Resample_<CubicTag,CTag>;
  194. case Resampler::BSinc12:
  195. case Resampler::BSinc24:
  196. if(increment <= FRACTIONONE)
  197. {
  198. /* fall-through */
  199. case Resampler::FastBSinc12:
  200. case Resampler::FastBSinc24:
  201. #ifdef HAVE_NEON
  202. if((CPUCapFlags&CPU_CAP_NEON))
  203. return Resample_<FastBSincTag,NEONTag>;
  204. #endif
  205. #ifdef HAVE_SSE
  206. if((CPUCapFlags&CPU_CAP_SSE))
  207. return Resample_<FastBSincTag,SSETag>;
  208. #endif
  209. return Resample_<FastBSincTag,CTag>;
  210. }
  211. #ifdef HAVE_NEON
  212. if((CPUCapFlags&CPU_CAP_NEON))
  213. return Resample_<BSincTag,NEONTag>;
  214. #endif
  215. #ifdef HAVE_SSE
  216. if((CPUCapFlags&CPU_CAP_SSE))
  217. return Resample_<BSincTag,SSETag>;
  218. #endif
  219. return Resample_<BSincTag,CTag>;
  220. }
  221. return Resample_<PointTag,CTag>;
  222. }
  223. } // namespace
  224. void aluInit(void)
  225. {
  226. MixSamples = SelectMixer();
  227. MixRowSamples = SelectRowMixer();
  228. MixDirectHrtf = SelectHrtfMixer();
  229. }
  230. ResamplerFunc PrepareResampler(Resampler resampler, ALuint increment, InterpState *state)
  231. {
  232. switch(resampler)
  233. {
  234. case Resampler::Point:
  235. case Resampler::Linear:
  236. case Resampler::Cubic:
  237. break;
  238. case Resampler::FastBSinc12:
  239. case Resampler::BSinc12:
  240. BsincPrepare(increment, &state->bsinc, &bsinc12);
  241. break;
  242. case Resampler::FastBSinc24:
  243. case Resampler::BSinc24:
  244. BsincPrepare(increment, &state->bsinc, &bsinc24);
  245. break;
  246. }
  247. return SelectResampler(resampler, increment);
  248. }
  249. void ALCdevice::ProcessHrtf(const size_t SamplesToDo)
  250. {
  251. /* HRTF is stereo output only. */
  252. const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
  253. const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
  254. MixDirectHrtf(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer, HrtfAccumData,
  255. mHrtfState.get(), SamplesToDo);
  256. }
  257. void ALCdevice::ProcessAmbiDec(const size_t SamplesToDo)
  258. {
  259. AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo);
  260. }
  261. void ALCdevice::ProcessUhj(const size_t SamplesToDo)
  262. {
  263. /* UHJ is stereo output only. */
  264. const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
  265. const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
  266. /* Encode to stereo-compatible 2-channel UHJ output. */
  267. Uhj_Encoder->encode(RealOut.Buffer[lidx], RealOut.Buffer[ridx], Dry.Buffer.data(),
  268. SamplesToDo);
  269. }
  270. void ALCdevice::ProcessBs2b(const size_t SamplesToDo)
  271. {
  272. /* First, decode the ambisonic mix to the "real" output. */
  273. AmbiDecoder->process(RealOut.Buffer, Dry.Buffer.data(), SamplesToDo);
  274. /* BS2B is stereo output only. */
  275. const ALuint lidx{RealOut.ChannelIndex[FrontLeft]};
  276. const ALuint ridx{RealOut.ChannelIndex[FrontRight]};
  277. /* Now apply the BS2B binaural/crossfeed filter. */
  278. bs2b_cross_feed(Bs2b.get(), RealOut.Buffer[lidx].data(), RealOut.Buffer[ridx].data(),
  279. SamplesToDo);
  280. }
  281. namespace {
  282. /* This RNG method was created based on the math found in opusdec. It's quick,
  283. * and starting with a seed value of 22222, is suitable for generating
  284. * whitenoise.
  285. */
  286. inline ALuint dither_rng(ALuint *seed) noexcept
  287. {
  288. *seed = (*seed * 96314165) + 907633515;
  289. return *seed;
  290. }
  291. inline alu::Vector aluCrossproduct(const alu::Vector &in1, const alu::Vector &in2)
  292. {
  293. return alu::Vector{
  294. in1[1]*in2[2] - in1[2]*in2[1],
  295. in1[2]*in2[0] - in1[0]*in2[2],
  296. in1[0]*in2[1] - in1[1]*in2[0],
  297. 0.0f
  298. };
  299. }
  300. inline ALfloat aluDotproduct(const alu::Vector &vec1, const alu::Vector &vec2)
  301. {
  302. return vec1[0]*vec2[0] + vec1[1]*vec2[1] + vec1[2]*vec2[2];
  303. }
  304. alu::Vector operator*(const alu::Matrix &mtx, const alu::Vector &vec) noexcept
  305. {
  306. return alu::Vector{
  307. vec[0]*mtx[0][0] + vec[1]*mtx[1][0] + vec[2]*mtx[2][0] + vec[3]*mtx[3][0],
  308. vec[0]*mtx[0][1] + vec[1]*mtx[1][1] + vec[2]*mtx[2][1] + vec[3]*mtx[3][1],
  309. vec[0]*mtx[0][2] + vec[1]*mtx[1][2] + vec[2]*mtx[2][2] + vec[3]*mtx[3][2],
  310. vec[0]*mtx[0][3] + vec[1]*mtx[1][3] + vec[2]*mtx[2][3] + vec[3]*mtx[3][3]
  311. };
  312. }
  313. bool CalcContextParams(ALCcontext *Context)
  314. {
  315. ALcontextProps *props{Context->mUpdate.exchange(nullptr, std::memory_order_acq_rel)};
  316. if(!props) return false;
  317. ALlistener &Listener = Context->mListener;
  318. Listener.Params.DopplerFactor = props->DopplerFactor;
  319. Listener.Params.SpeedOfSound = props->SpeedOfSound * props->DopplerVelocity;
  320. Listener.Params.SourceDistanceModel = props->SourceDistanceModel;
  321. Listener.Params.mDistanceModel = props->mDistanceModel;
  322. AtomicReplaceHead(Context->mFreeContextProps, props);
  323. return true;
  324. }
  325. bool CalcListenerParams(ALCcontext *Context)
  326. {
  327. ALlistener &Listener = Context->mListener;
  328. ALlistenerProps *props{Listener.Params.Update.exchange(nullptr, std::memory_order_acq_rel)};
  329. if(!props) return false;
  330. /* AT then UP */
  331. alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f};
  332. N.normalize();
  333. alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f};
  334. V.normalize();
  335. /* Build and normalize right-vector */
  336. alu::Vector U{aluCrossproduct(N, V)};
  337. U.normalize();
  338. Listener.Params.Matrix = alu::Matrix{
  339. U[0], V[0], -N[0], 0.0f,
  340. U[1], V[1], -N[1], 0.0f,
  341. U[2], V[2], -N[2], 0.0f,
  342. 0.0f, 0.0f, 0.0f, 1.0f
  343. };
  344. const alu::Vector P{Listener.Params.Matrix *
  345. alu::Vector{props->Position[0], props->Position[1], props->Position[2], 1.0f}};
  346. Listener.Params.Matrix.setRow(3, -P[0], -P[1], -P[2], 1.0f);
  347. const alu::Vector vel{props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f};
  348. Listener.Params.Velocity = Listener.Params.Matrix * vel;
  349. Listener.Params.Gain = props->Gain * Context->mGainBoost;
  350. Listener.Params.MetersPerUnit = props->MetersPerUnit;
  351. AtomicReplaceHead(Context->mFreeListenerProps, props);
  352. return true;
  353. }
  354. bool CalcEffectSlotParams(ALeffectslot *slot, ALCcontext *context)
  355. {
  356. ALeffectslotProps *props{slot->Params.Update.exchange(nullptr, std::memory_order_acq_rel)};
  357. if(!props) return false;
  358. slot->Params.Gain = props->Gain;
  359. slot->Params.AuxSendAuto = props->AuxSendAuto;
  360. slot->Params.Target = props->Target;
  361. slot->Params.EffectType = props->Type;
  362. slot->Params.mEffectProps = props->Props;
  363. if(IsReverbEffect(props->Type))
  364. {
  365. slot->Params.RoomRolloff = props->Props.Reverb.RoomRolloffFactor;
  366. slot->Params.DecayTime = props->Props.Reverb.DecayTime;
  367. slot->Params.DecayLFRatio = props->Props.Reverb.DecayLFRatio;
  368. slot->Params.DecayHFRatio = props->Props.Reverb.DecayHFRatio;
  369. slot->Params.DecayHFLimit = props->Props.Reverb.DecayHFLimit;
  370. slot->Params.AirAbsorptionGainHF = props->Props.Reverb.AirAbsorptionGainHF;
  371. }
  372. else
  373. {
  374. slot->Params.RoomRolloff = 0.0f;
  375. slot->Params.DecayTime = 0.0f;
  376. slot->Params.DecayLFRatio = 0.0f;
  377. slot->Params.DecayHFRatio = 0.0f;
  378. slot->Params.DecayHFLimit = AL_FALSE;
  379. slot->Params.AirAbsorptionGainHF = 1.0f;
  380. }
  381. EffectState *state{props->State};
  382. props->State = nullptr;
  383. EffectState *oldstate{slot->Params.mEffectState};
  384. slot->Params.mEffectState = state;
  385. /* Only release the old state if it won't get deleted, since we can't be
  386. * deleting/freeing anything in the mixer.
  387. */
  388. if(!oldstate->releaseIfNoDelete())
  389. {
  390. /* Otherwise, if it would be deleted send it off with a release event. */
  391. RingBuffer *ring{context->mAsyncEvents.get()};
  392. auto evt_vec = ring->getWriteVector();
  393. if LIKELY(evt_vec.first.len > 0)
  394. {
  395. AsyncEvent *evt{new (evt_vec.first.buf) AsyncEvent{EventType_ReleaseEffectState}};
  396. evt->u.mEffectState = oldstate;
  397. ring->writeAdvance(1);
  398. context->mEventSem.post();
  399. }
  400. else
  401. {
  402. /* If writing the event failed, the queue was probably full. Store
  403. * the old state in the property object where it can eventually be
  404. * cleaned up sometime later (not ideal, but better than blocking
  405. * or leaking).
  406. */
  407. props->State = oldstate;
  408. }
  409. }
  410. AtomicReplaceHead(context->mFreeEffectslotProps, props);
  411. EffectTarget output;
  412. if(ALeffectslot *target{slot->Params.Target})
  413. output = EffectTarget{&target->Wet, nullptr};
  414. else
  415. {
  416. ALCdevice *device{context->mDevice.get()};
  417. output = EffectTarget{&device->Dry, &device->RealOut};
  418. }
  419. state->update(context, slot, &slot->Params.mEffectProps, output);
  420. return true;
  421. }
  422. /* Scales the given azimuth toward the side (+/- pi/2 radians) for positions in
  423. * front.
  424. */
  425. inline float ScaleAzimuthFront(float azimuth, float scale)
  426. {
  427. const ALfloat abs_azi{std::fabs(azimuth)};
  428. if(!(abs_azi >= al::MathDefs<float>::Pi()*0.5f))
  429. return std::copysign(minf(abs_azi*scale, al::MathDefs<float>::Pi()*0.5f), azimuth);
  430. return azimuth;
  431. }
  432. void CalcPanningAndFilters(ALvoice *voice, const ALfloat xpos, const ALfloat ypos,
  433. const ALfloat zpos, const ALfloat Distance, const ALfloat Spread, const ALfloat DryGain,
  434. const ALfloat DryGainHF, const ALfloat DryGainLF, const ALfloat (&WetGain)[MAX_SENDS],
  435. const ALfloat (&WetGainLF)[MAX_SENDS], const ALfloat (&WetGainHF)[MAX_SENDS],
  436. ALeffectslot *(&SendSlots)[MAX_SENDS], const ALvoicePropsBase *props,
  437. const ALlistener &Listener, const ALCdevice *Device)
  438. {
  439. static const ChanMap MonoMap[1]{
  440. { FrontCenter, 0.0f, 0.0f }
  441. }, RearMap[2]{
  442. { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) },
  443. { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) }
  444. }, QuadMap[4]{
  445. { FrontLeft, Deg2Rad( -45.0f), Deg2Rad(0.0f) },
  446. { FrontRight, Deg2Rad( 45.0f), Deg2Rad(0.0f) },
  447. { BackLeft, Deg2Rad(-135.0f), Deg2Rad(0.0f) },
  448. { BackRight, Deg2Rad( 135.0f), Deg2Rad(0.0f) }
  449. }, X51Map[6]{
  450. { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
  451. { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
  452. { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
  453. { LFE, 0.0f, 0.0f },
  454. { SideLeft, Deg2Rad(-110.0f), Deg2Rad(0.0f) },
  455. { SideRight, Deg2Rad( 110.0f), Deg2Rad(0.0f) }
  456. }, X61Map[7]{
  457. { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) },
  458. { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
  459. { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
  460. { LFE, 0.0f, 0.0f },
  461. { BackCenter, Deg2Rad(180.0f), Deg2Rad(0.0f) },
  462. { SideLeft, Deg2Rad(-90.0f), Deg2Rad(0.0f) },
  463. { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
  464. }, X71Map[8]{
  465. { FrontLeft, Deg2Rad( -30.0f), Deg2Rad(0.0f) },
  466. { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) },
  467. { FrontCenter, Deg2Rad( 0.0f), Deg2Rad(0.0f) },
  468. { LFE, 0.0f, 0.0f },
  469. { BackLeft, Deg2Rad(-150.0f), Deg2Rad(0.0f) },
  470. { BackRight, Deg2Rad( 150.0f), Deg2Rad(0.0f) },
  471. { SideLeft, Deg2Rad( -90.0f), Deg2Rad(0.0f) },
  472. { SideRight, Deg2Rad( 90.0f), Deg2Rad(0.0f) }
  473. };
  474. ChanMap StereoMap[2]{
  475. { FrontLeft, Deg2Rad(-30.0f), Deg2Rad(0.0f) },
  476. { FrontRight, Deg2Rad( 30.0f), Deg2Rad(0.0f) }
  477. };
  478. const auto Frequency = static_cast<ALfloat>(Device->Frequency);
  479. const ALuint NumSends{Device->NumAuxSends};
  480. bool DirectChannels{props->DirectChannels != AL_FALSE};
  481. const ChanMap *chans{nullptr};
  482. ALuint num_channels{0};
  483. bool isbformat{false};
  484. ALfloat downmix_gain{1.0f};
  485. switch(voice->mFmtChannels)
  486. {
  487. case FmtMono:
  488. chans = MonoMap;
  489. num_channels = 1;
  490. /* Mono buffers are never played direct. */
  491. DirectChannels = false;
  492. break;
  493. case FmtStereo:
  494. /* Convert counter-clockwise to clockwise. */
  495. StereoMap[0].angle = -props->StereoPan[0];
  496. StereoMap[1].angle = -props->StereoPan[1];
  497. chans = StereoMap;
  498. num_channels = 2;
  499. downmix_gain = 1.0f / 2.0f;
  500. break;
  501. case FmtRear:
  502. chans = RearMap;
  503. num_channels = 2;
  504. downmix_gain = 1.0f / 2.0f;
  505. break;
  506. case FmtQuad:
  507. chans = QuadMap;
  508. num_channels = 4;
  509. downmix_gain = 1.0f / 4.0f;
  510. break;
  511. case FmtX51:
  512. chans = X51Map;
  513. num_channels = 6;
  514. /* NOTE: Excludes LFE. */
  515. downmix_gain = 1.0f / 5.0f;
  516. break;
  517. case FmtX61:
  518. chans = X61Map;
  519. num_channels = 7;
  520. /* NOTE: Excludes LFE. */
  521. downmix_gain = 1.0f / 6.0f;
  522. break;
  523. case FmtX71:
  524. chans = X71Map;
  525. num_channels = 8;
  526. /* NOTE: Excludes LFE. */
  527. downmix_gain = 1.0f / 7.0f;
  528. break;
  529. case FmtBFormat2D:
  530. num_channels = 3;
  531. isbformat = true;
  532. DirectChannels = false;
  533. break;
  534. case FmtBFormat3D:
  535. num_channels = 4;
  536. isbformat = true;
  537. DirectChannels = false;
  538. break;
  539. }
  540. ASSUME(num_channels > 0);
  541. std::for_each(voice->mChans.begin(), voice->mChans.begin()+num_channels,
  542. [NumSends](ALvoice::ChannelData &chandata) -> void
  543. {
  544. chandata.mDryParams.Hrtf.Target = HrtfFilter{};
  545. chandata.mDryParams.Gains.Target.fill(0.0f);
  546. std::for_each(chandata.mWetParams.begin(), chandata.mWetParams.begin()+NumSends,
  547. [](SendParams &params) -> void { params.Gains.Target.fill(0.0f); });
  548. });
  549. voice->mFlags &= ~(VOICE_HAS_HRTF | VOICE_HAS_NFC);
  550. if(isbformat)
  551. {
  552. /* Special handling for B-Format sources. */
  553. if(Distance > std::numeric_limits<float>::epsilon())
  554. {
  555. /* Panning a B-Format sound toward some direction is easy. Just pan
  556. * the first (W) channel as a normal mono sound and silence the
  557. * others.
  558. */
  559. if(Device->AvgSpeakerDist > 0.0f)
  560. {
  561. /* Clamp the distance for really close sources, to prevent
  562. * excessive bass.
  563. */
  564. const ALfloat mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)};
  565. const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (mdist * Frequency)};
  566. /* Only need to adjust the first channel of a B-Format source. */
  567. voice->mChans[0].mDryParams.NFCtrlFilter.adjust(w0);
  568. voice->mFlags |= VOICE_HAS_NFC;
  569. }
  570. ALfloat coeffs[MAX_AMBI_CHANNELS];
  571. if(Device->mRenderMode != StereoPair)
  572. CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
  573. else
  574. {
  575. /* Clamp Y, in case rounding errors caused it to end up outside
  576. * of -1...+1.
  577. */
  578. const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
  579. /* Negate Z for right-handed coords with -Z in front. */
  580. const ALfloat az{std::atan2(xpos, -zpos)};
  581. /* A scalar of 1.5 for plain stereo results in +/-60 degrees
  582. * being moved to +/-90 degrees for direct right and left
  583. * speaker responses.
  584. */
  585. CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, Spread, coeffs);
  586. }
  587. /* NOTE: W needs to be scaled due to FuMa normalization. */
  588. const ALfloat &scale0 = AmbiScale::FromFuMa[0];
  589. ComputePanGains(&Device->Dry, coeffs, DryGain*scale0,
  590. voice->mChans[0].mDryParams.Gains.Target);
  591. for(ALuint i{0};i < NumSends;i++)
  592. {
  593. if(const ALeffectslot *Slot{SendSlots[i]})
  594. ComputePanGains(&Slot->Wet, coeffs, WetGain[i]*scale0,
  595. voice->mChans[0].mWetParams[i].Gains.Target);
  596. }
  597. }
  598. else
  599. {
  600. if(Device->AvgSpeakerDist > 0.0f)
  601. {
  602. /* NOTE: The NFCtrlFilters were created with a w0 of 0, which
  603. * is what we want for FOA input. The first channel may have
  604. * been previously re-adjusted if panned, so reset it.
  605. */
  606. voice->mChans[0].mDryParams.NFCtrlFilter.adjust(0.0f);
  607. voice->mFlags |= VOICE_HAS_NFC;
  608. }
  609. /* Local B-Format sources have their XYZ channels rotated according
  610. * to the orientation.
  611. */
  612. /* AT then UP */
  613. alu::Vector N{props->OrientAt[0], props->OrientAt[1], props->OrientAt[2], 0.0f};
  614. N.normalize();
  615. alu::Vector V{props->OrientUp[0], props->OrientUp[1], props->OrientUp[2], 0.0f};
  616. V.normalize();
  617. if(!props->HeadRelative)
  618. {
  619. N = Listener.Params.Matrix * N;
  620. V = Listener.Params.Matrix * V;
  621. }
  622. /* Build and normalize right-vector */
  623. alu::Vector U{aluCrossproduct(N, V)};
  624. U.normalize();
  625. /* Build a rotate + conversion matrix (FuMa -> ACN+N3D). NOTE: This
  626. * matrix is transposed, for the inputs to align on the rows and
  627. * outputs on the columns.
  628. */
  629. const ALfloat &wscale = AmbiScale::FromFuMa[0];
  630. const ALfloat &yscale = AmbiScale::FromFuMa[1];
  631. const ALfloat &zscale = AmbiScale::FromFuMa[2];
  632. const ALfloat &xscale = AmbiScale::FromFuMa[3];
  633. const ALfloat matrix[4][MAX_AMBI_CHANNELS]{
  634. // ACN0 ACN1 ACN2 ACN3
  635. { wscale, 0.0f, 0.0f, 0.0f }, // FuMa W
  636. { 0.0f, -N[0]*xscale, N[1]*xscale, -N[2]*xscale }, // FuMa X
  637. { 0.0f, U[0]*yscale, -U[1]*yscale, U[2]*yscale }, // FuMa Y
  638. { 0.0f, -V[0]*zscale, V[1]*zscale, -V[2]*zscale } // FuMa Z
  639. };
  640. for(ALuint c{0};c < num_channels;c++)
  641. {
  642. ComputePanGains(&Device->Dry, matrix[c], DryGain,
  643. voice->mChans[c].mDryParams.Gains.Target);
  644. for(ALuint i{0};i < NumSends;i++)
  645. {
  646. if(const ALeffectslot *Slot{SendSlots[i]})
  647. ComputePanGains(&Slot->Wet, matrix[c], WetGain[i],
  648. voice->mChans[c].mWetParams[i].Gains.Target);
  649. }
  650. }
  651. }
  652. }
  653. else if(DirectChannels)
  654. {
  655. /* Direct source channels always play local. Skip the virtual channels
  656. * and write inputs to the matching real outputs.
  657. */
  658. voice->mDirect.Buffer = Device->RealOut.Buffer;
  659. for(ALuint c{0};c < num_channels;c++)
  660. {
  661. const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
  662. if(idx != INVALID_CHANNEL_INDEX)
  663. voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
  664. }
  665. /* Auxiliary sends still use normal channel panning since they mix to
  666. * B-Format, which can't channel-match.
  667. */
  668. for(ALuint c{0};c < num_channels;c++)
  669. {
  670. ALfloat coeffs[MAX_AMBI_CHANNELS];
  671. CalcAngleCoeffs(chans[c].angle, chans[c].elevation, 0.0f, coeffs);
  672. for(ALuint i{0};i < NumSends;i++)
  673. {
  674. if(const ALeffectslot *Slot{SendSlots[i]})
  675. ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
  676. voice->mChans[c].mWetParams[i].Gains.Target);
  677. }
  678. }
  679. }
  680. else if(Device->mRenderMode == HrtfRender)
  681. {
  682. /* Full HRTF rendering. Skip the virtual channels and render to the
  683. * real outputs.
  684. */
  685. voice->mDirect.Buffer = Device->RealOut.Buffer;
  686. if(Distance > std::numeric_limits<float>::epsilon())
  687. {
  688. const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
  689. const ALfloat az{std::atan2(xpos, -zpos)};
  690. /* Get the HRIR coefficients and delays just once, for the given
  691. * source direction.
  692. */
  693. GetHrtfCoeffs(Device->mHrtf, ev, az, Distance, Spread,
  694. voice->mChans[0].mDryParams.Hrtf.Target.Coeffs,
  695. voice->mChans[0].mDryParams.Hrtf.Target.Delay);
  696. voice->mChans[0].mDryParams.Hrtf.Target.Gain = DryGain * downmix_gain;
  697. /* Remaining channels use the same results as the first. */
  698. for(ALuint c{1};c < num_channels;c++)
  699. {
  700. /* Skip LFE */
  701. if(chans[c].channel == LFE) continue;
  702. voice->mChans[c].mDryParams.Hrtf.Target = voice->mChans[0].mDryParams.Hrtf.Target;
  703. }
  704. /* Calculate the directional coefficients once, which apply to all
  705. * input channels of the source sends.
  706. */
  707. ALfloat coeffs[MAX_AMBI_CHANNELS];
  708. CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
  709. for(ALuint c{0};c < num_channels;c++)
  710. {
  711. /* Skip LFE */
  712. if(chans[c].channel == LFE)
  713. continue;
  714. for(ALuint i{0};i < NumSends;i++)
  715. {
  716. if(const ALeffectslot *Slot{SendSlots[i]})
  717. ComputePanGains(&Slot->Wet, coeffs, WetGain[i] * downmix_gain,
  718. voice->mChans[c].mWetParams[i].Gains.Target);
  719. }
  720. }
  721. }
  722. else
  723. {
  724. /* Local sources on HRTF play with each channel panned to its
  725. * relative location around the listener, providing "virtual
  726. * speaker" responses.
  727. */
  728. for(ALuint c{0};c < num_channels;c++)
  729. {
  730. /* Skip LFE */
  731. if(chans[c].channel == LFE)
  732. continue;
  733. /* Get the HRIR coefficients and delays for this channel
  734. * position.
  735. */
  736. GetHrtfCoeffs(Device->mHrtf, chans[c].elevation, chans[c].angle,
  737. std::numeric_limits<float>::infinity(), Spread,
  738. voice->mChans[c].mDryParams.Hrtf.Target.Coeffs,
  739. voice->mChans[c].mDryParams.Hrtf.Target.Delay);
  740. voice->mChans[c].mDryParams.Hrtf.Target.Gain = DryGain;
  741. /* Normal panning for auxiliary sends. */
  742. ALfloat coeffs[MAX_AMBI_CHANNELS];
  743. CalcAngleCoeffs(chans[c].angle, chans[c].elevation, Spread, coeffs);
  744. for(ALuint i{0};i < NumSends;i++)
  745. {
  746. if(const ALeffectslot *Slot{SendSlots[i]})
  747. ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
  748. voice->mChans[c].mWetParams[i].Gains.Target);
  749. }
  750. }
  751. }
  752. voice->mFlags |= VOICE_HAS_HRTF;
  753. }
  754. else
  755. {
  756. /* Non-HRTF rendering. Use normal panning to the output. */
  757. if(Distance > std::numeric_limits<float>::epsilon())
  758. {
  759. /* Calculate NFC filter coefficient if needed. */
  760. if(Device->AvgSpeakerDist > 0.0f)
  761. {
  762. /* Clamp the distance for really close sources, to prevent
  763. * excessive bass.
  764. */
  765. const ALfloat mdist{maxf(Distance, Device->AvgSpeakerDist/4.0f)};
  766. const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (mdist * Frequency)};
  767. /* Adjust NFC filters. */
  768. for(ALuint c{0};c < num_channels;c++)
  769. voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0);
  770. voice->mFlags |= VOICE_HAS_NFC;
  771. }
  772. /* Calculate the directional coefficients once, which apply to all
  773. * input channels.
  774. */
  775. ALfloat coeffs[MAX_AMBI_CHANNELS];
  776. if(Device->mRenderMode != StereoPair)
  777. CalcDirectionCoeffs({xpos, ypos, zpos}, Spread, coeffs);
  778. else
  779. {
  780. const ALfloat ev{std::asin(clampf(ypos, -1.0f, 1.0f))};
  781. const ALfloat az{std::atan2(xpos, -zpos)};
  782. CalcAngleCoeffs(ScaleAzimuthFront(az, 1.5f), ev, Spread, coeffs);
  783. }
  784. for(ALuint c{0};c < num_channels;c++)
  785. {
  786. /* Special-case LFE */
  787. if(chans[c].channel == LFE)
  788. {
  789. if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data())
  790. {
  791. const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
  792. if(idx != INVALID_CHANNEL_INDEX)
  793. voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
  794. }
  795. continue;
  796. }
  797. ComputePanGains(&Device->Dry, coeffs, DryGain * downmix_gain,
  798. voice->mChans[c].mDryParams.Gains.Target);
  799. for(ALuint i{0};i < NumSends;i++)
  800. {
  801. if(const ALeffectslot *Slot{SendSlots[i]})
  802. ComputePanGains(&Slot->Wet, coeffs, WetGain[i] * downmix_gain,
  803. voice->mChans[c].mWetParams[i].Gains.Target);
  804. }
  805. }
  806. }
  807. else
  808. {
  809. if(Device->AvgSpeakerDist > 0.0f)
  810. {
  811. /* If the source distance is 0, set w0 to w1 to act as a pass-
  812. * through. We still want to pass the signal through the
  813. * filters so they keep an appropriate history, in case the
  814. * source moves away from the listener.
  815. */
  816. const ALfloat w0{SPEEDOFSOUNDMETRESPERSEC / (Device->AvgSpeakerDist * Frequency)};
  817. for(ALuint c{0};c < num_channels;c++)
  818. voice->mChans[c].mDryParams.NFCtrlFilter.adjust(w0);
  819. voice->mFlags |= VOICE_HAS_NFC;
  820. }
  821. for(ALuint c{0};c < num_channels;c++)
  822. {
  823. /* Special-case LFE */
  824. if(chans[c].channel == LFE)
  825. {
  826. if(Device->Dry.Buffer.data() == Device->RealOut.Buffer.data())
  827. {
  828. const ALuint idx{GetChannelIdxByName(Device->RealOut, chans[c].channel)};
  829. if(idx != INVALID_CHANNEL_INDEX)
  830. voice->mChans[c].mDryParams.Gains.Target[idx] = DryGain;
  831. }
  832. continue;
  833. }
  834. ALfloat coeffs[MAX_AMBI_CHANNELS];
  835. CalcAngleCoeffs(
  836. (Device->mRenderMode==StereoPair) ? ScaleAzimuthFront(chans[c].angle, 3.0f)
  837. : chans[c].angle,
  838. chans[c].elevation, Spread, coeffs
  839. );
  840. ComputePanGains(&Device->Dry, coeffs, DryGain,
  841. voice->mChans[c].mDryParams.Gains.Target);
  842. for(ALuint i{0};i < NumSends;i++)
  843. {
  844. if(const ALeffectslot *Slot{SendSlots[i]})
  845. ComputePanGains(&Slot->Wet, coeffs, WetGain[i],
  846. voice->mChans[c].mWetParams[i].Gains.Target);
  847. }
  848. }
  849. }
  850. }
  851. {
  852. const ALfloat hfScale{props->Direct.HFReference / Frequency};
  853. const ALfloat lfScale{props->Direct.LFReference / Frequency};
  854. const ALfloat gainHF{maxf(DryGainHF, 0.001f)}; /* Limit -60dB */
  855. const ALfloat gainLF{maxf(DryGainLF, 0.001f)};
  856. voice->mDirect.FilterType = AF_None;
  857. if(gainHF != 1.0f) voice->mDirect.FilterType |= AF_LowPass;
  858. if(gainLF != 1.0f) voice->mDirect.FilterType |= AF_HighPass;
  859. auto &lowpass = voice->mChans[0].mDryParams.LowPass;
  860. auto &highpass = voice->mChans[0].mDryParams.HighPass;
  861. lowpass.setParams(BiquadType::HighShelf, gainHF, hfScale,
  862. lowpass.rcpQFromSlope(gainHF, 1.0f));
  863. highpass.setParams(BiquadType::LowShelf, gainLF, lfScale,
  864. highpass.rcpQFromSlope(gainLF, 1.0f));
  865. for(ALuint c{1};c < num_channels;c++)
  866. {
  867. voice->mChans[c].mDryParams.LowPass.copyParamsFrom(lowpass);
  868. voice->mChans[c].mDryParams.HighPass.copyParamsFrom(highpass);
  869. }
  870. }
  871. for(ALuint i{0};i < NumSends;i++)
  872. {
  873. const ALfloat hfScale{props->Send[i].HFReference / Frequency};
  874. const ALfloat lfScale{props->Send[i].LFReference / Frequency};
  875. const ALfloat gainHF{maxf(WetGainHF[i], 0.001f)};
  876. const ALfloat gainLF{maxf(WetGainLF[i], 0.001f)};
  877. voice->mSend[i].FilterType = AF_None;
  878. if(gainHF != 1.0f) voice->mSend[i].FilterType |= AF_LowPass;
  879. if(gainLF != 1.0f) voice->mSend[i].FilterType |= AF_HighPass;
  880. auto &lowpass = voice->mChans[0].mWetParams[i].LowPass;
  881. auto &highpass = voice->mChans[0].mWetParams[i].HighPass;
  882. lowpass.setParams(BiquadType::HighShelf, gainHF, hfScale,
  883. lowpass.rcpQFromSlope(gainHF, 1.0f));
  884. highpass.setParams(BiquadType::LowShelf, gainLF, lfScale,
  885. highpass.rcpQFromSlope(gainLF, 1.0f));
  886. for(ALuint c{1};c < num_channels;c++)
  887. {
  888. voice->mChans[c].mWetParams[i].LowPass.copyParamsFrom(lowpass);
  889. voice->mChans[c].mWetParams[i].HighPass.copyParamsFrom(highpass);
  890. }
  891. }
  892. }
  893. void CalcNonAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALCcontext *ALContext)
  894. {
  895. const ALCdevice *Device{ALContext->mDevice.get()};
  896. ALeffectslot *SendSlots[MAX_SENDS];
  897. voice->mDirect.Buffer = Device->Dry.Buffer;
  898. for(ALuint i{0};i < Device->NumAuxSends;i++)
  899. {
  900. SendSlots[i] = props->Send[i].Slot;
  901. if(!SendSlots[i] && i == 0)
  902. SendSlots[i] = ALContext->mDefaultSlot.get();
  903. if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
  904. {
  905. SendSlots[i] = nullptr;
  906. voice->mSend[i].Buffer = {};
  907. }
  908. else
  909. voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer;
  910. }
  911. /* Calculate the stepping value */
  912. const auto Pitch = static_cast<ALfloat>(voice->mFrequency) /
  913. static_cast<ALfloat>(Device->Frequency) * props->Pitch;
  914. if(Pitch > float{MAX_PITCH})
  915. voice->mStep = MAX_PITCH<<FRACTIONBITS;
  916. else
  917. voice->mStep = maxu(fastf2u(Pitch * FRACTIONONE), 1);
  918. voice->mResampler = PrepareResampler(props->mResampler, voice->mStep, &voice->mResampleState);
  919. /* Calculate gains */
  920. const ALlistener &Listener = ALContext->mListener;
  921. ALfloat DryGain{clampf(props->Gain, props->MinGain, props->MaxGain)};
  922. DryGain *= props->Direct.Gain * Listener.Params.Gain;
  923. DryGain = minf(DryGain, GAIN_MIX_MAX);
  924. ALfloat DryGainHF{props->Direct.GainHF};
  925. ALfloat DryGainLF{props->Direct.GainLF};
  926. ALfloat WetGain[MAX_SENDS], WetGainHF[MAX_SENDS], WetGainLF[MAX_SENDS];
  927. for(ALuint i{0};i < Device->NumAuxSends;i++)
  928. {
  929. WetGain[i] = clampf(props->Gain, props->MinGain, props->MaxGain);
  930. WetGain[i] *= props->Send[i].Gain * Listener.Params.Gain;
  931. WetGain[i] = minf(WetGain[i], GAIN_MIX_MAX);
  932. WetGainHF[i] = props->Send[i].GainHF;
  933. WetGainLF[i] = props->Send[i].GainLF;
  934. }
  935. CalcPanningAndFilters(voice, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, DryGain, DryGainHF, DryGainLF,
  936. WetGain, WetGainLF, WetGainHF, SendSlots, props, Listener, Device);
  937. }
  938. void CalcAttnSourceParams(ALvoice *voice, const ALvoicePropsBase *props, const ALCcontext *ALContext)
  939. {
  940. const ALCdevice *Device{ALContext->mDevice.get()};
  941. const ALuint NumSends{Device->NumAuxSends};
  942. const ALlistener &Listener = ALContext->mListener;
  943. /* Set mixing buffers and get send parameters. */
  944. voice->mDirect.Buffer = Device->Dry.Buffer;
  945. ALeffectslot *SendSlots[MAX_SENDS];
  946. ALfloat RoomRolloff[MAX_SENDS];
  947. ALfloat DecayDistance[MAX_SENDS];
  948. ALfloat DecayLFDistance[MAX_SENDS];
  949. ALfloat DecayHFDistance[MAX_SENDS];
  950. for(ALuint i{0};i < NumSends;i++)
  951. {
  952. SendSlots[i] = props->Send[i].Slot;
  953. if(!SendSlots[i] && i == 0)
  954. SendSlots[i] = ALContext->mDefaultSlot.get();
  955. if(!SendSlots[i] || SendSlots[i]->Params.EffectType == AL_EFFECT_NULL)
  956. {
  957. SendSlots[i] = nullptr;
  958. RoomRolloff[i] = 0.0f;
  959. DecayDistance[i] = 0.0f;
  960. DecayLFDistance[i] = 0.0f;
  961. DecayHFDistance[i] = 0.0f;
  962. }
  963. else if(SendSlots[i]->Params.AuxSendAuto)
  964. {
  965. RoomRolloff[i] = SendSlots[i]->Params.RoomRolloff + props->RoomRolloffFactor;
  966. /* Calculate the distances to where this effect's decay reaches
  967. * -60dB.
  968. */
  969. DecayDistance[i] = SendSlots[i]->Params.DecayTime * SPEEDOFSOUNDMETRESPERSEC;
  970. DecayLFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayLFRatio;
  971. DecayHFDistance[i] = DecayDistance[i] * SendSlots[i]->Params.DecayHFRatio;
  972. if(SendSlots[i]->Params.DecayHFLimit)
  973. {
  974. ALfloat airAbsorption{SendSlots[i]->Params.AirAbsorptionGainHF};
  975. if(airAbsorption < 1.0f)
  976. {
  977. /* Calculate the distance to where this effect's air
  978. * absorption reaches -60dB, and limit the effect's HF
  979. * decay distance (so it doesn't take any longer to decay
  980. * than the air would allow).
  981. */
  982. ALfloat absorb_dist{std::log10(REVERB_DECAY_GAIN) / std::log10(airAbsorption)};
  983. DecayHFDistance[i] = minf(absorb_dist, DecayHFDistance[i]);
  984. }
  985. }
  986. }
  987. else
  988. {
  989. /* If the slot's auxiliary send auto is off, the data sent to the
  990. * effect slot is the same as the dry path, sans filter effects */
  991. RoomRolloff[i] = props->RolloffFactor;
  992. DecayDistance[i] = 0.0f;
  993. DecayLFDistance[i] = 0.0f;
  994. DecayHFDistance[i] = 0.0f;
  995. }
  996. if(!SendSlots[i])
  997. voice->mSend[i].Buffer = {};
  998. else
  999. voice->mSend[i].Buffer = SendSlots[i]->Wet.Buffer;
  1000. }
  1001. /* Transform source to listener space (convert to head relative) */
  1002. alu::Vector Position{props->Position[0], props->Position[1], props->Position[2], 1.0f};
  1003. alu::Vector Velocity{props->Velocity[0], props->Velocity[1], props->Velocity[2], 0.0f};
  1004. alu::Vector Direction{props->Direction[0], props->Direction[1], props->Direction[2], 0.0f};
  1005. if(props->HeadRelative == AL_FALSE)
  1006. {
  1007. /* Transform source vectors */
  1008. Position = Listener.Params.Matrix * Position;
  1009. Velocity = Listener.Params.Matrix * Velocity;
  1010. Direction = Listener.Params.Matrix * Direction;
  1011. }
  1012. else
  1013. {
  1014. /* Offset the source velocity to be relative of the listener velocity */
  1015. Velocity += Listener.Params.Velocity;
  1016. }
  1017. const bool directional{Direction.normalize() > 0.0f};
  1018. alu::Vector ToSource{Position[0], Position[1], Position[2], 0.0f};
  1019. const ALfloat Distance{ToSource.normalize()};
  1020. /* Initial source gain */
  1021. ALfloat DryGain{props->Gain};
  1022. ALfloat DryGainHF{1.0f};
  1023. ALfloat DryGainLF{1.0f};
  1024. ALfloat WetGain[MAX_SENDS], WetGainHF[MAX_SENDS], WetGainLF[MAX_SENDS];
  1025. for(ALuint i{0};i < NumSends;i++)
  1026. {
  1027. WetGain[i] = props->Gain;
  1028. WetGainHF[i] = 1.0f;
  1029. WetGainLF[i] = 1.0f;
  1030. }
  1031. /* Calculate distance attenuation */
  1032. ALfloat ClampedDist{Distance};
  1033. switch(Listener.Params.SourceDistanceModel ?
  1034. props->mDistanceModel : Listener.Params.mDistanceModel)
  1035. {
  1036. case DistanceModel::InverseClamped:
  1037. ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
  1038. if(props->MaxDistance < props->RefDistance) break;
  1039. /*fall-through*/
  1040. case DistanceModel::Inverse:
  1041. if(!(props->RefDistance > 0.0f))
  1042. ClampedDist = props->RefDistance;
  1043. else
  1044. {
  1045. ALfloat dist = lerp(props->RefDistance, ClampedDist, props->RolloffFactor);
  1046. if(dist > 0.0f) DryGain *= props->RefDistance / dist;
  1047. for(ALuint i{0};i < NumSends;i++)
  1048. {
  1049. dist = lerp(props->RefDistance, ClampedDist, RoomRolloff[i]);
  1050. if(dist > 0.0f) WetGain[i] *= props->RefDistance / dist;
  1051. }
  1052. }
  1053. break;
  1054. case DistanceModel::LinearClamped:
  1055. ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
  1056. if(props->MaxDistance < props->RefDistance) break;
  1057. /*fall-through*/
  1058. case DistanceModel::Linear:
  1059. if(!(props->MaxDistance != props->RefDistance))
  1060. ClampedDist = props->RefDistance;
  1061. else
  1062. {
  1063. ALfloat attn = props->RolloffFactor * (ClampedDist-props->RefDistance) /
  1064. (props->MaxDistance-props->RefDistance);
  1065. DryGain *= maxf(1.0f - attn, 0.0f);
  1066. for(ALuint i{0};i < NumSends;i++)
  1067. {
  1068. attn = RoomRolloff[i] * (ClampedDist-props->RefDistance) /
  1069. (props->MaxDistance-props->RefDistance);
  1070. WetGain[i] *= maxf(1.0f - attn, 0.0f);
  1071. }
  1072. }
  1073. break;
  1074. case DistanceModel::ExponentClamped:
  1075. ClampedDist = clampf(ClampedDist, props->RefDistance, props->MaxDistance);
  1076. if(props->MaxDistance < props->RefDistance) break;
  1077. /*fall-through*/
  1078. case DistanceModel::Exponent:
  1079. if(!(ClampedDist > 0.0f && props->RefDistance > 0.0f))
  1080. ClampedDist = props->RefDistance;
  1081. else
  1082. {
  1083. DryGain *= std::pow(ClampedDist/props->RefDistance, -props->RolloffFactor);
  1084. for(ALuint i{0};i < NumSends;i++)
  1085. WetGain[i] *= std::pow(ClampedDist/props->RefDistance, -RoomRolloff[i]);
  1086. }
  1087. break;
  1088. case DistanceModel::Disable:
  1089. ClampedDist = props->RefDistance;
  1090. break;
  1091. }
  1092. /* Calculate directional soundcones */
  1093. if(directional && props->InnerAngle < 360.0f)
  1094. {
  1095. const ALfloat Angle{Rad2Deg(std::acos(-aluDotproduct(Direction, ToSource)) *
  1096. ConeScale * 2.0f)};
  1097. ALfloat ConeVolume, ConeHF;
  1098. if(!(Angle > props->InnerAngle))
  1099. {
  1100. ConeVolume = 1.0f;
  1101. ConeHF = 1.0f;
  1102. }
  1103. else if(Angle < props->OuterAngle)
  1104. {
  1105. ALfloat scale = ( Angle-props->InnerAngle) /
  1106. (props->OuterAngle-props->InnerAngle);
  1107. ConeVolume = lerp(1.0f, props->OuterGain, scale);
  1108. ConeHF = lerp(1.0f, props->OuterGainHF, scale);
  1109. }
  1110. else
  1111. {
  1112. ConeVolume = props->OuterGain;
  1113. ConeHF = props->OuterGainHF;
  1114. }
  1115. DryGain *= ConeVolume;
  1116. if(props->DryGainHFAuto)
  1117. DryGainHF *= ConeHF;
  1118. if(props->WetGainAuto)
  1119. std::transform(std::begin(WetGain), std::begin(WetGain)+NumSends, std::begin(WetGain),
  1120. [ConeVolume](ALfloat gain) noexcept -> ALfloat { return gain * ConeVolume; }
  1121. );
  1122. if(props->WetGainHFAuto)
  1123. std::transform(std::begin(WetGainHF), std::begin(WetGainHF)+NumSends,
  1124. std::begin(WetGainHF),
  1125. [ConeHF](ALfloat gain) noexcept -> ALfloat { return gain * ConeHF; }
  1126. );
  1127. }
  1128. /* Apply gain and frequency filters */
  1129. DryGain = clampf(DryGain, props->MinGain, props->MaxGain);
  1130. DryGain = minf(DryGain*props->Direct.Gain*Listener.Params.Gain, GAIN_MIX_MAX);
  1131. DryGainHF *= props->Direct.GainHF;
  1132. DryGainLF *= props->Direct.GainLF;
  1133. for(ALuint i{0};i < NumSends;i++)
  1134. {
  1135. WetGain[i] = clampf(WetGain[i], props->MinGain, props->MaxGain);
  1136. WetGain[i] = minf(WetGain[i]*props->Send[i].Gain*Listener.Params.Gain, GAIN_MIX_MAX);
  1137. WetGainHF[i] *= props->Send[i].GainHF;
  1138. WetGainLF[i] *= props->Send[i].GainLF;
  1139. }
  1140. /* Distance-based air absorption and initial send decay. */
  1141. if(ClampedDist > props->RefDistance && props->RolloffFactor > 0.0f)
  1142. {
  1143. ALfloat meters_base{(ClampedDist-props->RefDistance) * props->RolloffFactor *
  1144. Listener.Params.MetersPerUnit};
  1145. if(props->AirAbsorptionFactor > 0.0f)
  1146. {
  1147. ALfloat hfattn{std::pow(AIRABSORBGAINHF, meters_base * props->AirAbsorptionFactor)};
  1148. DryGainHF *= hfattn;
  1149. std::transform(std::begin(WetGainHF), std::begin(WetGainHF)+NumSends,
  1150. std::begin(WetGainHF),
  1151. [hfattn](ALfloat gain) noexcept -> ALfloat { return gain * hfattn; }
  1152. );
  1153. }
  1154. if(props->WetGainAuto)
  1155. {
  1156. /* Apply a decay-time transformation to the wet path, based on the
  1157. * source distance in meters. The initial decay of the reverb
  1158. * effect is calculated and applied to the wet path.
  1159. */
  1160. for(ALuint i{0};i < NumSends;i++)
  1161. {
  1162. if(!(DecayDistance[i] > 0.0f))
  1163. continue;
  1164. const ALfloat gain{std::pow(REVERB_DECAY_GAIN, meters_base/DecayDistance[i])};
  1165. WetGain[i] *= gain;
  1166. /* Yes, the wet path's air absorption is applied with
  1167. * WetGainAuto on, rather than WetGainHFAuto.
  1168. */
  1169. if(gain > 0.0f)
  1170. {
  1171. ALfloat gainhf{std::pow(REVERB_DECAY_GAIN, meters_base/DecayHFDistance[i])};
  1172. WetGainHF[i] *= minf(gainhf / gain, 1.0f);
  1173. ALfloat gainlf{std::pow(REVERB_DECAY_GAIN, meters_base/DecayLFDistance[i])};
  1174. WetGainLF[i] *= minf(gainlf / gain, 1.0f);
  1175. }
  1176. }
  1177. }
  1178. }
  1179. /* Initial source pitch */
  1180. ALfloat Pitch{props->Pitch};
  1181. /* Calculate velocity-based doppler effect */
  1182. ALfloat DopplerFactor{props->DopplerFactor * Listener.Params.DopplerFactor};
  1183. if(DopplerFactor > 0.0f)
  1184. {
  1185. const alu::Vector &lvelocity = Listener.Params.Velocity;
  1186. ALfloat vss{aluDotproduct(Velocity, ToSource) * -DopplerFactor};
  1187. ALfloat vls{aluDotproduct(lvelocity, ToSource) * -DopplerFactor};
  1188. const ALfloat SpeedOfSound{Listener.Params.SpeedOfSound};
  1189. if(!(vls < SpeedOfSound))
  1190. {
  1191. /* Listener moving away from the source at the speed of sound.
  1192. * Sound waves can't catch it.
  1193. */
  1194. Pitch = 0.0f;
  1195. }
  1196. else if(!(vss < SpeedOfSound))
  1197. {
  1198. /* Source moving toward the listener at the speed of sound. Sound
  1199. * waves bunch up to extreme frequencies.
  1200. */
  1201. Pitch = std::numeric_limits<float>::infinity();
  1202. }
  1203. else
  1204. {
  1205. /* Source and listener movement is nominal. Calculate the proper
  1206. * doppler shift.
  1207. */
  1208. Pitch *= (SpeedOfSound-vls) / (SpeedOfSound-vss);
  1209. }
  1210. }
  1211. /* Adjust pitch based on the buffer and output frequencies, and calculate
  1212. * fixed-point stepping value.
  1213. */
  1214. Pitch *= static_cast<ALfloat>(voice->mFrequency)/static_cast<ALfloat>(Device->Frequency);
  1215. if(Pitch > float{MAX_PITCH})
  1216. voice->mStep = MAX_PITCH<<FRACTIONBITS;
  1217. else
  1218. voice->mStep = maxu(fastf2u(Pitch * FRACTIONONE), 1);
  1219. voice->mResampler = PrepareResampler(props->mResampler, voice->mStep, &voice->mResampleState);
  1220. ALfloat spread{0.0f};
  1221. if(props->Radius > Distance)
  1222. spread = al::MathDefs<float>::Tau() - Distance/props->Radius*al::MathDefs<float>::Pi();
  1223. else if(Distance > 0.0f)
  1224. spread = std::asin(props->Radius/Distance) * 2.0f;
  1225. CalcPanningAndFilters(voice, ToSource[0], ToSource[1], ToSource[2]*ZScale,
  1226. Distance*Listener.Params.MetersPerUnit, spread, DryGain, DryGainHF, DryGainLF, WetGain,
  1227. WetGainLF, WetGainHF, SendSlots, props, Listener, Device);
  1228. }
  1229. void CalcSourceParams(ALvoice *voice, ALCcontext *context, bool force)
  1230. {
  1231. ALvoiceProps *props{voice->mUpdate.exchange(nullptr, std::memory_order_acq_rel)};
  1232. if(!props && !force) return;
  1233. if(props)
  1234. {
  1235. voice->mProps = *props;
  1236. AtomicReplaceHead(context->mFreeVoiceProps, props);
  1237. }
  1238. if((voice->mProps.mSpatializeMode == SpatializeAuto && voice->mFmtChannels == FmtMono) ||
  1239. voice->mProps.mSpatializeMode == SpatializeOn)
  1240. CalcAttnSourceParams(voice, &voice->mProps, context);
  1241. else
  1242. CalcNonAttnSourceParams(voice, &voice->mProps, context);
  1243. }
  1244. void ProcessParamUpdates(ALCcontext *ctx, const ALeffectslotArray &slots,
  1245. const al::span<ALvoice> voices)
  1246. {
  1247. IncrementRef(ctx->mUpdateCount);
  1248. if LIKELY(!ctx->mHoldUpdates.load(std::memory_order_acquire))
  1249. {
  1250. bool force{CalcContextParams(ctx)};
  1251. force |= CalcListenerParams(ctx);
  1252. force = std::accumulate(slots.begin(), slots.end(), force,
  1253. [ctx](const bool f, ALeffectslot *slot) -> bool
  1254. { return CalcEffectSlotParams(slot, ctx) | f; }
  1255. );
  1256. auto calc_params = [ctx,force](ALvoice &voice) -> void
  1257. {
  1258. if(voice.mSourceID.load(std::memory_order_acquire) != 0)
  1259. CalcSourceParams(&voice, ctx, force);
  1260. };
  1261. std::for_each(voices.begin(), voices.end(), calc_params);
  1262. }
  1263. IncrementRef(ctx->mUpdateCount);
  1264. }
  1265. void ProcessContext(ALCcontext *ctx, const ALuint SamplesToDo)
  1266. {
  1267. ASSUME(SamplesToDo > 0);
  1268. const ALeffectslotArray &auxslots = *ctx->mActiveAuxSlots.load(std::memory_order_acquire);
  1269. const al::span<ALvoice> voices{ctx->mVoices.data(), ctx->mVoices.size()};
  1270. /* Process pending propery updates for objects on the context. */
  1271. ProcessParamUpdates(ctx, auxslots, voices);
  1272. /* Clear auxiliary effect slot mixing buffers. */
  1273. std::for_each(auxslots.begin(), auxslots.end(),
  1274. [SamplesToDo](ALeffectslot *slot) -> void
  1275. {
  1276. for(auto &buffer : slot->MixBuffer)
  1277. std::fill_n(buffer.begin(), SamplesToDo, 0.0f);
  1278. }
  1279. );
  1280. /* Process voices that have a playing source. */
  1281. std::for_each(voices.begin(), voices.end(),
  1282. [SamplesToDo,ctx](ALvoice &voice) -> void
  1283. {
  1284. const ALvoice::State vstate{voice.mPlayState.load(std::memory_order_acquire)};
  1285. if(vstate != ALvoice::Stopped) voice.mix(vstate, ctx, SamplesToDo);
  1286. }
  1287. );
  1288. /* Process effects. */
  1289. if(auxslots.empty()) return;
  1290. auto slots = auxslots.data();
  1291. auto slots_end = slots + auxslots.size();
  1292. /* First sort the slots into scratch storage, so that effects come before
  1293. * their effect target (or their targets' target).
  1294. */
  1295. auto sorted_slots = const_cast<ALeffectslot**>(slots_end);
  1296. auto sorted_slots_end = sorted_slots;
  1297. auto in_chain = [](const ALeffectslot *slot1, const ALeffectslot *slot2) noexcept -> bool
  1298. {
  1299. while((slot1=slot1->Params.Target) != nullptr) {
  1300. if(slot1 == slot2) return true;
  1301. }
  1302. return false;
  1303. };
  1304. *sorted_slots_end = *slots;
  1305. ++sorted_slots_end;
  1306. while(++slots != slots_end)
  1307. {
  1308. /* If this effect slot targets an effect slot already in the list (i.e.
  1309. * slots outputs to something in sorted_slots), directly or indirectly,
  1310. * insert it prior to that element.
  1311. */
  1312. auto checker = sorted_slots;
  1313. do {
  1314. if(in_chain(*slots, *checker)) break;
  1315. } while(++checker != sorted_slots_end);
  1316. checker = std::move_backward(checker, sorted_slots_end, sorted_slots_end+1);
  1317. *--checker = *slots;
  1318. ++sorted_slots_end;
  1319. }
  1320. std::for_each(sorted_slots, sorted_slots_end,
  1321. [SamplesToDo](const ALeffectslot *slot) -> void
  1322. {
  1323. EffectState *state{slot->Params.mEffectState};
  1324. state->process(SamplesToDo, slot->Wet.Buffer, state->mOutTarget);
  1325. }
  1326. );
  1327. }
  1328. void ApplyStablizer(FrontStablizer *Stablizer, const al::span<FloatBufferLine> Buffer,
  1329. const ALuint lidx, const ALuint ridx, const ALuint cidx, const ALuint SamplesToDo)
  1330. {
  1331. ASSUME(SamplesToDo > 0);
  1332. /* Apply a delay to all channels, except the front-left and front-right, so
  1333. * they maintain correct timing.
  1334. */
  1335. const size_t NumChannels{Buffer.size()};
  1336. for(size_t i{0u};i < NumChannels;i++)
  1337. {
  1338. if(i == lidx || i == ridx)
  1339. continue;
  1340. auto &DelayBuf = Stablizer->DelayBuf[i];
  1341. auto buffer_end = Buffer[i].begin() + SamplesToDo;
  1342. if LIKELY(SamplesToDo >= ALuint{FrontStablizer::DelayLength})
  1343. {
  1344. auto delay_end = std::rotate(Buffer[i].begin(),
  1345. buffer_end - FrontStablizer::DelayLength, buffer_end);
  1346. std::swap_ranges(Buffer[i].begin(), delay_end, std::begin(DelayBuf));
  1347. }
  1348. else
  1349. {
  1350. auto delay_start = std::swap_ranges(Buffer[i].begin(), buffer_end,
  1351. std::begin(DelayBuf));
  1352. std::rotate(std::begin(DelayBuf), delay_start, std::end(DelayBuf));
  1353. }
  1354. }
  1355. ALfloat (&lsplit)[2][BUFFERSIZE] = Stablizer->LSplit;
  1356. ALfloat (&rsplit)[2][BUFFERSIZE] = Stablizer->RSplit;
  1357. auto &tmpbuf = Stablizer->TempBuf;
  1358. /* This applies the band-splitter, preserving phase at the cost of some
  1359. * delay. The shorter the delay, the more error seeps into the result.
  1360. */
  1361. auto apply_splitter = [&tmpbuf,SamplesToDo](const FloatBufferLine &InBuf,
  1362. ALfloat (&DelayBuf)[FrontStablizer::DelayLength], BandSplitter &Filter,
  1363. ALfloat (&splitbuf)[2][BUFFERSIZE]) -> void
  1364. {
  1365. /* Combine the delayed samples and the input samples into the temp
  1366. * buffer, in reverse. Then copy the final samples back into the delay
  1367. * buffer for next time. Note that the delay buffer's samples are
  1368. * stored backwards here.
  1369. */
  1370. auto tmpbuf_end = std::begin(tmpbuf) + SamplesToDo;
  1371. std::copy_n(std::begin(DelayBuf), FrontStablizer::DelayLength, tmpbuf_end);
  1372. std::reverse_copy(InBuf.begin(), InBuf.begin()+SamplesToDo, std::begin(tmpbuf));
  1373. std::copy_n(std::begin(tmpbuf), FrontStablizer::DelayLength, std::begin(DelayBuf));
  1374. /* Apply an all-pass on the reversed signal, then reverse the samples
  1375. * to get the forward signal with a reversed phase shift.
  1376. */
  1377. Filter.applyAllpass(tmpbuf, SamplesToDo+FrontStablizer::DelayLength);
  1378. std::reverse(std::begin(tmpbuf), tmpbuf_end+FrontStablizer::DelayLength);
  1379. /* Now apply the band-splitter, combining its phase shift with the
  1380. * reversed phase shift, restoring the original phase on the split
  1381. * signal.
  1382. */
  1383. Filter.process(splitbuf[1], splitbuf[0], tmpbuf, SamplesToDo);
  1384. };
  1385. apply_splitter(Buffer[lidx], Stablizer->DelayBuf[lidx], Stablizer->LFilter, lsplit);
  1386. apply_splitter(Buffer[ridx], Stablizer->DelayBuf[ridx], Stablizer->RFilter, rsplit);
  1387. for(ALuint i{0};i < SamplesToDo;i++)
  1388. {
  1389. ALfloat lfsum{lsplit[0][i] + rsplit[0][i]};
  1390. ALfloat hfsum{lsplit[1][i] + rsplit[1][i]};
  1391. ALfloat s{lsplit[0][i] + lsplit[1][i] - rsplit[0][i] - rsplit[1][i]};
  1392. /* This pans the separate low- and high-frequency sums between being on
  1393. * the center channel and the left/right channels. The low-frequency
  1394. * sum is 1/3rd toward center (2/3rds on left/right) and the high-
  1395. * frequency sum is 1/4th toward center (3/4ths on left/right). These
  1396. * values can be tweaked.
  1397. */
  1398. ALfloat m{lfsum*std::cos(1.0f/3.0f * (al::MathDefs<float>::Pi()*0.5f)) +
  1399. hfsum*std::cos(1.0f/4.0f * (al::MathDefs<float>::Pi()*0.5f))};
  1400. ALfloat c{lfsum*std::sin(1.0f/3.0f * (al::MathDefs<float>::Pi()*0.5f)) +
  1401. hfsum*std::sin(1.0f/4.0f * (al::MathDefs<float>::Pi()*0.5f))};
  1402. /* The generated center channel signal adds to the existing signal,
  1403. * while the modified left and right channels replace.
  1404. */
  1405. Buffer[lidx][i] = (m + s) * 0.5f;
  1406. Buffer[ridx][i] = (m - s) * 0.5f;
  1407. Buffer[cidx][i] += c * 0.5f;
  1408. }
  1409. }
  1410. void ApplyDistanceComp(const al::span<FloatBufferLine> Samples, const ALuint SamplesToDo,
  1411. const DistanceComp::DistData *distcomp)
  1412. {
  1413. ASSUME(SamplesToDo > 0);
  1414. for(auto &chanbuffer : Samples)
  1415. {
  1416. const ALfloat gain{distcomp->Gain};
  1417. const ALuint base{distcomp->Length};
  1418. ALfloat *distbuf{al::assume_aligned<16>(distcomp->Buffer)};
  1419. ++distcomp;
  1420. if(base < 1)
  1421. continue;
  1422. ALfloat *inout{al::assume_aligned<16>(chanbuffer.data())};
  1423. auto inout_end = inout + SamplesToDo;
  1424. if LIKELY(SamplesToDo >= base)
  1425. {
  1426. auto delay_end = std::rotate(inout, inout_end - base, inout_end);
  1427. std::swap_ranges(inout, delay_end, distbuf);
  1428. }
  1429. else
  1430. {
  1431. auto delay_start = std::swap_ranges(inout, inout_end, distbuf);
  1432. std::rotate(distbuf, delay_start, distbuf + base);
  1433. }
  1434. std::transform(inout, inout_end, inout, std::bind(std::multiplies<float>{}, _1, gain));
  1435. }
  1436. }
  1437. void ApplyDither(const al::span<FloatBufferLine> Samples, ALuint *dither_seed,
  1438. const ALfloat quant_scale, const ALuint SamplesToDo)
  1439. {
  1440. /* Dithering. Generate whitenoise (uniform distribution of random values
  1441. * between -1 and +1) and add it to the sample values, after scaling up to
  1442. * the desired quantization depth amd before rounding.
  1443. */
  1444. const ALfloat invscale{1.0f / quant_scale};
  1445. ALuint seed{*dither_seed};
  1446. auto dither_channel = [&seed,invscale,quant_scale,SamplesToDo](FloatBufferLine &input) -> void
  1447. {
  1448. ASSUME(SamplesToDo > 0);
  1449. auto dither_sample = [&seed,invscale,quant_scale](const ALfloat sample) noexcept -> ALfloat
  1450. {
  1451. ALfloat val{sample * quant_scale};
  1452. ALuint rng0{dither_rng(&seed)};
  1453. ALuint rng1{dither_rng(&seed)};
  1454. val += static_cast<ALfloat>(rng0*(1.0/UINT_MAX) - rng1*(1.0/UINT_MAX));
  1455. return fast_roundf(val) * invscale;
  1456. };
  1457. std::transform(input.begin(), input.begin()+SamplesToDo, input.begin(), dither_sample);
  1458. };
  1459. std::for_each(Samples.begin(), Samples.end(), dither_channel);
  1460. *dither_seed = seed;
  1461. }
  1462. /* Base template left undefined. Should be marked =delete, but Clang 3.8.1
  1463. * chokes on that given the inline specializations.
  1464. */
  1465. template<typename T>
  1466. inline T SampleConv(float) noexcept;
  1467. template<> inline float SampleConv(float val) noexcept
  1468. { return val; }
  1469. template<> inline int32_t SampleConv(float val) noexcept
  1470. {
  1471. /* Floats have a 23-bit mantissa, plus an implied 1 bit and a sign bit.
  1472. * This means a normalized float has at most 25 bits of signed precision.
  1473. * When scaling and clamping for a signed 32-bit integer, these following
  1474. * values are the best a float can give.
  1475. */
  1476. return fastf2i(clampf(val*2147483648.0f, -2147483648.0f, 2147483520.0f));
  1477. }
  1478. template<> inline int16_t SampleConv(float val) noexcept
  1479. { return static_cast<int16_t>(fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f))); }
  1480. template<> inline int8_t SampleConv(float val) noexcept
  1481. { return static_cast<int8_t>(fastf2i(clampf(val*128.0f, -128.0f, 127.0f))); }
  1482. /* Define unsigned output variations. */
  1483. template<> inline uint32_t SampleConv(float val) noexcept
  1484. { return static_cast<uint32_t>(SampleConv<int32_t>(val)) + 2147483648u; }
  1485. template<> inline uint16_t SampleConv(float val) noexcept
  1486. { return static_cast<uint16_t>(SampleConv<int16_t>(val) + 32768); }
  1487. template<> inline uint8_t SampleConv(float val) noexcept
  1488. { return static_cast<uint8_t>(SampleConv<int8_t>(val) + 128); }
  1489. template<DevFmtType T>
  1490. void Write(const al::span<const FloatBufferLine> InBuffer, void *OutBuffer, const size_t Offset,
  1491. const ALuint SamplesToDo)
  1492. {
  1493. using SampleType = typename DevFmtTypeTraits<T>::Type;
  1494. const size_t numchans{InBuffer.size()};
  1495. ASSUME(numchans > 0);
  1496. SampleType *outbase = static_cast<SampleType*>(OutBuffer) + Offset*numchans;
  1497. auto conv_channel = [&outbase,SamplesToDo,numchans](const FloatBufferLine &inbuf) -> void
  1498. {
  1499. ASSUME(SamplesToDo > 0);
  1500. SampleType *out{outbase++};
  1501. auto conv_sample = [numchans,&out](const float s) noexcept -> void
  1502. {
  1503. *out = SampleConv<SampleType>(s);
  1504. out += numchans;
  1505. };
  1506. std::for_each(inbuf.begin(), inbuf.begin()+SamplesToDo, conv_sample);
  1507. };
  1508. std::for_each(InBuffer.cbegin(), InBuffer.cend(), conv_channel);
  1509. }
  1510. } // namespace
  1511. void aluMixData(ALCdevice *device, ALvoid *OutBuffer, const ALuint NumSamples)
  1512. {
  1513. FPUCtl mixer_mode{};
  1514. for(ALuint SamplesDone{0u};SamplesDone < NumSamples;)
  1515. {
  1516. const ALuint SamplesToDo{minu(NumSamples-SamplesDone, BUFFERSIZE)};
  1517. /* Clear main mixing buffers. */
  1518. std::for_each(device->MixBuffer.begin(), device->MixBuffer.end(),
  1519. [SamplesToDo](std::array<ALfloat,BUFFERSIZE> &buffer) -> void
  1520. { std::fill_n(buffer.begin(), SamplesToDo, 0.0f); }
  1521. );
  1522. /* Increment the mix count at the start (lsb should now be 1). */
  1523. IncrementRef(device->MixCount);
  1524. /* For each context on this device, process and mix its sources and
  1525. * effects.
  1526. */
  1527. for(ALCcontext *ctx : *device->mContexts.load(std::memory_order_acquire))
  1528. ProcessContext(ctx, SamplesToDo);
  1529. /* Increment the clock time. Every second's worth of samples is
  1530. * converted and added to clock base so that large sample counts don't
  1531. * overflow during conversion. This also guarantees a stable
  1532. * conversion.
  1533. */
  1534. device->SamplesDone += SamplesToDo;
  1535. device->ClockBase += std::chrono::seconds{device->SamplesDone / device->Frequency};
  1536. device->SamplesDone %= device->Frequency;
  1537. /* Increment the mix count at the end (lsb should now be 0). */
  1538. IncrementRef(device->MixCount);
  1539. /* Apply any needed post-process for finalizing the Dry mix to the
  1540. * RealOut (Ambisonic decode, UHJ encode, etc).
  1541. */
  1542. device->postProcess(SamplesToDo);
  1543. const al::span<FloatBufferLine> RealOut{device->RealOut.Buffer};
  1544. /* Apply front image stablization for surround sound, if applicable. */
  1545. if(device->Stablizer)
  1546. {
  1547. const ALuint lidx{GetChannelIdxByName(device->RealOut, FrontLeft)};
  1548. const ALuint ridx{GetChannelIdxByName(device->RealOut, FrontRight)};
  1549. const ALuint cidx{GetChannelIdxByName(device->RealOut, FrontCenter)};
  1550. ApplyStablizer(device->Stablizer.get(), RealOut, lidx, ridx, cidx, SamplesToDo);
  1551. }
  1552. /* Apply compression, limiting sample amplitude if needed or desired. */
  1553. if(Compressor *comp{device->Limiter.get()})
  1554. comp->process(SamplesToDo, RealOut.data());
  1555. /* Apply delays and attenuation for mismatched speaker distances. */
  1556. ApplyDistanceComp(RealOut, SamplesToDo, device->ChannelDelay.as_span().cbegin());
  1557. /* Apply dithering. The compressor should have left enough headroom for
  1558. * the dither noise to not saturate.
  1559. */
  1560. if(device->DitherDepth > 0.0f)
  1561. ApplyDither(RealOut, &device->DitherSeed, device->DitherDepth, SamplesToDo);
  1562. if LIKELY(OutBuffer)
  1563. {
  1564. /* Finally, interleave and convert samples, writing to the device's
  1565. * output buffer.
  1566. */
  1567. switch(device->FmtType)
  1568. {
  1569. #define HANDLE_WRITE(T) case T: \
  1570. Write<T>(RealOut, OutBuffer, SamplesDone, SamplesToDo); break;
  1571. HANDLE_WRITE(DevFmtByte)
  1572. HANDLE_WRITE(DevFmtUByte)
  1573. HANDLE_WRITE(DevFmtShort)
  1574. HANDLE_WRITE(DevFmtUShort)
  1575. HANDLE_WRITE(DevFmtInt)
  1576. HANDLE_WRITE(DevFmtUInt)
  1577. HANDLE_WRITE(DevFmtFloat)
  1578. #undef HANDLE_WRITE
  1579. }
  1580. }
  1581. SamplesDone += SamplesToDo;
  1582. }
  1583. }
  1584. void aluHandleDisconnect(ALCdevice *device, const char *msg, ...)
  1585. {
  1586. if(!device->Connected.exchange(false, std::memory_order_acq_rel))
  1587. return;
  1588. AsyncEvent evt{EventType_Disconnected};
  1589. evt.u.user.type = AL_EVENT_TYPE_DISCONNECTED_SOFT;
  1590. evt.u.user.id = 0;
  1591. evt.u.user.param = 0;
  1592. va_list args;
  1593. va_start(args, msg);
  1594. int msglen{vsnprintf(evt.u.user.msg, sizeof(evt.u.user.msg), msg, args)};
  1595. va_end(args);
  1596. if(msglen < 0 || static_cast<size_t>(msglen) >= sizeof(evt.u.user.msg))
  1597. evt.u.user.msg[sizeof(evt.u.user.msg)-1] = 0;
  1598. IncrementRef(device->MixCount);
  1599. for(ALCcontext *ctx : *device->mContexts.load())
  1600. {
  1601. const ALbitfieldSOFT enabledevt{ctx->mEnabledEvts.load(std::memory_order_acquire)};
  1602. if((enabledevt&EventType_Disconnected))
  1603. {
  1604. RingBuffer *ring{ctx->mAsyncEvents.get()};
  1605. auto evt_data = ring->getWriteVector().first;
  1606. if(evt_data.len > 0)
  1607. {
  1608. ::new (evt_data.buf) AsyncEvent{evt};
  1609. ring->writeAdvance(1);
  1610. ctx->mEventSem.post();
  1611. }
  1612. }
  1613. auto stop_voice = [](ALvoice &voice) -> void
  1614. {
  1615. voice.mCurrentBuffer.store(nullptr, std::memory_order_relaxed);
  1616. voice.mLoopBuffer.store(nullptr, std::memory_order_relaxed);
  1617. voice.mSourceID.store(0u, std::memory_order_relaxed);
  1618. voice.mPlayState.store(ALvoice::Stopped, std::memory_order_release);
  1619. };
  1620. std::for_each(ctx->mVoices.begin(), ctx->mVoices.end(), stop_voice);
  1621. }
  1622. IncrementRef(device->MixCount);
  1623. }