🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1838 lines
68 KiB

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