reverb.cpp 64 KB

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