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

1723 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. using MixOutT = void (ReverbState::*)(const al::span<FloatBufferLine> samplesOut,
  390. const size_t counter, const size_t offset, const size_t todo);
  391. MixOutT mMixOut{&ReverbState::MixOutPlain};
  392. std::array<float,MaxAmbiOrder+1> mOrderScales{};
  393. std::array<std::array<BandSplitter,NUM_LINES>,2> mAmbiSplitter;
  394. static void DoMixRow(const al::span<float> OutBuffer, const al::span<const float> Gains,
  395. const float *InSamples, const size_t InStride)
  396. {
  397. std::fill(OutBuffer.begin(), OutBuffer.end(), 0.0f);
  398. for(const float gain : Gains)
  399. {
  400. const float *RESTRICT input{al::assume_aligned<16>(InSamples)};
  401. InSamples += InStride;
  402. if(!(std::fabs(gain) > GainSilenceThreshold))
  403. continue;
  404. for(float &sample : OutBuffer)
  405. {
  406. sample += *input * gain;
  407. ++input;
  408. }
  409. }
  410. }
  411. void MixOutPlain(const al::span<FloatBufferLine> samplesOut, const size_t counter,
  412. const size_t offset, const size_t todo)
  413. {
  414. ASSUME(todo > 0);
  415. /* Convert back to B-Format, and mix the results to output. */
  416. const al::span<float> tmpspan{al::assume_aligned<16>(mTempLine.data()), todo};
  417. for(size_t c{0u};c < NUM_LINES;c++)
  418. {
  419. DoMixRow(tmpspan, EarlyA2B[c], mEarlySamples[0].data(), mEarlySamples[0].size());
  420. MixSamples(tmpspan, samplesOut, mEarly.CurrentGain[c], mEarly.PanGain[c], counter,
  421. offset);
  422. }
  423. for(size_t c{0u};c < NUM_LINES;c++)
  424. {
  425. DoMixRow(tmpspan, LateA2B[c], mLateSamples[0].data(), mLateSamples[0].size());
  426. MixSamples(tmpspan, samplesOut, mLate.CurrentGain[c], mLate.PanGain[c], counter,
  427. offset);
  428. }
  429. }
  430. void MixOutAmbiUp(const al::span<FloatBufferLine> samplesOut, const size_t counter,
  431. const size_t offset, const size_t todo)
  432. {
  433. ASSUME(todo > 0);
  434. const al::span<float> tmpspan{al::assume_aligned<16>(mTempLine.data()), todo};
  435. for(size_t c{0u};c < NUM_LINES;c++)
  436. {
  437. DoMixRow(tmpspan, EarlyA2B[c], mEarlySamples[0].data(), mEarlySamples[0].size());
  438. /* Apply scaling to the B-Format's HF response to "upsample" it to
  439. * higher-order output.
  440. */
  441. const float hfscale{(c==0) ? mOrderScales[0] : mOrderScales[1]};
  442. mAmbiSplitter[0][c].processHfScale(tmpspan, hfscale);
  443. MixSamples(tmpspan, samplesOut, mEarly.CurrentGain[c], mEarly.PanGain[c], counter,
  444. offset);
  445. }
  446. for(size_t c{0u};c < NUM_LINES;c++)
  447. {
  448. DoMixRow(tmpspan, LateA2B[c], mLateSamples[0].data(), mLateSamples[0].size());
  449. const float hfscale{(c==0) ? mOrderScales[0] : mOrderScales[1]};
  450. mAmbiSplitter[1][c].processHfScale(tmpspan, hfscale);
  451. MixSamples(tmpspan, samplesOut, mLate.CurrentGain[c], mLate.PanGain[c], counter,
  452. offset);
  453. }
  454. }
  455. void allocLines(const float frequency);
  456. void updateDelayLine(const float earlyDelay, const float lateDelay, const float density_mult,
  457. const float decayTime, const float frequency);
  458. void update3DPanning(const float *ReflectionsPan, const float *LateReverbPan,
  459. const float earlyGain, const float lateGain, const EffectTarget &target);
  460. void earlyUnfaded(const size_t offset, const size_t todo);
  461. void earlyFaded(const size_t offset, const size_t todo, const float fade,
  462. const float fadeStep);
  463. void lateUnfaded(const size_t offset, const size_t todo);
  464. void lateFaded(const size_t offset, const size_t todo, const float fade,
  465. const float fadeStep);
  466. void deviceUpdate(const DeviceBase *device, const Buffer &buffer) override;
  467. void update(const ContextBase *context, const EffectSlot *slot, const EffectProps *props,
  468. const EffectTarget target) override;
  469. void process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn,
  470. const al::span<FloatBufferLine> samplesOut) override;
  471. DEF_NEWDEL(ReverbState)
  472. };
  473. /**************************************
  474. * Device Update *
  475. **************************************/
  476. inline float CalcDelayLengthMult(float density)
  477. { return maxf(5.0f, std::cbrt(density*DENSITY_SCALE)); }
  478. /* Calculates the delay line metrics and allocates the shared sample buffer
  479. * for all lines given the sample rate (frequency).
  480. */
  481. void ReverbState::allocLines(const float frequency)
  482. {
  483. /* All delay line lengths are calculated to accomodate the full range of
  484. * lengths given their respective paramters.
  485. */
  486. size_t totalSamples{0u};
  487. /* Multiplier for the maximum density value, i.e. density=1, which is
  488. * actually the least density...
  489. */
  490. const float multiplier{CalcDelayLengthMult(1.0f)};
  491. /* The main delay length includes the maximum early reflection delay, the
  492. * largest early tap width, the maximum late reverb delay, and the
  493. * largest late tap width. Finally, it must also be extended by the
  494. * update size (BufferLineSize) for block processing.
  495. */
  496. constexpr float LateLineDiffAvg{(LATE_LINE_LENGTHS.back()-LATE_LINE_LENGTHS.front()) /
  497. float{NUM_LINES}};
  498. float length{ReverbMaxReflectionsDelay + EARLY_TAP_LENGTHS.back()*multiplier +
  499. ReverbMaxLateReverbDelay + LateLineDiffAvg*multiplier};
  500. totalSamples += mDelay.calcLineLength(length, totalSamples, frequency, BufferLineSize);
  501. /* The early vector all-pass line. */
  502. length = EARLY_ALLPASS_LENGTHS.back() * multiplier;
  503. totalSamples += mEarly.VecAp.Delay.calcLineLength(length, totalSamples, frequency, 0);
  504. /* The early reflection line. */
  505. length = EARLY_LINE_LENGTHS.back() * multiplier;
  506. totalSamples += mEarly.Delay.calcLineLength(length, totalSamples, frequency, 0);
  507. /* The late vector all-pass line. */
  508. length = LATE_ALLPASS_LENGTHS.back() * multiplier;
  509. totalSamples += mLate.VecAp.Delay.calcLineLength(length, totalSamples, frequency, 0);
  510. /* The modulator's line length is calculated from the maximum modulation
  511. * time and depth coefficient, and halfed for the low-to-high frequency
  512. * swing.
  513. */
  514. constexpr float max_mod_delay{MaxModulationTime*MODULATION_DEPTH_COEFF / 2.0f};
  515. /* The late delay lines are calculated from the largest maximum density
  516. * line length, and the maximum modulation delay. An additional sample is
  517. * added to keep it stable when there is no modulation.
  518. */
  519. length = LATE_LINE_LENGTHS.back()*multiplier + max_mod_delay;
  520. totalSamples += mLate.Delay.calcLineLength(length, totalSamples, frequency, 1);
  521. if(totalSamples != mSampleBuffer.size())
  522. decltype(mSampleBuffer)(totalSamples).swap(mSampleBuffer);
  523. /* Clear the sample buffer. */
  524. std::fill(mSampleBuffer.begin(), mSampleBuffer.end(), decltype(mSampleBuffer)::value_type{});
  525. /* Update all delays to reflect the new sample buffer. */
  526. mDelay.realizeLineOffset(mSampleBuffer.data());
  527. mEarly.VecAp.Delay.realizeLineOffset(mSampleBuffer.data());
  528. mEarly.Delay.realizeLineOffset(mSampleBuffer.data());
  529. mLate.VecAp.Delay.realizeLineOffset(mSampleBuffer.data());
  530. mLate.Delay.realizeLineOffset(mSampleBuffer.data());
  531. }
  532. void ReverbState::deviceUpdate(const DeviceBase *device, const Buffer&)
  533. {
  534. const auto frequency = static_cast<float>(device->Frequency);
  535. /* Allocate the delay lines. */
  536. allocLines(frequency);
  537. const float multiplier{CalcDelayLengthMult(1.0f)};
  538. /* The late feed taps are set a fixed position past the latest delay tap. */
  539. mLateFeedTap = float2uint((ReverbMaxReflectionsDelay + EARLY_TAP_LENGTHS.back()*multiplier) *
  540. frequency);
  541. /* Clear filters and gain coefficients since the delay lines were all just
  542. * cleared (if not reallocated).
  543. */
  544. for(auto &filter : mFilter)
  545. {
  546. filter.Lp.clear();
  547. filter.Hp.clear();
  548. }
  549. for(auto &coeff : mEarlyDelayCoeff)
  550. std::fill(std::begin(coeff), std::end(coeff), 0.0f);
  551. for(auto &coeff : mEarly.Coeff)
  552. std::fill(std::begin(coeff), std::end(coeff), 0.0f);
  553. mLate.DensityGain[0] = 0.0f;
  554. mLate.DensityGain[1] = 0.0f;
  555. for(auto &t60 : mLate.T60)
  556. {
  557. t60.MidGain[0] = 0.0f;
  558. t60.MidGain[1] = 0.0f;
  559. t60.HFFilter.clear();
  560. t60.LFFilter.clear();
  561. }
  562. mLate.Mod.Index = 0;
  563. mLate.Mod.Step = 1;
  564. std::fill(std::begin(mLate.Mod.Depth), std::end(mLate.Mod.Depth), 0.0f);
  565. for(auto &gains : mEarly.CurrentGain)
  566. std::fill(std::begin(gains), std::end(gains), 0.0f);
  567. for(auto &gains : mEarly.PanGain)
  568. std::fill(std::begin(gains), std::end(gains), 0.0f);
  569. for(auto &gains : mLate.CurrentGain)
  570. std::fill(std::begin(gains), std::end(gains), 0.0f);
  571. for(auto &gains : mLate.PanGain)
  572. std::fill(std::begin(gains), std::end(gains), 0.0f);
  573. /* Reset fading and offset base. */
  574. mDoFading = true;
  575. std::fill(std::begin(mMaxUpdate), std::end(mMaxUpdate), MAX_UPDATE_SAMPLES);
  576. mOffset = 0;
  577. if(device->mAmbiOrder > 1)
  578. {
  579. mMixOut = &ReverbState::MixOutAmbiUp;
  580. mOrderScales = AmbiScale::GetHFOrderScales(1, device->mAmbiOrder);
  581. }
  582. else
  583. {
  584. mMixOut = &ReverbState::MixOutPlain;
  585. mOrderScales.fill(1.0f);
  586. }
  587. mAmbiSplitter[0][0].init(device->mXOverFreq / frequency);
  588. std::fill(mAmbiSplitter[0].begin()+1, mAmbiSplitter[0].end(), mAmbiSplitter[0][0]);
  589. std::fill(mAmbiSplitter[1].begin(), mAmbiSplitter[1].end(), mAmbiSplitter[0][0]);
  590. }
  591. /**************************************
  592. * Effect Update *
  593. **************************************/
  594. /* Calculate a decay coefficient given the length of each cycle and the time
  595. * until the decay reaches -60 dB.
  596. */
  597. inline float CalcDecayCoeff(const float length, const float decayTime)
  598. { return std::pow(ReverbDecayGain, length/decayTime); }
  599. /* Calculate a decay length from a coefficient and the time until the decay
  600. * reaches -60 dB.
  601. */
  602. inline float CalcDecayLength(const float coeff, const float decayTime)
  603. {
  604. constexpr float log10_decaygain{-3.0f/*std::log10(ReverbDecayGain)*/};
  605. return std::log10(coeff) * decayTime / log10_decaygain;
  606. }
  607. /* Calculate an attenuation to be applied to the input of any echo models to
  608. * compensate for modal density and decay time.
  609. */
  610. inline float CalcDensityGain(const float a)
  611. {
  612. /* The energy of a signal can be obtained by finding the area under the
  613. * squared signal. This takes the form of Sum(x_n^2), where x is the
  614. * amplitude for the sample n.
  615. *
  616. * Decaying feedback matches exponential decay of the form Sum(a^n),
  617. * where a is the attenuation coefficient, and n is the sample. The area
  618. * under this decay curve can be calculated as: 1 / (1 - a).
  619. *
  620. * Modifying the above equation to find the area under the squared curve
  621. * (for energy) yields: 1 / (1 - a^2). Input attenuation can then be
  622. * calculated by inverting the square root of this approximation,
  623. * yielding: 1 / sqrt(1 / (1 - a^2)), simplified to: sqrt(1 - a^2).
  624. */
  625. return std::sqrt(1.0f - a*a);
  626. }
  627. /* Calculate the scattering matrix coefficients given a diffusion factor. */
  628. inline void CalcMatrixCoeffs(const float diffusion, float *x, float *y)
  629. {
  630. /* The matrix is of order 4, so n is sqrt(4 - 1). */
  631. constexpr float n{al::numbers::sqrt3_v<float>};
  632. const float t{diffusion * std::atan(n)};
  633. /* Calculate the first mixing matrix coefficient. */
  634. *x = std::cos(t);
  635. /* Calculate the second mixing matrix coefficient. */
  636. *y = std::sin(t) / n;
  637. }
  638. /* Calculate the limited HF ratio for use with the late reverb low-pass
  639. * filters.
  640. */
  641. float CalcLimitedHfRatio(const float hfRatio, const float airAbsorptionGainHF,
  642. const float decayTime)
  643. {
  644. /* Find the attenuation due to air absorption in dB (converting delay
  645. * time to meters using the speed of sound). Then reversing the decay
  646. * equation, solve for HF ratio. The delay length is cancelled out of
  647. * the equation, so it can be calculated once for all lines.
  648. */
  649. float limitRatio{1.0f / SpeedOfSoundMetersPerSec /
  650. CalcDecayLength(airAbsorptionGainHF, decayTime)};
  651. /* Using the limit calculated above, apply the upper bound to the HF ratio. */
  652. return minf(limitRatio, hfRatio);
  653. }
  654. /* Calculates the 3-band T60 damping coefficients for a particular delay line
  655. * of specified length, using a combination of two shelf filter sections given
  656. * decay times for each band split at two reference frequencies.
  657. */
  658. void T60Filter::calcCoeffs(const float length, const float lfDecayTime,
  659. const float mfDecayTime, const float hfDecayTime, const float lf0norm,
  660. const float hf0norm)
  661. {
  662. const float mfGain{CalcDecayCoeff(length, mfDecayTime)};
  663. const float lfGain{CalcDecayCoeff(length, lfDecayTime) / mfGain};
  664. const float hfGain{CalcDecayCoeff(length, hfDecayTime) / mfGain};
  665. MidGain[1] = mfGain;
  666. LFFilter.setParamsFromSlope(BiquadType::LowShelf, lf0norm, lfGain, 1.0f);
  667. HFFilter.setParamsFromSlope(BiquadType::HighShelf, hf0norm, hfGain, 1.0f);
  668. }
  669. /* Update the early reflection line lengths and gain coefficients. */
  670. void EarlyReflections::updateLines(const float density_mult, const float diffusion,
  671. const float decayTime, const float frequency)
  672. {
  673. /* Calculate the all-pass feed-back/forward coefficient. */
  674. VecAp.Coeff = diffusion*diffusion * InvSqrt2;
  675. for(size_t i{0u};i < NUM_LINES;i++)
  676. {
  677. /* Calculate the delay length of each all-pass line. */
  678. float length{EARLY_ALLPASS_LENGTHS[i] * density_mult};
  679. VecAp.Offset[i][1] = float2uint(length * frequency);
  680. /* Calculate the delay length of each delay line. */
  681. length = EARLY_LINE_LENGTHS[i] * density_mult;
  682. Offset[i][1] = float2uint(length * frequency);
  683. /* Calculate the gain (coefficient) for each line. */
  684. Coeff[i][1] = CalcDecayCoeff(length, decayTime);
  685. }
  686. }
  687. /* Update the EAX modulation step and depth. Keep in mind that this kind of
  688. * vibrato is additive and not multiplicative as one may expect. The downswing
  689. * will sound stronger than the upswing.
  690. */
  691. void Modulation::updateModulator(float modTime, float modDepth, float frequency)
  692. {
  693. /* Modulation is calculated in two parts.
  694. *
  695. * The modulation time effects the sinus rate, altering the speed of
  696. * frequency changes. An index is incremented for each sample with an
  697. * appropriate step size to generate an LFO, which will vary the feedback
  698. * delay over time.
  699. */
  700. Step = maxu(fastf2u(MOD_FRACONE / (frequency * modTime)), 1);
  701. /* The modulation depth effects the amount of frequency change over the
  702. * range of the sinus. It needs to be scaled by the modulation time so that
  703. * a given depth produces a consistent change in frequency over all ranges
  704. * of time. Since the depth is applied to a sinus value, it needs to be
  705. * halved once for the sinus range and again for the sinus swing in time
  706. * (half of it is spent decreasing the frequency, half is spent increasing
  707. * it).
  708. */
  709. if(modTime >= DefaultModulationTime)
  710. {
  711. /* To cancel the effects of a long period modulation on the late
  712. * reverberation, the amount of pitch should be varied (decreased)
  713. * according to the modulation time. The natural form is varying
  714. * inversely, in fact resulting in an invariant.
  715. */
  716. Depth[1] = MODULATION_DEPTH_COEFF / 4.0f * DefaultModulationTime * modDepth * frequency;
  717. }
  718. else
  719. Depth[1] = MODULATION_DEPTH_COEFF / 4.0f * modTime * modDepth * frequency;
  720. }
  721. /* Update the late reverb line lengths and T60 coefficients. */
  722. void LateReverb::updateLines(const float density_mult, const float diffusion,
  723. const float lfDecayTime, const float mfDecayTime, const float hfDecayTime,
  724. const float lf0norm, const float hf0norm, const float frequency)
  725. {
  726. /* Scaling factor to convert the normalized reference frequencies from
  727. * representing 0...freq to 0...max_reference.
  728. */
  729. constexpr float MaxHFReference{20000.0f};
  730. const float norm_weight_factor{frequency / MaxHFReference};
  731. const float late_allpass_avg{
  732. std::accumulate(LATE_ALLPASS_LENGTHS.begin(), LATE_ALLPASS_LENGTHS.end(), 0.0f) /
  733. float{NUM_LINES}};
  734. /* To compensate for changes in modal density and decay time of the late
  735. * reverb signal, the input is attenuated based on the maximal energy of
  736. * the outgoing signal. This approximation is used to keep the apparent
  737. * energy of the signal equal for all ranges of density and decay time.
  738. *
  739. * The average length of the delay lines is used to calculate the
  740. * attenuation coefficient.
  741. */
  742. float length{std::accumulate(LATE_LINE_LENGTHS.begin(), LATE_LINE_LENGTHS.end(), 0.0f) /
  743. float{NUM_LINES} + late_allpass_avg};
  744. length *= density_mult;
  745. /* The density gain calculation uses an average decay time weighted by
  746. * approximate bandwidth. This attempts to compensate for losses of energy
  747. * that reduce decay time due to scattering into highly attenuated bands.
  748. */
  749. const float decayTimeWeighted{
  750. lf0norm*norm_weight_factor*lfDecayTime +
  751. (hf0norm - lf0norm)*norm_weight_factor*mfDecayTime +
  752. (1.0f - hf0norm*norm_weight_factor)*hfDecayTime};
  753. DensityGain[1] = CalcDensityGain(CalcDecayCoeff(length, decayTimeWeighted));
  754. /* Calculate the all-pass feed-back/forward coefficient. */
  755. VecAp.Coeff = diffusion*diffusion * InvSqrt2;
  756. for(size_t i{0u};i < NUM_LINES;i++)
  757. {
  758. /* Calculate the delay length of each all-pass line. */
  759. length = LATE_ALLPASS_LENGTHS[i] * density_mult;
  760. VecAp.Offset[i][1] = float2uint(length * frequency);
  761. /* Calculate the delay length of each feedback delay line. */
  762. length = LATE_LINE_LENGTHS[i] * density_mult;
  763. Offset[i][1] = float2uint(length*frequency + 0.5f);
  764. /* Approximate the absorption that the vector all-pass would exhibit
  765. * given the current diffusion so we don't have to process a full T60
  766. * filter for each of its four lines. Also include the average
  767. * modulation delay (depth is half the max delay in samples).
  768. */
  769. length += lerpf(LATE_ALLPASS_LENGTHS[i], late_allpass_avg, diffusion)*density_mult +
  770. Mod.Depth[1]/frequency;
  771. /* Calculate the T60 damping coefficients for each line. */
  772. T60[i].calcCoeffs(length, lfDecayTime, mfDecayTime, hfDecayTime, lf0norm, hf0norm);
  773. }
  774. }
  775. /* Update the offsets for the main effect delay line. */
  776. void ReverbState::updateDelayLine(const float earlyDelay, const float lateDelay,
  777. const float density_mult, const float decayTime, const float frequency)
  778. {
  779. /* Early reflection taps are decorrelated by means of an average room
  780. * reflection approximation described above the definition of the taps.
  781. * This approximation is linear and so the above density multiplier can
  782. * be applied to adjust the width of the taps. A single-band decay
  783. * coefficient is applied to simulate initial attenuation and absorption.
  784. *
  785. * Late reverb taps are based on the late line lengths to allow a zero-
  786. * delay path and offsets that would continue the propagation naturally
  787. * into the late lines.
  788. */
  789. for(size_t i{0u};i < NUM_LINES;i++)
  790. {
  791. float length{EARLY_TAP_LENGTHS[i]*density_mult};
  792. mEarlyDelayTap[i][1] = float2uint((earlyDelay+length) * frequency);
  793. mEarlyDelayCoeff[i][1] = CalcDecayCoeff(length, decayTime);
  794. length = (LATE_LINE_LENGTHS[i] - LATE_LINE_LENGTHS.front())/float{NUM_LINES}*density_mult +
  795. lateDelay;
  796. mLateDelayTap[i][1] = mLateFeedTap + float2uint(length * frequency);
  797. }
  798. }
  799. /* Creates a transform matrix given a reverb vector. The vector pans the reverb
  800. * reflections toward the given direction, using its magnitude (up to 1) as a
  801. * focal strength. This function results in a B-Format transformation matrix
  802. * that spatially focuses the signal in the desired direction.
  803. */
  804. alu::Matrix GetTransformFromVector(const float *vec)
  805. {
  806. /* Normalize the panning vector according to the N3D scale, which has an
  807. * extra sqrt(3) term on the directional components. Converting from OpenAL
  808. * to B-Format also requires negating X (ACN 1) and Z (ACN 3). Note however
  809. * that the reverb panning vectors use left-handed coordinates, unlike the
  810. * rest of OpenAL which use right-handed. This is fixed by negating Z,
  811. * which cancels out with the B-Format Z negation.
  812. */
  813. float norm[3];
  814. float mag{std::sqrt(vec[0]*vec[0] + vec[1]*vec[1] + vec[2]*vec[2])};
  815. if(mag > 1.0f)
  816. {
  817. norm[0] = vec[0] / mag * -al::numbers::sqrt3_v<float>;
  818. norm[1] = vec[1] / mag * al::numbers::sqrt3_v<float>;
  819. norm[2] = vec[2] / mag * al::numbers::sqrt3_v<float>;
  820. mag = 1.0f;
  821. }
  822. else
  823. {
  824. /* If the magnitude is less than or equal to 1, just apply the sqrt(3)
  825. * term. There's no need to renormalize the magnitude since it would
  826. * just be reapplied in the matrix.
  827. */
  828. norm[0] = vec[0] * -al::numbers::sqrt3_v<float>;
  829. norm[1] = vec[1] * al::numbers::sqrt3_v<float>;
  830. norm[2] = vec[2] * al::numbers::sqrt3_v<float>;
  831. }
  832. return alu::Matrix{
  833. 1.0f, 0.0f, 0.0f, 0.0f,
  834. norm[0], 1.0f-mag, 0.0f, 0.0f,
  835. norm[1], 0.0f, 1.0f-mag, 0.0f,
  836. norm[2], 0.0f, 0.0f, 1.0f-mag
  837. };
  838. }
  839. /* Update the early and late 3D panning gains. */
  840. void ReverbState::update3DPanning(const float *ReflectionsPan, const float *LateReverbPan,
  841. const float earlyGain, const float lateGain, const EffectTarget &target)
  842. {
  843. /* Create matrices that transform a B-Format signal according to the
  844. * panning vectors.
  845. */
  846. const alu::Matrix earlymat{GetTransformFromVector(ReflectionsPan)};
  847. const alu::Matrix latemat{GetTransformFromVector(LateReverbPan)};
  848. mOutTarget = target.Main->Buffer;
  849. for(size_t i{0u};i < NUM_LINES;i++)
  850. {
  851. const float coeffs[MaxAmbiChannels]{earlymat[0][i], earlymat[1][i], earlymat[2][i],
  852. earlymat[3][i]};
  853. ComputePanGains(target.Main, coeffs, earlyGain, mEarly.PanGain[i]);
  854. }
  855. for(size_t i{0u};i < NUM_LINES;i++)
  856. {
  857. const float coeffs[MaxAmbiChannels]{latemat[0][i], latemat[1][i], latemat[2][i],
  858. latemat[3][i]};
  859. ComputePanGains(target.Main, coeffs, lateGain, mLate.PanGain[i]);
  860. }
  861. }
  862. void ReverbState::update(const ContextBase *Context, const EffectSlot *Slot,
  863. const EffectProps *props, const EffectTarget target)
  864. {
  865. const DeviceBase *Device{Context->mDevice};
  866. const auto frequency = static_cast<float>(Device->Frequency);
  867. /* Calculate the master filters */
  868. float hf0norm{minf(props->Reverb.HFReference/frequency, 0.49f)};
  869. mFilter[0].Lp.setParamsFromSlope(BiquadType::HighShelf, hf0norm, props->Reverb.GainHF, 1.0f);
  870. float lf0norm{minf(props->Reverb.LFReference/frequency, 0.49f)};
  871. mFilter[0].Hp.setParamsFromSlope(BiquadType::LowShelf, lf0norm, props->Reverb.GainLF, 1.0f);
  872. for(size_t i{1u};i < NUM_LINES;i++)
  873. {
  874. mFilter[i].Lp.copyParamsFrom(mFilter[0].Lp);
  875. mFilter[i].Hp.copyParamsFrom(mFilter[0].Hp);
  876. }
  877. /* The density-based room size (delay length) multiplier. */
  878. const float density_mult{CalcDelayLengthMult(props->Reverb.Density)};
  879. /* Update the main effect delay and associated taps. */
  880. updateDelayLine(props->Reverb.ReflectionsDelay, props->Reverb.LateReverbDelay,
  881. density_mult, props->Reverb.DecayTime, frequency);
  882. /* Update the early lines. */
  883. mEarly.updateLines(density_mult, props->Reverb.Diffusion, props->Reverb.DecayTime, frequency);
  884. /* Get the mixing matrix coefficients. */
  885. CalcMatrixCoeffs(props->Reverb.Diffusion, &mMixX, &mMixY);
  886. /* If the HF limit parameter is flagged, calculate an appropriate limit
  887. * based on the air absorption parameter.
  888. */
  889. float hfRatio{props->Reverb.DecayHFRatio};
  890. if(props->Reverb.DecayHFLimit && props->Reverb.AirAbsorptionGainHF < 1.0f)
  891. hfRatio = CalcLimitedHfRatio(hfRatio, props->Reverb.AirAbsorptionGainHF,
  892. props->Reverb.DecayTime);
  893. /* Calculate the LF/HF decay times. */
  894. constexpr float MinDecayTime{0.1f}, MaxDecayTime{20.0f};
  895. const float lfDecayTime{clampf(props->Reverb.DecayTime*props->Reverb.DecayLFRatio,
  896. MinDecayTime, MaxDecayTime)};
  897. const float hfDecayTime{clampf(props->Reverb.DecayTime*hfRatio, MinDecayTime, MaxDecayTime)};
  898. /* Update the modulator rate and depth. */
  899. mLate.Mod.updateModulator(props->Reverb.ModulationTime, props->Reverb.ModulationDepth,
  900. frequency);
  901. /* Update the late lines. */
  902. mLate.updateLines(density_mult, props->Reverb.Diffusion, lfDecayTime,
  903. props->Reverb.DecayTime, hfDecayTime, lf0norm, hf0norm, frequency);
  904. /* Update early and late 3D panning. */
  905. const float gain{props->Reverb.Gain * Slot->Gain * ReverbBoost};
  906. update3DPanning(props->Reverb.ReflectionsPan, props->Reverb.LateReverbPan,
  907. props->Reverb.ReflectionsGain*gain, props->Reverb.LateReverbGain*gain, target);
  908. /* Calculate the max update size from the smallest relevant delay. */
  909. mMaxUpdate[1] = minz(MAX_UPDATE_SAMPLES, minz(mEarly.Offset[0][1], mLate.Offset[0][1]));
  910. /* Determine if delay-line cross-fading is required. Density is essentially
  911. * a master control for the feedback delays, so changes the offsets of many
  912. * delay lines.
  913. */
  914. mDoFading |= (mParams.Density != props->Reverb.Density ||
  915. /* Diffusion and decay times influences the decay rate (gain) of the
  916. * late reverb T60 filter.
  917. */
  918. mParams.Diffusion != props->Reverb.Diffusion ||
  919. mParams.DecayTime != props->Reverb.DecayTime ||
  920. mParams.HFDecayTime != hfDecayTime ||
  921. mParams.LFDecayTime != lfDecayTime ||
  922. /* Modulation time and depth both require fading the modulation delay. */
  923. mParams.ModulationTime != props->Reverb.ModulationTime ||
  924. mParams.ModulationDepth != props->Reverb.ModulationDepth ||
  925. /* HF/LF References control the weighting used to calculate the density
  926. * gain.
  927. */
  928. mParams.HFReference != props->Reverb.HFReference ||
  929. mParams.LFReference != props->Reverb.LFReference);
  930. if(mDoFading)
  931. {
  932. mParams.Density = props->Reverb.Density;
  933. mParams.Diffusion = props->Reverb.Diffusion;
  934. mParams.DecayTime = props->Reverb.DecayTime;
  935. mParams.HFDecayTime = hfDecayTime;
  936. mParams.LFDecayTime = lfDecayTime;
  937. mParams.ModulationTime = props->Reverb.ModulationTime;
  938. mParams.ModulationDepth = props->Reverb.ModulationDepth;
  939. mParams.HFReference = props->Reverb.HFReference;
  940. mParams.LFReference = props->Reverb.LFReference;
  941. }
  942. }
  943. /**************************************
  944. * Effect Processing *
  945. **************************************/
  946. /* Applies a scattering matrix to the 4-line (vector) input. This is used
  947. * for both the below vector all-pass model and to perform modal feed-back
  948. * delay network (FDN) mixing.
  949. *
  950. * The matrix is derived from a skew-symmetric matrix to form a 4D rotation
  951. * matrix with a single unitary rotational parameter:
  952. *
  953. * [ d, a, b, c ] 1 = a^2 + b^2 + c^2 + d^2
  954. * [ -a, d, c, -b ]
  955. * [ -b, -c, d, a ]
  956. * [ -c, b, -a, d ]
  957. *
  958. * The rotation is constructed from the effect's diffusion parameter,
  959. * yielding:
  960. *
  961. * 1 = x^2 + 3 y^2
  962. *
  963. * Where a, b, and c are the coefficient y with differing signs, and d is the
  964. * coefficient x. The final matrix is thus:
  965. *
  966. * [ x, y, -y, y ] n = sqrt(matrix_order - 1)
  967. * [ -y, x, y, y ] t = diffusion_parameter * atan(n)
  968. * [ y, -y, x, y ] x = cos(t)
  969. * [ -y, -y, -y, x ] y = sin(t) / n
  970. *
  971. * Any square orthogonal matrix with an order that is a power of two will
  972. * work (where ^T is transpose, ^-1 is inverse):
  973. *
  974. * M^T = M^-1
  975. *
  976. * Using that knowledge, finding an appropriate matrix can be accomplished
  977. * naively by searching all combinations of:
  978. *
  979. * M = D + S - S^T
  980. *
  981. * Where D is a diagonal matrix (of x), and S is a triangular matrix (of y)
  982. * whose combination of signs are being iterated.
  983. */
  984. inline auto VectorPartialScatter(const std::array<float,NUM_LINES> &RESTRICT in,
  985. const float xCoeff, const float yCoeff) -> std::array<float,NUM_LINES>
  986. {
  987. return std::array<float,NUM_LINES>{{
  988. xCoeff*in[0] + yCoeff*( in[1] + -in[2] + in[3]),
  989. xCoeff*in[1] + yCoeff*(-in[0] + in[2] + in[3]),
  990. xCoeff*in[2] + yCoeff*( in[0] + -in[1] + in[3]),
  991. xCoeff*in[3] + yCoeff*(-in[0] + -in[1] + -in[2] )
  992. }};
  993. }
  994. /* Utilizes the above, but reverses the input channels. */
  995. void VectorScatterRevDelayIn(const DelayLineI delay, size_t offset, const float xCoeff,
  996. const float yCoeff, const al::span<const ReverbUpdateLine,NUM_LINES> in, const size_t count)
  997. {
  998. ASSUME(count > 0);
  999. for(size_t i{0u};i < count;)
  1000. {
  1001. offset &= delay.Mask;
  1002. size_t td{minz(delay.Mask+1 - offset, count-i)};
  1003. do {
  1004. std::array<float,NUM_LINES> f;
  1005. for(size_t j{0u};j < NUM_LINES;j++)
  1006. f[NUM_LINES-1-j] = in[j][i];
  1007. ++i;
  1008. delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff);
  1009. } while(--td);
  1010. }
  1011. }
  1012. /* This applies a Gerzon multiple-in/multiple-out (MIMO) vector all-pass
  1013. * filter to the 4-line input.
  1014. *
  1015. * It works by vectorizing a regular all-pass filter and replacing the delay
  1016. * element with a scattering matrix (like the one above) and a diagonal
  1017. * matrix of delay elements.
  1018. *
  1019. * Two static specializations are used for transitional (cross-faded) delay
  1020. * line processing and non-transitional processing.
  1021. */
  1022. void VecAllpass::processUnfaded(const al::span<ReverbUpdateLine,NUM_LINES> samples, size_t offset,
  1023. const float xCoeff, const float yCoeff, const size_t todo)
  1024. {
  1025. const DelayLineI delay{Delay};
  1026. const float feedCoeff{Coeff};
  1027. ASSUME(todo > 0);
  1028. size_t vap_offset[NUM_LINES];
  1029. for(size_t j{0u};j < NUM_LINES;j++)
  1030. vap_offset[j] = offset - Offset[j][0];
  1031. for(size_t i{0u};i < todo;)
  1032. {
  1033. for(size_t j{0u};j < NUM_LINES;j++)
  1034. vap_offset[j] &= delay.Mask;
  1035. offset &= delay.Mask;
  1036. size_t maxoff{offset};
  1037. for(size_t j{0u};j < NUM_LINES;j++)
  1038. maxoff = maxz(maxoff, vap_offset[j]);
  1039. size_t td{minz(delay.Mask+1 - maxoff, todo - i)};
  1040. do {
  1041. std::array<float,NUM_LINES> f;
  1042. for(size_t j{0u};j < NUM_LINES;j++)
  1043. {
  1044. const float input{samples[j][i]};
  1045. const float out{delay.Line[vap_offset[j]++][j] - feedCoeff*input};
  1046. f[j] = input + feedCoeff*out;
  1047. samples[j][i] = out;
  1048. }
  1049. ++i;
  1050. delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff);
  1051. } while(--td);
  1052. }
  1053. }
  1054. void VecAllpass::processFaded(const al::span<ReverbUpdateLine,NUM_LINES> samples, size_t offset,
  1055. const float xCoeff, const float yCoeff, float fadeCount, const float fadeStep,
  1056. const size_t todo)
  1057. {
  1058. const DelayLineI delay{Delay};
  1059. const float feedCoeff{Coeff};
  1060. ASSUME(todo > 0);
  1061. size_t vap_offset[NUM_LINES][2];
  1062. for(size_t j{0u};j < NUM_LINES;j++)
  1063. {
  1064. vap_offset[j][0] = offset - Offset[j][0];
  1065. vap_offset[j][1] = offset - Offset[j][1];
  1066. }
  1067. for(size_t i{0u};i < todo;)
  1068. {
  1069. for(size_t j{0u};j < NUM_LINES;j++)
  1070. {
  1071. vap_offset[j][0] &= delay.Mask;
  1072. vap_offset[j][1] &= delay.Mask;
  1073. }
  1074. offset &= delay.Mask;
  1075. size_t maxoff{offset};
  1076. for(size_t j{0u};j < NUM_LINES;j++)
  1077. maxoff = maxz(maxoff, maxz(vap_offset[j][0], vap_offset[j][1]));
  1078. size_t td{minz(delay.Mask+1 - maxoff, todo - i)};
  1079. do {
  1080. fadeCount += 1.0f;
  1081. const float fade{fadeCount * fadeStep};
  1082. std::array<float,NUM_LINES> f;
  1083. for(size_t j{0u};j < NUM_LINES;j++)
  1084. f[j] = delay.Line[vap_offset[j][0]++][j]*(1.0f-fade) +
  1085. delay.Line[vap_offset[j][1]++][j]*fade;
  1086. for(size_t j{0u};j < NUM_LINES;j++)
  1087. {
  1088. const float input{samples[j][i]};
  1089. const float out{f[j] - feedCoeff*input};
  1090. f[j] = input + feedCoeff*out;
  1091. samples[j][i] = out;
  1092. }
  1093. ++i;
  1094. delay.Line[offset++] = VectorPartialScatter(f, xCoeff, yCoeff);
  1095. } while(--td);
  1096. }
  1097. }
  1098. /* This generates early reflections.
  1099. *
  1100. * This is done by obtaining the primary reflections (those arriving from the
  1101. * same direction as the source) from the main delay line. These are
  1102. * attenuated and all-pass filtered (based on the diffusion parameter).
  1103. *
  1104. * The early lines are then fed in reverse (according to the approximately
  1105. * opposite spatial location of the A-Format lines) to create the secondary
  1106. * reflections (those arriving from the opposite direction as the source).
  1107. *
  1108. * The early response is then completed by combining the primary reflections
  1109. * with the delayed and attenuated output from the early lines.
  1110. *
  1111. * Finally, the early response is reversed, scattered (based on diffusion),
  1112. * and fed into the late reverb section of the main delay line.
  1113. *
  1114. * Two static specializations are used for transitional (cross-faded) delay
  1115. * line processing and non-transitional processing.
  1116. */
  1117. void ReverbState::earlyUnfaded(const size_t offset, const size_t todo)
  1118. {
  1119. const DelayLineI early_delay{mEarly.Delay};
  1120. const DelayLineI main_delay{mDelay};
  1121. const float mixX{mMixX};
  1122. const float mixY{mMixY};
  1123. ASSUME(todo > 0);
  1124. /* First, load decorrelated samples from the main delay line as the primary
  1125. * reflections.
  1126. */
  1127. for(size_t j{0u};j < NUM_LINES;j++)
  1128. {
  1129. size_t early_delay_tap{offset - mEarlyDelayTap[j][0]};
  1130. const float coeff{mEarlyDelayCoeff[j][0]};
  1131. for(size_t i{0u};i < todo;)
  1132. {
  1133. early_delay_tap &= main_delay.Mask;
  1134. size_t td{minz(main_delay.Mask+1 - early_delay_tap, todo - i)};
  1135. do {
  1136. mTempSamples[j][i++] = main_delay.Line[early_delay_tap++][j] * coeff;
  1137. } while(--td);
  1138. }
  1139. }
  1140. /* Apply a vector all-pass, to help color the initial reflections based on
  1141. * the diffusion strength.
  1142. */
  1143. mEarly.VecAp.processUnfaded(mTempSamples, offset, mixX, mixY, todo);
  1144. /* Apply a delay and bounce to generate secondary reflections, combine with
  1145. * the primary reflections and write out the result for mixing.
  1146. */
  1147. for(size_t j{0u};j < NUM_LINES;j++)
  1148. {
  1149. size_t feedb_tap{offset - mEarly.Offset[j][0]};
  1150. const float feedb_coeff{mEarly.Coeff[j][0]};
  1151. float *out{mEarlySamples[j].data()};
  1152. for(size_t i{0u};i < todo;)
  1153. {
  1154. feedb_tap &= early_delay.Mask;
  1155. size_t td{minz(early_delay.Mask+1 - feedb_tap, todo - i)};
  1156. do {
  1157. out[i] = mTempSamples[j][i] + early_delay.Line[feedb_tap++][j]*feedb_coeff;
  1158. ++i;
  1159. } while(--td);
  1160. }
  1161. }
  1162. for(size_t j{0u};j < NUM_LINES;j++)
  1163. early_delay.write(offset, NUM_LINES-1-j, mTempSamples[j].data(), todo);
  1164. /* Also write the result back to the main delay line for the late reverb
  1165. * stage to pick up at the appropriate time, appplying a scatter and
  1166. * bounce to improve the initial diffusion in the late reverb.
  1167. */
  1168. const size_t late_feed_tap{offset - mLateFeedTap};
  1169. VectorScatterRevDelayIn(main_delay, late_feed_tap, mixX, mixY, mEarlySamples, todo);
  1170. }
  1171. void ReverbState::earlyFaded(const size_t offset, const size_t todo, const float fade,
  1172. const float fadeStep)
  1173. {
  1174. const DelayLineI early_delay{mEarly.Delay};
  1175. const DelayLineI main_delay{mDelay};
  1176. const float mixX{mMixX};
  1177. const float mixY{mMixY};
  1178. ASSUME(todo > 0);
  1179. for(size_t j{0u};j < NUM_LINES;j++)
  1180. {
  1181. size_t early_delay_tap0{offset - mEarlyDelayTap[j][0]};
  1182. size_t early_delay_tap1{offset - mEarlyDelayTap[j][1]};
  1183. const float oldCoeff{mEarlyDelayCoeff[j][0]};
  1184. const float oldCoeffStep{-oldCoeff * fadeStep};
  1185. const float newCoeffStep{mEarlyDelayCoeff[j][1] * fadeStep};
  1186. float fadeCount{fade};
  1187. for(size_t i{0u};i < todo;)
  1188. {
  1189. early_delay_tap0 &= main_delay.Mask;
  1190. early_delay_tap1 &= main_delay.Mask;
  1191. size_t td{minz(main_delay.Mask+1 - maxz(early_delay_tap0, early_delay_tap1), todo-i)};
  1192. do {
  1193. fadeCount += 1.0f;
  1194. const float fade0{oldCoeff + oldCoeffStep*fadeCount};
  1195. const float fade1{newCoeffStep*fadeCount};
  1196. mTempSamples[j][i++] =
  1197. main_delay.Line[early_delay_tap0++][j]*fade0 +
  1198. main_delay.Line[early_delay_tap1++][j]*fade1;
  1199. } while(--td);
  1200. }
  1201. }
  1202. mEarly.VecAp.processFaded(mTempSamples, offset, mixX, mixY, fade, fadeStep, todo);
  1203. for(size_t j{0u};j < NUM_LINES;j++)
  1204. {
  1205. size_t feedb_tap0{offset - mEarly.Offset[j][0]};
  1206. size_t feedb_tap1{offset - mEarly.Offset[j][1]};
  1207. const float feedb_oldCoeff{mEarly.Coeff[j][0]};
  1208. const float feedb_oldCoeffStep{-feedb_oldCoeff * fadeStep};
  1209. const float feedb_newCoeffStep{mEarly.Coeff[j][1] * fadeStep};
  1210. float *out{mEarlySamples[j].data()};
  1211. float fadeCount{fade};
  1212. for(size_t i{0u};i < todo;)
  1213. {
  1214. feedb_tap0 &= early_delay.Mask;
  1215. feedb_tap1 &= early_delay.Mask;
  1216. size_t td{minz(early_delay.Mask+1 - maxz(feedb_tap0, feedb_tap1), todo - i)};
  1217. do {
  1218. fadeCount += 1.0f;
  1219. const float fade0{feedb_oldCoeff + feedb_oldCoeffStep*fadeCount};
  1220. const float fade1{feedb_newCoeffStep*fadeCount};
  1221. out[i] = mTempSamples[j][i] +
  1222. early_delay.Line[feedb_tap0++][j]*fade0 +
  1223. early_delay.Line[feedb_tap1++][j]*fade1;
  1224. ++i;
  1225. } while(--td);
  1226. }
  1227. }
  1228. for(size_t j{0u};j < NUM_LINES;j++)
  1229. early_delay.write(offset, NUM_LINES-1-j, mTempSamples[j].data(), todo);
  1230. const size_t late_feed_tap{offset - mLateFeedTap};
  1231. VectorScatterRevDelayIn(main_delay, late_feed_tap, mixX, mixY, mEarlySamples, todo);
  1232. }
  1233. void Modulation::calcDelays(size_t todo)
  1234. {
  1235. constexpr float inv_scale{MOD_FRACONE / al::numbers::pi_v<float> / 2.0f};
  1236. uint idx{Index};
  1237. const uint step{Step};
  1238. const float depth{Depth[0]};
  1239. for(size_t i{0};i < todo;++i)
  1240. {
  1241. idx += step;
  1242. const float lfo{std::sin(static_cast<float>(idx&MOD_FRACMASK) / inv_scale)};
  1243. ModDelays[i] = (lfo+1.0f) * depth;
  1244. }
  1245. Index = idx;
  1246. }
  1247. void Modulation::calcFadedDelays(size_t todo, float fadeCount, float fadeStep)
  1248. {
  1249. constexpr float inv_scale{MOD_FRACONE / al::numbers::pi_v<float> / 2.0f};
  1250. uint idx{Index};
  1251. const uint step{Step};
  1252. const float depth{Depth[0]};
  1253. const float depthStep{(Depth[1]-depth) * fadeStep};
  1254. for(size_t i{0};i < todo;++i)
  1255. {
  1256. fadeCount += 1.0f;
  1257. idx += step;
  1258. const float lfo{std::sin(static_cast<float>(idx&MOD_FRACMASK) / inv_scale)};
  1259. ModDelays[i] = (lfo+1.0f) * (depth + depthStep*fadeCount);
  1260. }
  1261. Index = idx;
  1262. }
  1263. /* This generates the reverb tail using a modified feed-back delay network
  1264. * (FDN).
  1265. *
  1266. * Results from the early reflections are mixed with the output from the
  1267. * modulated late delay lines.
  1268. *
  1269. * The late response is then completed by T60 and all-pass filtering the mix.
  1270. *
  1271. * Finally, the lines are reversed (so they feed their opposite directions)
  1272. * and scattered with the FDN matrix before re-feeding the delay lines.
  1273. *
  1274. * Two variations are made, one for for transitional (cross-faded) delay line
  1275. * processing and one for non-transitional processing.
  1276. */
  1277. void ReverbState::lateUnfaded(const size_t offset, const size_t todo)
  1278. {
  1279. const DelayLineI late_delay{mLate.Delay};
  1280. const DelayLineI main_delay{mDelay};
  1281. const float mixX{mMixX};
  1282. const float mixY{mMixY};
  1283. ASSUME(todo > 0);
  1284. /* First, calculate the modulated delays for the late feedback. */
  1285. mLate.Mod.calcDelays(todo);
  1286. /* Next, load decorrelated samples from the main and feedback delay lines.
  1287. * Filter the signal to apply its frequency-dependent decay.
  1288. */
  1289. for(size_t j{0u};j < NUM_LINES;j++)
  1290. {
  1291. size_t late_delay_tap{offset - mLateDelayTap[j][0]};
  1292. size_t late_feedb_tap{offset - mLate.Offset[j][0]};
  1293. const float midGain{mLate.T60[j].MidGain[0]};
  1294. const float densityGain{mLate.DensityGain[0] * midGain};
  1295. for(size_t i{0u};i < todo;)
  1296. {
  1297. late_delay_tap &= main_delay.Mask;
  1298. size_t td{minz(todo - i, main_delay.Mask+1 - late_delay_tap)};
  1299. do {
  1300. /* Calculate the read offset and fraction between it and the
  1301. * next sample.
  1302. */
  1303. const float fdelay{mLate.Mod.ModDelays[i]};
  1304. const size_t delay{float2uint(fdelay)};
  1305. const float frac{fdelay - static_cast<float>(delay)};
  1306. /* Feed the delay line with the late feedback sample, and get
  1307. * the two samples crossed by the delayed offset.
  1308. */
  1309. const float out0{late_delay.Line[(late_feedb_tap-delay) & late_delay.Mask][j]};
  1310. const float out1{late_delay.Line[(late_feedb_tap-delay-1) & late_delay.Mask][j]};
  1311. ++late_feedb_tap;
  1312. /* The output is obtained by linearly interpolating the two
  1313. * samples that were acquired above, and combined with the main
  1314. * delay tap.
  1315. */
  1316. mTempSamples[j][i] = lerpf(out0, out1, frac)*midGain +
  1317. main_delay.Line[late_delay_tap++][j]*densityGain;
  1318. ++i;
  1319. } while(--td);
  1320. }
  1321. mLate.T60[j].process({mTempSamples[j].data(), todo});
  1322. }
  1323. /* Apply a vector all-pass to improve micro-surface diffusion, and write
  1324. * out the results for mixing.
  1325. */
  1326. mLate.VecAp.processUnfaded(mTempSamples, offset, mixX, mixY, todo);
  1327. for(size_t j{0u};j < NUM_LINES;j++)
  1328. std::copy_n(mTempSamples[j].begin(), todo, mLateSamples[j].begin());
  1329. /* Finally, scatter and bounce the results to refeed the feedback buffer. */
  1330. VectorScatterRevDelayIn(late_delay, offset, mixX, mixY, mTempSamples, todo);
  1331. }
  1332. void ReverbState::lateFaded(const size_t offset, const size_t todo, const float fade,
  1333. const float fadeStep)
  1334. {
  1335. const DelayLineI late_delay{mLate.Delay};
  1336. const DelayLineI main_delay{mDelay};
  1337. const float mixX{mMixX};
  1338. const float mixY{mMixY};
  1339. ASSUME(todo > 0);
  1340. mLate.Mod.calcFadedDelays(todo, fade, fadeStep);
  1341. for(size_t j{0u};j < NUM_LINES;j++)
  1342. {
  1343. const float oldMidGain{mLate.T60[j].MidGain[0]};
  1344. const float midGain{mLate.T60[j].MidGain[1]};
  1345. const float oldMidStep{-oldMidGain * fadeStep};
  1346. const float midStep{midGain * fadeStep};
  1347. const float oldDensityGain{mLate.DensityGain[0] * oldMidGain};
  1348. const float densityGain{mLate.DensityGain[1] * midGain};
  1349. const float oldDensityStep{-oldDensityGain * fadeStep};
  1350. const float densityStep{densityGain * fadeStep};
  1351. size_t late_delay_tap0{offset - mLateDelayTap[j][0]};
  1352. size_t late_delay_tap1{offset - mLateDelayTap[j][1]};
  1353. size_t late_feedb_tap0{offset - mLate.Offset[j][0]};
  1354. size_t late_feedb_tap1{offset - mLate.Offset[j][1]};
  1355. float fadeCount{fade};
  1356. for(size_t i{0u};i < todo;)
  1357. {
  1358. late_delay_tap0 &= main_delay.Mask;
  1359. late_delay_tap1 &= main_delay.Mask;
  1360. size_t td{minz(todo - i, main_delay.Mask+1 - maxz(late_delay_tap0, late_delay_tap1))};
  1361. do {
  1362. fadeCount += 1.0f;
  1363. const float fdelay{mLate.Mod.ModDelays[i]};
  1364. const size_t delay{float2uint(fdelay)};
  1365. const float frac{fdelay - static_cast<float>(delay)};
  1366. const float out00{late_delay.Line[(late_feedb_tap0-delay) & late_delay.Mask][j]};
  1367. const float out01{late_delay.Line[(late_feedb_tap0-delay-1) & late_delay.Mask][j]};
  1368. ++late_feedb_tap0;
  1369. const float out10{late_delay.Line[(late_feedb_tap1-delay) & late_delay.Mask][j]};
  1370. const float out11{late_delay.Line[(late_feedb_tap1-delay-1) & late_delay.Mask][j]};
  1371. ++late_feedb_tap1;
  1372. const float fade0{oldDensityGain + oldDensityStep*fadeCount};
  1373. const float fade1{densityStep*fadeCount};
  1374. const float gfade0{oldMidGain + oldMidStep*fadeCount};
  1375. const float gfade1{midStep*fadeCount};
  1376. mTempSamples[j][i] = lerpf(out00, out01, frac)*gfade0 +
  1377. lerpf(out10, out11, frac)*gfade1 +
  1378. main_delay.Line[late_delay_tap0++][j]*fade0 +
  1379. main_delay.Line[late_delay_tap1++][j]*fade1;
  1380. ++i;
  1381. } while(--td);
  1382. }
  1383. mLate.T60[j].process({mTempSamples[j].data(), todo});
  1384. }
  1385. mLate.VecAp.processFaded(mTempSamples, offset, mixX, mixY, fade, fadeStep, todo);
  1386. for(size_t j{0u};j < NUM_LINES;j++)
  1387. std::copy_n(mTempSamples[j].begin(), todo, mLateSamples[j].begin());
  1388. VectorScatterRevDelayIn(late_delay, offset, mixX, mixY, mTempSamples, todo);
  1389. }
  1390. void ReverbState::process(const size_t samplesToDo, const al::span<const FloatBufferLine> samplesIn, const al::span<FloatBufferLine> samplesOut)
  1391. {
  1392. size_t offset{mOffset};
  1393. ASSUME(samplesToDo > 0);
  1394. /* Convert B-Format to A-Format for processing. */
  1395. const size_t numInput{minz(samplesIn.size(), NUM_LINES)};
  1396. const al::span<float> tmpspan{al::assume_aligned<16>(mTempLine.data()), samplesToDo};
  1397. for(size_t c{0u};c < NUM_LINES;c++)
  1398. {
  1399. std::fill(tmpspan.begin(), tmpspan.end(), 0.0f);
  1400. for(size_t i{0};i < numInput;++i)
  1401. {
  1402. const float gain{B2A[c][i]};
  1403. const float *RESTRICT input{al::assume_aligned<16>(samplesIn[i].data())};
  1404. for(float &sample : tmpspan)
  1405. {
  1406. sample += *input * gain;
  1407. ++input;
  1408. }
  1409. }
  1410. /* Band-pass the incoming samples and feed the initial delay line. */
  1411. DualBiquad{mFilter[c].Lp, mFilter[c].Hp}.process(tmpspan, tmpspan.data());
  1412. mDelay.write(offset, c, tmpspan.cbegin(), samplesToDo);
  1413. }
  1414. /* Process reverb for these samples. */
  1415. if LIKELY(!mDoFading)
  1416. {
  1417. for(size_t base{0};base < samplesToDo;)
  1418. {
  1419. /* Calculate the number of samples we can do this iteration. */
  1420. size_t todo{minz(samplesToDo - base, mMaxUpdate[0])};
  1421. /* Some mixers require maintaining a 4-sample alignment, so ensure
  1422. * that if it's not the last iteration.
  1423. */
  1424. if(base+todo < samplesToDo) todo &= ~size_t{3};
  1425. ASSUME(todo > 0);
  1426. /* Generate non-faded early reflections and late reverb. */
  1427. earlyUnfaded(offset, todo);
  1428. lateUnfaded(offset, todo);
  1429. /* Finally, mix early reflections and late reverb. */
  1430. (this->*mMixOut)(samplesOut, samplesToDo-base, base, todo);
  1431. offset += todo;
  1432. base += todo;
  1433. }
  1434. }
  1435. else
  1436. {
  1437. const float fadeStep{1.0f / static_cast<float>(samplesToDo)};
  1438. for(size_t base{0};base < samplesToDo;)
  1439. {
  1440. size_t todo{minz(samplesToDo - base, minz(mMaxUpdate[0], mMaxUpdate[1]))};
  1441. if(base+todo < samplesToDo) todo &= ~size_t{3};
  1442. ASSUME(todo > 0);
  1443. /* Generate cross-faded early reflections and late reverb. */
  1444. auto fadeCount = static_cast<float>(base);
  1445. earlyFaded(offset, todo, fadeCount, fadeStep);
  1446. lateFaded(offset, todo, fadeCount, fadeStep);
  1447. (this->*mMixOut)(samplesOut, samplesToDo-base, base, todo);
  1448. offset += todo;
  1449. base += todo;
  1450. }
  1451. /* Update the cross-fading delay line taps. */
  1452. for(size_t c{0u};c < NUM_LINES;c++)
  1453. {
  1454. mEarlyDelayTap[c][0] = mEarlyDelayTap[c][1];
  1455. mEarlyDelayCoeff[c][0] = mEarlyDelayCoeff[c][1];
  1456. mLateDelayTap[c][0] = mLateDelayTap[c][1];
  1457. mEarly.VecAp.Offset[c][0] = mEarly.VecAp.Offset[c][1];
  1458. mEarly.Offset[c][0] = mEarly.Offset[c][1];
  1459. mEarly.Coeff[c][0] = mEarly.Coeff[c][1];
  1460. mLate.Offset[c][0] = mLate.Offset[c][1];
  1461. mLate.T60[c].MidGain[0] = mLate.T60[c].MidGain[1];
  1462. mLate.VecAp.Offset[c][0] = mLate.VecAp.Offset[c][1];
  1463. }
  1464. mLate.DensityGain[0] = mLate.DensityGain[1];
  1465. mLate.Mod.Depth[0] = mLate.Mod.Depth[1];
  1466. mMaxUpdate[0] = mMaxUpdate[1];
  1467. mDoFading = false;
  1468. }
  1469. mOffset = offset;
  1470. }
  1471. struct ReverbStateFactory final : public EffectStateFactory {
  1472. al::intrusive_ptr<EffectState> create() override
  1473. { return al::intrusive_ptr<EffectState>{new ReverbState{}}; }
  1474. };
  1475. struct StdReverbStateFactory final : public EffectStateFactory {
  1476. al::intrusive_ptr<EffectState> create() override
  1477. { return al::intrusive_ptr<EffectState>{new ReverbState{}}; }
  1478. };
  1479. } // namespace
  1480. EffectStateFactory *ReverbStateFactory_getFactory()
  1481. {
  1482. static ReverbStateFactory ReverbFactory{};
  1483. return &ReverbFactory;
  1484. }
  1485. EffectStateFactory *StdReverbStateFactory_getFactory()
  1486. {
  1487. static StdReverbStateFactory ReverbFactory{};
  1488. return &ReverbFactory;
  1489. }