🛠️🐜 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.

1730 lines
64 KiB

  1. /**
  2. * Ambisonic reverb engine for the OpenAL cross platform audio library
  3. * Copyright (C) 2008-2017 by Chris Robinson and Christopher Fitzgerald.
  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 <algorithm>
  22. #include <array>
  23. #include <cstdio>
  24. #include <functional>
  25. #include <iterator>
  26. #include <numeric>
  27. #include <stdint.h>
  28. #include "alc/effects/base.h"
  29. #include "almalloc.h"
  30. #include "alnumbers.h"
  31. #include "alnumeric.h"
  32. #include "alspan.h"
  33. #include "core/ambidefs.h"
  34. #include "core/bufferline.h"
  35. #include "core/context.h"
  36. #include "core/devformat.h"
  37. #include "core/device.h"
  38. #include "core/effectslot.h"
  39. #include "core/filters/biquad.h"
  40. #include "core/filters/splitter.h"
  41. #include "core/mixer.h"
  42. #include "core/mixer/defs.h"
  43. #include "intrusive_ptr.h"
  44. #include "opthelpers.h"
  45. #include "vecmat.h"
  46. #include "vector.h"
  47. /* This is a user config option for modifying the overall output of the reverb
  48. * effect.
  49. */
  50. float ReverbBoost = 1.0f;
  51. namespace {
  52. using uint = unsigned int;
  53. constexpr float MaxModulationTime{4.0f};
  54. constexpr float DefaultModulationTime{0.25f};
  55. #define MOD_FRACBITS 24
  56. #define MOD_FRACONE (1<<MOD_FRACBITS)
  57. #define MOD_FRACMASK (MOD_FRACONE-1)
  58. using namespace std::placeholders;
  59. /* Max samples per process iteration. Used to limit the size needed for
  60. * temporary buffers. Must be a multiple of 4 for SIMD alignment.
  61. */
  62. constexpr size_t MAX_UPDATE_SAMPLES{256};
  63. /* The number of spatialized lines or channels to process. Four channels allows
  64. * for a 3D A-Format response. NOTE: This can't be changed without taking care
  65. * of the conversion matrices, and a few places where the length arrays are
  66. * assumed to have 4 elements.
  67. */
  68. constexpr size_t NUM_LINES{4u};
  69. /* This coefficient is used to define the maximum frequency range controlled by
  70. * the modulation depth. The current value of 0.05 will allow it to swing from
  71. * 0.95x to 1.05x. This value must be below 1. At 1 it will cause the sampler
  72. * to stall on the downswing, and above 1 it will cause it to sample backwards.
  73. * The value 0.05 seems be nearest to Creative hardware behavior.
  74. */
  75. constexpr float MODULATION_DEPTH_COEFF{0.05f};
  76. /* The B-Format to A-Format conversion matrix. The arrangement of rows is
  77. * deliberately chosen to align the resulting lines to their spatial opposites
  78. * (0:above front left <-> 3:above back right, 1:below front right <-> 2:below
  79. * back left). It's not quite opposite, since the A-Format results in a
  80. * tetrahedron, but it's close enough. Should the model be extended to 8-lines
  81. * in the future, true opposites can be used.
  82. */
  83. alignas(16) constexpr float B2A[NUM_LINES][NUM_LINES]{
  84. { 0.5f, 0.5f, 0.5f, 0.5f },
  85. { 0.5f, -0.5f, -0.5f, 0.5f },
  86. { 0.5f, 0.5f, -0.5f, -0.5f },
  87. { 0.5f, -0.5f, 0.5f, -0.5f }
  88. };
  89. /* Converts A-Format to B-Format for early reflections. */
  90. alignas(16) constexpr float EarlyA2B[NUM_LINES][NUM_LINES]{
  91. { 0.5f, 0.5f, 0.5f, 0.5f },
  92. { 0.5f, -0.5f, 0.5f, -0.5f },
  93. { 0.5f, -0.5f, -0.5f, 0.5f },
  94. { 0.5f, 0.5f, -0.5f, -0.5f }
  95. };
  96. /* Converts A-Format to B-Format for late reverb. */
  97. constexpr auto InvSqrt2 = static_cast<float>(1.0/al::numbers::sqrt2);
  98. alignas(16) constexpr float LateA2B[NUM_LINES][NUM_LINES]{
  99. { 0.5f, 0.5f, 0.5f, 0.5f },
  100. { InvSqrt2, -InvSqrt2, 0.0f, 0.0f },
  101. { 0.0f, 0.0f, InvSqrt2, -InvSqrt2 },
  102. { 0.5f, 0.5f, -0.5f, -0.5f }
  103. };
  104. /* The all-pass and delay lines have a variable length dependent on the
  105. * effect's density parameter, which helps alter the perceived environment
  106. * size. The size-to-density conversion is a cubed scale:
  107. *
  108. * density = min(1.0, pow(size, 3.0) / DENSITY_SCALE);
  109. *
  110. * The line lengths scale linearly with room size, so the inverse density
  111. * conversion is needed, taking the cube root of the re-scaled density to
  112. * calculate the line length multiplier:
  113. *
  114. * length_mult = max(5.0, cbrt(density*DENSITY_SCALE));
  115. *
  116. * The density scale below will result in a max line multiplier of 50, for an
  117. * effective size range of 5m to 50m.
  118. */
  119. constexpr float DENSITY_SCALE{125000.0f};
  120. /* All delay line lengths are specified in seconds.
  121. *
  122. * To approximate early reflections, we break them up into primary (those
  123. * arriving from the same direction as the source) and secondary (those
  124. * arriving from the opposite direction).
  125. *
  126. * The early taps decorrelate the 4-channel signal to approximate an average
  127. * room response for the primary reflections after the initial early delay.
  128. *
  129. * Given an average room dimension (d_a) and the speed of sound (c) we can
  130. * calculate the average reflection delay (r_a) regardless of listener and
  131. * source positions as:
  132. *
  133. * r_a = d_a / c
  134. * c = 343.3
  135. *
  136. * This can extended to finding the average difference (r_d) between the
  137. * maximum (r_1) and minimum (r_0) reflection delays:
  138. *
  139. * r_0 = 2 / 3 r_a
  140. * = r_a - r_d / 2
  141. * = r_d
  142. * r_1 = 4 / 3 r_a
  143. * = r_a + r_d / 2
  144. * = 2 r_d
  145. * r_d = 2 / 3 r_a
  146. * = r_1 - r_0
  147. *
  148. * As can be determined by integrating the 1D model with a source (s) and
  149. * listener (l) positioned across the dimension of length (d_a):
  150. *
  151. * r_d = int_(l=0)^d_a (int_(s=0)^d_a |2 d_a - 2 (l + s)| ds) dl / c
  152. *
  153. * The initial taps (T_(i=0)^N) are then specified by taking a power series
  154. * that ranges between r_0 and half of r_1 less r_0:
  155. *
  156. * R_i = 2^(i / (2 N - 1)) r_d
  157. * = r_0 + (2^(i / (2 N - 1)) - 1) r_d
  158. * = r_0 + T_i
  159. * T_i = R_i - r_0
  160. * = (2^(i / (2 N - 1)) - 1) r_d
  161. *
  162. * Assuming an average of 1m, we get the following taps:
  163. */
  164. constexpr std::array<float,NUM_LINES> EARLY_TAP_LENGTHS{{
  165. 0.0000000e+0f, 2.0213520e-4f, 4.2531060e-4f, 6.7171600e-4f
  166. }};
  167. /* The early all-pass filter lengths are based on the early tap lengths:
  168. *
  169. * A_i = R_i / a
  170. *
  171. * Where a is the approximate maximum all-pass cycle limit (20).
  172. */
  173. constexpr std::array<float,NUM_LINES> EARLY_ALLPASS_LENGTHS{{
  174. 9.7096800e-5f, 1.0720356e-4f, 1.1836234e-4f, 1.3068260e-4f
  175. }};
  176. /* The early delay lines are used to transform the primary reflections into
  177. * the secondary reflections. The A-format is arranged in such a way that
  178. * the channels/lines are spatially opposite:
  179. *
  180. * C_i is opposite C_(N-i-1)
  181. *
  182. * The delays of the two opposing reflections (R_i and O_i) from a source
  183. * anywhere along a particular dimension always sum to twice its full delay:
  184. *
  185. * 2 r_a = R_i + O_i
  186. *
  187. * With that in mind we can determine the delay between the two reflections
  188. * and thus specify our early line lengths (L_(i=0)^N) using:
  189. *
  190. * O_i = 2 r_a - R_(N-i-1)
  191. * L_i = O_i - R_(N-i-1)
  192. * = 2 (r_a - R_(N-i-1))
  193. * = 2 (r_a - T_(N-i-1) - r_0)
  194. * = 2 r_a (1 - (2 / 3) 2^((N - i - 1) / (2 N - 1)))
  195. *
  196. * Using an average dimension of 1m, we get:
  197. */
  198. constexpr std::array<float,NUM_LINES> EARLY_LINE_LENGTHS{{
  199. 5.9850400e-4f, 1.0913150e-3f, 1.5376658e-3f, 1.9419362e-3f
  200. }};
  201. /* The late all-pass filter lengths are based on the late line lengths:
  202. *
  203. * A_i = (5 / 3) L_i / r_1
  204. */
  205. constexpr std::array<float,NUM_LINES> LATE_ALLPASS_LENGTHS{{
  206. 1.6182800e-4f, 2.0389060e-4f, 2.8159360e-4f, 3.2365600e-4f
  207. }};
  208. /* The late lines are used to approximate the decaying cycle of recursive
  209. * late reflections.
  210. *
  211. * Splitting the lines in half, we start with the shortest reflection paths
  212. * (L_(i=0)^(N/2)):
  213. *
  214. * L_i = 2^(i / (N - 1)) r_d
  215. *
  216. * Then for the opposite (longest) reflection paths (L_(i=N/2)^N):
  217. *
  218. * L_i = 2 r_a - L_(i-N/2)
  219. * = 2 r_a - 2^((i - N / 2) / (N - 1)) r_d
  220. *
  221. * For our 1m average room, we get:
  222. */
  223. constexpr std::array<float,NUM_LINES> LATE_LINE_LENGTHS{{
  224. 1.9419362e-3f, 2.4466860e-3f, 3.3791220e-3f, 3.8838720e-3f
  225. }};
  226. using ReverbUpdateLine = std::array<float,MAX_UPDATE_SAMPLES>;
  227. struct DelayLineI {
  228. /* The delay lines use interleaved samples, with the lengths being powers
  229. * of 2 to allow the use of bit-masking instead of a modulus for wrapping.
  230. */
  231. size_t Mask{0u};
  232. union {
  233. uintptr_t LineOffset{0u};
  234. std::array<float,NUM_LINES> *Line;
  235. };
  236. /* Given the allocated sample buffer, this function updates each delay line
  237. * offset.
  238. */
  239. void realizeLineOffset(std::array<float,NUM_LINES> *sampleBuffer) noexcept
  240. { Line = sampleBuffer + LineOffset; }
  241. /* Calculate the length of a delay line and store its mask and offset. */
  242. uint calcLineLength(const float length, const uintptr_t offset, const float frequency,
  243. const uint extra)
  244. {
  245. /* All line lengths are powers of 2, calculated from their lengths in
  246. * seconds, rounded up.
  247. */
  248. uint samples{float2uint(std::ceil(length*frequency))};
  249. samples = NextPowerOf2(samples + extra);
  250. /* All lines share a single sample buffer. */
  251. Mask = samples - 1;
  252. LineOffset = offset;
  253. /* Return the sample count for accumulation. */
  254. return samples;
  255. }
  256. void write(size_t offset, const size_t c, const float *RESTRICT in, const size_t count) const noexcept
  257. {
  258. ASSUME(count > 0);
  259. for(size_t i{0u};i < count;)
  260. {
  261. offset &= Mask;
  262. size_t td{minz(Mask+1 - offset, count - i)};
  263. do {
  264. Line[offset++][c] = in[i++];
  265. } while(--td);
  266. }
  267. }
  268. };
  269. struct VecAllpass {
  270. DelayLineI Delay;
  271. float Coeff{0.0f};
  272. size_t Offset[NUM_LINES][2]{};
  273. void processFaded(const al::span<ReverbUpdateLine,NUM_LINES> samples, size_t offset,
  274. const float xCoeff, const float yCoeff, float fadeCount, const float fadeStep,
  275. const size_t todo);
  276. void processUnfaded(const al::span<ReverbUpdateLine,NUM_LINES> samples, size_t offset,
  277. const float xCoeff, const float yCoeff, const size_t todo);
  278. };
  279. struct T60Filter {
  280. /* Two filters are used to adjust the signal. One to control the low
  281. * frequencies, and one to control the high frequencies.
  282. */
  283. float MidGain[2]{0.0f, 0.0f};
  284. BiquadFilter HFFilter, LFFilter;
  285. void calcCoeffs(const float length, const float lfDecayTime, const float mfDecayTime,
  286. const float hfDecayTime, const float lf0norm, const float hf0norm);
  287. /* Applies the two T60 damping filter sections. */
  288. void process(const al::span<float> samples)
  289. { DualBiquad{HFFilter, LFFilter}.process(samples, samples.data()); }
  290. };
  291. struct EarlyReflections {
  292. /* A Gerzon vector all-pass filter is used to simulate initial diffusion.
  293. * The spread from this filter also helps smooth out the reverb tail.
  294. */
  295. VecAllpass VecAp;
  296. /* An echo line is used to complete the second half of the early
  297. * reflections.
  298. */
  299. DelayLineI Delay;
  300. size_t Offset[NUM_LINES][2]{};
  301. float Coeff[NUM_LINES][2]{};
  302. /* The gain for each output channel based on 3D panning. */
  303. float CurrentGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{};
  304. float PanGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{};
  305. void updateLines(const float density_mult, const float diffusion, const float decayTime,
  306. const float frequency);
  307. };
  308. struct Modulation {
  309. /* The vibrato time is tracked with an index over a (MOD_FRACONE)
  310. * normalized range.
  311. */
  312. uint Index, Step;
  313. /* The depth of frequency change, in samples. */
  314. float Depth[2];
  315. float ModDelays[MAX_UPDATE_SAMPLES];
  316. void updateModulator(float modTime, float modDepth, float frequency);
  317. void calcDelays(size_t todo);
  318. void calcFadedDelays(size_t todo, float fadeCount, float fadeStep);
  319. };
  320. struct LateReverb {
  321. /* A recursive delay line is used fill in the reverb tail. */
  322. DelayLineI Delay;
  323. size_t Offset[NUM_LINES][2]{};
  324. /* Attenuation to compensate for the modal density and decay rate of the
  325. * late lines.
  326. */
  327. float DensityGain[2]{0.0f, 0.0f};
  328. /* T60 decay filters are used to simulate absorption. */
  329. T60Filter T60[NUM_LINES];
  330. Modulation Mod;
  331. /* A Gerzon vector all-pass filter is used to simulate diffusion. */
  332. VecAllpass VecAp;
  333. /* The gain for each output channel based on 3D panning. */
  334. float CurrentGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{};
  335. float PanGain[NUM_LINES][MAX_OUTPUT_CHANNELS]{};
  336. void updateLines(const float density_mult, const float diffusion, const float lfDecayTime,
  337. const float mfDecayTime, const float hfDecayTime, const float lf0norm,
  338. const float hf0norm, const float frequency);
  339. };
  340. struct ReverbState final : public EffectState {
  341. /* All delay lines are allocated as a single buffer to reduce memory
  342. * fragmentation and management code.
  343. */
  344. al::vector<std::array<float,NUM_LINES>,16> mSampleBuffer;
  345. struct {
  346. /* Calculated parameters which indicate if cross-fading is needed after
  347. * an update.
  348. */
  349. float Density{1.0f};
  350. float Diffusion{1.0f};
  351. float DecayTime{1.49f};
  352. float HFDecayTime{0.83f * 1.49f};
  353. float LFDecayTime{1.0f * 1.49f};
  354. float ModulationTime{0.25f};
  355. float ModulationDepth{0.0f};
  356. float HFReference{5000.0f};
  357. float LFReference{250.0f};
  358. } mParams;
  359. /* Master effect filters */
  360. struct {
  361. BiquadFilter Lp;
  362. BiquadFilter Hp;
  363. } mFilter[NUM_LINES];
  364. /* Core delay line (early reflections and late reverb tap from this). */
  365. DelayLineI mDelay;
  366. /* Tap points for early reflection delay. */
  367. size_t mEarlyDelayTap[NUM_LINES][2]{};
  368. float mEarlyDelayCoeff[NUM_LINES][2]{};
  369. /* Tap points for late reverb feed and delay. */
  370. size_t mLateFeedTap{};
  371. size_t mLateDelayTap[NUM_LINES][2]{};
  372. /* Coefficients for the all-pass and line scattering matrices. */
  373. float mMixX{0.0f};
  374. float mMixY{0.0f};
  375. EarlyReflections mEarly;
  376. LateReverb mLate;
  377. bool mDoFading{};
  378. /* Maximum number of samples to process at once. */
  379. size_t mMaxUpdate[2]{MAX_UPDATE_SAMPLES, MAX_UPDATE_SAMPLES};
  380. /* The current write offset for all delay lines. */
  381. size_t mOffset{};
  382. /* Temporary storage used when processing. */
  383. union {
  384. alignas(16) FloatBufferLine mTempLine{};
  385. alignas(16) std::array<ReverbUpdateLine,NUM_LINES> mTempSamples;
  386. };
  387. alignas(16) std::array<ReverbUpdateLine,NUM_LINES> mEarlySamples{};
  388. alignas(16) std::array<ReverbUpdateLine,NUM_LINES> mLateSamples{};
  389. bool mUpmixOutput{false};
  390. std::array<float,MaxAmbiOrder+1> mOrderScales{};
  391. std::array<std::array<BandSplitter,NUM_LINES>,2> mAmbiSplitter;
  392. static void DoMixRow(const al::span<float> OutBuffer, const al::span<const float> Gains,
  393. const float *InSamples, const size_t InStride)
  394. {
  395. std::fill(OutBuffer.begin(), OutBuffer.end(), 0.0f);
  396. for(const float gain : Gains)
  397. {
  398. const float *RESTRICT input{al::assume_aligned<16>(InSamples)};
  399. InSamples += InStride;
  400. if(!(std::fabs(gain) > GainSilenceThreshold))
  401. continue;
  402. for(float &sample : OutBuffer)
  403. {
  404. sample += *input * gain;
  405. ++input;
  406. }
  407. }
  408. }
  409. void MixOutPlain(const al::span<FloatBufferLine> samplesOut, const size_t counter,
  410. const size_t offset, const size_t todo)
  411. {
  412. ASSUME(todo > 0);
  413. /* Convert back to B-Format, and mix the results to output. */
  414. const al::span<float> tmpspan{al::assume_aligned<16>(mTempLine.data()), todo};
  415. for(size_t c{0u};c < NUM_LINES;c++)
  416. {
  417. DoMixRow(tmpspan, EarlyA2B[c], mEarlySamples[0].data(), mEarlySamples[0].size());
  418. MixSamples(tmpspan, samplesOut, mEarly.CurrentGain[c], mEarly.PanGain[c], counter,
  419. offset);
  420. }
  421. for(size_t c{0u};c < NUM_LINES;c++)
  422. {
  423. DoMixRow(tmpspan, LateA2B[c], mLateSamples[0].data(), mLateSamples[0].size());
  424. MixSamples(tmpspan, samplesOut, mLate.CurrentGain[c], mLate.PanGain[c], counter,
  425. offset);
  426. }
  427. }
  428. void MixOutAmbiUp(const al::span<FloatBufferLine> samplesOut, const size_t counter,
  429. const size_t offset, const size_t todo)
  430. {
  431. ASSUME(todo > 0);
  432. const al::span<float> tmpspan{al::assume_aligned<16>(mTempLine.data()), todo};
  433. for(size_t c{0u};c < NUM_LINES;c++)
  434. {
  435. DoMixRow(tmpspan, EarlyA2B[c], mEarlySamples[0].data(), mEarlySamples[0].size());
  436. /* Apply scaling to the B-Format's HF response to "upsample" it to
  437. * higher-order output.
  438. */
  439. const float hfscale{(c==0) ? mOrderScales[0] : mOrderScales[1]};
  440. mAmbiSplitter[0][c].processHfScale(tmpspan, hfscale);
  441. MixSamples(tmpspan, samplesOut, mEarly.CurrentGain[c], mEarly.PanGain[c], counter,
  442. offset);
  443. }
  444. for(size_t c{0u};c < NUM_LINES;c++)
  445. {
  446. DoMixRow(tmpspan, LateA2B[c], mLateSamples[0].data(), mLateSamples[0].size());
  447. const float hfscale{(c==0) ? mOrderScales[0] : mOrderScales[1]};
  448. mAmbiSplitter[1][c].processHfScale(tmpspan, hfscale);
  449. MixSamples(tmpspan, samplesOut, mLate.CurrentGain[c], mLate.PanGain[c], counter,
  450. offset);
  451. }
  452. }
  453. void mixOut(const al::span<FloatBufferLine> samplesOut, const size_t counter,
  454. const size_t offset, const size_t todo)
  455. {
  456. if(mUpmixOutput)
  457. MixOutAmbiUp(samplesOut, counter, offset, todo);
  458. else
  459. MixOutPlain(samplesOut, counter, offset, todo);
  460. }
  461. void allocLines(const float frequency);
  462. void updateDelayLine(const float earlyDelay, const float lateDelay, const float density_mult,
  463. const float decayTime, const float frequency);
  464. void update3DPanning(const float *ReflectionsPan, const float *LateReverbPan,
  465. const float earlyGain, const float lateGain, const EffectTarget &target);
  466. void earlyUnfaded(const size_t offset, const size_t todo);
  467. void earlyFaded(const size_t offset, const size_t todo, const float fade,
  468. const float fadeStep);
  469. void lateUnfaded(const size_t offset, const size_t todo);
  470. void lateFaded(const size_t offset, const size_t todo, const float fade,
  471. const float fadeStep);
  472. void deviceUpdate(const DeviceBase *device, const Buffer &buffer) override;
  473. void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
  474. const EffectTarget target) override;
  475. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  476. const al::span<FloatBufferLine> samplesOut) override;
  477. DEF_NEWDEL(ReverbState)
  478. };
  479. /**************************************
  480. * Device Update *
  481. **************************************/
  482. inline float CalcDelayLengthMult(float density)
  483. { return maxf(5.0f, std::cbrt(density*DENSITY_SCALE)); }
  484. /* Calculates the delay line metrics and allocates the shared sample buffer
  485. * for all lines given the sample rate (frequency).
  486. */
  487. void ReverbState::allocLines(const float frequency)
  488. {
  489. /* All delay line lengths are calculated to accomodate the full range of
  490. * lengths given their respective paramters.
  491. */
  492. size_t totalSamples{0u};
  493. /* Multiplier for the maximum density value, i.e. density=1, which is
  494. * actually the least density...
  495. */
  496. const float multiplier{CalcDelayLengthMult(1.0f)};
  497. /* The main delay length includes the maximum early reflection delay, the
  498. * largest early tap width, the maximum late reverb delay, and the
  499. * largest late tap width. Finally, it must also be extended by the
  500. * update size (BufferLineSize) for block processing.
  501. */
  502. constexpr float LateLineDiffAvg{(LATE_LINE_LENGTHS.back()-LATE_LINE_LENGTHS.front()) /
  503. float{NUM_LINES}};
  504. float length{ReverbMaxReflectionsDelay + EARLY_TAP_LENGTHS.back()*multiplier +
  505. ReverbMaxLateReverbDelay + LateLineDiffAvg*multiplier};
  506. totalSamples += mDelay.calcLineLength(length, totalSamples, frequency, BufferLineSize);
  507. /* The early vector all-pass line. */
  508. length = EARLY_ALLPASS_LENGTHS.back() * multiplier;
  509. totalSamples += mEarly.VecAp.Delay.calcLineLength(length, totalSamples, frequency, 0);
  510. /* The early reflection line. */
  511. length = EARLY_LINE_LENGTHS.back() * multiplier;
  512. totalSamples += mEarly.Delay.calcLineLength(length, totalSamples, frequency, 0);
  513. /* The late vector all-pass line. */
  514. length = LATE_ALLPASS_LENGTHS.back() * multiplier;
  515. totalSamples += mLate.VecAp.Delay.calcLineLength(length, totalSamples, frequency, 0);
  516. /* The modulator's line length is calculated from the maximum modulation
  517. * time and depth coefficient, and halfed for the low-to-high frequency
  518. * swing.
  519. */
  520. constexpr float max_mod_delay{MaxModulationTime*MODULATION_DEPTH_COEFF / 2.0f};
  521. /* The late delay lines are calculated from the largest maximum density
  522. * line length, and the maximum modulation delay. An additional sample is
  523. * added to keep it stable when there is no modulation.
  524. */
  525. length = LATE_LINE_LENGTHS.back()*multiplier + max_mod_delay;
  526. totalSamples += mLate.Delay.calcLineLength(length, totalSamples, frequency, 1);
  527. if(totalSamples != mSampleBuffer.size())
  528. decltype(mSampleBuffer)(totalSamples).swap(mSampleBuffer);
  529. /* Clear the sample buffer. */
  530. std::fill(mSampleBuffer.begin(), mSampleBuffer.end(), decltype(mSampleBuffer)::value_type{});
  531. /* Update all delays to reflect the new sample buffer. */
  532. mDelay.realizeLineOffset(mSampleBuffer.data());
  533. mEarly.VecAp.Delay.realizeLineOffset(mSampleBuffer.data());
  534. mEarly.Delay.realizeLineOffset(mSampleBuffer.data());
  535. mLate.VecAp.Delay.realizeLineOffset(mSampleBuffer.data());
  536. mLate.Delay.realizeLineOffset(mSampleBuffer.data());
  537. }
  538. void ReverbState::deviceUpdate(const DeviceBase *device, const Buffer&)
  539. {
  540. const auto frequency = static_cast<float>(device->Frequency);
  541. /* Allocate the delay lines. */
  542. allocLines(frequency);
  543. const float multiplier{CalcDelayLengthMult(1.0f)};
  544. /* The late feed taps are set a fixed position past the latest delay tap. */
  545. mLateFeedTap = float2uint((ReverbMaxReflectionsDelay + EARLY_TAP_LENGTHS.back()*multiplier) *
  546. frequency);
  547. /* Clear filters and gain coefficients since the delay lines were all just
  548. * cleared (if not reallocated).
  549. */
  550. for(auto &filter : mFilter)
  551. {
  552. filter.Lp.clear();
  553. filter.Hp.clear();
  554. }
  555. for(auto &coeff : mEarlyDelayCoeff)
  556. std::fill(std::begin(coeff), std::end(coeff), 0.0f);
  557. for(auto &coeff : mEarly.Coeff)
  558. std::fill(std::begin(coeff), std::end(coeff), 0.0f);
  559. mLate.DensityGain[0] = 0.0f;
  560. mLate.DensityGain[1] = 0.0f;
  561. for(auto &t60 : mLate.T60)
  562. {
  563. t60.MidGain[0] = 0.0f;
  564. t60.MidGain[1] = 0.0f;
  565. t60.HFFilter.clear();
  566. t60.LFFilter.clear();
  567. }
  568. mLate.Mod.Index = 0;
  569. mLate.Mod.Step = 1;
  570. std::fill(std::begin(mLate.Mod.Depth), std::end(mLate.Mod.Depth), 0.0f);
  571. for(auto &gains : mEarly.CurrentGain)
  572. std::fill(std::begin(gains), std::end(gains), 0.0f);
  573. for(auto &gains : mEarly.PanGain)
  574. std::fill(std::begin(gains), std::end(gains), 0.0f);
  575. for(auto &gains : mLate.CurrentGain)
  576. std::fill(std::begin(gains), std::end(gains), 0.0f);
  577. for(auto &gains : mLate.PanGain)
  578. std::fill(std::begin(gains), std::end(gains), 0.0f);
  579. /* Reset fading and offset base. */
  580. mDoFading = true;
  581. std::fill(std::begin(mMaxUpdate), std::end(mMaxUpdate), MAX_UPDATE_SAMPLES);
  582. mOffset = 0;
  583. if(device->mAmbiOrder > 1)
  584. {
  585. mUpmixOutput = true;
  586. mOrderScales = AmbiScale::GetHFOrderScales(1, device->mAmbiOrder);
  587. }
  588. else
  589. {
  590. mUpmixOutput = false;
  591. mOrderScales.fill(1.0f);
  592. }
  593. mAmbiSplitter[0][0].init(device->mXOverFreq / frequency);
  594. std::fill(mAmbiSplitter[0].begin()+1, mAmbiSplitter[0].end(), mAmbiSplitter[0][0]);
  595. std::fill(mAmbiSplitter[1].begin(), mAmbiSplitter[1].end(), mAmbiSplitter[0][0]);
  596. }
  597. /**************************************
  598. * Effect Update *
  599. **************************************/
  600. /* Calculate a decay coefficient given the length of each cycle and the time
  601. * until the decay reaches -60 dB.
  602. */
  603. inline float CalcDecayCoeff(const float length, const float decayTime)
  604. { return std::pow(ReverbDecayGain, length/decayTime); }
  605. /* Calculate a decay length from a coefficient and the time until the decay
  606. * reaches -60 dB.
  607. */
  608. inline float CalcDecayLength(const float coeff, const float decayTime)
  609. {
  610. constexpr float log10_decaygain{-3.0f/*std::log10(ReverbDecayGain)*/};
  611. return std::log10(coeff) * decayTime / log10_decaygain;
  612. }
  613. /* Calculate an attenuation to be applied to the input of any echo models to
  614. * compensate for modal density and decay time.
  615. */
  616. inline float CalcDensityGain(const float a)
  617. {
  618. /* The energy of a signal can be obtained by finding the area under the
  619. * squared signal. This takes the form of Sum(x_n^2), where x is the
  620. * amplitude for the sample n.
  621. *
  622. * Decaying feedback matches exponential decay of the form Sum(a^n),
  623. * where a is the attenuation coefficient, and n is the sample. The area
  624. * under this decay curve can be calculated as: 1 / (1 - a).
  625. *
  626. * Modifying the above equation to find the area under the squared curve
  627. * (for energy) yields: 1 / (1 - a^2). Input attenuation can then be
  628. * calculated by inverting the square root of this approximation,
  629. * yielding: 1 / sqrt(1 / (1 - a^2)), simplified to: sqrt(1 - a^2).
  630. */
  631. return std::sqrt(1.0f - a*a);
  632. }
  633. /* Calculate the scattering matrix coefficients given a diffusion factor. */
  634. inline void CalcMatrixCoeffs(const float diffusion, float *x, float *y)
  635. {
  636. /* The matrix is of order 4, so n is sqrt(4 - 1). */
  637. constexpr float n{al::numbers::sqrt3_v<float>};
  638. const float t{diffusion * std::atan(n)};
  639. /* Calculate the first mixing matrix coefficient. */
  640. *x = std::cos(t);
  641. /* Calculate the second mixing matrix coefficient. */
  642. *y = std::sin(t) / n;
  643. }
  644. /* Calculate the limited HF ratio for use with the late reverb low-pass
  645. * filters.
  646. */
  647. float CalcLimitedHfRatio(const float hfRatio, const float airAbsorptionGainHF,
  648. const float decayTime)
  649. {
  650. /* Find the attenuation due to air absorption in dB (converting delay
  651. * time to meters using the speed of sound). Then reversing the decay
  652. * equation, solve for HF ratio. The delay length is cancelled out of
  653. * the equation, so it can be calculated once for all lines.
  654. */
  655. float limitRatio{1.0f / SpeedOfSoundMetersPerSec /
  656. CalcDecayLength(airAbsorptionGainHF, decayTime)};
  657. /* Using the limit calculated above, apply the upper bound to the HF ratio. */
  658. return minf(limitRatio, hfRatio);
  659. }
  660. /* Calculates the 3-band T60 damping coefficients for a particular delay line
  661. * of specified length, using a combination of two shelf filter sections given
  662. * decay times for each band split at two reference frequencies.
  663. */
  664. void T60Filter::calcCoeffs(const float length, const float lfDecayTime,
  665. const float mfDecayTime, const float hfDecayTime, const float lf0norm,
  666. const float hf0norm)
  667. {
  668. const float mfGain{CalcDecayCoeff(length, mfDecayTime)};
  669. const float lfGain{CalcDecayCoeff(length, lfDecayTime) / mfGain};
  670. const float hfGain{CalcDecayCoeff(length, hfDecayTime) / mfGain};
  671. MidGain[1] = mfGain;
  672. LFFilter.setParamsFromSlope(BiquadType::LowShelf, lf0norm, lfGain, 1.0f);
  673. HFFilter.setParamsFromSlope(BiquadType::HighShelf, hf0norm, hfGain, 1.0f);
  674. }
  675. /* Update the early reflection line lengths and gain coefficients. */
  676. void EarlyReflections::updateLines(const float density_mult, const float diffusion,
  677. const float decayTime, const float frequency)
  678. {
  679. /* Calculate the all-pass feed-back/forward coefficient. */
  680. VecAp.Coeff = diffusion*diffusion * InvSqrt2;
  681. for(size_t i{0u};i < NUM_LINES;i++)
  682. {
  683. /* Calculate the delay length of each all-pass line. */
  684. float length{EARLY_ALLPASS_LENGTHS[i] * density_mult};
  685. VecAp.Offset[i][1] = float2uint(length * frequency);
  686. /* Calculate the delay length of each delay line. */
  687. length = EARLY_LINE_LENGTHS[i] * density_mult;
  688. Offset[i][1] = float2uint(length * frequency);
  689. /* Calculate the gain (coefficient) for each line. */
  690. Coeff[i][1] = CalcDecayCoeff(length, decayTime);
  691. }
  692. }
  693. /* Update the EAX modulation step and depth. Keep in mind that this kind of
  694. * vibrato is additive and not multiplicative as one may expect. The downswing
  695. * will sound stronger than the upswing.
  696. */
  697. void Modulation::updateModulator(float modTime, float modDepth, float frequency)
  698. {
  699. /* Modulation is calculated in two parts.
  700. *
  701. * The modulation time effects the sinus rate, altering the speed of
  702. * frequency changes. An index is incremented for each sample with an
  703. * appropriate step size to generate an LFO, which will vary the feedback
  704. * delay over time.
  705. */
  706. Step = maxu(fastf2u(MOD_FRACONE / (frequency * modTime)), 1);
  707. /* The modulation depth effects the amount of frequency change over the
  708. * range of the sinus. It needs to be scaled by the modulation time so that
  709. * a given depth produces a consistent change in frequency over all ranges
  710. * of time. Since the depth is applied to a sinus value, it needs to be
  711. * halved once for the sinus range and again for the sinus swing in time
  712. * (half of it is spent decreasing the frequency, half is spent increasing
  713. * it).
  714. */
  715. if(modTime >= DefaultModulationTime)
  716. {
  717. /* To cancel the effects of a long period modulation on the late
  718. * reverberation, the amount of pitch should be varied (decreased)
  719. * according to the modulation time. The natural form is varying
  720. * inversely, in fact resulting in an invariant.
  721. */
  722. Depth[1] = MODULATION_DEPTH_COEFF / 4.0f * DefaultModulationTime * modDepth * frequency;
  723. }
  724. else
  725. Depth[1] = MODULATION_DEPTH_COEFF / 4.0f * modTime * modDepth * frequency;
  726. }
  727. /* Update the late reverb line lengths and T60 coefficients. */
  728. void LateReverb::updateLines(const float density_mult, const float diffusion,
  729. const float lfDecayTime, const float mfDecayTime, const float hfDecayTime,
  730. const float lf0norm, const float hf0norm, const float frequency)
  731. {
  732. /* Scaling factor to convert the normalized reference frequencies from
  733. * representing 0...freq to 0...max_reference.
  734. */
  735. constexpr float MaxHFReference{20000.0f};
  736. const float norm_weight_factor{frequency / MaxHFReference};
  737. const float late_allpass_avg{
  738. std::accumulate(LATE_ALLPASS_LENGTHS.begin(), LATE_ALLPASS_LENGTHS.end(), 0.0f) /
  739. float{NUM_LINES}};
  740. /* To compensate for changes in modal density and decay time of the late
  741. * reverb signal, the input is attenuated based on the maximal energy of
  742. * the outgoing signal. This approximation is used to keep the apparent
  743. * energy of the signal equal for all ranges of density and decay time.
  744. *
  745. * The average length of the delay lines is used to calculate the
  746. * attenuation coefficient.
  747. */
  748. float length{std::accumulate(LATE_LINE_LENGTHS.begin(), LATE_LINE_LENGTHS.end(), 0.0f) /
  749. float{NUM_LINES} + late_allpass_avg};
  750. length *= density_mult;
  751. /* The density gain calculation uses an average decay time weighted by
  752. * approximate bandwidth. This attempts to compensate for losses of energy
  753. * that reduce decay time due to scattering into highly attenuated bands.
  754. */
  755. const float decayTimeWeighted{
  756. lf0norm*norm_weight_factor*lfDecayTime +
  757. (hf0norm - lf0norm)*norm_weight_factor*mfDecayTime +
  758. (1.0f - hf0norm*norm_weight_factor)*hfDecayTime};
  759. DensityGain[1] = CalcDensityGain(CalcDecayCoeff(length, decayTimeWeighted));
  760. /* Calculate the all-pass feed-back/forward coefficient. */
  761. VecAp.Coeff = diffusion*diffusion * InvSqrt2;
  762. for(size_t i{0u};i < NUM_LINES;i++)
  763. {
  764. /* Calculate the delay length of each all-pass line. */
  765. length = LATE_ALLPASS_LENGTHS[i] * density_mult;
  766. VecAp.Offset[i][1] = float2uint(length * frequency);
  767. /* Calculate the delay length of each feedback delay line. */
  768. length = LATE_LINE_LENGTHS[i] * density_mult;
  769. Offset[i][1] = float2uint(length*frequency + 0.5f);
  770. /* Approximate the absorption that the vector all-pass would exhibit
  771. * given the current diffusion so we don't have to process a full T60
  772. * filter for each of its four lines. Also include the average
  773. * modulation delay (depth is half the max delay in samples).
  774. */
  775. length += lerpf(LATE_ALLPASS_LENGTHS[i], late_allpass_avg, diffusion)*density_mult +
  776. Mod.Depth[1]/frequency;
  777. /* Calculate the T60 damping coefficients for each line. */
  778. T60[i].calcCoeffs(length, lfDecayTime, mfDecayTime, hfDecayTime, lf0norm, hf0norm);
  779. }
  780. }
  781. /* Update the offsets for the main effect delay line. */
  782. void ReverbState::updateDelayLine(const float earlyDelay, const float lateDelay,
  783. const float density_mult, const float decayTime, const float frequency)
  784. {
  785. /* Early reflection taps are decorrelated by means of an average room
  786. * reflection approximation described above the definition of the taps.
  787. * This approximation is linear and so the above density multiplier can
  788. * be applied to adjust the width of the taps. A single-band decay
  789. * coefficient is applied to simulate initial attenuation and absorption.
  790. *
  791. * Late reverb taps are based on the late line lengths to allow a zero-
  792. * delay path and offsets that would continue the propagation naturally
  793. * into the late lines.
  794. */
  795. for(size_t i{0u};i < NUM_LINES;i++)
  796. {
  797. float length{EARLY_TAP_LENGTHS[i]*density_mult};
  798. mEarlyDelayTap[i][1] = float2uint((earlyDelay+length) * frequency);
  799. mEarlyDelayCoeff[i][1] = CalcDecayCoeff(length, decayTime);
  800. length = (LATE_LINE_LENGTHS[i] - LATE_LINE_LENGTHS.front())/float{NUM_LINES}*density_mult +
  801. lateDelay;
  802. mLateDelayTap[i][1] = mLateFeedTap + float2uint(length * frequency);
  803. }
  804. }
  805. /* Creates a transform matrix given a reverb vector. The vector pans the reverb
  806. * reflections toward the given direction, using its magnitude (up to 1) as a
  807. * focal strength. This function results in a B-Format transformation matrix
  808. * that spatially focuses the signal in the desired direction.
  809. */
  810. alu::Matrix GetTransformFromVector(const float *vec)
  811. {
  812. /* Normalize the panning vector according to the N3D scale, which has an
  813. * extra sqrt(3) term on the directional components. Converting from OpenAL
  814. * to B-Format also requires negating X (ACN 1) and Z (ACN 3). Note however
  815. * that the reverb panning vectors use left-handed coordinates, unlike the
  816. * rest of OpenAL which use right-handed. This is fixed by negating Z,
  817. * which cancels out with the B-Format Z negation.
  818. */
  819. float norm[3];
  820. float mag{std::sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2])};
  821. if(mag > 1.0f)
  822. {
  823. norm[0] = vec[0] / mag * -al::numbers::sqrt3_v<float>;
  824. norm[1] = vec[1] / mag * al::numbers::sqrt3_v<float>;
  825. norm[2] = vec[2] / mag * al::numbers::sqrt3_v<float>;
  826. mag = 1.0f;
  827. }
  828. else
  829. {
  830. /* If the magnitude is less than or equal to 1, just apply the sqrt(3)
  831. * term. There's no need to renormalize the magnitude since it would
  832. * just be reapplied in the matrix.
  833. */
  834. norm[0] = vec[0] * -al::numbers::sqrt3_v<float>;
  835. norm[1] = vec[1] * al::numbers::sqrt3_v<float>;
  836. norm[2] = vec[2] * al::numbers::sqrt3_v<float>;
  837. }
  838. return alu::Matrix{
  839. 1.0f, 0.0f, 0.0f, 0.0f,
  840. norm[0], 1.0f-mag, 0.0f, 0.0f,
  841. norm[1], 0.0f, 1.0f-mag, 0.0f,
  842. norm[2], 0.0f, 0.0f, 1.0f-mag
  843. };
  844. }
  845. /* Update the early and late 3D panning gains. */
  846. void ReverbState::update3DPanning(const float *ReflectionsPan, const float *LateReverbPan,
  847. const float earlyGain, const float lateGain, const EffectTarget &target)
  848. {
  849. /* Create matrices that transform a B-Format signal according to the
  850. * panning vectors.
  851. */
  852. const alu::Matrix earlymat{GetTransformFromVector(ReflectionsPan)};
  853. const alu::Matrix latemat{GetTransformFromVector(LateReverbPan)};
  854. mOutTarget = target.Main->Buffer;
  855. for(size_t i{0u};i < NUM_LINES;i++)
  856. {
  857. const float coeffs[MaxAmbiChannels]{earlymat[0][i], earlymat[1][i], earlymat[2][i],
  858. earlymat[3][i]};
  859. ComputePanGains(target.Main, coeffs, earlyGain, mEarly.PanGain[i]);
  860. }
  861. for(size_t i{0u};i < NUM_LINES;i++)
  862. {
  863. const float coeffs[MaxAmbiChannels]{latemat[0][i], latemat[1][i], latemat[2][i],
  864. latemat[3][i]};
  865. ComputePanGains(target.Main, coeffs, lateGain, mLate.PanGain[i]);
  866. }
  867. }
  868. void ReverbState::update(const ContextBase *Context, const EffectSlot *Slot,
  869. const EffectProps *props, const EffectTarget target)
  870. {
  871. const DeviceBase *Device{Context->mDevice};
  872. const auto frequency = static_cast<float>(Device->Frequency);
  873. /* Calculate the master filters */
  874. float hf0norm{minf(props->Reverb.HFReference/frequency, 0.49f)};
  875. mFilter[0].Lp.setParamsFromSlope(BiquadType::HighShelf, hf0norm, props->Reverb.GainHF, 1.0f);
  876. float lf0norm{minf(props->Reverb.LFReference/frequency, 0.49f)};
  877. mFilter[0].Hp.setParamsFromSlope(BiquadType::LowShelf, lf0norm, props->Reverb.GainLF, 1.0f);
  878. for(size_t i{1u};i < NUM_LINES;i++)
  879. {
  880. mFilter[i].Lp.copyParamsFrom(mFilter[0].Lp);
  881. mFilter[i].Hp.copyParamsFrom(mFilter[0].Hp);
  882. }
  883. /* The density-based room size (delay length) multiplier. */
  884. const float density_mult{CalcDelayLengthMult(props->Reverb.Density)};
  885. /* Update the main effect delay and associated taps. */
  886. updateDelayLine(props->Reverb.ReflectionsDelay, props->Reverb.LateReverbDelay,
  887. density_mult, props->Reverb.DecayTime, frequency);
  888. /* Update the early lines. */
  889. mEarly.updateLines(density_mult, props->Reverb.Diffusion, props->Reverb.DecayTime, frequency);
  890. /* Get the mixing matrix coefficients. */
  891. CalcMatrixCoeffs(props->Reverb.Diffusion, &mMixX, &mMixY);
  892. /* If the HF limit parameter is flagged, calculate an appropriate limit
  893. * based on the air absorption parameter.
  894. */
  895. float hfRatio{props->Reverb.DecayHFRatio};
  896. if(props->Reverb.DecayHFLimit && props->Reverb.AirAbsorptionGainHF < 1.0f)
  897. hfRatio = CalcLimitedHfRatio(hfRatio, props->Reverb.AirAbsorptionGainHF,
  898. props->Reverb.DecayTime);
  899. /* Calculate the LF/HF decay times. */
  900. constexpr float MinDecayTime{0.1f}, MaxDecayTime{20.0f};
  901. const float lfDecayTime{clampf(props->Reverb.DecayTime*props->Reverb.DecayLFRatio,
  902. MinDecayTime, MaxDecayTime)};
  903. const float hfDecayTime{clampf(props->Reverb.DecayTime*hfRatio, MinDecayTime, MaxDecayTime)};
  904. /* Update the modulator rate and depth. */
  905. mLate.Mod.updateModulator(props->Reverb.ModulationTime, props->Reverb.ModulationDepth,
  906. frequency);
  907. /* Update the late lines. */
  908. mLate.updateLines(density_mult, props->Reverb.Diffusion, lfDecayTime,
  909. props->Reverb.DecayTime, hfDecayTime, lf0norm, hf0norm, frequency);
  910. /* Update early and late 3D panning. */
  911. const float gain{props->Reverb.Gain * Slot->Gain * ReverbBoost};
  912. update3DPanning(props->Reverb.ReflectionsPan, props->Reverb.LateReverbPan,
  913. props->Reverb.ReflectionsGain*gain, props->Reverb.LateReverbGain*gain, target);
  914. /* Calculate the max update size from the smallest relevant delay. */
  915. mMaxUpdate[1] = minz(MAX_UPDATE_SAMPLES, minz(mEarly.Offset[0][1], mLate.Offset[0][1]));
  916. /* Determine if delay-line cross-fading is required. Density is essentially
  917. * a master control for the feedback delays, so changes the offsets of many
  918. * delay lines.
  919. */
  920. mDoFading |= (mParams.Density != props->Reverb.Density ||
  921. /* Diffusion and decay times influences the decay rate (gain) of the
  922. * late reverb T60 filter.
  923. */
  924. mParams.Diffusion != props->Reverb.Diffusion ||
  925. mParams.DecayTime != props->Reverb.DecayTime ||
  926. mParams.HFDecayTime != hfDecayTime ||
  927. mParams.LFDecayTime != lfDecayTime ||
  928. /* Modulation time and depth both require fading the modulation delay. */
  929. mParams.ModulationTime != props->Reverb.ModulationTime ||
  930. mParams.ModulationDepth != props->Reverb.ModulationDepth ||
  931. /* HF/LF References control the weighting used to calculate the density
  932. * gain.
  933. */
  934. mParams.HFReference != props->Reverb.HFReference ||
  935. mParams.LFReference != props->Reverb.LFReference);
  936. if(mDoFading)
  937. {
  938. mParams.Density = props->Reverb.Density;
  939. mParams.Diffusion = props->Reverb.Diffusion;
  940. mParams.DecayTime = props->Reverb.DecayTime;
  941. mParams.HFDecayTime = hfDecayTime;
  942. mParams.LFDecayTime = lfDecayTime;
  943. mParams.ModulationTime = props->Reverb.ModulationTime;
  944. mParams.ModulationDepth = props->Reverb.ModulationDepth;
  945. mParams.HFReference = props->Reverb.HFReference;
  946. mParams.LFReference = props->Reverb.LFReference;
  947. }
  948. }
  949. /**************************************
  950. * Effect Processing *
  951. **************************************/
  952. /* Applies a scattering matrix to the 4-line (vector) input. This is used
  953. * for both the below vector all-pass model and to perform modal feed-back
  954. * delay network (FDN) mixing.
  955. *
  956. * The matrix is derived from a skew-symmetric matrix to form a 4D rotation
  957. * matrix with a single unitary rotational parameter:
  958. *
  959. * [ d, a, b, c ] 1 = a^2 + b^2 + c^2 + d^2
  960. * [ -a, d, c, -b ]
  961. * [ -b, -c, d, a ]
  962. * [ -c, b, -a, d ]
  963. *
  964. * The rotation is constructed from the effect's diffusion parameter,
  965. * yielding:
  966. *
  967. * 1 = x^2 + 3 y^2
  968. *
  969. * Where a, b, and c are the coefficient y with differing signs, and d is the
  970. * coefficient x. The final matrix is thus:
  971. *
  972. * [ x, y, -y, y ] n = sqrt(matrix_order - 1)
  973. * [ -y, x, y, y ] t = diffusion_parameter * atan(n)
  974. * [ y, -y, x, y ] x = cos(t)
  975. * [ -y, -y, -y, x ] y = sin(t) / n
  976. *
  977. * Any square orthogonal matrix with an order that is a power of two will
  978. * work (where ^T is transpose, ^-1 is inverse):
  979. *
  980. * M^T = M^-1
  981. *
  982. * Using that knowledge, finding an appropriate matrix can be accomplished
  983. * naively by searching all combinations of:
  984. *
  985. * M = D + S - S^T
  986. *
  987. * Where D is a diagonal matrix (of x), and S is a triangular matrix (of y)
  988. * whose combination of signs are being iterated.
  989. */
  990. inline auto VectorPartialScatter(const std::array<float,NUM_LINES> &RESTRICT in,
  991. const float xCoeff, const float yCoeff) -> std::array<float,NUM_LINES>
  992. {
  993. return std::array<float,NUM_LINES>{{
  994. xCoeff*in[0] + yCoeff*( in[1] + -in[2] + in[3]),
  995. xCoeff*in[1] + yCoeff*(-in[0] + in[2] + in[3]),
  996. xCoeff*in[2] + yCoeff*( in[0] + -in[1] + in[3]),
  997. xCoeff*in[3] + yCoeff*(-in[0] + -in[1] + -in[2] )
  998. }};
  999. }
  1000. /* Utilizes the above, but reverses the input channels. */
  1001. void VectorScatterRevDelayIn(const DelayLineI delay, size_t offset, const float xCoeff,
  1002. const float yCoeff, const al::span<const ReverbUpdateLine,NUM_LINES> in, const size_t count)
  1003. {
  1004. ASSUME(count > 0);
  1005. for(size_t i{0u};i < count;)
  1006. {
  1007. offset &= delay.Mask;
  1008. size_t td{minz(delay.Mask+1 - offset, count-i)};
  1009. do {
  1010. std::array<float,NUM_LINES> f;
  1011. for(size_t j{0u};j < NUM_LINES;j++)
  1012. f[NUM_LINES-1-j] = in[j][i];
  1013. ++i;
  1014. delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff);
  1015. } while(--td);
  1016. }
  1017. }
  1018. /* This applies a Gerzon multiple-in/multiple-out (MIMO) vector all-pass
  1019. * filter to the 4-line input.
  1020. *
  1021. * It works by vectorizing a regular all-pass filter and replacing the delay
  1022. * element with a scattering matrix (like the one above) and a diagonal
  1023. * matrix of delay elements.
  1024. *
  1025. * Two static specializations are used for transitional (cross-faded) delay
  1026. * line processing and non-transitional processing.
  1027. */
  1028. void VecAllpass::processUnfaded(const al::span<ReverbUpdateLine,NUM_LINES> samples, size_t offset,
  1029. const float xCoeff, const float yCoeff, const size_t todo)
  1030. {
  1031. const DelayLineI delay{Delay};
  1032. const float feedCoeff{Coeff};
  1033. ASSUME(todo > 0);
  1034. size_t vap_offset[NUM_LINES];
  1035. for(size_t j{0u};j < NUM_LINES;j++)
  1036. vap_offset[j] = offset - Offset[j][0];
  1037. for(size_t i{0u};i < todo;)
  1038. {
  1039. for(size_t j{0u};j < NUM_LINES;j++)
  1040. vap_offset[j] &= delay.Mask;
  1041. offset &= delay.Mask;
  1042. size_t maxoff{offset};
  1043. for(size_t j{0u};j < NUM_LINES;j++)
  1044. maxoff = maxz(maxoff, vap_offset[j]);
  1045. size_t td{minz(delay.Mask+1 - maxoff, todo - i)};
  1046. do {
  1047. std::array<float,NUM_LINES> f;
  1048. for(size_t j{0u};j < NUM_LINES;j++)
  1049. {
  1050. const float input{samples[j][i]};
  1051. const float out{delay.Line[vap_offset[j]++][j] - feedCoeff*input};
  1052. f[j] = input + feedCoeff*out;
  1053. samples[j][i] = out;
  1054. }
  1055. ++i;
  1056. delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff);
  1057. } while(--td);
  1058. }
  1059. }
  1060. void VecAllpass::processFaded(const al::span<ReverbUpdateLine,NUM_LINES> samples, size_t offset,
  1061. const float xCoeff, const float yCoeff, float fadeCount, const float fadeStep,
  1062. const size_t todo)
  1063. {
  1064. const DelayLineI delay{Delay};
  1065. const float feedCoeff{Coeff};
  1066. ASSUME(todo > 0);
  1067. size_t vap_offset[NUM_LINES][2];
  1068. for(size_t j{0u};j < NUM_LINES;j++)
  1069. {
  1070. vap_offset[j][0] = offset - Offset[j][0];
  1071. vap_offset[j][1] = offset - Offset[j][1];
  1072. }
  1073. for(size_t i{0u};i < todo;)
  1074. {
  1075. for(size_t j{0u};j < NUM_LINES;j++)
  1076. {
  1077. vap_offset[j][0] &= delay.Mask;
  1078. vap_offset[j][1] &= delay.Mask;
  1079. }
  1080. offset &= delay.Mask;
  1081. size_t maxoff{offset};
  1082. for(size_t j{0u};j < NUM_LINES;j++)
  1083. maxoff = maxz(maxoff, maxz(vap_offset[j][0], vap_offset[j][1]));
  1084. size_t td{minz(delay.Mask+1 - maxoff, todo - i)};
  1085. do {
  1086. fadeCount += 1.0f;
  1087. const float fade{fadeCount * fadeStep};
  1088. std::array<float,NUM_LINES> f;
  1089. for(size_t j{0u};j < NUM_LINES;j++)
  1090. f[j] = delay.Line[vap_offset[j][0]++][j]*(1.0f-fade) +
  1091. delay.Line[vap_offset[j][1]++][j]*fade;
  1092. for(size_t j{0u};j < NUM_LINES;j++)
  1093. {
  1094. const float input{samples[j][i]};
  1095. const float out{f[j] - feedCoeff*input};
  1096. f[j] = input + feedCoeff*out;
  1097. samples[j][i] = out;
  1098. }
  1099. ++i;
  1100. delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff);
  1101. } while(--td);
  1102. }
  1103. }
  1104. /* This generates early reflections.
  1105. *
  1106. * This is done by obtaining the primary reflections (those arriving from the
  1107. * same direction as the source) from the main delay line. These are
  1108. * attenuated and all-pass filtered (based on the diffusion parameter).
  1109. *
  1110. * The early lines are then fed in reverse (according to the approximately
  1111. * opposite spatial location of the A-Format lines) to create the secondary
  1112. * reflections (those arriving from the opposite direction as the source).
  1113. *
  1114. * The early response is then completed by combining the primary reflections
  1115. * with the delayed and attenuated output from the early lines.
  1116. *
  1117. * Finally, the early response is reversed, scattered (based on diffusion),
  1118. * and fed into the late reverb section of the main delay line.
  1119. *
  1120. * Two static specializations are used for transitional (cross-faded) delay
  1121. * line processing and non-transitional processing.
  1122. */
  1123. void ReverbState::earlyUnfaded(const size_t offset, const size_t todo)
  1124. {
  1125. const DelayLineI early_delay{mEarly.Delay};
  1126. const DelayLineI main_delay{mDelay};
  1127. const float mixX{mMixX};
  1128. const float mixY{mMixY};
  1129. ASSUME(todo > 0);
  1130. /* First, load decorrelated samples from the main delay line as the primary
  1131. * reflections.
  1132. */
  1133. for(size_t j{0u};j < NUM_LINES;j++)
  1134. {
  1135. size_t early_delay_tap{offset - mEarlyDelayTap[j][0]};
  1136. const float coeff{mEarlyDelayCoeff[j][0]};
  1137. for(size_t i{0u};i < todo;)
  1138. {
  1139. early_delay_tap &= main_delay.Mask;
  1140. size_t td{minz(main_delay.Mask+1 - early_delay_tap, todo - i)};
  1141. do {
  1142. mTempSamples[j][i++] = main_delay.Line[early_delay_tap++][j] * coeff;
  1143. } while(--td);
  1144. }
  1145. }
  1146. /* Apply a vector all-pass, to help color the initial reflections based on
  1147. * the diffusion strength.
  1148. */
  1149. mEarly.VecAp.processUnfaded(mTempSamples, offset, mixX, mixY, todo);
  1150. /* Apply a delay and bounce to generate secondary reflections, combine with
  1151. * the primary reflections and write out the result for mixing.
  1152. */
  1153. for(size_t j{0u};j < NUM_LINES;j++)
  1154. {
  1155. size_t feedb_tap{offset - mEarly.Offset[j][0]};
  1156. const float feedb_coeff{mEarly.Coeff[j][0]};
  1157. float *out{mEarlySamples[j].data()};
  1158. for(size_t i{0u};i < todo;)
  1159. {
  1160. feedb_tap &= early_delay.Mask;
  1161. size_t td{minz(early_delay.Mask+1 - feedb_tap, todo - i)};
  1162. do {
  1163. out[i] = mTempSamples[j][i] + early_delay.Line[feedb_tap++][j]*feedb_coeff;
  1164. ++i;
  1165. } while(--td);
  1166. }
  1167. }
  1168. for(size_t j{0u};j < NUM_LINES;j++)
  1169. early_delay.write(offset, NUM_LINES-1-j, mTempSamples[j].data(), todo);
  1170. /* Also write the result back to the main delay line for the late reverb
  1171. * stage to pick up at the appropriate time, appplying a scatter and
  1172. * bounce to improve the initial diffusion in the late reverb.
  1173. */
  1174. const size_t late_feed_tap{offset - mLateFeedTap};
  1175. VectorScatterRevDelayIn(main_delay, late_feed_tap, mixX, mixY, mEarlySamples, todo);
  1176. }
  1177. void ReverbState::earlyFaded(const size_t offset, const size_t todo, const float fade,
  1178. const float fadeStep)
  1179. {
  1180. const DelayLineI early_delay{mEarly.Delay};
  1181. const DelayLineI main_delay{mDelay};
  1182. const float mixX{mMixX};
  1183. const float mixY{mMixY};
  1184. ASSUME(todo > 0);
  1185. for(size_t j{0u};j < NUM_LINES;j++)
  1186. {
  1187. size_t early_delay_tap0{offset - mEarlyDelayTap[j][0]};
  1188. size_t early_delay_tap1{offset - mEarlyDelayTap[j][1]};
  1189. const float oldCoeff{mEarlyDelayCoeff[j][0]};
  1190. const float oldCoeffStep{-oldCoeff * fadeStep};
  1191. const float newCoeffStep{mEarlyDelayCoeff[j][1] * fadeStep};
  1192. float fadeCount{fade};
  1193. for(size_t i{0u};i < todo;)
  1194. {
  1195. early_delay_tap0 &= main_delay.Mask;
  1196. early_delay_tap1 &= main_delay.Mask;
  1197. size_t td{minz(main_delay.Mask+1 - maxz(early_delay_tap0, early_delay_tap1), todo-i)};
  1198. do {
  1199. fadeCount += 1.0f;
  1200. const float fade0{oldCoeff + oldCoeffStep*fadeCount};
  1201. const float fade1{newCoeffStep*fadeCount};
  1202. mTempSamples[j][i++] =
  1203. main_delay.Line[early_delay_tap0++][j]*fade0 +
  1204. main_delay.Line[early_delay_tap1++][j]*fade1;
  1205. } while(--td);
  1206. }
  1207. }
  1208. mEarly.VecAp.processFaded(mTempSamples, offset, mixX, mixY, fade, fadeStep, todo);
  1209. for(size_t j{0u};j < NUM_LINES;j++)
  1210. {
  1211. size_t feedb_tap0{offset - mEarly.Offset[j][0]};
  1212. size_t feedb_tap1{offset - mEarly.Offset[j][1]};
  1213. const float feedb_oldCoeff{mEarly.Coeff[j][0]};
  1214. const float feedb_oldCoeffStep{-feedb_oldCoeff * fadeStep};
  1215. const float feedb_newCoeffStep{mEarly.Coeff[j][1] * fadeStep};
  1216. float *out{mEarlySamples[j].data()};
  1217. float fadeCount{fade};
  1218. for(size_t i{0u};i < todo;)
  1219. {
  1220. feedb_tap0 &= early_delay.Mask;
  1221. feedb_tap1 &= early_delay.Mask;
  1222. size_t td{minz(early_delay.Mask+1 - maxz(feedb_tap0, feedb_tap1), todo - i)};
  1223. do {
  1224. fadeCount += 1.0f;
  1225. const float fade0{feedb_oldCoeff + feedb_oldCoeffStep*fadeCount};
  1226. const float fade1{feedb_newCoeffStep*fadeCount};
  1227. out[i] = mTempSamples[j][i] +
  1228. early_delay.Line[feedb_tap0++][j]*fade0 +
  1229. early_delay.Line[feedb_tap1++][j]*fade1;
  1230. ++i;
  1231. } while(--td);
  1232. }
  1233. }
  1234. for(size_t j{0u};j < NUM_LINES;j++)
  1235. early_delay.write(offset, NUM_LINES-1-j, mTempSamples[j].data(), todo);
  1236. const size_t late_feed_tap{offset - mLateFeedTap};
  1237. VectorScatterRevDelayIn(main_delay, late_feed_tap, mixX, mixY, mEarlySamples, todo);
  1238. }
  1239. void Modulation::calcDelays(size_t todo)
  1240. {
  1241. constexpr float mod_scale{al::numbers::pi_v<float> * 2.0f / MOD_FRACONE};
  1242. uint idx{Index};
  1243. const uint step{Step};
  1244. const float depth{Depth[0]};
  1245. for(size_t i{0};i < todo;++i)
  1246. {
  1247. idx += step;
  1248. const float lfo{std::sin(static_cast<float>(idx&MOD_FRACMASK) * mod_scale)};
  1249. ModDelays[i] = (lfo+1.0f) * depth;
  1250. }
  1251. Index = idx;
  1252. }
  1253. void Modulation::calcFadedDelays(size_t todo, float fadeCount, float fadeStep)
  1254. {
  1255. constexpr float mod_scale{al::numbers::pi_v<float> * 2.0f / MOD_FRACONE};
  1256. uint idx{Index};
  1257. const uint step{Step};
  1258. const float depth{Depth[0]};
  1259. const float depthStep{(Depth[1]-depth) * fadeStep};
  1260. for(size_t i{0};i < todo;++i)
  1261. {
  1262. fadeCount += 1.0f;
  1263. idx += step;
  1264. const float lfo{std::sin(static_cast<float>(idx&MOD_FRACMASK) * mod_scale)};
  1265. ModDelays[i] = (lfo+1.0f) * (depth + depthStep*fadeCount);
  1266. }
  1267. Index = idx;
  1268. }
  1269. /* This generates the reverb tail using a modified feed-back delay network
  1270. * (FDN).
  1271. *
  1272. * Results from the early reflections are mixed with the output from the
  1273. * modulated late delay lines.
  1274. *
  1275. * The late response is then completed by T60 and all-pass filtering the mix.
  1276. *
  1277. * Finally, the lines are reversed (so they feed their opposite directions)
  1278. * and scattered with the FDN matrix before re-feeding the delay lines.
  1279. *
  1280. * Two variations are made, one for for transitional (cross-faded) delay line
  1281. * processing and one for non-transitional processing.
  1282. */
  1283. void ReverbState::lateUnfaded(const size_t offset, const size_t todo)
  1284. {
  1285. const DelayLineI late_delay{mLate.Delay};
  1286. const DelayLineI main_delay{mDelay};
  1287. const float mixX{mMixX};
  1288. const float mixY{mMixY};
  1289. ASSUME(todo > 0);
  1290. /* First, calculate the modulated delays for the late feedback. */
  1291. mLate.Mod.calcDelays(todo);
  1292. /* Next, load decorrelated samples from the main and feedback delay lines.
  1293. * Filter the signal to apply its frequency-dependent decay.
  1294. */
  1295. for(size_t j{0u};j < NUM_LINES;j++)
  1296. {
  1297. size_t late_delay_tap{offset - mLateDelayTap[j][0]};
  1298. size_t late_feedb_tap{offset - mLate.Offset[j][0]};
  1299. const float midGain{mLate.T60[j].MidGain[0]};
  1300. const float densityGain{mLate.DensityGain[0] * midGain};
  1301. for(size_t i{0u};i < todo;)
  1302. {
  1303. late_delay_tap &= main_delay.Mask;
  1304. size_t td{minz(todo - i, main_delay.Mask+1 - late_delay_tap)};
  1305. do {
  1306. /* Calculate the read offset and fraction between it and the
  1307. * next sample.
  1308. */
  1309. const float fdelay{mLate.Mod.ModDelays[i]};
  1310. const size_t delay{float2uint(fdelay)};
  1311. const float frac{fdelay - static_cast<float>(delay)};
  1312. /* Feed the delay line with the late feedback sample, and get
  1313. * the two samples crossed by the delayed offset.
  1314. */
  1315. const float out0{late_delay.Line[(late_feedb_tap-delay) & late_delay.Mask][j]};
  1316. const float out1{late_delay.Line[(late_feedb_tap-delay-1) & late_delay.Mask][j]};
  1317. ++late_feedb_tap;
  1318. /* The output is obtained by linearly interpolating the two
  1319. * samples that were acquired above, and combined with the main
  1320. * delay tap.
  1321. */
  1322. mTempSamples[j][i] = lerpf(out0, out1, frac)*midGain +
  1323. main_delay.Line[late_delay_tap++][j]*densityGain;
  1324. ++i;
  1325. } while(--td);
  1326. }
  1327. mLate.T60[j].process({mTempSamples[j].data(), todo});
  1328. }
  1329. /* Apply a vector all-pass to improve micro-surface diffusion, and write
  1330. * out the results for mixing.
  1331. */
  1332. mLate.VecAp.processUnfaded(mTempSamples, offset, mixX, mixY, todo);
  1333. for(size_t j{0u};j < NUM_LINES;j++)
  1334. std::copy_n(mTempSamples[j].begin(), todo, mLateSamples[j].begin());
  1335. /* Finally, scatter and bounce the results to refeed the feedback buffer. */
  1336. VectorScatterRevDelayIn(late_delay, offset, mixX, mixY, mTempSamples, todo);
  1337. }
  1338. void ReverbState::lateFaded(const size_t offset, const size_t todo, const float fade,
  1339. const float fadeStep)
  1340. {
  1341. const DelayLineI late_delay{mLate.Delay};
  1342. const DelayLineI main_delay{mDelay};
  1343. const float mixX{mMixX};
  1344. const float mixY{mMixY};
  1345. ASSUME(todo > 0);
  1346. mLate.Mod.calcFadedDelays(todo, fade, fadeStep);
  1347. for(size_t j{0u};j < NUM_LINES;j++)
  1348. {
  1349. const float oldMidGain{mLate.T60[j].MidGain[0]};
  1350. const float midGain{mLate.T60[j].MidGain[1]};
  1351. const float oldMidStep{-oldMidGain * fadeStep};
  1352. const float midStep{midGain * fadeStep};
  1353. const float oldDensityGain{mLate.DensityGain[0] * oldMidGain};
  1354. const float densityGain{mLate.DensityGain[1] * midGain};
  1355. const float oldDensityStep{-oldDensityGain * fadeStep};
  1356. const float densityStep{densityGain * fadeStep};
  1357. size_t late_delay_tap0{offset - mLateDelayTap[j][0]};
  1358. size_t late_delay_tap1{offset - mLateDelayTap[j][1]};
  1359. size_t late_feedb_tap0{offset - mLate.Offset[j][0]};
  1360. size_t late_feedb_tap1{offset - mLate.Offset[j][1]};
  1361. float fadeCount{fade};
  1362. for(size_t i{0u};i < todo;)
  1363. {
  1364. late_delay_tap0 &= main_delay.Mask;
  1365. late_delay_tap1 &= main_delay.Mask;
  1366. size_t td{minz(todo - i, main_delay.Mask+1 - maxz(late_delay_tap0, late_delay_tap1))};
  1367. do {
  1368. fadeCount += 1.0f;
  1369. const float fdelay{mLate.Mod.ModDelays[i]};
  1370. const size_t delay{float2uint(fdelay)};
  1371. const float frac{fdelay - static_cast<float>(delay)};
  1372. const float out00{late_delay.Line[(late_feedb_tap0-delay) & late_delay.Mask][j]};
  1373. const float out01{late_delay.Line[(late_feedb_tap0-delay-1) & late_delay.Mask][j]};
  1374. ++late_feedb_tap0;
  1375. const float out10{late_delay.Line[(late_feedb_tap1-delay) & late_delay.Mask][j]};
  1376. const float out11{late_delay.Line[(late_feedb_tap1-delay-1) & late_delay.Mask][j]};
  1377. ++late_feedb_tap1;
  1378. const float fade0{oldDensityGain + oldDensityStep*fadeCount};
  1379. const float fade1{densityStep*fadeCount};
  1380. const float gfade0{oldMidGain + oldMidStep*fadeCount};
  1381. const float gfade1{midStep*fadeCount};
  1382. mTempSamples[j][i] = lerpf(out00, out01, frac)*gfade0 +
  1383. lerpf(out10, out11, frac)*gfade1 +
  1384. main_delay.Line[late_delay_tap0++][j]*fade0 +
  1385. main_delay.Line[late_delay_tap1++][j]*fade1;
  1386. ++i;
  1387. } while(--td);
  1388. }
  1389. mLate.T60[j].process({mTempSamples[j].data(), todo});
  1390. }
  1391. mLate.VecAp.processFaded(mTempSamples, offset, mixX, mixY, fade, fadeStep, todo);
  1392. for(size_t j{0u};j < NUM_LINES;j++)
  1393. std::copy_n(mTempSamples[j].begin(), todo, mLateSamples[j].begin());
  1394. VectorScatterRevDelayIn(late_delay, offset, mixX, mixY, mTempSamples, todo);
  1395. }
  1396. void ReverbState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  1397. {
  1398. size_t offset{mOffset};
  1399. ASSUME(samplesToDo > 0);
  1400. /* Convert B-Format to A-Format for processing. */
  1401. const size_t numInput{minz(samplesIn.size(), NUM_LINES)};
  1402. const al::span<float> tmpspan{al::assume_aligned<16>(mTempLine.data()), samplesToDo};
  1403. for(size_t c{0u};c < NUM_LINES;c++)
  1404. {
  1405. std::fill(tmpspan.begin(), tmpspan.end(), 0.0f);
  1406. for(size_t i{0};i < numInput;++i)
  1407. {
  1408. const float gain{B2A[c][i]};
  1409. const float *RESTRICT input{al::assume_aligned<16>(samplesIn[i].data())};
  1410. for(float &sample : tmpspan)
  1411. {
  1412. sample += *input * gain;
  1413. ++input;
  1414. }
  1415. }
  1416. /* Band-pass the incoming samples and feed the initial delay line. */
  1417. DualBiquad{mFilter[c].Lp, mFilter[c].Hp}.process(tmpspan, tmpspan.data());
  1418. mDelay.write(offset, c, tmpspan.cbegin(), samplesToDo);
  1419. }
  1420. /* Process reverb for these samples. */
  1421. if LIKELY(!mDoFading)
  1422. {
  1423. for(size_t base{0};base < samplesToDo;)
  1424. {
  1425. /* Calculate the number of samples we can do this iteration. */
  1426. size_t todo{minz(samplesToDo - base, mMaxUpdate[0])};
  1427. /* Some mixers require maintaining a 4-sample alignment, so ensure
  1428. * that if it's not the last iteration.
  1429. */
  1430. if(base+todo < samplesToDo) todo &= ~size_t{3};
  1431. ASSUME(todo > 0);
  1432. /* Generate non-faded early reflections and late reverb. */
  1433. earlyUnfaded(offset, todo);
  1434. lateUnfaded(offset, todo);
  1435. /* Finally, mix early reflections and late reverb. */
  1436. mixOut(samplesOut, samplesToDo-base, base, todo);
  1437. offset += todo;
  1438. base += todo;
  1439. }
  1440. }
  1441. else
  1442. {
  1443. const float fadeStep{1.0f / static_cast<float>(samplesToDo)};
  1444. for(size_t base{0};base < samplesToDo;)
  1445. {
  1446. size_t todo{minz(samplesToDo - base, minz(mMaxUpdate[0], mMaxUpdate[1]))};
  1447. if(base+todo < samplesToDo) todo &= ~size_t{3};
  1448. ASSUME(todo > 0);
  1449. /* Generate cross-faded early reflections and late reverb. */
  1450. auto fadeCount = static_cast<float>(base);
  1451. earlyFaded(offset, todo, fadeCount, fadeStep);
  1452. lateFaded(offset, todo, fadeCount, fadeStep);
  1453. mixOut(samplesOut, samplesToDo-base, base, todo);
  1454. offset += todo;
  1455. base += todo;
  1456. }
  1457. /* Update the cross-fading delay line taps. */
  1458. for(size_t c{0u};c < NUM_LINES;c++)
  1459. {
  1460. mEarlyDelayTap[c][0] = mEarlyDelayTap[c][1];
  1461. mEarlyDelayCoeff[c][0] = mEarlyDelayCoeff[c][1];
  1462. mLateDelayTap[c][0] = mLateDelayTap[c][1];
  1463. mEarly.VecAp.Offset[c][0] = mEarly.VecAp.Offset[c][1];
  1464. mEarly.Offset[c][0] = mEarly.Offset[c][1];
  1465. mEarly.Coeff[c][0] = mEarly.Coeff[c][1];
  1466. mLate.Offset[c][0] = mLate.Offset[c][1];
  1467. mLate.T60[c].MidGain[0] = mLate.T60[c].MidGain[1];
  1468. mLate.VecAp.Offset[c][0] = mLate.VecAp.Offset[c][1];
  1469. }
  1470. mLate.DensityGain[0] = mLate.DensityGain[1];
  1471. mLate.Mod.Depth[0] = mLate.Mod.Depth[1];
  1472. mMaxUpdate[0] = mMaxUpdate[1];
  1473. mDoFading = false;
  1474. }
  1475. mOffset = offset;
  1476. }
  1477. struct ReverbStateFactory final : public EffectStateFactory {
  1478. al::intrusive_ptr<EffectState> create() override
  1479. { return al::intrusive_ptr<EffectState>{new ReverbState{}}; }
  1480. };
  1481. struct StdReverbStateFactory final : public EffectStateFactory {
  1482. al::intrusive_ptr<EffectState> create() override
  1483. { return al::intrusive_ptr<EffectState>{new ReverbState{}}; }
  1484. };
  1485. } // namespace
  1486. EffectStateFactory *ReverbStateFactory_getFactory()
  1487. {
  1488. static ReverbStateFactory ReverbFactory{};
  1489. return &ReverbFactory;
  1490. }
  1491. EffectStateFactory *StdReverbStateFactory_getFactory()
  1492. {
  1493. static StdReverbStateFactory ReverbFactory{};
  1494. return &ReverbFactory;
  1495. }