DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
AlgorithmicReverb.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
217#include "../Core/DryWetMixer.h"
218#include "../Core/DspMath.h"
219#include "../Core/AudioSpec.h"
220#include "../Core/AudioBuffer.h"
221#include "../Core/DenormalGuard.h"
222#include "../Core/Biquad.h"
223#include "../Core/BiquadCascade.h"
224#include "../Core/FilterDesign.h"
225#include "../Core/StateBlob.h"
226#include "../Core/SimdOps.h"
227#include "../Core/KeyEqualizer.h"
228#include "../Core/TailShaper.h"
229
230#include <algorithm>
231#include <array>
232#include <atomic>
233#include <cmath>
234#include <cstddef>
235#include <cstdint>
236#include <cstdio>
237#include <utility>
238#include <vector>
239
240namespace dspark {
241
248template <FloatType T>
250{
251public:
253 enum class Type
254 {
255 Room,
256 Hall,
257 Chamber,
258 Plate,
259 Spring,
260 Cathedral
261 };
262
266 enum class Quality
267 {
268 Full,
269 Eco
270 };
271
274
277 {
279 T frequency = T(1000);
280 T q = T(0.7071);
281 T multiplier = T(1);
282 };
283
286
288 enum class NoteFeel { Straight, Dotted, Triplet };
289
291 enum class WidthLaw { Side, PowerKept };
292
295
297 enum class SpaceLayout { Prime, Geometric };
298
299 static constexpr int kDecayBands = 6;
300 static constexpr int kPostBands = KeyEqualizer<T, 2>::kBands;
301
302 ~AlgorithmicReverb() = default; // non-virtual: leaf class (no virtual dispatch)
303
304 // -- Lifecycle --------------------------------------------------------------
305
314 void prepare(const AudioSpec& spec)
315 {
316 if (!spec.isValid()) return; // release-safe: keep previous state
317
318 spec_ = spec;
319 // A stereo buffer is reverberated in true stereo even on a mono spec,
320 // so the mixer keeps a dry copy of both channels it blends.
321 AudioSpec mixSpec = spec;
322 mixSpec.numChannels = std::max(spec.numChannels, 2);
323 mixer_.prepare(mixSpec);
324 const double sr = spec.sampleRate;
325 tail_.prepare(sr);
327 postEq_.prepare(sr);
328 wall_.prepare(sr);
329 {
330 auto& p = plate_;
331 p.scale = sr / PlateTank::kRate;
332 for (int b = 0; b < 2; ++b)
333 {
334 const auto s = static_cast<std::size_t>(b);
335 p.lAp1[s] = p.at(PlateTank::kAp1[s]);
336 p.lD1[s] = p.at(PlateTank::kD1[s]);
337 p.lAp2[s] = p.at(PlateTank::kAp2[s]);
338 p.lD2[s] = p.at(PlateTank::kD2[s]);
339 p.ap1[s].prepare(p.lAp1[s] + p.at(PlateTank::kExcursion) + 4);
340 p.d1[s].prepare(p.lD1[s] + 1);
341 p.ap2[s].prepare(p.lAp2[s] + 1);
342 p.d2[s].prepare(p.lD2[s] + 1);
343 }
344 p.loopSec = 0.5 * (p.lAp1[0] + p.lD1[0] + p.lAp2[0] + p.lD2[0] + p.lAp1[1] + p.lD1[1] + p.lAp2[1] + p.lD2[1]) / sr;
345 }
346 for (int j = 0; j < SecondSlope::kLines; ++j)
347 {
348 const auto s = static_cast<std::size_t>(j);
349 slope2_.len[s] = nearestPrime(static_cast<int>(std::lround(kSecondMs[s] * 1e-3 * sr)));
350 slope2_.line[s].prepare(slope2_.len[s] + 1);
351 }
352 {
353 int size = 1;
354 while (size < static_cast<int>(2.0 * kShimmerMaxMs * 0.001 * sr) + 8) size <<= 1;
355 shimBuf_.assign(static_cast<size_t>(size), T(0));
356 shimMask_ = size - 1;
357 }
358 levelRelease_ = std::exp(-1.0 / (0.5 * sr));
359 levelHoldSamples_ = static_cast<int>(std::lround(0.03 * sr));
360
361 // Re-derive the sample counts stored at set-time: after a re-prepare
362 // at a different rate they would keep the OLD rate's sample count.
363 preDelaySamples_.store(msToSamples(static_cast<T>(effectivePreDelayMs())),
364 std::memory_order_relaxed);
365 erToLateSamples_.store(msToSamples(erToLateMs_.load(std::memory_order_relaxed)),
366 std::memory_order_relaxed);
367
368 const auto samples = [sr](double ms) { return static_cast<int>(ms * sr / 1000.0) + 8; };
369 for (int c = 0; c < 2; ++c)
370 {
371 // The early taps read the raw input straight from here.
372 preDelay_[c].prepare(samples(kMaxPreDelayMs + kMaxErMs));
373 // The diffused ring feeds the early taps (up to 170 ms, their
374 // contralateral copies up to 1.3x that) and the late injection
375 // (ER-to-late gap plus the injection spread).
376 ring_[c].prepare(samples(kMaxErToLateMs + kMaxInjectMs));
377 for (auto& ap : inAP_[c]) ap.prepare(samples(kMaxInDiffMs));
378 for (int k = 0; k < kOutStages; ++k)
379 {
380 outAP_[c][k].prepare(samples(kOutDiffMs_[c][k]));
381 outAPLen_[c][k] = nearestPrime(std::max(1, static_cast<int>(kOutDiffMs_[c][k] * sr / 1000.0)));
382 }
383 }
384 const int maxLine = samples(kBaseDelaysMs_[kMaxLines - 1] + kModMaxMs) + 4;
385 lines_.prepare(kMaxLines, maxLine);
387
388 // Spring dispersion: stretching factor K puts the chirp band edge at
389 // fs / (2K) ~ kSpringCutHz; a 4th-order Butterworth just below it
390 // removes the stretched allpasses' mirrored bands.
391 springK_ = std::max(1, static_cast<int>(std::lround(sr / (2.0 * kSpringCutHz))));
392 springP_ = 1;
393 while (springP_ < springK_ + 1) springP_ <<= 1;
394 springHist_.assign(static_cast<std::size_t>(kSprings * (kSpringStages + 1) * springP_), T(0));
395 {
396 const double fc = 0.9 * sr / (2.0 * springK_);
397 const double qs[2] = { 0.5411961001461970, 1.3065629648763764 };
398 for (int k = 0; k < 2; ++k)
399 {
400 const auto c = BiquadCoeffs::makeLowPass(sr, fc, qs[k]);
401 springLP_[k] = { static_cast<T>(c.b0), static_cast<T>(c.b1), static_cast<T>(c.b2),
402 static_cast<T>(c.a1), static_cast<T>(c.a2) };
403 }
404 }
405
408 sr, std::min(kCoherenceHz, 0.45 * sr), kCoherenceQ));
409 shadowCoeff_ = static_cast<T>(1.0 - std::exp(-6.283185307179586 * kShadowHz / sr));
410 erGlidePerSample_ = static_cast<T>(1.0 / (0.02 * sr));
411 maxReadPos_ = static_cast<T>(maxLine - 2);
412
413 eco_ = quality_.load(std::memory_order_relaxed) == Quality::Eco;
414 spring_ = type_.load(std::memory_order_relaxed) == Type::Spring;
416 prepared_ = true;
417
418 applyPreset(type_.load(std::memory_order_relaxed));
419 // prepare() applied whatever the caller configured before it, so no
420 // drain is needed on the first processBlock.
421 presetDirty_.store(false, std::memory_order_relaxed);
422 paramsDirty_.store(false, std::memory_order_relaxed);
423 qualityDirty_.store(false, std::memory_order_relaxed);
424 toneDirty_.store(true, std::memory_order_relaxed);
425 drainTone();
426 reset();
427 }
428
440 void processBlock(AudioBufferView<T> buffer) noexcept
441 {
442 DenormalGuard guard;
443 const int nCh = std::min(buffer.getNumChannels(), 2);
444 const int nS = buffer.getNumSamples();
445 if (nCh == 0 || nS == 0 || !prepared_) return;
446
447 // The dry copy holds maxBlockSize samples, so a longer block would
448 // lose its dry signal past that point: split it.
449 if (nS > spec_.maxBlockSize)
450 {
451 for (int start = 0; start < nS; start += spec_.maxBlockSize)
452 processBlock(buffer.getSubView(start, std::min(spec_.maxBlockSize, nS - start)));
453 return;
454 }
455
456 // Front-door non-finite guard: the FDN is fully recursive, so a single
457 // NaN/Inf input would poison the tail forever. No-op on finite input.
458 for (int ch = 0; ch < nCh; ++ch)
459 {
460 T* d = buffer.getChannel(ch);
461 for (int i = 0; i < nS; ++i)
462 if (!std::isfinite(d[i])) d[i] = T(0);
463 }
464
466
467 mixer_.pushDry(buffer);
469
470 T* chL = buffer.getChannel(0);
471 T* chR = nCh >= 2 ? buffer.getChannel(1) : nullptr;
472 alignas(64) T outL[kChunk];
473 alignas(64) T outR[kChunk];
474 for (int start = 0; start < nS; start += kChunk)
475 {
476 const int n = std::min(kChunk, nS - start);
477 processChunk(chL + start, (chR ? chR : chL) + start, outL, outR, n);
478 if (chR)
479 {
480 std::copy(outL, outL + n, chL + start);
481 std::copy(outR, outR + n, chR + start);
482 }
483 else
484 {
485 for (int i = 0; i < n; ++i)
486 chL[start + i] = (outL[i] + outR[i]) * T(0.5);
487 }
488 }
489
490 // The wet signal's equalizer.
491 if (postEq_.sync())
492 {
493 // A frame at a time, advanced by samples: a band on the middle
494 // or on the sides takes both channels at once, and the
495 // coefficients of a band on the move do not depend on the size
496 // of the host's block.
497 for (int i = 0; i < nS; ++i)
498 {
499 T frame[2] = {};
500 for (int ch = 0; ch < nCh; ++ch) frame[ch] = buffer.getChannel(ch)[i];
501 postEq_.processFrame(frame, nCh);
502 for (int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] = frame[ch];
503 postEq_.advance(1);
504 }
505 }
506
507 // The band limit, on the whole wet signal.
508 wall_.retarget(static_cast<double>(bandLimit_.load(std::memory_order_relaxed)));
509 if (wall_.active())
510 {
511 T* l = buffer.getChannel(0);
512 T* r = nCh >= 2 ? buffer.getChannel(1) : nullptr;
513 for (int i = 0; i < nS; ++i)
514 {
515 T a = l[i], b = r ? r[i] : l[i];
516 wall_.frame(a, b);
517 l[i] = a;
518 if (r) r[i] = b;
519 }
520 }
521
522 mixer_.mixWet(buffer, mix_.load(std::memory_order_relaxed));
523 }
524
535 [[nodiscard]] std::pair<T, T> processSample(T input) noexcept
536 {
537 if (!prepared_) return { T(0), T(0) };
538 DenormalGuard guard;
541 // Front-door non-finite guard (see processBlock).
542 if (!std::isfinite(input)) input = T(0);
543 T outL = T(0), outR = T(0);
544 processChunk(&input, &input, &outL, &outR, 1);
545 if (postEq_.sync())
546 {
547 T frame[2] = { outL, outR };
548 postEq_.processFrame(frame, 2);
549 outL = frame[0];
550 outR = frame[1];
551 postEq_.advance(1);
552 }
553 wall_.retarget(static_cast<double>(bandLimit_.load(std::memory_order_relaxed)));
554 if (wall_.active()) wall_.frame(outL, outR);
555 return { outL, outR };
556 }
557
562 void reset() noexcept
563 {
564 for (int c = 0; c < 2; ++c)
565 {
566 preDelay_[c].clear();
567 ring_[c].clear();
568 for (auto& ap : inAP_[c]) ap.clear();
569 for (auto& ap : outAP_[c]) ap.clear();
570 erLP_[c].fill(T(0));
571 erShadowLP_[c].fill(T(0));
572 erGain_[c] = erGainTarget_[c];
574 }
575 lines_.clear();
576 loopAP_.clear();
579 std::fill(springHist_.begin(), springHist_.end(), T(0));
580 springW_ = 0;
581 for (auto& st : springLPState_) st.fill(T(0));
582 apY1_.fill(T(0));
583 jotX1_.fill(T(0));
584 jotY1_.fill(T(0));
585 bassX1_.fill(T(0));
586 bassY1_.fill(T(0));
587 for (auto& v : airHist_) v.fill(T(0));
588 airW_ = 0;
589 for (auto& z : dqZ1_) z.fill(T(0));
590 for (auto& z : dqZ2_) z.fill(T(0));
591 std::fill(shimBuf_.begin(), shimBuf_.end(), T(0));
592 shimW_ = 0;
593 shimPhase_ = { 0.0, 0.5 };
594 shimLen_ = { 0.045, 0.045 };
595 shimRng_ = 0x51ED27u;
596 lastLateMono_ = T(0);
597 levelGr_ = 0.0;
598 levelHold_ = 0;
599 distLp_ = { T(0), T(0) };
600 distMix_ = sourceDepth_.load(std::memory_order_relaxed) > T(0) ? T(1) : T(0);
601 tail_.reset();
602 postEq_.reset();
603 wall_.reset();
604 for (auto& l : slope2_.line) l.clear();
605 for (int b = 0; b < 2; ++b)
606 {
607 plate_.ap1[static_cast<std::size_t>(b)].clear();
608 plate_.d1[static_cast<std::size_t>(b)].clear();
609 plate_.ap2[static_cast<std::size_t>(b)].clear();
610 plate_.d2[static_cast<std::size_t>(b)].clear();
611 }
612 plate_.lp.fill(T(0));
613 plate_.phase = 0.0;
614 slope2_.x1.fill(T(0));
615 slope2_.y1.fill(T(0));
618 holdNow_ = tailHold_.load(std::memory_order_relaxed) ? T(1) : T(0);
619 quietSamples_ = 1e300;
622
623 const double sr = spec_.sampleRate > 0 ? spec_.sampleRate : 48000.0;
624 const T rate = modRate_.load(std::memory_order_relaxed);
625 for (int i = 0; i < kMaxLines; ++i)
626 {
627 lfo_[i].prepare(sr, rate * lfoRateFactor(i), lfoSeed(i));
628 if (i < kMaxLines / 2)
629 {
630 rotLfo_[i].prepare(sr, rotRate() * rotRateFactor(i), rotSeed(i));
631 rotC_[i] = T(1);
632 rotS_[i] = T(0);
633 }
634 seg_[i].prepare(lfoSeed(i) ^ 0x9E3779B9u);
635 lenCur_[i] = static_cast<T>(lenTarget_[i]);
636 loopAPCur_[i] = static_cast<T>(loopAPLen_[i]);
637 pos_[i] = static_cast<double>(std::max(lenCur_[i], T(kMinReadPos)));
638 posInc_[i] = 0.0;
639 }
640 ctrlPhase_ = 0;
641 rotTick_ = 0; // the rotation refresh phase restarts with the LFOs
642 loopAPGliding_ = false;
643 sizeFade_ = false;
644
645 // Parameter glides snap to their targets with the state.
646 snapGlides();
647 fresh_ = true;
648
651 mixer_.reset();
652 }
653
654 // =========================================================================
655 // Level 1: Simple API
656 // =========================================================================
657
667 void setType(Type type) noexcept
668 {
669 // Wild enum values (a corrupted blob, a stray cast) clamp into range.
670 const int t = std::clamp(static_cast<int>(type), 0,
671 static_cast<int>(Type::Cathedral));
672 type_.store(static_cast<Type>(t), std::memory_order_relaxed);
673 // A preset load re-establishes the baseline: forget prior overrides so
674 // the preset's own values apply, unless a setter is called AFTER this.
675 userParamMask_.store(0u, std::memory_order_relaxed);
676 commitPreset(presetValues(static_cast<Type>(t)));
677 presetDirty_.store(true, std::memory_order_release);
678 }
679
705 void setQuality(Quality q) noexcept
706 {
708 std::memory_order_relaxed);
709 qualityDirty_.store(true, std::memory_order_release);
710 }
711
721 void setDecay(T seconds) noexcept
722 {
723 if (!std::isfinite(seconds)) return;
724 decayTime_.store(std::clamp(seconds, T(0.1), T(30)),
725 std::memory_order_relaxed);
727 paramsDirty_.store(true, std::memory_order_release);
728 }
729
738 void setMix(T dryWet) noexcept
739 {
740 if (!std::isfinite(dryWet)) return;
741 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
742 }
743
744 // =========================================================================
745 // Level 2: Intermediate API
746 // =========================================================================
747
755 void setSize(T size) noexcept
756 {
757 if (!std::isfinite(size)) return;
758 size_.store(std::clamp(size, T(0.01), T(1)), std::memory_order_relaxed);
760 paramsDirty_.store(true, std::memory_order_release);
761 }
762
769 void setDamping(T amount) noexcept
770 {
771 if (!std::isfinite(amount)) return;
772 T clamped = std::clamp(amount, T(0), T(1));
773 damping_.store(clamped, std::memory_order_relaxed);
774 highDecayMult_.store(T(1) - clamped * T(0.9), std::memory_order_relaxed);
776 paramsDirty_.store(true, std::memory_order_release);
777 }
778
781 void setPreDelay(T ms) noexcept
782 {
783 if (!std::isfinite(ms)) return;
784 T clamped = std::clamp(ms, T(0), T(kMaxPreDelayMs));
785 preDelayMs_.store(clamped, std::memory_order_relaxed);
787 }
788
797 void setDiffusion(T amount) noexcept
798 {
799 if (!std::isfinite(amount)) return;
800 diffusion_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
802 paramsDirty_.store(true, std::memory_order_release);
803 }
804
810 void setModulation(T amount) noexcept
811 {
812 if (!std::isfinite(amount)) return;
813 modDepth_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
815 paramsDirty_.store(true, std::memory_order_release);
816 }
817
827 void setWidth(T width) noexcept
828 {
829 if (!std::isfinite(width)) return;
830 width_.store(std::clamp(width, T(0), T(2)), std::memory_order_relaxed);
831 }
832
834 void setErToLateDelay(T ms) noexcept
835 {
836 if (!std::isfinite(ms)) return;
837 T clamped = std::clamp(ms, T(0), T(kMaxErToLateMs));
838 erToLateMs_.store(clamped, std::memory_order_relaxed);
840 if (spec_.sampleRate > 0)
841 erToLateSamples_.store(msToSamples(clamped), std::memory_order_relaxed);
842 }
843
844 // =========================================================================
845 // Level 3: Expert API - Frequency-Dependent Decay
846 // =========================================================================
847
857 void setHighDecayMultiplier(T mult) noexcept
858 {
859 if (!std::isfinite(mult)) return;
860 T clamped = std::clamp(mult, T(0.05), T(1));
861 highDecayMult_.store(clamped, std::memory_order_relaxed);
862 damping_.store(std::clamp((T(1) - clamped) / T(0.9), T(0), T(1)),
863 std::memory_order_relaxed);
865 paramsDirty_.store(true, std::memory_order_release);
866 }
867
878 void setBassDecayMultiplier(T mult) noexcept
879 {
880 if (!std::isfinite(mult)) return;
881 bassDecayMult_.store(std::clamp(mult, T(0.3), T(3)),
882 std::memory_order_relaxed);
884 paramsDirty_.store(true, std::memory_order_release);
885 }
886
900 void setHighCrossover(T hz) noexcept
901 {
902 if (!std::isfinite(hz)) return;
903 highCrossover_.store(std::clamp(hz, T(1000), T(16000)),
904 std::memory_order_relaxed);
906 paramsDirty_.store(true, std::memory_order_release);
907 }
908
934 void setAirAbsorption(T amount) noexcept
935 {
936 if (!std::isfinite(amount)) return;
937 airAbsorption_.store(std::clamp(amount, T(0), T(2)), std::memory_order_relaxed);
938 paramsDirty_.store(true, std::memory_order_release);
939 }
940
942 [[nodiscard]] T getAirAbsorption() const noexcept { return airAbsorption_.load(std::memory_order_relaxed); }
943
952 void setBassCrossover(T hz) noexcept
953 {
954 if (!std::isfinite(hz)) return;
955 bassCrossover_.store(std::clamp(hz, T(50), T(500)),
956 std::memory_order_relaxed);
958 paramsDirty_.store(true, std::memory_order_release);
959 }
960
961 // =========================================================================
962 // Level 3: Expert API - Tone & Levels
963 // =========================================================================
964
972 void setEarlyLevel(T dB) noexcept
973 {
974 if (!std::isfinite(dB)) return;
975 earlyLevel_.store(decibelsToGain(std::clamp(dB, T(-60), T(6))), std::memory_order_relaxed);
977 }
978
980 void setLateLevel(T dB) noexcept
981 {
982 if (!std::isfinite(dB)) return;
983 lateLevel_.store(decibelsToGain(std::clamp(dB, T(-60), T(6))), std::memory_order_relaxed);
985 }
986
988 void setModRate(T hz) noexcept
989 {
990 if (!std::isfinite(hz)) return;
991 modRate_.store(std::clamp(hz, T(0.1), T(5)), std::memory_order_relaxed);
993 paramsDirty_.store(true, std::memory_order_release);
994 }
995
1003 void setToneLowCut(T hz) noexcept
1004 {
1005 if (!std::isfinite(hz)) return;
1006 toneLowCutHz_.store(hz, std::memory_order_relaxed);
1007 toneDirty_.store(true, std::memory_order_release);
1008 }
1009
1017 void setToneHighCut(T hz) noexcept
1018 {
1019 if (!std::isfinite(hz)) return;
1020 toneHighCutHz_.store(hz, std::memory_order_relaxed);
1021 toneDirty_.store(true, std::memory_order_release);
1022 }
1023
1024 // =========================================================================
1025 // Level 3: Around the tank (all off by default)
1026 // =========================================================================
1027
1043 void setDecayBand(int index, const DecayBand& band) noexcept
1044 {
1045 if (index < 0 || index >= kDecayBands) return;
1046 auto& d = decayBands_[static_cast<size_t>(index)];
1047 d.shape.store(std::clamp(static_cast<int>(band.shape), 0, 3), std::memory_order_relaxed);
1048 if (std::isfinite(band.frequency)) d.frequency.store(std::clamp(band.frequency, T(20), T(20000)), std::memory_order_relaxed);
1049 if (std::isfinite(band.q)) d.q.store(std::clamp(band.q, T(0.1), T(10)), std::memory_order_relaxed);
1050 if (std::isfinite(band.multiplier)) d.multiplier.store(std::clamp(band.multiplier, T(0.1), T(4)), std::memory_order_relaxed);
1051 paramsDirty_.store(true, std::memory_order_release);
1052 }
1053
1055 [[nodiscard]] DecayBand getDecayBand(int index) const noexcept
1056 {
1057 DecayBand b;
1058 if (index < 0 || index >= kDecayBands) return b;
1059 const auto& d = decayBands_[static_cast<size_t>(index)];
1060 b.shape = static_cast<DecayShape>(d.shape.load(std::memory_order_relaxed));
1061 b.frequency = d.frequency.load(std::memory_order_relaxed);
1062 b.q = d.q.load(std::memory_order_relaxed);
1063 b.multiplier = d.multiplier.load(std::memory_order_relaxed);
1064 return b;
1065 }
1066
1072 void setTailHold(bool on) noexcept { tailHold_.store(on, std::memory_order_relaxed); }
1074 [[nodiscard]] bool isTailHeld() const noexcept { return tailHold_.load(std::memory_order_relaxed); }
1075
1081 void setDryDip(T dB) noexcept { tail_.setDryDip(dB); }
1082
1088 void setGate(T thresholdDb) noexcept { tail_.setGate(thresholdDb); }
1089
1091 void setGateHold(T ms) noexcept
1092 {
1093 if (!std::isfinite(ms)) return;
1094 gateHoldMs_.store(std::clamp(ms, T(0), T(4000)), std::memory_order_relaxed);
1096 }
1097
1099 void setGateRelease(T ms) noexcept { tail_.setGateRelease(ms); }
1100
1110 void setSourceDepth(T amount) noexcept
1111 {
1112 if (!std::isfinite(amount)) return;
1113 sourceDepth_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1114 paramsDirty_.store(true, std::memory_order_release);
1115 }
1116
1127 void setTankLeveling(T amount) noexcept
1128 {
1129 if (std::isfinite(amount)) tankLeveling_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1130 }
1131
1133 void setTankSaturation(bool on) noexcept { tankSat_.store(on, std::memory_order_relaxed); }
1134
1136 void setTempo(T bpm) noexcept
1137 {
1138 if (!std::isfinite(bpm)) return;
1139 tempo_.store(std::clamp(bpm, T(20), T(400)), std::memory_order_relaxed);
1142 }
1143
1146 {
1147 preNote_.store(std::clamp(static_cast<int>(note), 0, 6), std::memory_order_relaxed);
1148 preFeel_.store(std::clamp(static_cast<int>(feel), 0, 2), std::memory_order_relaxed);
1150 }
1151
1154 {
1155 gateNote_.store(std::clamp(static_cast<int>(note), 0, 6), std::memory_order_relaxed);
1156 gateFeel_.store(std::clamp(static_cast<int>(feel), 0, 2), std::memory_order_relaxed);
1158 }
1159
1165 void setInputWidth(T width) noexcept
1166 {
1167 if (std::isfinite(width)) inputWidth_.store(std::clamp(width, T(0), T(1)), std::memory_order_relaxed);
1168 }
1169
1176 void setWidthLaw(WidthLaw law) noexcept
1177 {
1178 widthLaw_.store(std::clamp(static_cast<int>(law), 0, 1), std::memory_order_relaxed);
1179 }
1180
1189 void setPostEqBand(int index, const typename KeyEqualizer<T, 2>::Band& band) noexcept { postEq_.setBand(index, band); }
1190
1196 void setPostEqLoudness(bool on) noexcept { postEq_.setLoudnessCompensation(on); }
1197
1199 [[nodiscard]] bool getPostEqLoudness() const noexcept { return postEq_.getLoudnessCompensation(); }
1201 [[nodiscard]] typename KeyEqualizer<T, 2>::Band getPostEqBand(int index) const noexcept { return postEq_.getBand(index); }
1202
1212 {
1213 modStyle_.store(std::clamp(static_cast<int>(style), 0, 1), std::memory_order_relaxed);
1214 }
1215
1223 void setSpaceLayout(SpaceLayout layout) noexcept
1224 {
1225 layout_.store(std::clamp(static_cast<int>(layout), 0, 1), std::memory_order_relaxed);
1226 paramsDirty_.store(true, std::memory_order_release);
1227 }
1228
1242 void setPlateTank(bool on) noexcept
1243 {
1244 plateTank_.store(on, std::memory_order_relaxed);
1245 paramsDirty_.store(true, std::memory_order_release);
1246 }
1247
1249 [[nodiscard]] bool isPlateTank() const noexcept { return plateTank_.load(std::memory_order_relaxed); }
1250
1260 void setDoubleSlope(T amount) noexcept
1261 {
1262 if (!std::isfinite(amount)) return;
1263 doubleSlope_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1264 paramsDirty_.store(true, std::memory_order_release);
1265 }
1266
1268 [[nodiscard]] T getDoubleSlope() const noexcept { return doubleSlope_.load(std::memory_order_relaxed); }
1269
1278 void setBandLimit(T hz) noexcept
1279 {
1280 if (std::isfinite(hz)) bandLimit_.store(hz <= T(0) ? T(0) : std::max(hz, T(1000)), std::memory_order_relaxed);
1281 }
1282
1284 [[nodiscard]] T getBandLimit() const noexcept { return bandLimit_.load(std::memory_order_relaxed); }
1285
1292 void setShimmer(T amount) noexcept
1293 {
1294 if (std::isfinite(amount)) shimmer_.store(std::clamp(amount, T(0), T(1)), std::memory_order_relaxed);
1295 }
1296
1297 [[nodiscard]] T getDryDip() const noexcept { return tail_.getDryDip(); }
1298 [[nodiscard]] T getGate() const noexcept { return tail_.getGate(); }
1299 [[nodiscard]] T getGateHold() const noexcept { return gateHoldMs_.load(std::memory_order_relaxed); }
1300 [[nodiscard]] T getGateRelease() const noexcept { return tail_.getGateRelease(); }
1301 [[nodiscard]] T getSourceDepth() const noexcept { return sourceDepth_.load(std::memory_order_relaxed); }
1302 [[nodiscard]] T getTankLeveling() const noexcept { return tankLeveling_.load(std::memory_order_relaxed); }
1303 [[nodiscard]] bool isThicknessSaturated() const noexcept { return tankSat_.load(std::memory_order_relaxed); }
1304 [[nodiscard]] T getTempo() const noexcept { return tempo_.load(std::memory_order_relaxed); }
1305 [[nodiscard]] NoteValue getPreDelayNote() const noexcept { return static_cast<NoteValue>(preNote_.load(std::memory_order_relaxed)); }
1306 [[nodiscard]] NoteValue getGateHoldNote() const noexcept { return static_cast<NoteValue>(gateNote_.load(std::memory_order_relaxed)); }
1307 [[nodiscard]] T getInputWidth() const noexcept { return inputWidth_.load(std::memory_order_relaxed); }
1308 [[nodiscard]] WidthLaw getWidthLaw() const noexcept { return static_cast<WidthLaw>(widthLaw_.load(std::memory_order_relaxed)); }
1309 [[nodiscard]] ModulationStyle getModulationStyle() const noexcept { return static_cast<ModulationStyle>(modStyle_.load(std::memory_order_relaxed)); }
1310 [[nodiscard]] SpaceLayout getSpaceLayout() const noexcept { return static_cast<SpaceLayout>(layout_.load(std::memory_order_relaxed)); }
1311 [[nodiscard]] T getShimmer() const noexcept { return shimmer_.load(std::memory_order_relaxed); }
1312
1314 [[nodiscard]] T getEffectivePreDelay() const noexcept { return static_cast<T>(effectivePreDelayMs()); }
1315
1316 // =========================================================================
1317 // Getters
1318 // =========================================================================
1319
1320 [[nodiscard]] Type getType() const noexcept { return type_.load(std::memory_order_relaxed); }
1321 [[nodiscard]] Quality getQuality() const noexcept { return quality_.load(std::memory_order_relaxed); }
1322 [[nodiscard]] T getDecay() const noexcept { return decayTime_.load(std::memory_order_relaxed); }
1323 [[nodiscard]] T getMix() const noexcept { return mix_.load(std::memory_order_relaxed); }
1324 [[nodiscard]] T getSize() const noexcept { return size_.load(std::memory_order_relaxed); }
1325 [[nodiscard]] T getDamping() const noexcept { return damping_.load(std::memory_order_relaxed); }
1326 [[nodiscard]] T getDiffusion() const noexcept { return diffusion_.load(std::memory_order_relaxed); }
1327 [[nodiscard]] T getModulation() const noexcept { return modDepth_.load(std::memory_order_relaxed); }
1328 [[nodiscard]] T getModRate() const noexcept { return modRate_.load(std::memory_order_relaxed); }
1329 [[nodiscard]] T getPreDelay() const noexcept { return preDelayMs_.load(std::memory_order_relaxed); }
1330 [[nodiscard]] T getErToLateDelay() const noexcept { return erToLateMs_.load(std::memory_order_relaxed); }
1331 [[nodiscard]] T getHighDecayMultiplier() const noexcept { return highDecayMult_.load(std::memory_order_relaxed); }
1332 [[nodiscard]] T getBassDecayMultiplier() const noexcept { return bassDecayMult_.load(std::memory_order_relaxed); }
1333 [[nodiscard]] T getWidth() const noexcept { return width_.load(std::memory_order_relaxed); }
1334 [[nodiscard]] T getHighCrossover() const noexcept { return highCrossover_.load(std::memory_order_relaxed); }
1336 [[nodiscard]] T getEarlyLevel() const noexcept { return levelDb(earlyLevel_.load(std::memory_order_relaxed)); }
1338 [[nodiscard]] T getLateLevel() const noexcept { return levelDb(lateLevel_.load(std::memory_order_relaxed)); }
1339 [[nodiscard]] T getBassCrossover() const noexcept { return bassCrossover_.load(std::memory_order_relaxed); }
1340
1342 [[nodiscard]] std::vector<uint8_t> getState() const
1343 {
1344 StateWriter w(stateId("ARVB"), 1);
1345 w.write("type", static_cast<int32_t>(type_.load(std::memory_order_relaxed)));
1346 w.write("quality", static_cast<int32_t>(quality_.load(std::memory_order_relaxed)));
1347 w.write("decay", static_cast<float>(decayTime_.load(std::memory_order_relaxed)));
1348 w.write("size", static_cast<float>(size_.load(std::memory_order_relaxed)));
1349 w.write("damping", static_cast<float>(damping_.load(std::memory_order_relaxed)));
1350 w.write("diffusion", static_cast<float>(diffusion_.load(std::memory_order_relaxed)));
1351 w.write("modDepth", static_cast<float>(modDepth_.load(std::memory_order_relaxed)));
1352 w.write("modRate", static_cast<float>(modRate_.load(std::memory_order_relaxed)));
1353 w.write("preDelay", static_cast<float>(preDelayMs_.load(std::memory_order_relaxed)));
1354 w.write("erToLate", static_cast<float>(erToLateMs_.load(std::memory_order_relaxed)));
1355 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
1356 w.write("width", static_cast<float>(width_.load(std::memory_order_relaxed)));
1357 w.write("highDecay", static_cast<float>(highDecayMult_.load(std::memory_order_relaxed)));
1358 w.write("bassDecay", static_cast<float>(bassDecayMult_.load(std::memory_order_relaxed)));
1359 w.write("highXover", static_cast<float>(highCrossover_.load(std::memory_order_relaxed)));
1360 w.write("bassXover", static_cast<float>(bassCrossover_.load(std::memory_order_relaxed)));
1361 w.write("earlyDb", static_cast<float>(getEarlyLevel()));
1362 w.write("lateDb", static_cast<float>(getLateLevel()));
1363 w.write("toneLowCut", static_cast<float>(toneLowCutHz_.load(std::memory_order_relaxed)));
1364 w.write("toneHighCut", static_cast<float>(toneHighCutHz_.load(std::memory_order_relaxed)));
1365 char key[24];
1366 for (int b = 0; b < kDecayBands; ++b)
1367 {
1368 const DecayBand band = getDecayBand(b);
1369 std::snprintf(key, sizeof(key), "db%d.shape", b); w.write(key, static_cast<int32_t>(band.shape));
1370 std::snprintf(key, sizeof(key), "db%d.freq", b); w.write(key, static_cast<float>(band.frequency));
1371 std::snprintf(key, sizeof(key), "db%d.q", b); w.write(key, static_cast<float>(band.q));
1372 std::snprintf(key, sizeof(key), "db%d.mult", b); w.write(key, static_cast<float>(band.multiplier));
1373 }
1374 w.write("tailHold", isTailHeld());
1375 w.write("dryDip", static_cast<float>(getDryDip()));
1376 w.write("gate", static_cast<float>(getGate()));
1377 w.write("gateHold", static_cast<float>(getGateHold()));
1378 w.write("gateRelease", static_cast<float>(getGateRelease()));
1379 w.write("sourceDepth", static_cast<float>(getSourceDepth()));
1380 w.write("tankLeveling", static_cast<float>(getTankLeveling()));
1381 w.write("tankSat", isThicknessSaturated());
1382 w.write("tempo", static_cast<float>(getTempo()));
1383 w.write("preNote", preNote_.load(std::memory_order_relaxed));
1384 w.write("preFeel", preFeel_.load(std::memory_order_relaxed));
1385 w.write("gateNote", gateNote_.load(std::memory_order_relaxed));
1386 w.write("gateFeel", gateFeel_.load(std::memory_order_relaxed));
1387 w.write("inWidth", static_cast<float>(getInputWidth()));
1388 w.write("widthLaw", widthLaw_.load(std::memory_order_relaxed));
1389 w.write("modStyle", modStyle_.load(std::memory_order_relaxed));
1390 w.write("layout", layout_.load(std::memory_order_relaxed));
1391 w.write("shimmer", static_cast<float>(getShimmer()));
1392 w.write("bandLimit", static_cast<float>(getBandLimit()));
1393 w.write("doubleSlope", static_cast<float>(getDoubleSlope()));
1394 w.write("plateTank", isPlateTank());
1395 w.write("airAbsorption", static_cast<float>(getAirAbsorption()));
1396 postEq_.writeState(w, "post");
1397 return w.blob();
1398 }
1399
1401 bool setState(const uint8_t* data, size_t size)
1402 {
1403 StateReader r(data, size);
1404 if (!r.isValid() || r.processorId() != stateId("ARVB")) return false;
1405 setType(static_cast<Type>(r.read("type", 0)));
1406 // Older blobs have no "quality" key: default 0 = Full.
1407 setQuality(r.read("quality", 0) == 1 ? Quality::Eco : Quality::Full);
1408 setDecay(static_cast<T>(r.read("decay", 1.0f)));
1409 setSize(static_cast<T>(r.read("size", 0.5f)));
1410 setDamping(static_cast<T>(r.read("damping", 0.5f)));
1411 setDiffusion(static_cast<T>(r.read("diffusion", 0.7f)));
1412 setModulation(static_cast<T>(r.read("modDepth", 0.1f)));
1413 setModRate(static_cast<T>(r.read("modRate", 1.0f)));
1414 setPreDelay(static_cast<T>(r.read("preDelay", 0.0f)));
1415 setErToLateDelay(static_cast<T>(r.read("erToLate", 0.0f)));
1416 setMix(static_cast<T>(r.read("mix", 0.3f)));
1417 setWidth(static_cast<T>(r.read("width", 1.0f)));
1418 setHighDecayMultiplier(static_cast<T>(r.read("highDecay", 0.5f)));
1419 setBassDecayMultiplier(static_cast<T>(r.read("bassDecay", 1.2f)));
1420 setHighCrossover(static_cast<T>(r.read("highXover", 5000.0f)));
1421 setBassCrossover(static_cast<T>(r.read("bassXover", 200.0f)));
1422 setEarlyLevel(static_cast<T>(r.read("earlyDb", 0.0f)));
1423 setLateLevel(static_cast<T>(r.read("lateDb", 0.0f)));
1424 // A missing or non-positive cutoff restores the filter as off, like
1425 // the blob's source instance.
1426 setToneLowCut(static_cast<T>(r.read("toneLowCut", -1.0f)));
1427 setToneHighCut(static_cast<T>(r.read("toneHighCut", -1.0f)));
1428 char key[24];
1429 for (int b = 0; b < kDecayBands; ++b)
1430 {
1431 DecayBand band;
1432 std::snprintf(key, sizeof(key), "db%d.shape", b); band.shape = static_cast<DecayShape>(r.read(key, 0));
1433 std::snprintf(key, sizeof(key), "db%d.freq", b); band.frequency = static_cast<T>(r.read(key, 1000.0f));
1434 std::snprintf(key, sizeof(key), "db%d.q", b); band.q = static_cast<T>(r.read(key, 0.7071f));
1435 std::snprintf(key, sizeof(key), "db%d.mult", b); band.multiplier = static_cast<T>(r.read(key, 1.0f));
1436 setDecayBand(b, band);
1437 }
1438 setTailHold(r.read("tailHold", false));
1439 setDryDip(static_cast<T>(r.read("dryDip", 0.0f)));
1440 setGate(static_cast<T>(r.read("gate", -200.0f)));
1441 setGateHold(static_cast<T>(r.read("gateHold", 100.0f)));
1442 setGateRelease(static_cast<T>(r.read("gateRelease", 150.0f)));
1443 setSourceDepth(static_cast<T>(r.read("sourceDepth", 0.0f)));
1444 setTankLeveling(static_cast<T>(r.read("tankLeveling", 0.0f)));
1445 setTankSaturation(r.read("tankSat", false));
1446 setTempo(static_cast<T>(r.read("tempo", 120.0f)));
1447 setPreDelayNote(static_cast<NoteValue>(r.read("preNote", 0)), static_cast<NoteFeel>(r.read("preFeel", 0)));
1448 setGateHoldNote(static_cast<NoteValue>(r.read("gateNote", 0)), static_cast<NoteFeel>(r.read("gateFeel", 0)));
1449 setInputWidth(static_cast<T>(r.read("inWidth", 1.0f)));
1450 setWidthLaw(static_cast<WidthLaw>(r.read("widthLaw", 0)));
1451 setModulationStyle(static_cast<ModulationStyle>(r.read("modStyle", 0)));
1452 setSpaceLayout(static_cast<SpaceLayout>(r.read("layout", 0)));
1453 setShimmer(static_cast<T>(r.read("shimmer", 0.0f)));
1454 setBandLimit(static_cast<T>(r.read("bandLimit", 0.0f)));
1455 setDoubleSlope(static_cast<T>(r.read("doubleSlope", 0.0f)));
1456 setPlateTank(r.read("plateTank", false));
1457 setAirAbsorption(static_cast<T>(r.read("airAbsorption", 0.0f)));
1458 postEq_.readState(r, "post");
1459 return true;
1460 }
1461
1462protected:
1463 // --- Constants -----------------------------------------------------------
1464
1465 static constexpr int kMaxLines = 32;
1466 static constexpr int kEcoLines = 16;
1467 static constexpr int kInStages = 4;
1468 static constexpr int kMaxERTaps = 128;
1469 static constexpr int kEcoERTaps = 48;
1470 static constexpr int kShadowBins = 2;
1471 static constexpr int kMaxDiscreteER = 7;
1476 static constexpr int kMaxERSlots = kMaxERTaps + 2 * kMaxDiscreteER;
1477 static constexpr int kERGroups = 4;
1478 static constexpr int kCtrl = 16;
1479 static constexpr int kChunk = 64;
1480
1481 static constexpr double kMaxPreDelayMs = 500.0;
1482 static constexpr double kShimmerMinMs = 30.0;
1483 static constexpr double kShimmerMaxMs = 60.0;
1484 static constexpr T kShimmerFeed = T(0.08);
1485 static constexpr double kMaxDecayLoopGain = 0.9995;
1486 static constexpr double kMaxErToLateMs = 200.0;
1487 static constexpr double kMaxErMs = 170.0;
1488 static constexpr double kMaxInjectMs = 8.0;
1489 static constexpr double kMaxInDiffMs = 2.0;
1490 static constexpr double kMaxLoopApMs = 5.5;
1491 static constexpr double kCoherenceHz = 355.0;
1492 static constexpr double kCoherenceQ = 0.74;
1493 static constexpr double kShadowHz = 1000.0;
1494 static constexpr double kShadowHF = 0.5;
1495 static constexpr double kModMaxMs = 2.0;
1500 static constexpr double kRotMaxRad = 10.0;
1501 static constexpr double kRotRateHz = 0.35;
1505 static constexpr int kRotPairStride = 4;
1506 static constexpr double kGlideMs = 60.0;
1507 static constexpr double kMaxGlideSpeed = 0.04;
1508 static constexpr double kSizeFadeOver = 0.002;
1509 static constexpr double kSizeFadeSeconds = 0.25;
1510 static constexpr double kSubsonicHz = 20.0;
1511 static constexpr T kMinReadPos = T(2);
1521 static constexpr double kApLow = 0.1;
1524 static T allpassCoeff(double d) noexcept { return static_cast<T>((1.0 - d) / (1.0 + d)); }
1525 static constexpr T kSoftLimit = T(2);
1526
1529 static constexpr T kOutGain = T(0.25);
1534 static constexpr double kWetCalibration = 4.73;
1535 static constexpr double kWetCalibrationSpring = 2.85;
1536
1537 // FDN base delay times in ms (at size = 1); lengths are rounded to primes.
1538 // About 3.7 s of delay in all: the modal density (modes per Hz equals the
1539 // total delay in seconds) keeps the modes overlapping, so they do not
1540 // ring out on their own.
1541 static constexpr double kBaseDelaysMs_[kMaxLines] = {
1542 44.5, 46.5, 49.7, 52.3, 56.1, 58.9, 61.9, 65.2,
1543 68.6, 73.7, 76.2, 79.8, 86.4, 89.8, 95.7, 101.2,
1544 105.4, 112.5, 116.7, 126.4, 132.1, 140.6, 146.9, 154.1,
1545 162.9, 175.8, 184.1, 192.8, 204.0, 218.5, 224.2, 240.1
1546 };
1547
1548 // In-loop allpass delays (ms): short and fixed in time, shuffled against
1549 // the line lengths so no line's total is a near multiple of another's.
1550 static constexpr double kLoopApMs_[kMaxLines] = {
1551 3.55, 1.47, 3.80, 1.96, 1.84, 2.33, 4.41, 4.90,
1552 1.10, 1.35, 4.29, 3.43, 4.16, 4.53, 2.08, 3.06,
1553 1.22, 2.94, 3.92, 3.18, 2.57, 4.04, 4.65, 2.45,
1554 2.69, 4.78, 3.67, 1.71, 2.20, 1.59, 2.82, 3.31
1555 };
1556
1557 // Input diffusion allpass delays (ms) of the late-field feed,
1558 // decorrelated between channels. Short, so the frequencies an allpass
1559 // holds back longest (its group-delay peaks) are not heard ringing on
1560 // through a short decay.
1561 static constexpr double kInDiffMs_[2][kInStages] = {
1562 { 0.36, 0.69, 1.10, 1.65 },
1563 { 0.43, 0.80, 1.20, 1.79 }
1564 };
1565 static constexpr double kInDiffCoeffs_[kInStages] = { 0.75, 0.72, 0.68, 0.64 };
1566
1567 // Output diffusion allpass delays (ms) on the late sum, per channel: each
1568 // echo of the tank leaves as a short dense burst, so the late field is
1569 // smooth from its first milliseconds.
1570 static constexpr int kOutStages = 2;
1571 static constexpr double kOutDiffMs_[2][kOutStages] = {
1572 { 1.13, 2.41 },
1573 { 1.31, 2.67 }
1574 };
1575
1576 static constexpr double kMeanInjectMs = 4.0;
1577 // Late injection taps (ms after the ER-to-late gap), one per line.
1578 static constexpr double kInjectMs_[kMaxLines] = {
1579 7.14, 3.31, 0.76, 0.25, 5.86, 2.04, 4.84, 5.35,
1580 5.61, 6.88, 0.00, 7.65, 2.80, 1.02, 7.90, 1.53,
1581 1.27, 4.33, 6.63, 2.55, 3.06, 6.12, 5.10, 6.37,
1582 3.82, 1.78, 3.57, 7.39, 2.29, 0.51, 4.08, 4.59
1583 };
1584 static constexpr int kInjectSign_[kMaxLines] = {
1585 1, 1, -1, 1, -1, 1, 1, -1,
1586 -1, 1, 1, -1, 1, -1, 1, 1,
1587 1, 1, 1, -1, 1, 1, 1, 1,
1588 1, -1, 1, 1, -1, 1, -1, -1
1589 };
1590
1591 // Orthogonal stereo output sign vectors (inner product 0; the first 8
1592 // entries are orthogonal too, so Eco keeps the decorrelation).
1593 static constexpr int kOutSignL_[kMaxLines] = {
1594 -1, -1, 1, -1, -1, 1, 1, 1,
1595 -1, -1, 1, 1, -1, -1, -1, 1,
1596 -1, -1, 1, -1, -1, 1, 1, -1,
1597 1, 1, -1, -1, -1, -1, -1, 1
1598 };
1599 static constexpr int kOutSignR_[kMaxLines] = {
1600 -1, 1, 1, 1, -1, -1, 1, -1,
1601 -1, 1, 1, -1, -1, 1, -1, -1,
1602 -1, 1, 1, 1, -1, -1, 1, 1,
1603 1, -1, -1, 1, -1, 1, -1, -1
1604 };
1605
1606 // Spring tanks (Type::Spring): six springs per side (even = left), all
1607 // of different lengths; Eco keeps one per side.
1608 static constexpr int kSprings = 12;
1609 static constexpr int kEcoSprings = 2;
1610 static constexpr int kSpringStages = 72;
1611 static constexpr int kEcoSpringStages = 40;
1612 static constexpr double kSpringJitterMs = 3.0;
1615 static double springBaseMs(int s) noexcept
1616 {
1617 return 33.0 + 27.0 * s / (kSprings - 1) + 1.3 * (hash01(s, 90) - 0.5);
1618 }
1619 static constexpr double kSpringCutHz = 4400.0;
1620 static constexpr T kSpringOutGain = T(2);
1621
1622 // =========================================================================
1623 // Building blocks
1624 // =========================================================================
1625
1627 struct Line
1628 {
1629 std::vector<T> buf;
1630 int mask = 0;
1631 int w = 0;
1632
1633 void prepare(int maxDelay)
1634 {
1635 int size = 1;
1636 while (size < maxDelay + 2) size <<= 1;
1637 buf.assign(static_cast<std::size_t>(size), T(0));
1638 mask = size - 1;
1639 w = 0;
1640 }
1641 void clear() noexcept { std::fill(buf.begin(), buf.end(), T(0)); w = 0; }
1642 [[nodiscard]] T at(int k) const noexcept { return buf[static_cast<std::size_t>((w - k) & mask)]; }
1643 void push(T x) noexcept { buf[static_cast<std::size_t>(w)] = x; w = (w + 1) & mask; }
1644 };
1645
1652 {
1653 std::vector<T> buf;
1654 int size = 0;
1655 int stride = 0;
1656 int mask = 0;
1657 int w = 0;
1658
1659 void prepare(int numLines, int maxDelay)
1660 {
1661 size = 1;
1662 while (size < maxDelay + 2) size <<= 1;
1663 mask = size - 1;
1664 // One cache line of padding per line: with a power-of-two stride
1665 // every line would start in the same L1 set, and the 32 streams
1666 // read each sample would keep evicting each other.
1667 stride = size + 64 / static_cast<int>(sizeof(T));
1668 buf.assign(static_cast<std::size_t>(stride) * static_cast<std::size_t>(numLines), T(0));
1669 w = 0;
1670 }
1671 void clear() noexcept { std::fill(buf.begin(), buf.end(), T(0)); w = 0; }
1672 [[nodiscard]] T at(int i, int k) const noexcept
1673 { return buf[static_cast<std::size_t>(i * stride + ((w - k) & mask))]; }
1674 void write(int i, T x) noexcept { buf[static_cast<std::size_t>(i * stride + w)] = x; }
1675 void advance() noexcept { w = (w + 1) & mask; }
1676 };
1677
1687 struct Wall
1688 {
1689 static constexpr int kSections = 6;
1691
1692 void prepare(double sampleRate)
1693 {
1694 rate = sampleRate;
1695 step = 1.0 / (0.02 * sampleRate);
1696 for (auto& b : bank)
1697 {
1698 b.setNumSections(kSections);
1699 b.reset();
1700 }
1701 hz = 0.0;
1702 fade = 1.0;
1703 fromOn = toOn = false;
1704 }
1705
1706 void reset() noexcept
1707 {
1708 for (auto& b : bank) b.reset();
1709 fade = 1.0;
1710 fromOn = toOn;
1711 }
1712
1713 [[nodiscard]] bool active() const noexcept { return toOn || fade < 1.0; }
1714
1716 void retarget(double want) noexcept
1717 {
1718 if (want > 0.0) want = std::min(want, 0.4 * rate);
1719 if (want == hz || fade < 1.0) return;
1720 fromOn = toOn;
1721 live = 1 - live;
1722 toOn = want > 0.0;
1723 if (toOn)
1724 {
1726 // By the bilinear transform with the corner mapped exactly: the
1727 // ripple of the pass band stays the prototype's (a fit of each
1728 // section moves it by half a decibel), the stop band only gets deeper.
1729 const AnalogCascade proto = FilterDesign::ellipticHighCut(want);
1730 const int n = std::min(proto.count, kSections);
1731 for (int s = 0; s < n; ++s) c[s] = FilterDesign::bilinear(proto.sections[static_cast<std::size_t>(s)], rate, want);
1732 for (int s = 0; s < kSections; ++s) bank[live].setCoeffs(s, s < n ? c[s] : BiquadCoeffs {});
1733 bank[live].reset();
1734 }
1735 hz = want;
1736 fade = 0.0;
1737 }
1738
1739 void frame(T& l, T& r) noexcept
1740 {
1741 const double x[2] = { static_cast<double>(l), static_cast<double>(r) };
1742 double to[2] = { x[0], x[1] };
1743 if (toOn)
1744 for (int c = 0; c < 2; ++c) to[c] = bank[live].processSample(x[c], c);
1745 if (fade < 1.0)
1746 {
1747 double from[2] = { x[0], x[1] };
1748 if (fromOn)
1749 for (int c = 0; c < 2; ++c) from[c] = bank[1 - live].processSample(x[c], c);
1750 fade = std::min(1.0, fade + step);
1751 for (int c = 0; c < 2; ++c) to[c] = from[c] + fade * (to[c] - from[c]);
1752 }
1753 l = static_cast<T>(to[0]);
1754 r = static_cast<T>(to[1]);
1755 }
1756
1758 double rate = 48000.0, hz = 0.0, fade = 1.0, step = 0.0;
1759 int live = 0;
1760 bool fromOn = false, toOn = false;
1761 };
1762
1764 std::atomic<T> bandLimit_ { T(0) };
1765
1770 {
1771 static constexpr int kLines = 4;
1772 std::array<Line, kLines> line;
1773 std::array<int, kLines> len {};
1774 std::array<T, kLines> b0 {}, b1 {}, a1 {}, x1 {}, y1 {};
1775 T gain = T(0), keep = T(1);
1776 T gainNow = T(0), keepNow = T(1);
1777 double loopSec = 0.0;
1778 bool on = false;
1779 };
1783 {
1784 static constexpr double kRate = 29761.0;
1785 static constexpr std::array<int, 2> kAp1 { 672, 908 }, kD1 { 4453, 4217 }, kAp2 { 1800, 2656 }, kD2 { 3720, 3163 };
1786 static constexpr double kExcursion = 16.0;
1787 static constexpr T kDiffusion1 = T(-0.7), kDiffusion2 = T(0.5);
1788 std::array<Line, 2> ap1, d1, ap2, d2;
1789 std::array<int, 2> lAp1 {}, lD1 {}, lAp2 {}, lD2 {};
1790 std::array<T, 2> gain {}, lp {};
1791 T damp = T(0);
1792 double excursion = 0.0, phase = 0.0, phaseStep = 0.0;
1793 double loopSec = 0.0;
1794 double scale = 1.0;
1795 bool on = false;
1796
1797 [[nodiscard]] int at(double samples29k) const noexcept { return std::max(1, static_cast<int>(std::lround(samples29k * scale))); }
1798 };
1800 std::atomic<bool> plateTank_ { false };
1801 static constexpr double kPlateEnergy = 0.50;
1802
1804 std::atomic<T> doubleSlope_ { T(0) };
1805 static constexpr std::array<double, SecondSlope::kLines> kSecondMs { 23.3, 29.1, 37.9, 44.7 };
1806 static constexpr double kSecondRatio = 0.3;
1807 static constexpr double kSecondShare = 0.30;
1808
1810 {
1811 // Double state whatever T is: the increment is tiny against the phase,
1812 // so a float accumulator rounds every step and drifts in rate, and a
1813 // rotation of up to kRotMaxRad turns that drift into an audible change.
1814 double h0_ = 0.0, h1_ = 0.0, h2_ = 0.0, h3_ = 0.0;
1815 double phase_ = 0.0;
1816 double phaseInc_ = 0.0;
1817 uint32_t state_ = 1;
1818
1819 void prepare(double sr, T rate, uint32_t seed) noexcept
1820 {
1821 phaseInc_ = static_cast<double>(rate) / sr;
1822 state_ = seed ? seed : 1;
1823 h0_ = nextRandom(); h1_ = nextRandom();
1824 h2_ = nextRandom(); h3_ = nextRandom();
1825 phase_ = 0.0;
1826 }
1827
1828 void setRate(T rate, double sr) noexcept { phaseInc_ = static_cast<double>(rate) / sr; }
1829
1832 T nextStride(int stride) noexcept
1833 {
1834 phase_ += phaseInc_ * static_cast<double>(stride);
1835 if (phase_ >= 1.0)
1836 {
1837 phase_ -= 1.0;
1838 h0_ = h1_; h1_ = h2_; h2_ = h3_;
1839 h3_ = nextRandom();
1840 }
1841 const double d = phase_;
1842 const double c1 = 0.5 * (h2_ - h0_);
1843 const double c2 = h0_ - 2.5 * h1_ + 2.0 * h2_ - 0.5 * h3_;
1844 const double c3 = 0.5 * (h3_ - h0_) + 1.5 * (h1_ - h2_);
1845 return static_cast<T>(((c3 * d + c2) * d + c1) * d + h1_);
1846 }
1847
1848 private:
1849 double nextRandom() noexcept
1850 {
1851 state_ ^= state_ << 13;
1852 state_ ^= state_ >> 17;
1853 state_ ^= state_ << 5;
1854 return static_cast<double>(state_) / static_cast<double>(0xFFFFFFFFu) * 2.0 - 1.0;
1855 }
1856 };
1857
1867 {
1868 double pos = 0.0, vel = 0.0, goal = 0.0, target = 0.0, step = 0.0, side = 1.0;
1869 uint32_t state = 1;
1870
1871 void prepare(uint32_t seed) noexcept
1872 {
1873 state = seed ? seed : 1;
1874 pos = vel = goal = target = step = 0.0;
1875 side = 1.0;
1876 }
1877
1878 double next(int stride, double rateHz, double sr) noexcept
1879 {
1880 if (step == 0.0)
1881 {
1882 // Toward the other side, a random share of the way to its limit.
1883 target = goal + (side - goal) * (0.3 + 0.65 * random());
1884 side = -side;
1885 const double seconds = (0.5 + random()) / std::max(rateHz, 0.01);
1886 step = std::abs(target - goal) / std::max(1.0, seconds * sr);
1887 if (step == 0.0) step = 1e-9;
1888 }
1889 const double move = step * static_cast<double>(stride);
1890 if (std::abs(target - goal) <= move) { goal = target; step = 0.0; }
1891 else goal += target > goal ? move : -move;
1892 // A critically damped follower of the segments: the delay and its
1893 // rate of change stay continuous (no step of pitch at a corner).
1894 const double dt = static_cast<double>(stride) / sr;
1895 const double w = std::min(2.0 * 3.14159265358979323846 * std::clamp(2.0 * rateHz, 0.2, 20.0), 0.5 / dt);
1896 vel += (w * w * (goal - pos) - 2.0 * w * vel) * dt;
1897 pos += vel * dt;
1898 return pos;
1899 }
1900
1901 private:
1902 double random() noexcept
1903 {
1904 state ^= state << 13;
1905 state ^= state >> 17;
1906 state ^= state << 5;
1907 return static_cast<double>(state) / 4294967296.0;
1908 }
1909 };
1910
1911 static constexpr T lfoRateFactor(int i) noexcept
1912 {
1913 return T(0.71) + T(0.063) * static_cast<T>(i);
1914 }
1915 static constexpr uint32_t lfoSeed(int i) noexcept
1916 {
1917 return static_cast<uint32_t>(i) * 7919u + 1u;
1918 }
1919 static constexpr T rotRate() noexcept { return static_cast<T>(kRotRateHz); }
1920 static constexpr T rotRateFactor(int i) noexcept
1921 {
1922 return T(0.83) + T(0.051) * static_cast<T>(i);
1923 }
1924 static constexpr uint32_t rotSeed(int i) noexcept
1925 {
1926 return static_cast<uint32_t>(i) * 104729u + 7u;
1927 }
1928
1930 static double hash01(int k, int s) noexcept
1931 {
1932 const double v = std::sin(static_cast<double>(k) * 12.9898
1933 + static_cast<double>(s) * 78.233) * 43758.5453;
1934 return v - std::floor(v);
1935 }
1936
1938 static T levelDb(T gain) noexcept
1939 {
1940 return static_cast<T>(20.0 * std::log10(std::max(static_cast<double>(gain), 1e-6)));
1941 }
1942
1943 int msToSamples(T ms) const noexcept
1944 {
1945 return static_cast<int>(static_cast<T>(spec_.sampleRate) * ms / T(1000));
1946 }
1947
1948 // --- State ---------------------------------------------------------------
1949
1951 bool prepared_ = false;
1952 bool eco_ = false;
1954 int ctrlPhase_ = 0;
1955
1956 // Input stage (per channel)
1957 std::array<Line, 2> preDelay_;
1958 std::array<std::array<Line, kInStages>, 2> inAP_;
1959 std::array<std::array<int, kInStages>, 2> inAPLen_ {};
1960 std::array<T, kInStages> inAPCoeff_ {};
1961 std::array<T, kInStages> inAPCoeffTarget_ {};
1962 std::array<Line, 2> ring_;
1963 std::array<std::array<Line, kOutStages>, 2> outAP_;
1964 std::array<std::array<int, kOutStages>, 2> outAPLen_ {};
1965 T outAPCoeff_ = T(0.5);
1967
1968 // Early reflections (per side): velvet taps, each reading its own side
1969 // (erChan_ 0) or the other (1)
1970 int numERTaps_ = 0;
1971 int numERSlots_ = 0;
1973 std::array<std::array<int, kMaxERSlots>, 2> erTap_ {}, erChan_ {}, erBin_ {};
1974 std::array<std::array<T, kMaxERSlots>, 2> erGain_ {};
1975 std::array<std::array<T, kMaxERSlots>, 2> erGainTarget_ {};
1976 std::array<T, kERGroups> erShelfGainTarget_ {};
1977 T erGlidePerSample_ = T(0.001);
1978 std::array<std::array<int, kERGroups + 1>, 2> erGroupStart_ {};
1979 std::array<T, kERGroups> erShelfGain_ {};
1980 T erShelfCoeff_ = T(0.5);
1981 std::array<std::array<T, kERGroups>, 2> erLP_ {};
1982 std::array<std::array<T, kERGroups>, 2> erShadowLP_ {};
1983 double meanLoopSec_ = 0.1;
1984 T wetLevel_ = T(1);
1986
1987 // FDN
1989 std::array<int, kMaxLines> lenTarget_ {};
1990 std::array<T, kMaxLines> lenCur_ {};
1991 // Double whatever T is: a float position on a line thousands of samples long
1992 // resolves only about 0.001 samples, which is jitter on every modulated read.
1993 std::array<double, kMaxLines> pos_ {};
1994 std::array<double, kMaxLines> posInc_ {};
1995 // A change of size under way: the second read heads (see beginSizeFade()).
1996 std::array<double, kMaxLines> pos2_ {}, posInc2_ {};
1997 std::array<T, kMaxLines> apY2_ {}, lenNew_ {};
1998 std::array<int, kMaxLines> loopAPFrom_ {}, loopAPTo_ {};
1999 double fadeAt_ = 0.0, fadeStep_ = 0.0;
2000 bool sizeFade_ = false;
2001 std::array<T, kMaxLines> apY1_ {};
2002 std::array<int, kMaxLines> injTap_ {};
2003 std::array<T, kMaxLines> injGain_ {};
2004 std::array<T, kMaxLines> outSignL_ {}, outSignR_ {};
2005 std::array<SmoothRandomLFO, kMaxLines> lfo_;
2006 // Time-varying mixing: one slow Givens rotation per line pair after the
2007 // Hadamard mix (orthogonal, so the loop stays lossless).
2009 alignas(64) std::array<T, kMaxLines / 2> rotC_ {};
2010 alignas(64) std::array<T, kMaxLines / 2> rotS_ {};
2011 T rotDepth_ = T(0);
2012 unsigned rotTick_ = 0;
2014 T glideCoeff_ = T(0);
2016 T maxReadPos_ = T(8);
2017
2018 // Spring tanks: stretched-allpass histories [spring][stage + 1][P]
2019 // (stage m reads history m and writes history m + 1), shared write
2020 // index; 4th-order Butterworth band limit per spring.
2021 bool spring_ = false;
2022 std::vector<T> springHist_;
2023 int springP_ = 8;
2024 int springW_ = 0;
2025 int springK_ = 5;
2027 T springA_ = T(0.5);
2028 std::array<std::array<T, 5>, 2> springLP_ {};
2029 std::array<std::array<T, kSprings>, 4> springLPState_ {};
2030
2031 // In-loop allpasses
2033 std::array<int, kMaxLines> loopAPLen_ {};
2034 std::array<T, kMaxLines> loopAPCur_ {};
2035 bool loopAPGliding_ = false;
2036 T loopAPCoeff_ = T(0.4);
2038
2039 // Absorption: Jot shelf (mid/high) and bass shelf, per line
2040 std::array<T, kMaxLines> jotB0_ {}, jotB1_ {}, jotA1_ {}, jotX1_ {}, jotY1_ {};
2041 std::array<T, kMaxLines> bassB0_ {}, bassB1_ {}, bassA1_ {}, bassX1_ {}, bassY1_ {};
2042 // Air absorption: per line, the taps of e^-b sum (b z^-1)^n / n! over the
2043 // last kAirTaps samples of what the shelves leave ([tap][line]), their
2044 // ramp across a chunk, and b designed, gliding and in use (with the hold).
2045 static constexpr int kAirTaps = 16;
2046 using AirTaps = std::array<std::array<T, kMaxLines>, kAirTaps>;
2047 static constexpr AirTaps identityAirTaps() noexcept
2048 {
2049 AirTaps t {};
2050 for (auto& v : t[0]) v = T(1);
2051 return t;
2052 }
2054 int airW_ = 0;
2056 bool airInUse_ = false;
2057 std::array<T, kMaxLines> airGoal_ {}, airBase_ {}, airNow_ {};
2058
2059 // Output stage
2060 // These low-frequency recursions need the shared double-precision core.
2061 // Coefficients are owned by prepare(); no cross-thread publications.
2064
2065 // Tone correction EQ (Biquad 12 dB/oct)
2068 bool toneLPActive_ = false;
2069 bool toneHPActive_ = false;
2070 // Cutoff changes glide in the log domain, chunk by chunk; switching a
2071 // filter on or off crossfades between the filtered and the plain signal.
2072 double toneLPCurHz_ = 0.0, toneLPTargetHz_ = 0.0;
2073 double toneHPCurHz_ = 0.0, toneHPTargetHz_ = 0.0;
2074 bool toneLPOn_ = false, toneHPOn_ = false;
2075 T toneLPMix_ = T(0), toneHPMix_ = T(0);
2076
2077 // Gliding output gains (setEarlyLevel/setLateLevel/setWidth targets).
2078 T earlyCur_ = T(1), lateCur_ = T(1), widthCur_ = T(1);
2079 bool fresh_ = true;
2080
2082
2083 // --- Parameters ----------------------------------------------------------
2084 //
2085 // Thread-safety model: every setter mutates only the atomic shadows below
2086 // and raises a dirty flag; the audio thread drains the flags at the top of
2087 // processBlock()/processSample() and rebuilds the non-atomic coefficient
2088 // arrays there, so nothing on the audio path is written from other threads.
2089 // The parameter atomics have one writer, the control thread: setType()
2090 // writes the preset's values itself, and the audio thread only reads them.
2091
2092 std::atomic<Type> type_ { Type::Room };
2093 std::atomic<T> decayTime_ { T(1) };
2094 std::atomic<T> size_ { T(0.5) };
2095 std::atomic<T> damping_ { T(0.5) };
2096 std::atomic<T> diffusion_ { T(0.7) };
2097 std::atomic<T> modDepth_ { T(0.1) };
2098 std::atomic<T> modRate_ { T(1) };
2099 std::atomic<T> preDelayMs_ { T(0) };
2100 std::atomic<T> erToLateMs_ { T(0) };
2101 std::atomic<T> mix_ { T(0.3) };
2102 std::atomic<T> earlyLevel_ { T(1) };
2103 std::atomic<T> lateLevel_ { T(1) };
2104 std::atomic<T> width_ { T(1) }; // 0 = mono, 1 = natural, 2 = wide
2105
2106 std::atomic<T> highDecayMult_ { T(0.5) }; // HF T60 multiplier (0.05-1.0)
2107 std::atomic<T> bassDecayMult_ { T(1.2) }; // bass T60 multiplier (0.3-3.0)
2108 std::atomic<T> highCrossover_ { T(5000) }; // Hz
2109 std::atomic<T> airAbsorption_ { T(0) }; // 0 off, 1 the air of ISO 9613-1
2110 std::atomic<T> bassCrossover_ { T(200) }; // Hz
2111
2112 std::atomic<Quality> quality_ { Quality::Full };
2113
2114 std::atomic<int> preDelaySamples_ { 0 };
2115 std::atomic<int> erToLateSamples_ { 0 };
2116
2117 std::atomic<bool> presetDirty_ { false }; // setType() -> rebuild + reset
2118 std::atomic<bool> paramsDirty_ { false }; // other setters -> refresh coefficients
2119 std::atomic<bool> qualityDirty_ { false }; // setQuality() -> resize engine + reset
2120 std::atomic<bool> toneDirty_ { false }; // tone EQ cutoff changes
2121 std::atomic<T> toneLowCutHz_ { T(-1) }; // <= 0 = off
2122 std::atomic<T> toneHighCutHz_ { T(-1) };
2123
2124 // Per-param user-override mask. setType() clears it and writes the preset
2125 // on the calling thread, so a setter issued after it simply overwrites the
2126 // preset's value (the documented quick-start is
2127 // `setType(Hall); setDecay(2.0f);`). prepare() re-applies the selected
2128 // preset and skips every atomic whose bit is set, so the values configured
2129 // before prepare() survive it.
2130 enum : uint32_t {
2133 kUserModDepth = 128u, kUserModRate = 256u, kUserEarly = 512u,
2134 kUserLate = 1024u, kUserErToLate = 2048u
2136 std::atomic<uint32_t> userParamMask_ { 0u };
2137 void markUserParam(uint32_t bit) noexcept
2138 { userParamMask_.fetch_or(bit, std::memory_order_release); }
2139
2142 {
2145 T earlyLevel = T(1);
2146 T lateLevel = T(1);
2147 T width = T(1);
2148 T inputWidth = T(1);
2150 bool tankSat = false;
2151 bool powerKept = false;
2152 bool segments = false;
2153 T shimmer = T(0);
2154 T sourceDepth = T(0);
2155 };
2157
2158 // Around the tank (settings).
2160 {
2161 std::atomic<int> shape { 0 };
2162 std::atomic<T> frequency { T(1000) };
2163 std::atomic<T> q { T(0.7071) };
2164 std::atomic<T> multiplier { T(1) };
2165 };
2166 std::array<PublishedDecayBand, kDecayBands> decayBands_;
2167 std::atomic<bool> tailHold_ { false }, tankSat_ { false };
2168 std::atomic<T> sourceDepth_ { T(0) }, tankLeveling_ { T(0) }, tempo_ { T(120) }, inputWidth_ { T(1) };
2169 std::atomic<T> shimmer_ { T(0) }, gateHoldMs_ { T(100) };
2170 std::atomic<int> preNote_ { 0 }, preFeel_ { 0 }, gateNote_ { 0 }, gateFeel_ { 0 };
2171 std::atomic<int> widthLaw_ { 0 }, modStyle_ { 0 }, layout_ { 0 };
2174
2175 // ... and their state (audio thread).
2176 std::array<std::array<T, kMaxLines>, 3> jotBase_ {}, bassBase_ {};
2177 std::array<std::array<std::array<T, kMaxLines>, kDecayBands>, 5> dqBase_ {};
2178 // The designed absorption the above glide to after a change of decay,
2179 // size or band while the tank holds signal (see updateDecayParams()).
2180 std::array<std::array<T, kMaxLines>, 3> jotGoal_ {}, bassGoal_ {};
2181 std::array<std::array<std::array<T, kMaxLines>, kDecayBands>, 5> dqGoal_ {};
2182 bool absorbGlide_ = false;
2184 std::array<std::array<T, kMaxLines>, 6> absFrom_ {}, absStep_ {};
2185 std::array<std::array<std::array<T, kMaxLines>, kDecayBands>, 5> dqFrom_ {}, dqStep_ {};
2186 double quietSamples_ = 1e300;
2187 double tankEmptyAfter_ = 0.0;
2188 std::array<std::array<T, kMaxLines>, kDecayBands> dqB0_ {}, dqB1_ {}, dqB2_ {}, dqA1_ {}, dqA2_ {};
2189 std::array<std::array<T, kMaxLines>, kDecayBands> dqZ1_ {}, dqZ2_ {};
2190 std::array<int, kDecayBands> dqList_ {};
2191 int dqCount_ = 0;
2192 T holdNow_ = T(0);
2193 double levelGr_ = 0.0, levelRelease_ = 0.0;
2195 std::array<T, 2> distLp_ {};
2196 T distCoeff_ = T(1), distMix_ = T(0);
2197 std::array<SegmentLfo, kMaxLines> seg_ {};
2198 std::vector<T> shimBuf_;
2199 int shimMask_ = 0, shimW_ = 0;
2200 std::array<double, 2> shimPhase_ { 0.0, 0.5 };
2201 std::array<double, 2> shimLen_ { 0.045, 0.045 };
2202 uint32_t shimRng_ = 0x51ED27u;
2204
2205 // =========================================================================
2206 // Audio-thread control
2207 // =========================================================================
2208
2216 void drainPendingChanges() noexcept
2217 {
2218 if (qualityDirty_.load(std::memory_order_acquire)
2219 && qualityDirty_.exchange(false, std::memory_order_acquire))
2220 {
2221 const bool eco = quality_.load(std::memory_order_relaxed) == Quality::Eco;
2222 if (eco != eco_)
2223 {
2224 eco_ = eco;
2226 updateAll();
2227 reset(); // engine topology changed: old state is stale
2228 }
2229 }
2230
2231 if (presetDirty_.load(std::memory_order_acquire)
2232 && presetDirty_.exchange(false, std::memory_order_acquire))
2233 {
2234 // setType() already wrote the preset's values; build the engine.
2235 applyTopology(type_.load(std::memory_order_relaxed));
2236 reset(); // new room: drop the old tail, snap the lengths
2237 paramsDirty_.store(false, std::memory_order_relaxed);
2238 }
2239 else if (paramsDirty_.load(std::memory_order_acquire)
2240 && paramsDirty_.exchange(false, std::memory_order_acquire))
2241 {
2242 // Knob change: refresh coefficients without touching the audio
2243 // state; line lengths glide to their new targets.
2244 updateAll();
2245 }
2246
2247 drainTone();
2248 // Before the first sample after prepare() or reset() there is nothing
2249 // to glide from: settings made then apply at once.
2250 if (fresh_) snapGlides();
2251 }
2252
2254 void snapGlides() noexcept
2255 {
2256 const T d = sourceDepth_.load(std::memory_order_relaxed);
2257 earlyCur_ = earlyLevel_.load(std::memory_order_relaxed) * wetLevel_ * (d > T(0) ? T(1) - T(0.5) * d : T(1));
2258 lateCur_ = lateLevel_.load(std::memory_order_relaxed) * wetLevel_ * (d > T(0) ? T(1) + T(0.5) * d : T(1));
2259 widthCur_ = width_.load(std::memory_order_relaxed);
2263 snapTone();
2264 }
2265
2268 static T glideTo(T cur, T target, T amount) noexcept
2269 {
2270 const T next = cur + amount * (target - cur);
2271 return std::abs(target - next) <= T(1e-6) * std::max(T(1), std::abs(target)) ? target : next;
2272 }
2273
2274 void drainTone() noexcept
2275 {
2276 if (!(toneDirty_.load(std::memory_order_acquire)
2277 && toneDirty_.exchange(false, std::memory_order_acquire)))
2278 return;
2279 if (!(spec_.sampleRate > 0)) return;
2280 const T hpHz = toneLowCutHz_.load(std::memory_order_relaxed);
2281 const T lpHz = toneHighCutHz_.load(std::memory_order_relaxed);
2282 toneHPOn_ = hpHz > T(0);
2283 if (toneHPOn_)
2284 {
2285 toneHPTargetHz_ = static_cast<double>(std::clamp(hpHz, T(20), T(500)));
2286 if (!toneHPActive_)
2287 {
2288 // Off before: start at the target, from a clean state, while
2289 // the crossfade brings the filtered signal in.
2290 toneHPActive_ = true;
2294 }
2295 }
2296 toneLPOn_ = lpHz > T(0);
2297 if (toneLPOn_)
2298 {
2299 toneLPTargetHz_ = static_cast<double>(std::clamp(lpHz, T(2000), T(16000)));
2300 if (!toneLPActive_)
2301 {
2302 toneLPActive_ = true;
2306 }
2307 }
2308 }
2309
2311 static void glideHz(double& cur, double target, double amount) noexcept
2312 {
2313 const double ratio = target / cur;
2314 if (std::abs(ratio - 1.0) < 1e-4) cur = target;
2315 else cur *= std::pow(ratio, amount);
2316 }
2317
2321 void advanceTone(T amount, T& hp0, T& lp0) noexcept
2322 {
2323 hp0 = toneHPMix_;
2324 lp0 = toneLPMix_;
2325 const double a = static_cast<double>(amount);
2326 if (toneHPActive_)
2327 {
2329 {
2332 }
2333 toneHPMix_ = glideTo(toneHPMix_, toneHPOn_ ? T(1) : T(0), amount);
2334 if (!toneHPOn_ && toneHPMix_ == T(0) && hp0 == T(0)) toneHPActive_ = false;
2335 }
2336 if (toneLPActive_)
2337 {
2339 {
2342 }
2343 toneLPMix_ = glideTo(toneLPMix_, toneLPOn_ ? T(1) : T(0), amount);
2344 if (!toneLPOn_ && toneLPMix_ == T(0) && lp0 == T(0)) toneLPActive_ = false;
2345 }
2346 }
2347
2363
2365 void refreshCachedParams() noexcept
2366 {
2367 cachedParams_.preDelaySamples = preDelaySamples_.load(std::memory_order_relaxed);
2368 cachedParams_.erToLateSamples = erToLateSamples_.load(std::memory_order_relaxed);
2369 cachedParams_.earlyLevel = earlyLevel_.load(std::memory_order_relaxed) * wetLevel_;
2370 cachedParams_.lateLevel = lateLevel_.load(std::memory_order_relaxed) * wetLevel_;
2371 cachedParams_.width = width_.load(std::memory_order_relaxed);
2372 cachedParams_.inputWidth = inputWidth_.load(std::memory_order_relaxed);
2373 cachedParams_.tankLeveling = tankLeveling_.load(std::memory_order_relaxed);
2374 cachedParams_.tankSat = tankSat_.load(std::memory_order_relaxed);
2375 cachedParams_.powerKept = widthLaw_.load(std::memory_order_relaxed) == 1;
2376 cachedParams_.segments = modStyle_.load(std::memory_order_relaxed) == 1;
2377 cachedParams_.shimmer = shimmer_.load(std::memory_order_relaxed);
2378 cachedParams_.sourceDepth = sourceDepth_.load(std::memory_order_relaxed);
2379 const T d = cachedParams_.sourceDepth;
2380 if (d > T(0))
2381 {
2382 // Source depth: from the early field to the tail, a shorter gap.
2383 cachedParams_.earlyLevel *= T(1) - T(0.5) * d;
2384 cachedParams_.lateLevel *= T(1) + T(0.5) * d;
2385 cachedParams_.preDelaySamples = static_cast<int>(static_cast<T>(cachedParams_.preDelaySamples)
2386 * (T(1) - T(0.8) * d));
2387 }
2388 tail_.sync();
2389 }
2390
2396 void controlTick() noexcept
2397 {
2398 const int n = nLines_;
2399 // The pair angles move by under 0.005 rad per 64 samples: refresh
2400 // their sine and cosine every fourth control tick.
2401 if ((++rotTick_ & 3) == 0)
2402 for (int k = 0; k < n / 2; ++k)
2403 {
2404 const T theta = rotLfo_[k].nextStride(4 * kCtrl) * rotDepth_;
2405 // Form the rotation in double before rounding coefficients to T.
2406 // Single-precision libm differences are otherwise recirculated
2407 // through the feedback network on every sample.
2408 rotC_[k] = static_cast<T>(std::cos(static_cast<double>(theta)));
2409 rotS_[k] = static_cast<T>(std::sin(static_cast<double>(theta)));
2410 }
2411 const bool segments = cachedParams_.segments;
2412 const double sr = spec_.sampleRate;
2413 const double rate = static_cast<double>(modRate_.load(std::memory_order_relaxed));
2414 // A change of size beyond kSizeFadeOver of a line's length opens a
2415 // second read head at the new lengths and cross-fades to it (a glide
2416 // of the lengths is a glide of pitch); a smaller one glides. While a
2417 // fade runs the next change waits.
2418 if (!sizeFade_)
2419 {
2420 T widest = T(0);
2421 for (int i = 0; i < n; ++i)
2422 widest = std::max(widest, std::abs(static_cast<T>(lenTarget_[i]) - lenCur_[i]) / std::max(lenCur_[i], T(1)));
2423 if (widest > static_cast<T>(kSizeFadeOver)) beginSizeFade();
2424 }
2425 for (int i = 0; i < n; ++i)
2426 {
2427 if (!sizeFade_)
2428 {
2429 const T diff = static_cast<T>(lenTarget_[i]) - lenCur_[i];
2430 lenCur_[i] += std::clamp(diff * glideCoeff_, -maxGlideStep_, maxGlideStep_);
2431 }
2432 // Segments: every other line, its depth held under 2 % of its length.
2433 const T wander = segments
2434 ? ((i & 1) ? T(0) : static_cast<T>(seg_[i].next(kCtrl, rate * static_cast<double>(lfoRateFactor(i)), sr)))
2435 : lfo_[i].nextStride(kCtrl);
2436 const auto aim = [&](T length) {
2437 const T m = wander * (segments ? std::min(modDepthSamples_, T(0.02) * length) : modDepthSamples_);
2438 return std::clamp(static_cast<double>(length) + static_cast<double>(m),
2439 static_cast<double>(kMinReadPos), static_cast<double>(maxReadPos_));
2440 };
2441 posInc_[i] = (aim(lenCur_[i]) - pos_[i]) * (1.0 / static_cast<double>(kCtrl));
2442 if (sizeFade_) posInc2_[i] = (aim(lenNew_[i]) - pos2_[i]) * (1.0 / static_cast<double>(kCtrl));
2443 }
2444 if (loopAPGliding_ && !sizeFade_)
2445 {
2446 // The in-loop allpasses follow a size change with the lines.
2447 bool moving = false;
2448 for (int i = 0; i < n; ++i)
2449 {
2450 const T diff = static_cast<T>(loopAPLen_[i]) - loopAPCur_[i];
2451 if (std::abs(diff) < T(0.01))
2452 loopAPCur_[i] = static_cast<T>(loopAPLen_[i]);
2453 else
2454 {
2455 loopAPCur_[i] += std::clamp(diff * glideCoeff_, -maxGlideStep_, maxGlideStep_);
2456 moving = true;
2457 }
2458 }
2459 loopAPGliding_ = moving;
2460 }
2461 }
2462
2470 void beginSizeFade() noexcept
2471 {
2472 for (int i = 0; i < nLines_; ++i)
2473 {
2474 const auto l = static_cast<std::size_t>(i);
2475 lenNew_[l] = static_cast<T>(lenTarget_[l]);
2476 pos2_[l] = std::clamp(static_cast<double>(lenNew_[l]) + (pos_[l] - static_cast<double>(lenCur_[l])),
2477 static_cast<double>(kMinReadPos), static_cast<double>(maxReadPos_));
2478 posInc2_[l] = 0.0;
2479 apY2_[l] = lines_.at(i, static_cast<int>(pos2_[l] - kApLow) + 1);
2480 loopAPFrom_[l] = static_cast<int>(loopAPCur_[l] + T(0.5));
2481 loopAPTo_[l] = loopAPLen_[l];
2482 }
2483 fadeAt_ = 0.0;
2484 sizeFade_ = true;
2485 }
2486
2488 void endSizeFade() noexcept
2489 {
2490 bool allpassesMoved = false;
2491 for (int i = 0; i < nLines_; ++i)
2492 {
2493 const auto l = static_cast<std::size_t>(i);
2494 pos_[l] = pos2_[l];
2495 posInc_[l] = posInc2_[l];
2496 apY1_[l] = apY2_[l];
2497 lenCur_[l] = lenNew_[l];
2498 loopAPCur_[l] = static_cast<T>(loopAPTo_[l]);
2499 allpassesMoved = allpassesMoved || loopAPTo_[l] != loopAPLen_[l];
2500 }
2501 loopAPGliding_ = allpassesMoved;
2502 sizeFade_ = false;
2503 }
2504
2507 template <int M>
2508 static void hadamardSmall(T* x) noexcept
2509 {
2510 if constexpr (M > 1)
2511 {
2512 hadamardSmall<M / 2>(x);
2513 hadamardSmall<M / 2>(x + M / 2);
2514 [x]<std::size_t... I>(std::index_sequence<I...>) {
2515 ((void) [x] {
2516 const T a = x[I], b = x[I + M / 2];
2517 x[I] = a + b;
2518 x[I + M / 2] = a - b;
2519 }(), ...);
2520 }(std::make_index_sequence<M / 2> {});
2521 }
2522 }
2523
2526 template <int N, int W, typename O>
2527 static void fwht(T* x) noexcept
2528 {
2529 using V = typename O::V;
2530 for (int b = 0; b < N; b += W)
2531 hadamardSmall<W>(x + b);
2532 for (int h = W; h < N; h <<= 1)
2533 for (int i = 0; i < N; i += h << 1)
2534 for (int j = i; j < i + h; j += W)
2535 {
2536 const V a = O::load(x + j), b = O::load(x + j + h);
2537 O::store(x + j, O::add(a, b));
2538 O::store(x + j + h, O::sub(a, b));
2539 }
2540 }
2541
2548 template <int N>
2549 void runFdn(T& lateL, T& lateR, int injLag, T loopAPCoeff, T inGain, T extra) noexcept
2550 {
2551 constexpr int W = std::min(simd::kVecWidth<T>, N);
2552 using O = simd::Vec<T, W>;
2553 using V = typename O::V;
2554 static_assert(N % W == 0, "line count must be a multiple of the SIMD width");
2555
2556 alignas(64) std::array<T, N + 1> r; // +1: wrap slot for the rotation
2557 alignas(64) std::array<T, N> v;
2558 alignas(64) std::array<T, N> tmp;
2559 alignas(64) std::array<int, N> idx;
2560
2561 // Allpass-interpolated modulated reads: eta = (1 - d) / (1 + d) for
2562 // the fractional delay d in [kApLow, kApLow + 1) (see allpassRead).
2563 // The arithmetic runs in separate (vectorizable) passes around the
2564 // scalar gather.
2565 for (int i = 0; i < N; ++i)
2566 {
2567 const double p = pos_[i] += posInc_[i];
2568 const int M = static_cast<int>(p - kApLow);
2569 v[i] = allpassCoeff(p - static_cast<double>(M));
2570 idx[i] = M;
2571 }
2572 for (int i = 0; i < N; ++i)
2573 {
2574 r[i] = lines_.at(i, idx[i]);
2575 tmp[i] = lines_.at(i, idx[i] + 1);
2576 }
2577 for (int i = 0; i < N; i += W)
2578 {
2579 const V y = O::madd(O::load(v.data() + i),
2580 O::sub(O::load(r.data() + i), O::load(apY1_.data() + i)),
2581 O::load(tmp.data() + i));
2582 O::store(apY1_.data() + i, y);
2583 O::store(r.data() + i, y);
2584 }
2585 // A change of size under way: the second head, at the new lengths,
2586 // takes over from the first at constant power.
2587 const bool fading = sizeFade_;
2588 const T fadeNew = fading ? static_cast<T>(std::sin(1.5707963267948966 * fadeAt_)) : T(0);
2589 const T fadeOld = fading ? static_cast<T>(std::cos(1.5707963267948966 * fadeAt_)) : T(1);
2590 if (fading) [[unlikely]]
2591 for (int i = 0; i < N; ++i)
2592 {
2593 const double p = pos2_[i] += posInc2_[i];
2594 const int M = static_cast<int>(p - kApLow);
2595 const T y = allpassCoeff(p - static_cast<double>(M)) * (lines_.at(i, M) - apY2_[i]) + lines_.at(i, M + 1);
2596 apY2_[i] = y;
2597 r[i] = fadeOld * r[i] + fadeNew * y;
2598 }
2599
2600 // Absorption of what each line delivers (its own round trip: the
2601 // in-loop allpass that fed it plus the line): Jot mid/high shelf,
2602 // then bass shelf, y = b0 x + b1 x1 - a1 y1 each.
2603 for (int i = 0; i < N; i += W)
2604 {
2605 const V x = O::load(r.data() + i);
2606 const V j = O::sub(O::madd(O::load(jotB0_.data() + i), x,
2607 O::mul(O::load(jotB1_.data() + i), O::load(jotX1_.data() + i))),
2608 O::mul(O::load(jotA1_.data() + i), O::load(jotY1_.data() + i)));
2609 O::store(jotX1_.data() + i, x);
2610 O::store(jotY1_.data() + i, j);
2611 const V b = O::sub(O::madd(O::load(bassB0_.data() + i), j,
2612 O::mul(O::load(bassB1_.data() + i), O::load(bassX1_.data() + i))),
2613 O::mul(O::load(bassA1_.data() + i), O::load(bassY1_.data() + i)));
2614 O::store(bassX1_.data() + i, j);
2615 O::store(bassY1_.data() + i, b);
2616 O::store(r.data() + i, b);
2617 }
2618 if (airInUse_)
2619 {
2620 const int at = airW_;
2621 T* const now = airHist_[static_cast<std::size_t>(at)].data();
2622 for (int i = 0; i < N; i += W) O::store(now + i, O::load(r.data() + i));
2623 for (int i = 0; i < N; i += W)
2624 {
2625 V acc = O::mul(O::load(airTap_[0].data() + i), O::load(now + i));
2626 for (int n = 1; n < airTapCount_; ++n)
2627 acc = O::madd(O::load(airTap_[static_cast<std::size_t>(n)].data() + i),
2628 O::load(airHist_[static_cast<std::size_t>((at - n) & (kAirTaps - 1))].data() + i), acc);
2629 O::store(r.data() + i, acc);
2630 }
2631 airW_ = (at + 1) & (kAirTaps - 1);
2632 }
2633 if (dqCount_ > 0) applyDecayBands<N, W, O>(r.data());
2634
2635 // Orthogonal L/R output sums, taken after the absorption: even the
2636 // first pass through a line leaves attenuated by that line's own
2637 // decay, so the tail decays exponentially from its first echoes
2638 // instead of holding a plateau for one round trip.
2639 {
2640 V aL = O::set1(T(0)), aR = aL;
2641 for (int i = 0; i < N; i += W)
2642 {
2643 const V x = O::load(r.data() + i);
2644 aL = O::madd(O::load(outSignL_.data() + i), x, aL);
2645 aR = O::madd(O::load(outSignR_.data() + i), x, aR);
2646 }
2647 alignas(64) std::array<T, W> sumL, sumR;
2648 O::store(sumL.data(), aL);
2649 O::store(sumR.data(), aR);
2650 for (int k = 0; k < W; ++k) { lateL += sumL[k]; lateR += sumR[k]; }
2651 }
2652
2653 // Hadamard mix, rotation of the lines by one, normalisation.
2654 const V norm = O::set1(T(1) / std::sqrt(static_cast<T>(N)));
2655 fwht<N, W, O>(r.data());
2656 r[N] = r[0];
2657 for (int i = 0; i < N; i += W)
2658 O::store(v.data() + i, O::mul(norm, O::load(r.data() + i + 1)));
2659 // Slow Givens rotation of each line pair: the mixing matrix drifts
2660 // while staying orthogonal (lossless), so modes exchange energy
2661 // without the pitch deviation of delay modulation, whose spread
2662 // grows with frequency.
2663 // Pairs (i, i + 4) inside each block of 8: contiguous, branch-free,
2664 // so the four rotations of a block run as one vector operation.
2665 static_assert(kRotPairStride == 4 && N % 8 == 0, "rotation pairs are (i, i + 4) in blocks of 8");
2666 for (int blk = 0; blk < N; blk += 8)
2667 {
2668 T* lo = v.data() + blk;
2669 T* hi = lo + 4;
2670 const T* c = rotC_.data() + blk / 2;
2671 const T* sn = rotS_.data() + blk / 2;
2672 for (int q = 0; q < 4; ++q)
2673 {
2674 const T a = lo[q], b = hi[q];
2675 lo[q] = c[q] * a - sn[q] * b;
2676 hi[q] = sn[q] * a + c[q] * b;
2677 }
2678 }
2679
2680 {
2681 if (fading) [[unlikely]]
2682 {
2683 for (int i = 0; i < N; ++i)
2684 tmp[i] = fadeOld * loopAP_.at(i, loopAPFrom_[i]) + fadeNew * loopAP_.at(i, loopAPTo_[i]);
2685 }
2686 else if (loopAPGliding_) [[unlikely]]
2687 {
2688 for (int i = 0; i < N; ++i)
2689 {
2690 const int k = static_cast<int>(loopAPCur_[i]);
2691 const T f = loopAPCur_[i] - static_cast<T>(k);
2692 const T a = loopAP_.at(i, k);
2693 tmp[i] = a + f * (loopAP_.at(i, k + 1) - a);
2694 }
2695 }
2696 else
2697 {
2698 for (int i = 0; i < N; ++i)
2699 tmp[i] = loopAP_.at(i, loopAPLen_[i]);
2700 }
2701 const V g = O::set1(loopAPCoeff);
2702 for (int i = 0; i < N; i += W)
2703 {
2704 const V d = O::load(tmp.data() + i);
2705 const V w = O::madd(g, d, O::load(v.data() + i));
2706 O::store(v.data() + i, O::sub(d, O::mul(g, w)));
2707 O::store(tmp.data() + i, w);
2708 }
2709 for (int i = 0; i < N; ++i)
2710 loopAP_.write(i, tmp[i]);
2711 loopAP_.advance();
2712 }
2713
2714 for (int i = 0; i < N; ++i)
2715 {
2716 T x = v[i];
2717 // Safety limiter (never reached at sane levels): identity below
2718 // kSoftLimit, a rational soft knee above.
2719 if (std::abs(x) > kSoftLimit) [[unlikely]]
2720 {
2721 const T over = std::abs(x) - kSoftLimit;
2722 x = std::copysign(kSoftLimit + over / (T(1) + over), x);
2723 }
2724 lines_.write(i, x + injGain_[i] * (inGain * ring_[(i >> 1) & 1].at(injLag + injTap_[i]) + extra));
2725 }
2726 lines_.advance();
2727 if (fading) [[unlikely]] advanceSizeFade();
2728 }
2729
2736 void designPlate(double decay, double t60H, double crossoverHz) noexcept
2737 {
2738 auto& p = plate_;
2739 const double sr = spec_.sampleRate;
2740 p.on = plateTank_.load(std::memory_order_relaxed) && erType_ == Type::Plate && !spring_;
2741 if (!p.on) return;
2742 double damp = 0.0;
2743 for (int b = 0; b < 2; ++b)
2744 {
2745 const auto s = static_cast<std::size_t>(b);
2746 const double L = static_cast<double>(p.lAp1[s] + p.lD1[s] + p.lAp2[s] + p.lD2[s]);
2747 p.gain[s] = static_cast<T>(std::pow(0.001, L / (decay * sr)));
2748 // |(1 - d) / (1 - d e^-jw)| at the crossover equals what the high
2749 // decay takes over the mid one in a pass: the lower root of
2750 // (1 - q^2) d^2 - 2 (1 - q^2 c) d + (1 - q^2) = 0.
2751 const double q = std::pow(0.001, L / sr * (1.0 / t60H - 1.0 / decay));
2752 if (q < 1.0)
2753 {
2754 const double c = std::cos(2.0 * 3.14159265358979323846 * crossoverHz / sr), q2 = q * q;
2755 const double A = 1.0 - q2, B = 1.0 - q2 * c;
2756 damp = std::max(damp, (B - std::sqrt(std::max(0.0, B * B - A * A))) / A);
2757 }
2758 }
2759 p.damp = static_cast<T>(std::clamp(damp, 0.0, 0.99));
2760 p.excursion = static_cast<double>(modDepth_.load(std::memory_order_relaxed)) * PlateTank::kExcursion * p.scale;
2761 p.phaseStep = static_cast<double>(modRate_.load(std::memory_order_relaxed)) / sr;
2762 // The taps read inside the branches, so the first pass counts in full.
2763 const double tail = 1.0 / -std::expm1(-std::min(2.0 * 6.907755278982137 * p.loopSec / std::max(1e-3, decay), 50.0));
2764 wetLevel_ = static_cast<T>(kWetCalibration / std::sqrt(std::max(1e-6, kPlateEnergy * tail)));
2765 }
2766
2768 void runPlate(T& lateL, T& lateR, int injLag, T inGain, T extra) noexcept
2769 {
2770 auto& p = plate_;
2771 const T in = T(0.5) * (ring_[0].at(injLag + 1) + ring_[1].at(injLag + 1)) * inGain + extra;
2772 const T hold = holdNow_;
2773 const std::array<T, 2> ends { p.d2[0].at(p.lD2[0]), p.d2[1].at(p.lD2[1]) };
2774 p.phase += p.phaseStep;
2775 if (p.phase >= 1.0) p.phase -= 1.0;
2776 for (int b = 0; b < 2; ++b)
2777 {
2778 const auto s = static_cast<std::size_t>(b);
2779 T x = in + ends[1 - s];
2780 // The first all-pass, its length moved by the modulation (the
2781 // two branches a quarter of a turn apart), read between samples.
2782 const double turn = p.phase + 0.25 * b;
2783 const double pos = static_cast<double>(p.lAp1[s])
2784 + p.excursion * static_cast<double>(fastSin(static_cast<T>(6.283185307179586 * (turn - std::floor(turn)) - 3.141592653589793)));
2785 const int k = static_cast<int>(pos);
2786 const T fr = static_cast<T>(pos - k);
2787 const T dl = p.ap1[s].at(k) + fr * (p.ap1[s].at(k + 1) - p.ap1[s].at(k));
2788 const T w1 = x + PlateTank::kDiffusion1 * dl;
2789 p.ap1[s].push(w1);
2790 x = dl - PlateTank::kDiffusion1 * w1;
2791 const T v = p.d1[s].at(p.lD1[s]);
2792 p.d1[s].push(x);
2793 // Damping and decay (both open while the tail is held).
2794 const T damp = p.damp * (T(1) - hold);
2795 p.lp[s] = v + damp * (p.lp[s] - v);
2796 x = p.lp[s] * (p.gain[s] + (T(1) - p.gain[s]) * hold);
2797 const T d2 = p.ap2[s].at(p.lAp2[s]);
2798 const T w2 = x + PlateTank::kDiffusion2 * d2;
2799 p.ap2[s].push(w2);
2800 p.d2[s].push(d2 - PlateTank::kDiffusion2 * w2);
2801 }
2802 // Dattorro's taps (at 29761 Hz), each side mostly from the other branch.
2803 auto tap = [&p](const Line& l, double at29k) { return l.at(p.at(at29k)); };
2804 lateL += T(0.6) * (tap(p.d1[1], 266) + tap(p.d1[1], 2974) - tap(p.ap2[1], 1913) + tap(p.d2[1], 1996)
2805 - tap(p.d1[0], 1990) - tap(p.ap2[0], 187) - tap(p.d2[0], 1066));
2806 lateR += T(0.6) * (tap(p.d1[0], 353) + tap(p.d1[0], 3627) - tap(p.ap2[0], 1228) + tap(p.d2[0], 2673)
2807 - tap(p.d1[1], 2111) - tap(p.ap2[1], 335) - tap(p.d2[1], 121));
2808 }
2809
2817 void designSecondSlope(double decay, double t60H, double Kh) noexcept
2818 {
2819 auto& s = slope2_;
2820 const double sr = spec_.sampleRate;
2821 const double d2 = kSecondRatio * decay, h2 = kSecondRatio * t60H;
2822 double loop = 0.0;
2823 for (int j = 0; j < SecondSlope::kLines; ++j)
2824 {
2825 const auto l = static_cast<std::size_t>(j);
2826 const double M = static_cast<double>(s.len[l]);
2827 loop += M;
2828 const double gM = std::pow(0.001, M / (d2 * sr));
2829 const double gH = std::min(std::pow(0.001, M / (h2 * sr)), gM);
2830 const double ratio = std::sqrt(gM / gH);
2831 const double a = Kh * ratio, b = Kh / ratio, inv = 1.0 / (1.0 + b);
2832 s.b0[l] = static_cast<T>(gH * (1.0 + a) * inv);
2833 s.b1[l] = static_cast<T>(gH * (a - 1.0) * inv);
2834 s.a1[l] = static_cast<T>((b - 1.0) * inv);
2835 }
2836 s.loopSec = loop / (SecondSlope::kLines * sr);
2837 const double amount = static_cast<double>(doubleSlope_.load(std::memory_order_relaxed));
2838 s.on = amount > 0.0 && !spring_;
2839 if (!s.on)
2840 {
2841 s.gain = T(0);
2842 s.keep = T(1);
2843 return;
2844 }
2845 const double share = kSecondShare * amount;
2846 // Each network's tail: g^2 / (1 - g^2) per unit in, g^2 = e^-(13.8 loop / T60).
2847 const auto tail = [](double loopSec, double t60) { return 1.0 / std::expm1(std::min(2.0 * 6.907755278982137 * loopSec / std::max(1e-3, t60), 50.0)); };
2848 const double own = tail(s.loopSec, kSecondRatio * decay) / std::max(1e-9, tail(meanLoopSec_, decay)); // its energy over the tank's
2849 s.gain = static_cast<T>(std::sqrt(share / ((1.0 - share) * own)));
2850 s.keep = static_cast<T>(std::sqrt(1.0 - share));
2851 }
2852
2854 void runSecondSlope(T& lateL, T& lateR, int injLag) noexcept
2855 {
2856 auto& s = slope2_;
2857 constexpr T kGlide = T(0.001);
2858 s.gainNow += kGlide * (s.gain - s.gainNow);
2859 s.keepNow += kGlide * (s.keep - s.keepNow);
2861 for (int j = 0; j < SecondSlope::kLines; ++j)
2862 {
2863 const auto l = static_cast<std::size_t>(j);
2864 const T x = s.line[l].at(s.len[l]);
2865 const T v = s.b0[l] * x + s.b1[l] * s.x1[l] - s.a1[l] * s.y1[l];
2866 s.x1[l] = x;
2867 s.y1[l] = v;
2868 y[j] = v;
2869 }
2870 const T outL = y[0] - y[1] + y[2] - y[3];
2871 const T outR = y[0] + y[1] - y[2] - y[3];
2872 hadamardSmall<SecondSlope::kLines>(y);
2873 for (int j = 0; j < SecondSlope::kLines; ++j)
2874 {
2875 const auto l = static_cast<std::size_t>(j);
2876 const T feed = ring_[static_cast<std::size_t>(j & 1)].at(injLag + 1 + 7 * j);
2877 s.line[l].push(T(0.5) * (y[j] + ((j & 2) ? -feed : feed)));
2878 }
2879 lateL = s.keepNow * lateL + s.gainNow * outL;
2880 lateR = s.keepNow * lateR + s.gainNow * outR;
2881 }
2882
2884 void advanceSizeFade() noexcept
2885 {
2886 fadeAt_ += fadeStep_;
2887 if (fadeAt_ >= 1.0) endSizeFade();
2888 }
2889
2894 template <int N, int W, typename O>
2895 void applyDecayBands(T* r) noexcept
2896 {
2897 using V = typename O::V;
2898 for (int k = 0; k < dqCount_; ++k)
2899 {
2900 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(k)]);
2901 T* z1 = dqZ1_[b].data();
2902 T* z2 = dqZ2_[b].data();
2903 const T* b0 = dqB0_[b].data();
2904 const T* b1 = dqB1_[b].data();
2905 const T* b2 = dqB2_[b].data();
2906 const T* a1 = dqA1_[b].data();
2907 const T* a2 = dqA2_[b].data();
2908 for (int i = 0; i < N; i += W)
2909 {
2910 const V x = O::load(r + i);
2911 const V y = O::madd(O::load(b0 + i), x, O::load(z1 + i));
2912 O::store(z1 + i, O::sub(O::madd(O::load(b1 + i), x, O::load(z2 + i)), O::mul(O::load(a1 + i), y)));
2913 O::store(z2 + i, O::sub(O::mul(O::load(b2 + i), x), O::mul(O::load(a2 + i), y)));
2914 O::store(r + i, y);
2915 }
2916 }
2917 }
2918
2936 template <int Springs, int Stages>
2937 void runSprings(T& lateL, T& lateR, const T (&raw)[2]) noexcept
2938 {
2939 // The springs are independent, so the stage cascade runs across
2940 // them: one SIMD lane per spring, the history laid out as
2941 // [stage][slot][spring].
2942 constexpr int NW = simd::kVecNarrowWidth<T>;
2943 constexpr int W = (Springs % NW == 0) ? NW : 1;
2944 using O = simd::Vec<T, W>;
2945 using V = typename O::V;
2946
2947 const int P = springP_;
2948 const int mask = P - 1;
2949 const int iw = springW_;
2950 const int ik = (springW_ - springK_) & mask;
2951 // Each spring hears mostly its own side (a mono input drives both);
2952 // the raw transducer signal, since any diffusion would blur the chirps.
2953 const T drive[2] = { T(0.75) * raw[0] + T(0.25) * raw[1],
2954 T(0.25) * raw[0] + T(0.75) * raw[1] };
2955
2956 // A change of size under way: a second head at the new lengths takes
2957 // over from the first at constant power (see beginSizeFade()).
2958 const bool fading = sizeFade_;
2959 const T fadeNew = fading ? static_cast<T>(std::sin(1.5707963267948966 * fadeAt_)) : T(0);
2960 const T fadeOld = fading ? static_cast<T>(std::cos(1.5707963267948966 * fadeAt_)) : T(1);
2961 alignas(64) std::array<T, Springs> x;
2962 for (int s = 0; s < Springs; ++s)
2963 {
2964 const double p = pos_[s] += posInc_[s];
2965 const int M = static_cast<int>(p - kApLow);
2966 const T eta = allpassCoeff(p - static_cast<double>(M));
2967 const T y = eta * (lines_.at(s, M) - apY1_[s]) + lines_.at(s, M + 1);
2968 apY1_[s] = y;
2969 x[s] = y;
2970 if (fading) [[unlikely]]
2971 {
2972 const double p2 = pos2_[s] += posInc2_[s];
2973 const int M2 = static_cast<int>(p2 - kApLow);
2974 const T y2 = allpassCoeff(p2 - static_cast<double>(M2)) * (lines_.at(s, M2) - apY2_[s]) + lines_.at(s, M2 + 1);
2975 apY2_[s] = y2;
2976 x[s] = fadeOld * y + fadeNew * y2;
2977 }
2978 }
2979
2980 // Dispersion: y = a (x - y[n-K]) + x[n-K], stage by stage.
2981 const V a = O::set1(springA_);
2982 T* hist = springHist_.data();
2983 const std::size_t stageStride = static_cast<std::size_t>(P) * kSprings;
2984 const std::size_t wOff = static_cast<std::size_t>(iw) * kSprings;
2985 const std::size_t kOff = static_cast<std::size_t>(ik) * kSprings;
2986 for (int g = 0; g < Springs; g += W)
2987 {
2988 V xv = O::load(x.data() + g);
2989 T* hin = hist + g;
2990 for (int m = 0; m < Stages; ++m, hin += stageStride)
2991 {
2992 O::store(hin + wOff, xv);
2993 xv = O::madd(a, O::sub(xv, O::load(hin + stageStride + kOff)), O::load(hin + kOff));
2994 }
2995 O::store(hin + wOff, xv);
2996 O::store(x.data() + g, xv);
2997 }
2998
2999 // Band limit: two TDF-II Butterworth sections.
3000 for (int k = 0; k < 2; ++k)
3001 {
3002 const auto& c = springLP_[static_cast<std::size_t>(k)];
3003 const V b0 = O::set1(c[0]), b1 = O::set1(c[1]), b2 = O::set1(c[2]);
3004 const V a1 = O::set1(c[3]), a2 = O::set1(c[4]);
3005 T* s1 = springLPState_[static_cast<std::size_t>(2 * k)].data();
3006 T* s2 = springLPState_[static_cast<std::size_t>(2 * k + 1)].data();
3007 for (int g = 0; g < Springs; g += W)
3008 {
3009 const V xv = O::load(x.data() + g);
3010 const V y = O::madd(b0, xv, O::load(s1 + g));
3011 O::store(s1 + g, O::sub(O::madd(b1, xv, O::load(s2 + g)), O::mul(a1, y)));
3012 O::store(s2 + g, O::sub(O::mul(b2, xv), O::mul(a2, y)));
3013 O::store(x.data() + g, y);
3014 }
3015 }
3016
3017 T out[2] = { T(0), T(0) };
3018 for (int s = 0; s < Springs; ++s) out[s & 1] += x[s];
3019
3020 // Absorption shelves (exact per-band T60), limiter, injection.
3021 for (int g = 0; g < Springs; g += W)
3022 {
3023 const V xv = O::load(x.data() + g);
3024 const V j = O::sub(O::madd(O::load(jotB0_.data() + g), xv,
3025 O::mul(O::load(jotB1_.data() + g), O::load(jotX1_.data() + g))),
3026 O::mul(O::load(jotA1_.data() + g), O::load(jotY1_.data() + g)));
3027 O::store(jotX1_.data() + g, xv);
3028 O::store(jotY1_.data() + g, j);
3029 const V b = O::sub(O::madd(O::load(bassB0_.data() + g), j,
3030 O::mul(O::load(bassB1_.data() + g), O::load(bassX1_.data() + g))),
3031 O::mul(O::load(bassA1_.data() + g), O::load(bassY1_.data() + g)));
3032 O::store(bassX1_.data() + g, j);
3033 O::store(bassY1_.data() + g, b);
3034 O::store(x.data() + g, b);
3035 }
3036 if (dqCount_ > 0) applyDecayBands<Springs, W, O>(x.data());
3037 for (int s = 0; s < Springs; ++s)
3038 {
3039 T v = x[s];
3040 if (std::abs(v) > kSoftLimit) [[unlikely]]
3041 {
3042 const T over = std::abs(v) - kSoftLimit;
3043 v = std::copysign(kSoftLimit + over / (T(1) + over), v);
3044 }
3045 lines_.write(s, v + drive[s & 1]);
3046 }
3047 lines_.advance();
3048 springW_ = (springW_ + 1) & mask;
3049 const T og = kSpringOutGain / std::sqrt(static_cast<T>(Springs / 2));
3050 lateL += out[0] * og;
3051 lateR += out[1] * og;
3052 if (fading) [[unlikely]] advanceSizeFade();
3053 }
3054
3056 void refreshTopology() noexcept
3057 {
3059 }
3060
3063 static void addTap(T* acc, const Line& l, int lag0, T gain, int count) noexcept
3064 {
3065 // The span is contiguous in the ring except across its wrap: split it
3066 // there so both parts run as SIMD multiply-adds.
3067 const T* b = l.buf.data();
3068 const int start = (l.w - lag0) & l.mask;
3069 const int first = std::min(count, l.mask + 1 - start);
3070 simd::addWithGain(acc, b + start, gain, first);
3071 if (first < count)
3072 simd::addWithGain(acc + first, b, gain, count - first);
3073 }
3074
3076 static void writeSpan(Line& l, const T* src, int count) noexcept
3077 {
3078 for (int s = 0; s < count;)
3079 {
3080 const int m = std::min(count - s, l.mask + 1 - l.w);
3081 T* DSPARK_RESTRICT dst = l.buf.data() + l.w;
3082 for (int k = 0; k < m; ++k) dst[k] = src[s + k];
3083 l.w = (l.w + m) & l.mask;
3084 s += m;
3085 }
3086 }
3087
3097 static void diffuseSpans(Line& ap, int len, T g0, T gDelta, const T* ramp, T* x, int count) noexcept
3098 {
3099 const int size = ap.mask + 1;
3100 const int delay = std::max(1, len);
3101 for (int s = 0; s < count;)
3102 {
3103 const int readAt = (ap.w - delay) & ap.mask;
3104 const int m = std::max(1, std::min({ delay, count - s, size - readAt, size - ap.w, size - delay }));
3105 const T* DSPARK_RESTRICT rd = ap.buf.data() + readAt;
3106 T* DSPARK_RESTRICT wr = ap.buf.data() + ap.w;
3107 T* DSPARK_RESTRICT xs = x + s;
3108 const T* rs = ramp + s;
3109 for (int k = 0; k < m; ++k)
3110 {
3111 const T g = g0 + gDelta * rs[k];
3112 const T d = rd[k];
3113 const T w = xs[k] + g * d;
3114 wr[k] = w;
3115 xs[k] = d - g * w;
3116 }
3117 ap.w = (ap.w + m) & ap.mask;
3118 s += m;
3119 }
3120 }
3121
3129 void processChunk(const T* inL, const T* inR, T* outL, T* outR, int count) noexcept
3130 {
3131 const int pd = cachedParams_.preDelaySamples;
3132 const int gap = cachedParams_.erToLateSamples;
3133 const int last = count - 1;
3134
3135 // One step of the ~20 ms parameter glides for this chunk: diffusion
3136 // coefficients and tone cutoffs per chunk, output gains per sample
3137 // (ramped below), so automating them does not click.
3138 const T gc = std::min(T(1), erGlidePerSample_ * static_cast<T>(count));
3139 const std::array<T, kInStages> inAP0 = inAPCoeff_;
3140 const T loopAP0 = loopAPCoeff_, outAP0 = outAPCoeff_;
3141 for (int st = 0; st < kInStages; ++st)
3142 inAPCoeff_[static_cast<std::size_t>(st)] = glideTo(inAPCoeff_[static_cast<std::size_t>(st)],
3143 inAPCoeffTarget_[static_cast<std::size_t>(st)], gc);
3146 T toneHP0 = T(0), toneLP0 = T(0);
3147 advanceTone(gc, toneHP0, toneLP0);
3148 const T early0 = earlyCur_, late0 = lateCur_, width0 = widthCur_;
3151 widthCur_ = glideTo(width0, cachedParams_.width, gc);
3152 const T rampStep = T(1) / static_cast<T>(count);
3153 fresh_ = false;
3154
3155 // Tail hold: the absorption fades to unity and the input out.
3156 const T hold0 = holdNow_;
3157 holdNow_ = glideTo(holdNow_, tailHold_.load(std::memory_order_relaxed) ? T(1) : T(0), gc);
3158 // The loop gains move toward their design (and toward unity while
3159 // the tail is held) sample by sample across the chunk: a step of
3160 // them is a step of every line's output.
3161 const bool absorbMoved = absorbGlide_;
3162 const bool absorbRamp = holdNow_ != hold0 || absorbMoved;
3163 if (absorbRamp)
3164 {
3166 if (absorbMoved) glideAbsorption(gc);
3168 rampAbsorption(rampStep);
3169 }
3170 {
3171 // Input entering the tank (for the empty-tank test of updateDecayParams()).
3172 T peak = T(0);
3173 for (int n = 0; n < count; ++n) peak = std::max(peak, std::max(std::abs(inL[n]), std::abs(inR[n])));
3174 quietSamples_ = peak > T(1e-6) ? 0.0 : quietSamples_ + count;
3175 }
3176 const bool holding = holdNow_ != T(0) || hold0 != T(0);
3177 const T in0 = T(1) - hold0, in1 = T(1) - holdNow_;
3178
3179 // Input width: the side of the input before the tank.
3180 alignas(64) T narrowL[kChunk];
3181 alignas(64) T narrowR[kChunk];
3182 if (cachedParams_.inputWidth != T(1))
3183 {
3184 const T w = cachedParams_.inputWidth;
3185 for (int n = 0; n < count; ++n)
3186 {
3187 const T mid = (inL[n] + inR[n]) * T(0.5), side = (inL[n] - inR[n]) * T(0.5) * w;
3188 narrowL[n] = mid + side;
3189 narrowR[n] = mid - side;
3190 }
3191 inL = narrowL;
3192 inR = narrowR;
3193 }
3194
3195 // Source depth: the low-pass on the wet signal, crossfaded in and out.
3196 {
3197 const T d = cachedParams_.sourceDepth;
3198 distMix_ = glideTo(distMix_, d > T(0) ? T(1) : T(0), gc);
3199 if (d > T(0))
3200 {
3201 const double hd = static_cast<double>(highDecayMult_.load(std::memory_order_relaxed));
3202 const double darkness = static_cast<double>(d) * (1.25 - 0.5 * hd);
3203 const double fc = std::min(18000.0 * std::exp2(-3.0 * darkness), 0.45 * spec_.sampleRate);
3204 distCoeff_ = static_cast<T>(1.0 - std::exp(-6.283185307179586 * fc / spec_.sampleRate));
3205 }
3206 }
3207
3208 // --- Pre-delay, then the allpass diffusers of the late-field feed ---
3209 alignas(64) T raw[2][kChunk];
3210 for (int c = 0; c < 2; ++c)
3211 {
3212 Line& pre = preDelay_[static_cast<std::size_t>(c)];
3213 const T* in = c == 0 ? inL : inR;
3214 for (int n = 0; n < count; ++n) pre.push(in[n]);
3215 std::fill(raw[c], raw[c] + count, T(0));
3216 addTap(raw[c], pre, pd + 1 + last, T(1), count);
3217 }
3218
3219 // Tank leveling: a compressor on the tank's input, both sides linked.
3220 if (cachedParams_.tankLeveling > T(0))
3221 {
3222 const double ratio = 1.0 + 3.0 * static_cast<double>(cachedParams_.tankLeveling);
3223 const double slope = 1.0 / ratio - 1.0;
3224 constexpr double kThreshold = -30.0, kKnee = 24.0;
3225 const double makeup = -slope * 12.0; // -18 dBFS sits on the knee's top
3226 const bool saturate = cachedParams_.tankSat;
3227 for (int n = 0; n < count; ++n)
3228 {
3229 const double peak = std::max(static_cast<double>(raw[0][n]) * raw[0][n],
3230 static_cast<double>(raw[1][n]) * raw[1][n]);
3231 const double over = 10.0 * std::log10(0.5 * peak + 1e-30) - kThreshold;
3232 const double gr = over <= -0.5 * kKnee ? 0.0
3233 : over >= 0.5 * kKnee ? slope * over
3234 : slope * (over + 0.5 * kKnee) * (over + 0.5 * kKnee) / (2.0 * kKnee);
3235 // Deeper at once; a crest within 0.01 dB of the reduction held
3236 // holds it again; after the hold it comes back slowly.
3237 if (gr <= levelGr_ + 0.01)
3238 {
3239 levelGr_ = std::min(levelGr_, gr);
3241 }
3242 else if (levelHold_ > 0) --levelHold_;
3243 else levelGr_ = gr + levelRelease_ * (levelGr_ - gr);
3244 const T g = static_cast<T>(std::pow(10.0, (levelGr_ + makeup) / 20.0));
3245 for (int c = 0; c < 2; ++c)
3246 {
3247 T x = raw[c][n] * g;
3248 if (saturate) x = std::tanh(T(1.5) * x) * T(1.0 / 1.5);
3249 raw[c][n] = x;
3250 }
3251 }
3252 }
3253
3254 // The input diffusers, one stage at a time over the chunk: a stage
3255 // reads its line for a whole span before writing it, which holds
3256 // while the span is no longer than its delay, so each span runs as
3257 // array arithmetic (the same operations, in the same order, as one
3258 // sample through all four stages).
3259 alignas(64) T ramp[kChunk];
3260 for (int n = 0; n < count; ++n) ramp[n] = static_cast<T>(n + 1) * rampStep;
3261 for (int c = 0; c < 2; ++c)
3262 {
3263 alignas(64) T x[kChunk];
3264 std::copy_n(raw[c], count, x);
3265 auto& aps = inAP_[static_cast<std::size_t>(c)];
3266 for (int st = 0; st < kInStages; ++st)
3267 {
3268 const T g0 = inAP0[static_cast<std::size_t>(st)];
3269 diffuseSpans(aps[static_cast<std::size_t>(st)], inAPLen_[static_cast<std::size_t>(c)][static_cast<std::size_t>(st)],
3270 g0, inAPCoeff_[static_cast<std::size_t>(st)] - g0, ramp, x, count);
3271 }
3272 writeSpan(ring_[static_cast<std::size_t>(c)], x, count);
3273 }
3274
3275 // The early gains follow size and decay changes in a ~20 ms glide
3276 // (per chunk), so automating them does not click.
3277 {
3278 for (int s = 0; s < 2; ++s)
3279 for (int k = 0; k < numERSlots_; ++k)
3280 erGain_[s][k] = glideTo(erGain_[s][k], erGainTarget_[s][k], gc);
3281 for (int g = 0; g < kERGroups; ++g)
3282 erShelfGain_[g] += gc * (erShelfGainTarget_[g] - erShelfGain_[g]);
3283 }
3284
3285 // --- Early reflections: velvet taps with rising density, each on its
3286 // own side or the other; the first few read the raw input (crisp
3287 // discrete reflections), the rest the diffused feed (each a short
3288 // dense burst); grouped absorption, later groups darker ---
3289 alignas(64) T early[2][kChunk];
3290 for (int s = 0; s < 2; ++s)
3291 {
3292 const Line* src[4] = { &ring_[static_cast<std::size_t>(s)], &ring_[static_cast<std::size_t>(1 - s)],
3293 &preDelay_[static_cast<std::size_t>(s)], &preDelay_[static_cast<std::size_t>(1 - s)] };
3294 const int lagOff[4] = { last, last, pd + last, pd + last };
3295 std::fill(early[s], early[s] + count, T(0));
3296 auto& lp = erLP_[static_cast<std::size_t>(s)];
3297 for (int g = 0; g < kERGroups; ++g)
3298 {
3299 // Each tap lands in its head-shadow class: open (the ear
3300 // facing the reflection) or shadowed (the far ear).
3301 alignas(64) T acc[kShadowBins][kChunk];
3302 for (auto& a : acc) std::fill(a, a + count, T(0));
3303 for (int k = erGroupStart_[s][g]; k < erGroupStart_[s][g + 1]; ++k)
3304 if (erGain_[s][k] != T(0)) // an idle crossfade slot adds nothing
3305 addTap(acc[erBin_[s][k]], *src[erChan_[s][k]], erTap_[s][k] + lagOff[erChan_[s][k]],
3306 erGain_[s][k], count);
3307 {
3308 // The shadowed class keeps its lows, loses half its highs.
3309 constexpr T hf = static_cast<T>(kShadowHF) - T(1);
3310 T z = erShadowLP_[static_cast<std::size_t>(s)][static_cast<std::size_t>(g)];
3311 for (int n = 0; n < count; ++n)
3312 {
3313 const T x = acc[1][n];
3314 z += shadowCoeff_ * (x - z);
3315 acc[0][n] += x + hf * (x - z);
3316 }
3317 erShadowLP_[static_cast<std::size_t>(s)][static_cast<std::size_t>(g)] = z;
3318 }
3319 // Frequency-dependent absorption: a first-order high shelf
3320 // at the high crossover, the group's highs attenuated as the
3321 // late field's are by that time (its HF T60).
3322 const T c = erShelfCoeff_;
3323 const T hg = erShelfGain_[static_cast<std::size_t>(g)];
3324 T y = lp[g];
3325 for (int n = 0; n < count; ++n)
3326 {
3327 const T x = acc[0][n];
3328 y += c * (x - y);
3329 early[s][n] += y + hg * (x - y);
3330 }
3331 lp[g] = y;
3332 }
3333 }
3334
3335 for (int n = 0; n < count; ++n)
3336 {
3337 if (ctrlPhase_ == 0) controlTick();
3338 ctrlPhase_ = (ctrlPhase_ + 1) & (kCtrl - 1);
3339 if (absorbRamp) stepAbsorption();
3340
3341 // --- Late field ---
3342 T lateL = T(0), lateR = T(0);
3343 const T a = static_cast<T>(n + 1) * rampStep;
3344 const T inGain = holding ? in0 + (in1 - in0) * a : T(1);
3345 if (spring_)
3346 {
3347 const T rawN[2] = { raw[0][n] * inGain, raw[1][n] * inGain };
3348 if (eco_) runSprings<kEcoSprings, kEcoSpringStages>(lateL, lateR, rawN);
3349 else runSprings<kSprings, kSpringStages>(lateL, lateR, rawN);
3350 }
3351 if (!spring_)
3352 {
3353 const T loopG = loopAP0 + (loopAPCoeff_ - loopAP0) * a;
3355 if (plate_.on) runPlate(lateL, lateR, gap + last - n, inGain, extra);
3356 else if (eco_) runFdn<kEcoLines>(lateL, lateR, gap + last - n, loopG, inGain, extra);
3357 else runFdn<kMaxLines>(lateL, lateR, gap + last - n, loopG, inGain, extra);
3358 lastLateMono_ = (lateL + lateR) * T(0.5);
3359 if (slope2_.on || slope2_.gainNow != T(0)) runSecondSlope(lateL, lateR, gap + last - n);
3360 }
3361
3362 const T earlyNow = early0 + (earlyCur_ - early0) * a;
3363 auto [yl, yr] = outputStage(lateL, lateR, early[0][n], early[1][n],
3364 holding ? earlyNow * inGain : earlyNow,
3365 late0 + (lateCur_ - late0) * a,
3366 width0 + (widthCur_ - width0) * a,
3367 toneHP0 + (toneHPMix_ - toneHP0) * a,
3368 toneLP0 + (toneLPMix_ - toneLP0) * a,
3369 outAP0 + (outAPCoeff_ - outAP0) * a);
3370 if (tail_.isActive())
3371 {
3372 const T g = tail_.next(std::max(std::abs(inL[n]), std::abs(inR[n])));
3373 yl *= g;
3374 yr *= g;
3375 }
3376 outL[n] = yl;
3377 outR[n] = yr;
3378 }
3379 if (absorbRamp) applyHoldCoeffs(); // the chunk's end, without the ramp's rounding
3380 }
3381
3388 T shimmerStep(T input) noexcept
3389 {
3390 shimBuf_[static_cast<std::size_t>(shimW_)] = input;
3391 const double sr = spec_.sampleRate;
3392 T sum = T(0), weight = T(0);
3393 for (int h = 0; h < 2; ++h)
3394 {
3395 const auto hh = static_cast<std::size_t>(h);
3396 const double ph = shimPhase_[hh];
3397 const double len = shimLen_[hh] * sr;
3398 // The delay falls by one sample per sample: the head reads at
3399 // twice the speed of the writing, an octave up.
3400 const double delay = 1.0 + len * (1.0 - ph);
3401 const int di = static_cast<int>(delay);
3402 const T f = static_cast<T>(delay - di);
3403 const T s0 = shimBuf_[static_cast<std::size_t>((shimW_ - di) & shimMask_)];
3404 const T s1 = shimBuf_[static_cast<std::size_t>((shimW_ - di - 1) & shimMask_)];
3405 const T w = static_cast<T>(0.5 - 0.5 * std::cos(6.283185307179586 * ph));
3406 sum += w * (s0 + f * (s1 - s0));
3407 weight += w;
3408 shimPhase_[hh] += 1.0 / std::max(1.0, len);
3409 if (shimPhase_[hh] >= 1.0)
3410 {
3411 shimPhase_[hh] -= 1.0;
3413 }
3414 }
3415 shimW_ = (shimW_ + 1) & shimMask_;
3416 // The windows of heads of different lengths do not sum to one: the
3417 // sum is normalized, and attenuated where both heads are near a wrap.
3418 return weight > T(0.25) ? sum / weight : sum * T(4);
3419 }
3420
3421 double drawShimmerLength() noexcept
3422 {
3423 shimRng_ ^= shimRng_ << 13;
3424 shimRng_ ^= shimRng_ >> 17;
3425 shimRng_ ^= shimRng_ << 5;
3426 const double u = static_cast<double>(shimRng_) / 4294967296.0;
3427 return 0.001 * (kShimmerMinMs + (kShimmerMaxMs - kShimmerMinMs) * u);
3428 }
3429
3431 void applyHoldCoeffs() noexcept
3432 {
3434 if (airInUse_)
3435 {
3436 // As many taps as the line with the largest b needs.
3437 T most = T(0);
3438 for (const T b : airNow_) most = std::max(most, b);
3439 const double b = static_cast<double>(most);
3440 double t = 1.0, sum = 1.0;
3441 int count = 1;
3442 while (count < kAirTaps)
3443 {
3444 t *= b / static_cast<double>(count);
3445 if (t <= 1e-7 * (sum + t)) break;
3446 sum += t;
3447 ++count;
3448 }
3449 airTapCount_ = count;
3450 for (int i = 0; i < kMaxLines; ++i) setAirTaps(static_cast<std::size_t>(i));
3451 }
3452 }
3453
3456 void setAirTaps(std::size_t l) noexcept
3457 {
3458 const double b = static_cast<double>(airNow_[l]);
3459 double taps[kAirTaps] = {};
3460 double t = 1.0, sum = 0.0;
3461 for (int n = 0; n < airTapCount_; ++n)
3462 {
3463 if (n > 0) t *= b / static_cast<double>(n);
3464 taps[n] = t;
3465 sum += t;
3466 }
3467 for (int n = 0; n < kAirTaps; ++n) airTap_[static_cast<std::size_t>(n)][l] = static_cast<T>(taps[n] / sum);
3468 }
3469
3471 void applyHoldShelves() noexcept
3472 {
3473 const T f = holdNow_, k = T(1) - f;
3474 for (int i = 0; i < kMaxLines; ++i)
3475 {
3476 const auto l = static_cast<std::size_t>(i);
3477 jotB0_[l] = jotBase_[0][l] + (T(1) - jotBase_[0][l]) * f;
3478 jotB1_[l] = jotBase_[1][l] * k;
3479 jotA1_[l] = jotBase_[2][l] * k;
3480 bassB0_[l] = bassBase_[0][l] + (T(1) - bassBase_[0][l]) * f;
3481 bassB1_[l] = bassBase_[1][l] * k;
3482 bassA1_[l] = bassBase_[2][l] * k;
3483 airNow_[l] = airBase_[l] * k;
3484 for (int q = 0; q < dqCount_; ++q)
3485 {
3486 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(q)]);
3487 dqB0_[b][l] = dqBase_[0][b][l] + (T(1) - dqBase_[0][b][l]) * f;
3488 dqB1_[b][l] = dqBase_[1][b][l] * k;
3489 dqB2_[b][l] = dqBase_[2][b][l] * k;
3490 dqA1_[b][l] = dqBase_[3][b][l] * k;
3491 dqA2_[b][l] = dqBase_[4][b][l] * k;
3492 }
3493 }
3494 }
3495
3497 void holdAbsorption() noexcept
3498 {
3499 absFrom_[0] = jotB0_; absFrom_[1] = jotB1_; absFrom_[2] = jotA1_;
3502 for (int q = 0; q < dqCount_; ++q)
3503 {
3504 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(q)]);
3505 dqFrom_[0][b] = dqB0_[b]; dqFrom_[1][b] = dqB1_[b]; dqFrom_[2][b] = dqB2_[b];
3506 dqFrom_[3][b] = dqA1_[b]; dqFrom_[4][b] = dqA2_[b];
3507 }
3508 }
3509
3512 void rampAbsorption(T perSample) noexcept
3513 {
3514 const auto ramp = [perSample](auto& now, auto& from, auto& step) {
3515 for (std::size_t i = 0; i < now.size(); ++i)
3516 {
3517 step[i] = (now[i] - from[i]) * perSample;
3518 now[i] = from[i];
3519 }
3520 };
3521 ramp(jotB0_, absFrom_[0], absStep_[0]); ramp(jotB1_, absFrom_[1], absStep_[1]); ramp(jotA1_, absFrom_[2], absStep_[2]);
3522 ramp(bassB0_, absFrom_[3], absStep_[3]); ramp(bassB1_, absFrom_[4], absStep_[4]); ramp(bassA1_, absFrom_[5], absStep_[5]);
3523 if (airInUse_)
3524 for (int n = 0; n < kAirTaps; ++n)
3525 ramp(airTap_[static_cast<std::size_t>(n)], airTapFrom_[static_cast<std::size_t>(n)], airTapStep_[static_cast<std::size_t>(n)]);
3526 for (int q = 0; q < dqCount_; ++q)
3527 {
3528 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(q)]);
3529 ramp(dqB0_[b], dqFrom_[0][b], dqStep_[0][b]); ramp(dqB1_[b], dqFrom_[1][b], dqStep_[1][b]);
3530 ramp(dqB2_[b], dqFrom_[2][b], dqStep_[2][b]); ramp(dqA1_[b], dqFrom_[3][b], dqStep_[3][b]);
3531 ramp(dqA2_[b], dqFrom_[4][b], dqStep_[4][b]);
3532 }
3533 }
3534
3536 void stepAbsorption() noexcept
3537 {
3538 const auto add = [](auto& now, const auto& step) {
3539 for (std::size_t i = 0; i < now.size(); ++i) now[i] += step[i];
3540 };
3541 add(jotB0_, absStep_[0]); add(jotB1_, absStep_[1]); add(jotA1_, absStep_[2]);
3542 add(bassB0_, absStep_[3]); add(bassB1_, absStep_[4]); add(bassA1_, absStep_[5]);
3543 if (airInUse_)
3544 for (int n = 0; n < kAirTaps; ++n) add(airTap_[static_cast<std::size_t>(n)], airTapStep_[static_cast<std::size_t>(n)]);
3545 for (int q = 0; q < dqCount_; ++q)
3546 {
3547 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(q)]);
3548 add(dqB0_[b], dqStep_[0][b]); add(dqB1_[b], dqStep_[1][b]); add(dqB2_[b], dqStep_[2][b]);
3549 add(dqA1_[b], dqStep_[3][b]); add(dqA2_[b], dqStep_[4][b]);
3550 }
3551 }
3552
3555 std::pair<T, T> outputStage(T lateL, T lateR, T earlyL, T earlyR,
3556 T earlyLevel, T lateLevel, T width,
3557 T toneHPMix, T toneLPMix, T outAPCoeff) noexcept
3558 {
3559 // --- Output: coherent low band, width, early + late, subsonic high-pass, tone ---
3560 const T lateLvl = lateLevel * kOutGain;
3561 lateL *= lateLvl;
3562 lateR *= lateLvl;
3563 if (!spring_)
3564 {
3565 // Output diffusion (the springs' chirps stay crisp).
3566 T* lr[2] = { &lateL, &lateR };
3567 const T g = outAPCoeff;
3568 for (int c = 0; c < 2; ++c)
3569 {
3570 T x = *lr[c];
3571 for (int k = 0; k < kOutStages; ++k)
3572 {
3573 Line& ap = outAP_[static_cast<std::size_t>(c)][static_cast<std::size_t>(k)];
3574 const T d = ap.at(outAPLen_[static_cast<std::size_t>(c)][static_cast<std::size_t>(k)]);
3575 const T w = x + g * d;
3576 ap.push(w);
3577 x = d - g * w;
3578 }
3579 *lr[c] = x;
3580 }
3581 }
3582 {
3583 // A diffuse field is coherent between the ears at low frequencies
3584 // (the wavelength dwarfs the head) and incoherent above about
3585 // 500 Hz. The side signal is high-passed (Butterworth-like at
3586 // kCoherenceHz), which reproduces the interaural coherence of a
3587 // measured concert hall seat: about 0.97 at 125 Hz, 0.65 at
3588 // 250 Hz, under 0.1 from 500 Hz up.
3589 T mid = (lateL + lateR) * T(0.5);
3590 T side = (lateL - lateR) * T(0.5);
3591 const double hp = coherenceFilter_.processSampleCore(static_cast<double>(side), 0);
3592 side = static_cast<T>(hp * static_cast<double>(width));
3593 if (cachedParams_.powerKept) mid *= std::sqrt(std::max(T(0), T(2) - width * width));
3594 lateL = mid + side;
3595 lateR = mid - side;
3596 }
3597
3598 T out[2] = { earlyL * earlyLevel + lateL,
3599 earlyR * earlyLevel + lateR };
3600 for (int c = 0; c < 2; ++c)
3601 out[c] = subsonicFilter_.processSample(out[c], c);
3602 if (distMix_ > T(0))
3603 for (int c = 0; c < 2; ++c)
3604 {
3605 T& z = distLp_[static_cast<std::size_t>(c)];
3606 z += distCoeff_ * (out[c] - z);
3607 out[c] += distMix_ * (z - out[c]);
3608 }
3609 // Tone EQ, crossfaded in and out when it is switched (a settled
3610 // filter's share is exactly 1 or 0).
3611 if (toneHPActive_)
3612 for (int c = 0; c < 2; ++c)
3613 {
3614 const T f = toneHPBiquad_.processSample(out[c], c);
3615 out[c] = toneHPMix == T(1) ? f : out[c] + toneHPMix * (f - out[c]);
3616 }
3617 if (toneLPActive_)
3618 for (int c = 0; c < 2; ++c)
3619 {
3620 const T f = toneLPBiquad_.processSample(out[c], c);
3621 out[c] = toneLPMix == T(1) ? f : out[c] + toneLPMix * (f - out[c]);
3622 }
3623 return { out[0], out[1] };
3624 }
3625
3626 // =========================================================================
3627 // Coefficient update helpers (audio thread or prepare)
3628 // =========================================================================
3629
3630 void updateAll() noexcept
3631 {
3632 if (spec_.sampleRate <= 0) return;
3637 // damping_ and erToLateSamples_ are kept current by their setters and
3638 // by commitPreset(): the audio thread only reads parameter atomics.
3639 generateERTapsForType(erType_); // the discrete/diffuse split follows the diffusion
3640 }
3641
3643 T sizeFactor() const noexcept
3644 {
3645 return T(0.35) + T(0.65) * size_.load(std::memory_order_relaxed);
3646 }
3647
3648 void updateDelayLengths() noexcept
3649 {
3650 const double sr = spec_.sampleRate;
3651 const double sz = static_cast<double>(sizeFactor());
3652 const auto ms = [sr](double v) { return std::max(1, static_cast<int>(v * sr / 1000.0)); };
3653 const bool geometric = layout_.load(std::memory_order_relaxed) == 1;
3654
3655 for (int i = 0; i < kMaxLines; ++i)
3656 {
3657 // Eco picks every other base delay, so its 16 lines still span
3658 // the full range (even mode density).
3659 const int src = eco_ ? std::min(i * (kMaxLines / kEcoLines) + 1, kMaxLines - 1) : i;
3660 // Geometric layout: the same range, even in log.
3661 const double baseMs = geometric
3662 ? kBaseDelaysMs_[0] * std::pow(kBaseDelaysMs_[kMaxLines - 1] / kBaseDelaysMs_[0],
3663 static_cast<double>(src) / (kMaxLines - 1))
3664 : kBaseDelaysMs_[src];
3665 lenTarget_[i] = nearestPrime(ms(baseMs * sz));
3666 // The in-loop allpasses scale with the room like the lines, so
3667 // their group-delay ripple stays a small, size-independent share
3668 // of each loop: no frequency lingers longer in a small room.
3669 loopAPLen_[i] = nearestPrime(ms(kLoopApMs_[i] * sz));
3670 loopAPGliding_ = true;
3671 injTap_[i] = std::max(1, ms(kInjectMs_[i]));
3672 injGain_[i] = static_cast<T>(kInjectSign_[i]) / std::sqrt(static_cast<T>(nLines_));
3673 outSignL_[i] = static_cast<T>(kOutSignL_[i]);
3674 outSignR_[i] = static_cast<T>(kOutSignR_[i]);
3675 }
3676 if (spring_)
3677 {
3678 // Round trips of 27-49 ms at the preset size (0.11), up to
3679 // 156 ms at size 1 (within the line capacity).
3680 const double springScale = 0.6 + 2.0 * static_cast<double>(size_.load(std::memory_order_relaxed));
3681 for (int s = 0; s < nLines_; ++s)
3682 lenTarget_[s] = nearestPrime(ms(springBaseMs(s) * springScale));
3683 }
3684 for (int c = 0; c < 2; ++c)
3685 for (int st = 0; st < kInStages; ++st)
3686 inAPLen_[static_cast<std::size_t>(c)][static_cast<std::size_t>(st)]
3687 = nearestPrime(ms(kInDiffMs_[c][st]));
3688 }
3689
3690 void updateDiffCoeffs() noexcept
3691 {
3692 const double diff = static_cast<double>(diffusion_.load(std::memory_order_relaxed));
3693 // Targets: the running coefficients glide to them chunk by chunk
3694 // (processChunk), and snap with reset().
3695 const double dist = static_cast<double>(sourceDepth_.load(std::memory_order_relaxed));
3696 for (int st = 0; st < kInStages; ++st)
3697 inAPCoeffTarget_[static_cast<std::size_t>(st)] = dist > 0.0
3698 ? static_cast<T>(std::min(0.8, kInDiffCoeffs_[st] * diff + 0.25 * dist * dist))
3699 : static_cast<T>(kInDiffCoeffs_[st] * diff);
3700 loopAPCoeffTarget_ = static_cast<T>(0.075 + 0.175 * diff);
3701 outAPCoeffTarget_ = static_cast<T>(0.6 * diff);
3702
3703 // Spring chirp strength: the group-delay rise per stage is
3704 // (1 + a) / (1 - a) - (1 - a) / (1 + a). The total dispersion is
3705 // that of a 72-stage cascade at a = 0.3 + 0.5 x diffusion; shorter
3706 // cascades get a larger coefficient to match it.
3707 {
3708 const double aRef = 0.3 + 0.5 * diff;
3710 const double f = 72.0 / springStages_ * (1.0 + aRef) / (1.0 - aRef);
3711 springA_ = static_cast<T>((f - 1.0) / (f + 1.0));
3712 }
3713 }
3714
3715 void updateModulation() noexcept
3716 {
3717 const double sr = spec_.sampleRate;
3718 const T rate = modRate_.load(std::memory_order_relaxed);
3719 for (int i = 0; i < kMaxLines; ++i)
3720 lfo_[i].setRate(rate * lfoRateFactor(i), sr);
3721 // Springs jitter by a fixed time (the random round-trip variation of
3722 // spring models, which smears their sparse modes); the FDN wanders
3723 // in proportion to the room size.
3724 modDepthSamples_ = modDepth_.load(std::memory_order_relaxed)
3725 * (spring_ ? static_cast<T>(kSpringJitterMs * sr / 1000.0)
3726 : static_cast<T>(kModMaxMs * sr / 1000.0) * sizeFactor());
3727 rotDepth_ = spring_ ? T(0)
3728 : modDepth_.load(std::memory_order_relaxed) * static_cast<T>(kRotMaxRad);
3729 for (int k = 0; k < kMaxLines / 2; ++k)
3730 rotLfo_[k].setRate(rotRate() * rotRateFactor(k), sr);
3731 glideCoeff_ = static_cast<T>(1.0 - std::exp(-kCtrl / (kGlideMs * sr / 1000.0)));
3732 fadeStep_ = 1.0 / (kSizeFadeSeconds * sr);
3733 maxGlideStep_ = static_cast<T>(kMaxGlideSpeed * kCtrl);
3734 }
3735
3749 void updateDecayParams() noexcept
3750 {
3751 const double sr = spec_.sampleRate;
3752 const double decay = calibratedMidDecay();
3753 const double t60H = std::max(0.05, decay * static_cast<double>(
3754 highDecayMult_.load(std::memory_order_relaxed)));
3755 const double t60B = std::max(0.05, decay * static_cast<double>(
3756 bassDecayMult_.load(std::memory_order_relaxed)));
3757 const double kPi = 3.14159265358979323846;
3758 const double fh = std::clamp(static_cast<double>(
3759 highCrossover_.load(std::memory_order_relaxed)), 100.0, 0.45 * sr);
3760 const double fb = std::clamp(static_cast<double>(
3761 bassCrossover_.load(std::memory_order_relaxed)), 10.0, 0.45 * sr);
3762 const double Kh = std::tan(kPi * fh / sr);
3763 const double Kb = std::tan(kPi * fb / sr);
3764 const double air = static_cast<double>(airAbsorption_.load(std::memory_order_relaxed));
3765 double loopSum = 0.0;
3766 for (int i = 0; i < kMaxLines; ++i)
3767 {
3768 // Loop length: line + group delay of the in-loop allpasses. The
3769 // FDN's short allpasses count their mean (their length). A
3770 // spring's dispersion makes the loop time frequency dependent,
3771 // from K (1 - a) / (1 + a) per stage at DC up to the chirp at the
3772 // band edge; the low and mid band, where the energy is, set it.
3773 const double M = spring_
3774 ? static_cast<double>(lenTarget_[i]) + springStages_ * springK_
3775 * (1.0 - static_cast<double>(springA_)) / (1.0 + static_cast<double>(springA_))
3776 : static_cast<double>(lenTarget_[i] + loopAPLen_[i]);
3777 const double gM = std::pow(0.001, M / (decay * sr));
3778 if (i < nLines_) loopSum += M;
3779 const double gH = std::min(std::pow(0.001, M / (t60H * sr)), gM);
3780 // Keep the bass loop gain below 1 so extreme settings ring out
3781 // instead of self-sustaining.
3782 const double gB = std::min(std::pow(0.001, M / (t60B * sr)), 0.9995);
3783
3784 {
3785 const double ratio = std::sqrt(gM / gH);
3786 const double a = Kh * ratio, b = Kh / ratio, inv = 1.0 / (1.0 + b);
3787 jotB0_[i] = static_cast<T>(gH * (1.0 + a) * inv);
3788 jotB1_[i] = static_cast<T>(gH * (a - 1.0) * inv);
3789 jotA1_[i] = static_cast<T>((b - 1.0) * inv);
3790 }
3791 {
3792 const double sq = std::sqrt(gB / gM);
3793 const double a = Kb * sq, b = Kb / sq, inv = 1.0 / (1.0 + b);
3794 bassB0_[i] = static_cast<T>((1.0 + a) * inv);
3795 bassB1_[i] = static_cast<T>((a - 1.0) * inv);
3796 bassA1_[i] = static_cast<T>((b - 1.0) * inv);
3797 }
3798 airGoal_[static_cast<std::size_t>(i)] = spring_ ? T(0) : static_cast<T>(airDepth(air, M / sr, sr));
3799 }
3800 meanLoopSec_ = loopSum / std::max(1, nLines_) / sr;
3801 for (int i = 0; i < kMaxLines; ++i)
3802 {
3803 const auto l = static_cast<std::size_t>(i);
3804 jotGoal_[0][l] = jotB0_[l]; jotGoal_[1][l] = jotB1_[l]; jotGoal_[2][l] = jotA1_[l];
3805 bassGoal_[0][l] = bassB0_[l]; bassGoal_[1][l] = bassB1_[l]; bassGoal_[2][l] = bassA1_[l];
3806 }
3807 const auto prevList = dqList_;
3808 const int prevCount = dqCount_;
3809 designDecayBands(decay, t60H, t60B, Kh, Kb);
3810 // The wet signal's energy is that of the tail (the passes round the
3811 // tank, band by band as heard) plus that of the early field: this
3812 // gain takes both back, so the wet signal at full mix has the dry
3813 // signal's level whatever the type, decay, damping and size.
3815 / std::sqrt(std::max(1e-6, heardTailEnergy(decay, t60H, t60B, Kh, Kb) + earlyEnergy())));
3816 designSecondSlope(decay, t60H, Kh);
3817 designPlate(decay, t60H, fh);
3818
3819 // With signal in the tank the loop gains glide to the new design (a
3820 // step of them is a step of every line's output: a click); an empty
3821 // tank, after prepare() or once its content is under -120 dB, takes
3822 // the design at once.
3823 const bool empty = fresh_ || (holdNow_ == T(0) && quietSamples_ > tankEmptyAfter_);
3824 double longest = std::max({ decay, t60H, t60B });
3825 for (int q = 0; q < dqCount_; ++q)
3826 {
3827 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(q)]);
3828 longest = std::max(longest, decay * static_cast<double>(getDecayBand(static_cast<int>(b)).multiplier));
3829 const bool known = std::find(prevList.begin(), prevList.begin() + prevCount, static_cast<int>(b))
3830 != prevList.begin() + prevCount;
3831 if (!known && !empty)
3832 for (int i = 0; i < kMaxLines; ++i)
3833 {
3834 // A band coming in glides from a flat filter, its state cleared.
3835 const auto l = static_cast<std::size_t>(i);
3836 dqBase_[0][b][l] = T(1);
3837 for (int r = 1; r < 5; ++r) dqBase_[static_cast<std::size_t>(r)][b][l] = T(0);
3838 dqZ1_[b][l] = dqZ2_[b][l] = T(0);
3839 }
3840 }
3841 // Content decays 60 dB per T60; the pre-delay and the ER-to-late gap
3842 // (up to 0.6 s together) hold input back before the tank.
3843 tankEmptyAfter_ = (2.0 * longest + 0.6) * sr;
3844 if (empty) snapAbsorption();
3845 else absorbGlide_ = true;
3847 }
3848
3850 void snapAbsorption() noexcept
3851 {
3856 for (int q = 0; q < dqCount_; ++q)
3857 {
3858 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(q)]);
3859 for (int r = 0; r < 5; ++r)
3860 dqBase_[static_cast<std::size_t>(r)][b] = dqGoal_[static_cast<std::size_t>(r)][b];
3861 }
3862 absorbGlide_ = false;
3863 }
3864
3868 void glideAbsorption(T gc) noexcept
3869 {
3870 bool moving = false;
3871 const auto step = [&](T& cur, T goal) {
3872 cur = glideTo(cur, goal, gc);
3873 moving = moving || cur != goal;
3874 };
3875 for (int r = 0; r < 3; ++r)
3876 for (int i = 0; i < kMaxLines; ++i)
3877 {
3878 const auto rr = static_cast<std::size_t>(r), l = static_cast<std::size_t>(i);
3879 step(jotBase_[rr][l], jotGoal_[rr][l]);
3880 step(bassBase_[rr][l], bassGoal_[rr][l]);
3881 }
3882 for (int i = 0; i < kMaxLines; ++i)
3883 step(airBase_[static_cast<std::size_t>(i)], airGoal_[static_cast<std::size_t>(i)]);
3884 // Going off, one more chunk takes the taps in use to the identity.
3885 for (int i = 0; i < kMaxLines; ++i)
3886 {
3887 const auto l = static_cast<std::size_t>(i);
3888 moving = moving || (airNow_[l] != T(0) && airBase_[l] == T(0));
3889 }
3890 for (int q = 0; q < dqCount_; ++q)
3891 {
3892 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(q)]);
3893 for (int r = 0; r < 5; ++r)
3894 for (int i = 0; i < kMaxLines; ++i)
3895 step(dqBase_[static_cast<std::size_t>(r)][b][static_cast<std::size_t>(i)],
3896 dqGoal_[static_cast<std::size_t>(r)][b][static_cast<std::size_t>(i)]);
3897 }
3898 absorbGlide_ = moving;
3900 }
3901
3905 void refreshAirInUse() noexcept
3906 {
3907 bool on = false;
3908 for (int i = 0; i < kMaxLines; ++i)
3909 {
3910 const auto l = static_cast<std::size_t>(i);
3911 on = on || airGoal_[l] != T(0) || airBase_[l] != T(0) || airNow_[l] != T(0);
3912 }
3913 if (on && !airInUse_)
3914 {
3915 for (auto& v : airHist_) v.fill(T(0));
3916 airW_ = 0;
3917 airTapFrom_ = airTap_; // the identity: a ramp starts from it
3918 }
3919 if (!on) airTap_ = identityAirTaps();
3920 airInUse_ = on;
3921 }
3922
3926 static constexpr double kSoundSpeed = 343.2;
3927 static constexpr double kAirFitHz = 12000.0;
3928 static constexpr double kAirMaxDepth = 5.0;
3929
3935 [[nodiscard]] static double airAttenuationDbPerMetre(double hz) noexcept
3936 {
3937 const double t = 293.15, t0 = 293.15, t01 = 273.16, hr = 50.0;
3938 const double psat = std::pow(10.0, -6.8346 * std::pow(t01 / t, 1.261) + 4.6151);
3939 const double h = hr * psat; // molar concentration of water vapour, %
3940 const double frO = 24.0 + 4.04e4 * h * (0.02 + h) / (0.391 + h);
3941 const double frN = std::pow(t / t0, -0.5) * (9.0 + 280.0 * h * std::exp(-4.170 * (std::pow(t / t0, -1.0 / 3.0) - 1.0)));
3942 const double f2 = hz * hz;
3943 return 8.686 * f2 * (1.84e-11 * std::sqrt(t / t0)
3944 + std::pow(t / t0, -2.5) * (0.01275 * std::exp(-2239.1 / t) / (frO + f2 / frO)
3945 + 0.1068 * std::exp(-3352.0 / t) / (frN + f2 / frN)));
3946 }
3947
3953 [[nodiscard]] static double airDepth(double amount, double loopSeconds, double sr) noexcept
3954 {
3955 if (!(amount > 0.0) || !(loopSeconds > 0.0)) return 0.0;
3956 const double hz = std::min(kAirFitHz, 0.4 * sr);
3957 const double lossDb = amount * airAttenuationDbPerMetre(hz) * kSoundSpeed * loopSeconds;
3958 const double x = 1.0 - std::cos(2.0 * 3.14159265358979323846 * hz / sr);
3959 return std::min(lossDb / (8.685889638065037 * x), kAirMaxDepth);
3960 }
3961
3963 [[nodiscard]] static double shelfGain(double a, double b, double w) noexcept
3964 {
3965 const double c = std::cos(w), sn = std::sin(w);
3966 const double nr = (1.0 + a) + (a - 1.0) * c, ni = -(a - 1.0) * sn;
3967 const double dr = (1.0 + b) + (b - 1.0) * c, di = -(b - 1.0) * sn;
3968 return std::sqrt((nr * nr + ni * ni) / (dr * dr + di * di));
3969 }
3970
3985 [[nodiscard]] double heardTailEnergy(double decay, double t60H, double t60B, double Kh, double Kb) const noexcept
3986 {
3987 const double sr = spec_.sampleRate, kPi = 3.14159265358979323846;
3988 constexpr int kPoints = 24;
3989 const double top = std::min(16000.0, 0.45 * sr);
3990 double sum = 0.0, weight = 0.0;
3991 for (int p = 0; p < kPoints; ++p)
3992 {
3993 const double f = 31.25 * std::pow(top / 31.25, static_cast<double>(p) / (kPoints - 1));
3994 const double f2 = f * f, f4 = f2 * f2, hp = f4 / (f4 + 38.0 * 38.0 * 38.0 * 38.0);
3995 const double heard = hp * (1.0 + 1.51 * f2 / (f2 + 1700.0 * 1700.0));
3996 const double w = 2.0 * kPi * f / sr;
3997 double t60 = 0.0, firstPass = 0.0;
3998 for (int i = 0; i < nLines_; ++i)
3999 {
4000 const auto l = static_cast<std::size_t>(i);
4001 const double M = spring_
4002 ? static_cast<double>(lenTarget_[l]) + springStages_ * springK_
4003 * (1.0 - static_cast<double>(springA_)) / (1.0 + static_cast<double>(springA_))
4004 : static_cast<double>(lenTarget_[l] + loopAPLen_[l]);
4005 const double gM = std::pow(0.001, M / (decay * sr));
4006 const double gH = std::min(std::pow(0.001, M / (t60H * sr)), gM);
4007 const double gB = std::min(std::pow(0.001, M / (t60B * sr)), 0.9995);
4008 const double rh = std::sqrt(gM / gH), rb = std::sqrt(gB / gM);
4009 double g = gH * shelfGain(Kh * rh, Kh / rh, w) * shelfGain(Kb * rb, Kb / rb, w)
4010 * std::exp(-static_cast<double>(airGoal_[l]) * (1.0 - std::cos(w)));
4011 for (int k = 0; k < dqCount_; ++k)
4012 {
4013 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(k)]);
4014 BiquadCoeffs c;
4015 c.b0 = static_cast<double>(dqGoal_[0][b][l]);
4016 c.b1 = static_cast<double>(dqGoal_[1][b][l]);
4017 c.b2 = static_cast<double>(dqGoal_[2][b][l]);
4018 c.a1 = static_cast<double>(dqGoal_[3][b][l]);
4019 c.a2 = static_cast<double>(dqGoal_[4][b][l]);
4020 g *= biquadGain(c, w);
4021 }
4022 g = std::clamp(g, 1e-9, 0.9999999);
4023 t60 += -3.0 * M / (sr * std::log10(g));
4024 firstPass += g * g;
4025 }
4026 t60 /= static_cast<double>(std::max(1, nLines_));
4027 firstPass /= static_cast<double>(std::max(1, nLines_));
4028 const double x = std::min(2.0 * 6.907755278982137 * meanLoopSec_ / std::max(1e-3, t60), 50.0);
4029 sum += heard * (spring_ ? 1.0 + 1.0 / std::expm1(x) : firstPass / -std::expm1(-x));
4030 weight += heard;
4031 }
4032 return sum / weight;
4033 }
4034
4036 static constexpr std::array<double, 2> earlyWindow(Type type) noexcept
4037 {
4038 switch (type)
4039 {
4040 case Type::Room: return { 1.5, 35.0 };
4041 case Type::Hall: return { 5.0, 110.0 };
4042 case Type::Chamber: return { 3.0, 60.0 };
4043 case Type::Cathedral: return { 10.0, 160.0 };
4044 case Type::Plate:
4045 case Type::Spring: break;
4046 }
4047 return { 0.0, 0.0 };
4048 }
4049
4054 [[nodiscard]] double earlyEnergy() const noexcept
4055 {
4056 const auto window = earlyWindow(erType_);
4057 if (!(window[1] > window[0]) || meanLoopSec_ <= 0.0) return 0.0;
4058 const double tau = static_cast<double>(decayTime_.load(std::memory_order_relaxed)) / (2.0 * 6.907755278982137);
4059 const double tInj = static_cast<double>(erToLateSamples_.load(std::memory_order_relaxed)) / spec_.sampleRate
4060 + kMeanInjectMs * 1e-3;
4061 return tau / meanLoopSec_
4062 * (std::exp(-(window[0] * 1e-3 - tInj) / tau) - std::exp(-(window[1] * 1e-3 - tInj) / tau));
4063 }
4064
4066 [[nodiscard]] static double biquadGain(const BiquadCoeffs& q, double w) noexcept
4067 {
4068 const double c1 = std::cos(w), s1 = std::sin(w), c2 = std::cos(2.0 * w), s2 = std::sin(2.0 * w);
4069 const double nr = q.b0 + q.b1 * c1 + q.b2 * c2, ni = -(q.b1 * s1 + q.b2 * s2);
4070 const double dr = 1.0 + q.a1 * c1 + q.a2 * c2, di = -(q.a1 * s1 + q.a2 * s2);
4071 return std::sqrt((nr * nr + ni * ni) / std::max(1e-300, dr * dr + di * di));
4072 }
4073
4080 void designDecayBands(double decay, double t60H, double t60B, double Kh, double Kb) noexcept
4081 {
4082 const double sr = spec_.sampleRate;
4083 dqCount_ = 0;
4084 std::array<DecayBand, kDecayBands> bands {};
4085 for (int k = 0; k < kDecayBands; ++k)
4086 {
4087 const DecayBand b = getDecayBand(k);
4088 if (b.shape == DecayShape::Off || std::abs(static_cast<double>(b.multiplier) - 1.0) < 1e-3) continue;
4089 bands[static_cast<std::size_t>(dqCount_)] = b;
4090 dqList_[static_cast<std::size_t>(dqCount_++)] = k;
4091 }
4092 if (dqCount_ == 0) return;
4093
4094 constexpr int kGrid = 32;
4095 std::array<double, kGrid> grid {};
4096 for (int g = 0; g < kGrid; ++g)
4097 grid[static_cast<std::size_t>(g)] = 2.0 * 3.14159265358979323846
4098 * 20.0 * std::pow(0.45 * sr / 20.0, static_cast<double>(g) / (kGrid - 1)) / sr;
4099 for (int i = 0; i < kMaxLines; ++i)
4100 {
4101 const double M = spring_
4102 ? static_cast<double>(lenTarget_[i]) + springStages_ * springK_
4103 * (1.0 - static_cast<double>(springA_)) / (1.0 + static_cast<double>(springA_))
4104 : static_cast<double>(lenTarget_[i] + loopAPLen_[i]);
4105 const double gM = std::pow(0.001, M / (decay * sr));
4106 const double gH = std::min(std::pow(0.001, M / (t60H * sr)), gM);
4107 const double gB = std::min(std::pow(0.001, M / (t60B * sr)), 0.9995);
4108 const double rh = std::sqrt(gM / gH), rb = std::sqrt(gB / gM);
4109 const auto loopGain = [&](double w) { return gH * shelfGain(Kh * rh, Kh / rh, w) * shelfGain(Kb * rb, Kb / rb, w); };
4110
4111 std::array<double, kDecayBands> gains {};
4112 for (int k = 0; k < dqCount_; ++k)
4113 {
4114 const DecayBand& b = bands[static_cast<std::size_t>(k)];
4115 const double ref = b.shape == DecayShape::LowShelf ? gB
4116 : b.shape == DecayShape::HighShelf ? gH
4117 : loopGain(2.0 * 3.14159265358979323846 * static_cast<double>(b.frequency) / sr);
4118 gains[static_cast<std::size_t>(k)] = 20.0 * std::log10(std::clamp(ref, 1e-6, 0.999999))
4119 * (1.0 / static_cast<double>(b.multiplier) - 1.0);
4120 }
4121 std::array<BiquadCoeffs, kDecayBands> coeffs {};
4122 const auto design = [&](double boostScale) {
4123 for (int k = 0; k < dqCount_; ++k)
4124 {
4125 const DecayBand& b = bands[static_cast<std::size_t>(k)];
4126 double g = gains[static_cast<std::size_t>(k)];
4127 if (g > 0.0) g *= boostScale;
4128 const double f = std::min(static_cast<double>(b.frequency), 0.45 * sr);
4129 coeffs[static_cast<std::size_t>(k)] =
4132 : BiquadCoeffs::makePeak(sr, f, static_cast<double>(b.q), g);
4133 }
4134 };
4135 const auto peakLoop = [&]() {
4136 double top = 0.0;
4137 for (double w : grid)
4138 {
4139 double v = loopGain(w);
4140 for (int k = 0; k < dqCount_; ++k) v *= biquadGain(coeffs[static_cast<std::size_t>(k)], w);
4141 top = std::max(top, v);
4142 }
4143 return top;
4144 };
4145 design(1.0);
4146 if (peakLoop() > kMaxDecayLoopGain)
4147 {
4148 double lo = 0.0, hi = 1.0;
4149 for (int it = 0; it < 12; ++it)
4150 {
4151 const double mid = 0.5 * (lo + hi);
4152 design(mid);
4153 (peakLoop() > kMaxDecayLoopGain ? hi : lo) = mid;
4154 }
4155 design(lo);
4156 }
4157 for (int k = 0; k < dqCount_; ++k)
4158 {
4159 const auto b = static_cast<std::size_t>(dqList_[static_cast<std::size_t>(k)]);
4160 const auto l = static_cast<std::size_t>(i);
4161 const BiquadCoeffs& c = coeffs[static_cast<std::size_t>(k)];
4162 dqGoal_[0][b][l] = static_cast<T>(c.b0);
4163 dqGoal_[1][b][l] = static_cast<T>(c.b1);
4164 dqGoal_[2][b][l] = static_cast<T>(c.b2);
4165 dqGoal_[3][b][l] = static_cast<T>(c.a1);
4166 dqGoal_[4][b][l] = static_cast<T>(c.a2);
4167 }
4168 }
4169 }
4170
4172 [[nodiscard]] double effectivePreDelayMs() const noexcept
4173 {
4174 const int note = preNote_.load(std::memory_order_relaxed);
4175 if (note == 0) return static_cast<double>(preDelayMs_.load(std::memory_order_relaxed));
4176 return std::min(noteMs(note, preFeel_.load(std::memory_order_relaxed)), kMaxPreDelayMs);
4177 }
4178
4179 void refreshPreDelay() noexcept
4180 {
4181 if (spec_.sampleRate > 0)
4182 preDelaySamples_.store(msToSamples(static_cast<T>(effectivePreDelayMs())), std::memory_order_relaxed);
4183 }
4184
4185 void refreshGateHold() noexcept
4186 {
4187 const int note = gateNote_.load(std::memory_order_relaxed);
4188 const double ms = note == 0 ? static_cast<double>(gateHoldMs_.load(std::memory_order_relaxed))
4189 : std::min(noteMs(note, gateFeel_.load(std::memory_order_relaxed)), 4000.0);
4190 tail_.setGateHold(static_cast<T>(ms));
4191 }
4192
4194 [[nodiscard]] double noteMs(int note, int feel) const noexcept
4195 {
4196 static constexpr double kBeats[7] = { 0.0, 4.0, 2.0, 1.0, 0.5, 0.25, 0.125 };
4197 const double beat = 60000.0 / static_cast<double>(tempo_.load(std::memory_order_relaxed));
4198 const double factor = feel == 1 ? 1.5 : feel == 2 ? 2.0 / 3.0 : 1.0;
4199 return beat * kBeats[static_cast<std::size_t>(std::clamp(note, 0, 6))] * factor;
4200 }
4201
4218 [[nodiscard]] double calibratedMidDecay() const noexcept
4219 {
4220 const double sr = spec_.sampleRate;
4221 const double target = static_cast<double>(decayTime_.load(std::memory_order_relaxed));
4222 if (!(sr > 0.0) || nLines_ < 1) return target;
4223 const double hd = static_cast<double>(highDecayMult_.load(std::memory_order_relaxed));
4224 const double bd = static_cast<double>(bassDecayMult_.load(std::memory_order_relaxed));
4225 const double kPi = 3.14159265358979323846;
4226 const double Kh = std::tan(kPi * std::clamp(static_cast<double>(
4227 highCrossover_.load(std::memory_order_relaxed)), 100.0, 0.45 * sr) / sr);
4228 const double Kb = std::tan(kPi * std::clamp(static_cast<double>(
4229 bassCrossover_.load(std::memory_order_relaxed)), 10.0, 0.45 * sr) / sr);
4230 auto loopLen = [&](int i) {
4231 return spring_
4232 ? static_cast<double>(lenTarget_[i]) + springStages_ * springK_
4233 * (1.0 - static_cast<double>(springA_)) / (1.0 + static_cast<double>(springA_))
4234 : static_cast<double>(lenTarget_[i] + loopAPLen_[i]);
4235 };
4236
4237 // |H(e^jw)| of ((1 + a) + (a - 1) z^-1) / ((1 + b) + (b - 1) z^-1).
4238 auto shelf = [](double a, double b, double w) {
4239 const double c = std::cos(w), sn = std::sin(w);
4240 const double nr = (1.0 + a) + (a - 1.0) * c, ni = -(a - 1.0) * sn;
4241 const double dr = (1.0 + b) + (b - 1.0) * c, di = -(b - 1.0) * sn;
4242 return std::sqrt((nr * nr + ni * ni) / (dr * dr + di * di));
4243 };
4244 // Decay rate (1/T60) of the line mix at hz: each line's shelves are
4245 // designed from its own length, so the rate between the anchors
4246 // differs from line to line; the tail decays at their mean rate.
4247 auto t60At = [&](double d, double hz) {
4248 const double w = 2.0 * kPi * hz / sr;
4249 double rate = 0.0;
4250 int used = 0;
4251 for (int i = 0; i < nLines_; ++i)
4252 {
4253 const double M = loopLen(i);
4254 if (!(M > 0.0)) continue;
4255 const double gM = std::pow(0.001, M / (d * sr));
4256 const double gH = std::min(std::pow(0.001, M / (std::max(0.05, d * hd) * sr)), gM);
4257 const double gB = std::min(std::pow(0.001, M / (std::max(0.05, d * bd) * sr)), 0.9995);
4258 const double rh = std::sqrt(gM / gH), rb = std::sqrt(gB / gM);
4259 const double g = gH * shelf(Kh * rh, Kh / rh, w) * shelf(Kb * rb, Kb / rb, w);
4260 if (!(g > 0.0 && g < 1.0)) continue;
4261 rate += -sr * std::log10(g) / (3.0 * M);
4262 ++used;
4263 }
4264 return (used > 0 && rate > 0.0) ? used / rate : d;
4265 };
4266 double d = target;
4267 for (int it = 0; it < 4; ++it)
4268 {
4269 const double tm = 0.5 * (t60At(d, 500.0) + t60At(d, 1000.0));
4270 if (!(tm > 0.0)) break;
4271 d *= target / tm;
4272 }
4273 return std::clamp(d, 0.05, 120.0);
4274 }
4275
4276 // --- Early reflection generation -----------------------------------------
4277
4279 void generateERTapsForType(Type type) noexcept
4280 {
4281 const int cap = eco_ ? kEcoERTaps : kMaxERTaps;
4282 switch (type)
4283 {
4284 case Type::Room:
4285 case Type::Hall:
4286 case Type::Chamber:
4287 case Type::Cathedral:
4288 {
4289 const auto window = earlyWindow(type);
4290 generateERTaps(window[0], window[1], cap);
4291 break;
4292 }
4293 case Type::Plate:
4294 case Type::Spring: generateERTaps(0.0, 0.0, 0); break;
4295 }
4296 }
4297
4311 void generateERTaps(double minMs, double maxMs, int numTaps) noexcept
4312 {
4313 numERTaps_ = std::clamp(numTaps, 0, kMaxERTaps) / 2 * 2;
4314 numERSlots_ = 0;
4315 for (auto& side : erGroupStart_) side.fill(0);
4316 if (numERTaps_ == 0) return;
4317
4318 const double sr = spec_.sampleRate;
4319 const int R = numERTaps_ / 2; // reflections per input channel
4320 constexpr double p = 1.6;
4321 // Diffusion sets how many of the first reflections stay discrete
4322 // (crisp, room-like) instead of reading the diffused feed (smooth).
4323 const int discrete = 1 + static_cast<int>(std::lround(
4324 (kMaxDiscreteER - 1) * (1.0 - static_cast<double>(diffusion_.load(std::memory_order_relaxed)))));
4325
4326 const double decay = static_cast<double>(decayTime_.load(std::memory_order_relaxed));
4327 constexpr double kLn1000 = 6.907755278982137;
4328 // One record per reflection; a candidate for the discrete set keeps
4329 // two slots (raw and diffused feed), weighted by `raw`.
4330 struct Tap { double ms; int chan; int bin; double gain; bool candidate; bool raw; };
4331 std::array<std::array<Tap, kMaxERTaps>, 2> taps {};
4332 std::array<int, 2> used { 0, 0 };
4333 for (int c = 0; c < 2; ++c) // input channel: a source on that side
4334 {
4335 std::array<double, kMaxERTaps / 2> gv {}, msv {}, lat {};
4336 double dcSum = 0.0;
4337 for (int k = 0; k < R; ++k)
4338 {
4339 const double u = (k + 0.15 + 0.7 * hash01(k, c + 20)) / R;
4340 // Warped time in [0, 1): a floor of uniform density plus a
4341 // share rising like t^(p - 1).
4342 const double w = 0.3 * u + 0.7 * std::pow(u, 1.0 / p);
4343 msv[k] = minMs + (maxMs - minMs) * w;
4344 const double density = 1.0 / (0.3 + 0.7 / p * std::pow(std::max(u, 1e-3), 1.0 / p - 1.0)); // dk/dw
4345 const double sign = k < 4 || hash01(k, c + 40) < 0.5 ? 1.0 : -1.0;
4346 // Energy per unit time follows the room's own decay (the
4347 // late field's rate, so the two join without a swell or a
4348 // dip at any decay time): sparse taps are individually
4349 // louder.
4350 gv[k] = sign * std::exp(-kLn1000 * msv[k] * 1e-3 / decay) / std::sqrt(density);
4351 if (k >= discrete) dcSum += gv[k];
4352 // Arrival direction as the lateral coordinate (sine of the
4353 // lateral angle, uniform over a diffuse field), positive
4354 // toward the source's side: the first two (floor and
4355 // ceiling) share the source's own direction (30 degrees, a
4356 // hard-panned input), the next come mostly from the source's
4357 // side of the room, the later ones from everywhere.
4358 const double side = hash01(k, c + 50) < 0.92 - 0.42 * w ? 1.0 : -1.0;
4359 lat[k] = k < 2 ? 0.5 : side * (0.25 + 0.75 * hash01(k, c + 60));
4360 }
4361 // No DC: the early field's low end is left to the (coherent) late
4362 // field, and the output high-pass never has to drain a step.
4363 if (R > discrete)
4364 for (int k = discrete; k < R; ++k) gv[k] -= dcSum / (R - discrete);
4365 double energy = 0.0;
4366 for (int k = 0; k < R; ++k) energy += gv[k] * gv[k];
4367 // The early field joins the late one on a single exponential:
4368 // the late field's energy flow at time t after its injection is
4369 // exp(-t / tau) / (mean round trip) (the output taps follow the
4370 // absorption, so even its first echoes sit on that curve), and
4371 // the early reflections carry that same density over their
4372 // window. Half per input, so a mono source keeps it.
4373 const double tau = decay / (2.0 * kLn1000);
4374 const double tInj = static_cast<double>(erToLateSamples_.load(std::memory_order_relaxed)) / sr
4375 + kMeanInjectMs * 1e-3;
4376 const double target = static_cast<double>(kOutGain) * static_cast<double>(kOutGain)
4377 * tau / meanLoopSec_
4378 * (std::exp(-(minMs * 1e-3 - tInj) / tau) - std::exp(-(maxMs * 1e-3 - tInj) / tau));
4379 const double norm = std::sqrt(0.5 * target / energy);
4380
4381 // Every reflection reaches both outputs like both ears: the far
4382 // one later (Woodworth ITD, up to 0.66 ms), quieter (up to
4383 // -6 dB) and, beyond a lateral angle of 17 degrees, duller (half
4384 // its highs); the near one up to 1.6 dB louder.
4385 for (int e = 0; e < 2; ++e)
4386 {
4387 for (int k = 0; k < R; ++k)
4388 {
4389 const double x = e == c ? lat[k] : -lat[k]; // toward this ear
4390 const double phi = std::asin(std::min(1.0, std::abs(x)));
4391 const double itdMs = x < 0.0 ? 1000.0 * 0.0875 / 343.0 * (phi + std::sin(phi)) : 0.0;
4392 const int bin = x < -0.3 ? 1 : 0;
4393 const double ild = x > 0.0 ? 1.0 + 0.2 * x : 1.0 + 0.5 * x;
4394 taps[e][used[e]++] = { msv[k] + itdMs, e == c ? 0 : 1, bin, gv[k] * norm * ild,
4395 k < kMaxDiscreteER, k < discrete };
4396 }
4397 }
4398 }
4399 for (int e = 0; e < 2; ++e)
4400 {
4401 // Time order, so the absorption groups run from early to late.
4402 std::sort(taps[e].begin(), taps[e].begin() + used[e],
4403 [](const Tap& a, const Tap& b) { return a.ms < b.ms; });
4404 // Slots in time order. The absorption groups split the
4405 // reflections (not the slots) evenly, as before the crossfade
4406 // slots existed, so a crossfade slot shares its reflection's group.
4407 int slot = 0, group = 1;
4408 erGroupStart_[e][0] = 0;
4409 for (int k = 0; k < used[e]; ++k)
4410 {
4411 while (group < kERGroups && k == used[e] * group / kERGroups)
4412 erGroupStart_[e][group++] = slot;
4413 const Tap& t = taps[e][k];
4414 const int lag = std::max(1, static_cast<int>(t.ms * sr / 1000.0));
4415 const auto put = [&](int chan, double gain) {
4416 erTap_[e][slot] = lag;
4417 erChan_[e][slot] = chan;
4418 erBin_[e][slot] = t.bin;
4419 erGainTarget_[e][slot] = static_cast<T>(gain);
4420 ++slot;
4421 };
4422 if (t.candidate)
4423 {
4424 put(t.chan + 2, t.raw ? t.gain : 0.0); // raw input: discrete
4425 put(t.chan, t.raw ? 0.0 : t.gain); // diffused feed
4426 }
4427 else
4428 {
4429 put(t.chan, t.gain);
4430 }
4431 }
4432 while (group <= kERGroups) erGroupStart_[e][group++] = slot;
4433 numERSlots_ = slot; // the same on both sides
4434 }
4435
4436 // Each absorption group loses its highs as the late field does by
4437 // the group's mean arrival time: 60 dB per HF T60 beyond the mid band.
4438 const double fh = std::clamp(static_cast<double>(highCrossover_.load(std::memory_order_relaxed)),
4439 100.0, 0.45 * sr);
4440 erShelfCoeff_ = static_cast<T>(1.0 - std::exp(-6.283185307179586 * fh / sr));
4441 const double t60H = std::max(0.05, calibratedMidDecay()
4442 * static_cast<double>(highDecayMult_.load(std::memory_order_relaxed)));
4443 for (int g = 0; g < kERGroups; ++g)
4444 {
4445 double tSum = 0.0;
4446 int cnt = 0;
4447 // Mean arrival time of the group's reflections (each counted
4448 // once, whatever its slots).
4449 for (int e = 0; e < 2; ++e)
4450 {
4451 int last = -1;
4452 for (int k = erGroupStart_[e][g]; k < erGroupStart_[e][g + 1]; ++k)
4453 {
4454 const bool second = k > erGroupStart_[e][g] && erTap_[e][k] == last
4455 && erChan_[e][k] + 2 == erChan_[e][k - 1];
4456 last = erTap_[e][k];
4457 if (second) continue;
4458 tSum += erTap_[e][k] / sr;
4459 ++cnt;
4460 }
4461 }
4462 const double t = cnt > 0 ? tSum / cnt : 0.0;
4463 erShelfGainTarget_[g] = static_cast<T>(std::pow(10.0, -3.0 * t * std::max(0.0, 1.0 / t60H - 1.0 / decay)));
4464 }
4465 }
4466
4467 // Sieve of Eratosthenes up to kPrimeTableMax, computed once on first use.
4468 static constexpr int kPrimeTableMax = 131072;
4469
4470 static const std::vector<uint8_t>& getPrimeSieve() noexcept
4471 {
4472 static const std::vector<uint8_t> sieve = []
4473 {
4474 std::vector<uint8_t> s(static_cast<size_t>(kPrimeTableMax), 1);
4475 s[0] = 0;
4476 s[1] = 0;
4477 for (int i = 2; i * i < kPrimeTableMax; ++i)
4478 if (s[static_cast<size_t>(i)])
4479 for (int j = i * i; j < kPrimeTableMax; j += i)
4480 s[static_cast<size_t>(j)] = 0;
4481 return s;
4482 }();
4483 return sieve;
4484 }
4485
4487 static int nearestPrime(int n) noexcept
4488 {
4489 if (n <= 2) return 2;
4490 if (n < kPrimeTableMax)
4491 {
4492 const auto& sieve = getPrimeSieve();
4493 while (n < kPrimeTableMax && !sieve[static_cast<size_t>(n)])
4494 ++n;
4495 if (n < kPrimeTableMax) return n;
4496 }
4497 if (n % 2 == 0) ++n;
4498 while (true)
4499 {
4500 bool isPrime = true;
4501 for (int d = 3; d * d <= n; d += 2)
4502 if (n % d == 0) { isPrime = false; break; }
4503 if (isPrime) return n;
4504 n += 2;
4505 }
4506 }
4507
4508 // --- Preset application --------------------------------------------------
4509
4514
4519 void commitPreset(const PresetValues& p) noexcept
4520 {
4521 const uint32_t m = userParamMask_.load(std::memory_order_acquire);
4522 if (!(m & kUserSize)) size_.store(p.size, std::memory_order_relaxed);
4523 if (!(m & kUserDecay)) decayTime_.store(p.decay, std::memory_order_relaxed);
4524 if (!(m & kUserDamping))
4525 {
4526 highDecayMult_.store(p.hdMult, std::memory_order_relaxed);
4527 damping_.store(std::clamp((T(1) - p.hdMult) / T(0.9), T(0), T(1)),
4528 std::memory_order_relaxed);
4529 }
4530 if (!(m & kUserBassDecay)) bassDecayMult_.store(p.bdMult, std::memory_order_relaxed);
4531 if (!(m & kUserHighXover)) highCrossover_.store(p.hxover, std::memory_order_relaxed);
4532 if (!(m & kUserBassXover)) bassCrossover_.store(p.bxover, std::memory_order_relaxed);
4533 if (!(m & kUserDiffusion)) diffusion_.store(p.diff, std::memory_order_relaxed);
4534 if (!(m & kUserModDepth)) modDepth_.store(p.modDepth, std::memory_order_relaxed);
4535 if (!(m & kUserModRate)) modRate_.store(p.modRate, std::memory_order_relaxed);
4536 if (!(m & kUserEarly)) earlyLevel_.store(p.earlyLvl, std::memory_order_relaxed);
4537 if (!(m & kUserLate)) lateLevel_.store(p.lateLvl, std::memory_order_relaxed);
4538 if (!(m & kUserErToLate)) erToLateMs_.store(p.erToLate, std::memory_order_relaxed);
4539 if (spec_.sampleRate > 0)
4540 erToLateSamples_.store(msToSamples(erToLateMs_.load(std::memory_order_relaxed)),
4541 std::memory_order_relaxed);
4542 }
4543
4545 static PresetValues presetValues(Type type) noexcept
4546 {
4547 // size decay hdMult bdMult hxover bxover
4548 // diff modDep modRate early late erToLate
4549 switch (type)
4550 {
4551 case Type::Room:
4552 return { T(0.22), T(0.5), T(0.40), T(1.1), T(5000), T(250),
4553 T(0.72), T(0.07), T(0.5), T(1), T(0.8), T(0) };
4554 case Type::Hall:
4555 return { T(0.68), T(2.2), T(0.32), T(1.3), T(4500), T(200),
4556 T(0.84), T(0.10), T(0.55), T(1), T(1), T(15) };
4557 case Type::Chamber:
4558 return { T(0.38), T(1.2), T(0.38), T(1.1), T(5000), T(250),
4559 T(0.78), T(0.08), T(0.6), T(1), T(0.9), T(8) };
4560 case Type::Plate:
4561 return { T(0.14), T(1.5), T(0.55), T(0.8), T(7000), T(150),
4562 T(0.94), T(0.16), T(1.4), T(0), T(1), T(0) };
4563 case Type::Spring:
4564 return { T(0.11), T(0.9), T(0.28), T(1.0), T(4000), T(200),
4565 T(0.6), T(0.08), T(0.35), T(0.5), T(1), T(0) };
4566 case Type::Cathedral:
4567 break;
4568 }
4569 return { T(0.98), T(5.0), T(0.24), T(1.5), T(3500), T(150),
4570 T(0.91), T(0.12), T(0.35), T(1), T(1), T(25) };
4571 }
4572
4575 void applyTopology(Type type) noexcept
4576 {
4577 spring_ = type == Type::Spring;
4578 erType_ = type;
4580 if (prepared_)
4581 updateAll();
4582 }
4583
4586 void applyPreset(Type type) noexcept
4587 {
4589 applyTopology(type);
4590 }
4591};
4592
4593} // namespace dspark
True-stereo 32-line FDN reverb with exact per-band decay and 6 presets.
static constexpr T rotRateFactor(int i) noexcept
std::array< std::array< T, kMaxLines >, kDecayBands > dqB2_
void setGateRelease(T ms) noexcept
Release of the gate, 5 to 4000 ms (default 150).
bool isTailHeld() const noexcept
void setBandLimit(T hz) noexcept
Limits the band of the wet signal, as early digital reverbs did: an elliptic wall (order 12,...
static constexpr double kOutDiffMs_[2][kOutStages]
void setSpaceLayout(SpaceLayout layout) noexcept
How the line lengths are laid out: Prime (the default) takes the tuned base lengths; Geometric spaces...
static double shelfGain(double a, double b, double w) noexcept
Quality
Engine quality / CPU cost trade-off (see setQuality()).
@ Eco
Reduced 8-line engine, about 3x cheaper. For constrained targets.
@ Full
Complete 32-line engine. Default.
void runSprings(T &lateL, T &lateR, const T(&raw)[2]) noexcept
One sample of the spring tanks (Type::Spring): six springs per side (one in Eco), all of different le...
std::array< T, kMaxLines > airNow_
std::array< int, kMaxLines > loopAPFrom_
std::array< std::array< T, kERGroups >, 2 > erShadowLP_
T getHighDecayMultiplier() const noexcept
KeyEqualizer< T, 2 > postEq_
static constexpr double kLoopApMs_[kMaxLines]
static void hadamardSmall(T *x) noexcept
T sizeFactor() const noexcept
Size factor: size 0 -> 0.35, size 1 -> 1.
std::array< PublishedDecayBand, kDecayBands > decayBands_
double quietSamples_
samples since input last entered the tank
std::array< int, kMaxLines > loopAPLen_
in-loop allpass target lengths
std::pair< T, T > outputStage(T lateL, T lateR, T earlyL, T earlyR, T earlyLevel, T lateLevel, T width, T toneHPMix, T toneLPMix, T outAPCoeff) noexcept
double meanLoopSec_
mean FDN round trip (s), for the early/late energy match
T getTankLeveling() const noexcept
std::atomic< int > erToLateSamples_
void setWidthLaw(WidthLaw law) noexcept
How setWidth() acts on the tail: Side (the default) scales the side; PowerKept also raises the middle...
void processChunk(const T *inL, const T *inR, T *outL, T *outR, int count) noexcept
Core processing of up to kChunk samples: stereo in, wet stereo out.
T erGlidePerSample_
glide rate of the two (1 / samples)
static constexpr double kAirFitHz
void setTankLeveling(T amount) noexcept
Leveling of the tank, 0 to 1 (0, the default, is off): a compressor on the tank's input (ratio 1 + 3 ...
void beginSizeFade() noexcept
Opens the second read head of every line at the new lengths (with the wander the first one carries) a...
std::array< T, kERGroups > erShelfGainTarget_
static constexpr double kSecondRatio
its decay times, as a share of the tank's
void holdAbsorption() noexcept
The loop gains as they stand, kept for the ramp of a chunk.
static constexpr double kInjectMs_[kMaxLines]
void endSizeFade() noexcept
The fade is over: the second heads become the first.
static constexpr double kMaxInjectMs
T wetLevel_
the wet signal's level against the decay (see updateDecayParams())
static constexpr int kShadowBins
head-shadow classes of the early taps (open, shadowed)
static constexpr int kInStages
input diffusers per channel feeding the late field (Full)
static constexpr double kSpringCutHz
dispersion band edge (transition frequency)
std::array< T, kInStages > inAPCoeffTarget_
inAPCoeff_ glides here (setDiffusion)
void snapGlides() noexcept
Puts every gliding parameter (levels, width, diffusion, tone) at its target.
std::array< std::array< std::array< T, kMaxLines >, kDecayBands >, 5 > dqGoal_
void applyHoldShelves() noexcept
The shelves and decay bands of applyHoldCoeffs().
T getInputWidth() const noexcept
std::array< std::array< T, kMaxLines >, 6 > absFrom_
The loop gains' ramp across a chunk: where they stood and their step per sample.
static constexpr double kMaxErToLateMs
void setSourceDepth(T amount) noexcept
Depth of the source in the room, 0 to 1 (0, the default, is off): one control that moves the balance ...
std::array< T, kMaxLines/2 > rotC_
std::array< std::array< T, kERGroups >, 2 > erLP_
std::array< T, kMaxLines > bassY1_
std::array< T, kMaxLines > airGoal_
std::array< double, kMaxLines > posInc_
per-sample ramp
void setTailHold(bool on) noexcept
Holds the tail: the input to the tank and the early field fade out over about 20 ms while every loop'...
static constexpr double kInDiffCoeffs_[kInStages]
static constexpr double kInDiffMs_[2][kInStages]
static void diffuseSpans(Line &ap, int len, T g0, T gDelta, const T *ramp, T *x, int count) noexcept
One Schroeder allpass stage over a chunk: w = x + g d, out = d - g w, with g = g0 + gDelta ramp[n] at...
std::array< T, kMaxLines > airBase_
void runPlate(T &lateL, T &lateR, int injLag, T inGain, T extra) noexcept
One sample of the plate tank: the late pair, from the diffused feed.
static double hash01(int k, int s) noexcept
Deterministic hash in [0, 1) for the early-reflection layout.
void setQuality(Quality q) noexcept
Selects the engine quality / CPU cost trade-off.
Type getType() const noexcept
static void glideHz(double &cur, double target, double amount) noexcept
One glide step of a running cutoff toward its target (log domain).
static constexpr AirTaps identityAirTaps() noexcept
static constexpr uint32_t rotSeed(int i) noexcept
NoteValue getPreDelayNote() const noexcept
std::array< std::array< T, kMaxLines >, kAirTaps > AirTaps
std::array< int, kMaxLines > lenTarget_
prime line lengths (samples)
static constexpr int kMaxERSlots
static void fwht(T *x) noexcept
std::array< std::array< int, kMaxERSlots >, 2 > erBin_
std::array< std::array< T, kMaxLines >, 3 > bassGoal_
void setTankSaturation(bool on) noexcept
Soft saturation after the leveling compressor (off by default).
NoteValue
A note value for the tempo-synced times.
void setToneHighCut(T hz) noexcept
Sets a post-reverb high-cut filter on the wet signal (12 dB/oct).
static constexpr double kMaxInDiffMs
static constexpr double kMaxGlideSpeed
max length change per sample (4% Doppler)
static constexpr double kMaxDecayLoopGain
Highest loop gain the decay bands may reach.
static constexpr double kSizeFadeSeconds
the cross-fade of the two read heads
static constexpr double kPlateEnergy
The plate's tail energy over the tail formula (measured, 1.5 to 8 s: within 0.25 dB).
double calibratedMidDecay() const noexcept
The loop's DC decay that puts the ISO 3382 mid-frequency reverberation time on the decay setting.
void applyPreset(Type type) noexcept
static const std::vector< uint8_t > & getPrimeSieve() noexcept
std::array< T, kMaxLines > lenCur_
gliding length
std::pair< T, T > processSample(T input) noexcept
Processes a single mono sample and returns the wet stereo pair.
void generateERTapsForType(Type type) noexcept
Regenerates the early-reflection taps for a reverb type (Eco caps the count).
void refreshCachedParams() noexcept
Pulls the atomic parameters into the block-local cache (audio thread).
static constexpr int kPrimeTableMax
void setDiffusion(T amount) noexcept
Diffusion (0 - 1): the strength of the input, in-loop and output allpass diffusers,...
void setType(Type type) noexcept
Loads the selected preset baseline.
std::array< double, kMaxLines > posInc2_
void setGateHoldNote(NoteValue note, NoteFeel feel=NoteFeel::Straight) noexcept
Gate hold as a note value at the tempo (Off, the default, uses setGateHold()); up to 4 s.
static constexpr int kEcoSprings
static constexpr double kMaxPreDelayMs
std::atomic< bool > tailHold_
std::array< double, kMaxLines > pos2_
double tankEmptyAfter_
quiet samples after which the tank is under -120 dB
static constexpr double kApLow
void setEarlyLevel(T dB) noexcept
Early reflections level in dB (-60 to +6). 0 dB is the physical balance: the early field then carries...
static constexpr int kMaxERTaps
early taps per output side: 64 reflections per input (Full)
Quality getQuality() const noexcept
std::array< T, kMaxLines > outSignR_
static constexpr double kMeanInjectMs
mean of kInjectMs_
static constexpr int kOutSignR_[kMaxLines]
static constexpr double kWetCalibrationSpring
static constexpr int kSpringStages
dispersion allpasses per spring (Full)
void setGate(T thresholdDb) noexcept
Gate on the wet signal (see TailShaper): it closes once the dry signal has stayed thresholdDb under i...
double drawShimmerLength() noexcept
std::array< std::array< std::array< T, kMaxLines >, kDecayBands >, 5 > dqBase_
T getErToLateDelay() const noexcept
std::array< T, kMaxLines > jotB1_
std::atomic< bool > plateTank_
bool isThicknessSaturated() const noexcept
DecayBand getDecayBand(int index) const noexcept
T getEffectivePreDelay() const noexcept
std::array< double, kMaxLines > pos_
current read position
static constexpr double kShadowHz
head-shadow corner of the early taps
static constexpr int kOutStages
int airTapCount_
taps that carry more than 1e-7 of the largest b's sum
std::array< std::array< T, kMaxLines >, kDecayBands > dqA2_
static constexpr int kChunk
sparse-FIR processing chunk (samples)
T toneHPMix_
share of the filtered signal
static constexpr std::array< double, SecondSlope::kLines > kSecondMs
std::array< T, kMaxLines > jotA1_
int levelHoldSamples_
Tank leveling: hold left and its length.
static constexpr int kMaxLines
std::atomic< bool > paramsDirty_
void runSecondSlope(T &lateL, T &lateR, int injLag) noexcept
One sample of the second slope, added to the late pair.
std::array< T, kInStages > inAPCoeff_
std::array< T, kMaxLines/2 > rotS_
std::array< std::array< T, 5 >, 2 > springLP_
b0 b1 b2 a1 a2, two sections
std::array< std::array< T, kMaxLines >, kDecayBands > dqB0_
std::array< T, kMaxLines > apY1_
allpass interpolator state
void controlTick() noexcept
Control-rate update: glides the line lengths toward their targets, draws the next modulation values a...
static constexpr double kCoherenceQ
static constexpr T rotRate() noexcept
void glideAbsorption(T gc) noexcept
std::array< std::array< T, kMaxLines >, 3 > jotBase_
std::array< T, kMaxLines > outSignL_
std::array< T, kMaxLines > lenNew_
T erShelfCoeff_
one-pole coefficient at the high crossover
static int nearestPrime(int n) noexcept
Smallest prime >= n (lengths only grow by a few samples).
void rampAbsorption(T perSample) noexcept
T getBassDecayMultiplier() const noexcept
T shimmerStep(T input) noexcept
One sample of the octave-up shimmer: two read heads, half a window apart, sweep the recent input at t...
double earlyEnergy() const noexcept
The energy of the early field in the tail's units: the tail's own energy flow over the early window (...
void setModulation(T amount) noexcept
Modulation depth (0 - 1) of the delay-line wander. It smears the tail's resonances; 0 is fully static...
void setAirAbsorption(T amount) noexcept
The absorption of the air inside the tank, on top of the walls' (opt-in; the network types).
T getSourceDepth() const noexcept
void setDryDip(T dB) noexcept
Dips the wet signal under the dry one while it plays (see TailShaper): by up to dB (0 to 48; 0,...
T getHighCrossover() const noexcept
T getModulation() const noexcept
static constexpr double kBaseDelaysMs_[kMaxLines]
static double biquadGain(const BiquadCoeffs &q, double w) noexcept
static double airDepth(double amount, double loopSeconds, double sr) noexcept
The b of a line: its loss in decibels, 8.686 b (1 - cos w), at kAirFitHz is the air's over a round tr...
static constexpr uint32_t lfoSeed(int i) noexcept
static constexpr int kDecayBands
Bands of the decay equalizer.
std::array< std::array< Line, kOutStages >, 2 > outAP_
late-field output diffusers
static T levelDb(T gain) noexcept
Linear gain to dB (a zero gain, a preset's muted early field, reads -120 dB).
void setBassCrossover(T hz) noexcept
Frequency where the bass decay transition is centered.
std::array< std::array< T, kMaxLines >, 3 > bassBase_
static constexpr int kInjectSign_[kMaxLines]
T getEarlyLevel() const noexcept
Early reflections level in dB (as set, or the preset's).
void setPreDelay(T ms) noexcept
Pre-delay before the early reflections, in ms (0 - 500); a note value set by setPreDelayNote() takes ...
static constexpr T kSpringOutGain
std::array< T, kERGroups > erShelfGain_
HF gain of each absorption group.
void setPreDelayNote(NoteValue note, NoteFeel feel=NoteFeel::Straight) noexcept
Pre-delay as a note value at the tempo (Off, the default, uses setPreDelay()); up to 500 ms.
ModulationStyle getModulationStyle() const noexcept
std::array< std::array< int, kInStages >, 2 > inAPLen_
static constexpr double kShimmerMaxMs
Longest window of the shimmer's heads.
std::array< std::array< T, kMaxLines >, kDecayBands > dqA1_
void setMix(T dryWet) noexcept
Dry/wet mix (0 = dry, 1 = wet). The wet signal is calibrated to the dry one's level: on pink noise at...
void drainPendingChanges() noexcept
Drains deferred parameter changes on the audio thread.
std::array< SegmentLfo, kMaxLines > seg_
int msToSamples(T ms) const noexcept
void setGateHold(T ms) noexcept
Hold of the gate, 0 to 4000 ms (default 100); a note value set by setGateHoldNote() takes its place.
static constexpr double kWetCalibration
static constexpr int kEcoSpringStages
void setShimmer(T amount) noexcept
Octave-up shimmer, 0 to 1 (0, the default, is off): the tail is pitched up an octave by two read head...
void reset() noexcept
Clears all delay lines and filter states and restarts the modulation, snapping any length glide to it...
static constexpr int kCtrl
modulation control period (samples)
double effectivePreDelayMs() const noexcept
The pre-delay in ms: the note value's time at the tempo, or the one set.
std::array< std::array< T, kMaxERSlots >, 2 > erGain_
current (gliding) tap gains
std::array< std::array< int, kMaxERSlots >, 2 > erChan_
bool fresh_
no sample processed since prepare()/reset()
static constexpr T kShimmerFeed
Share of the shimmer fed back at full amount.
std::array< std::array< std::array< T, kMaxLines >, kDecayBands >, 5 > dqStep_
std::array< T, kMaxLines > bassX1_
static constexpr T lfoRateFactor(int i) noexcept
static constexpr double kSpringJitterMs
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
T getBassCrossover() const noexcept
std::array< std::array< T, kSprings >, 4 > springLPState_
[section * 2 + state][spring]
static constexpr int kRotPairStride
void setInputWidth(T width) noexcept
Width of the input, 0 to 1 (1, the default, is the input as it is): the side of the input is scaled b...
void runFdn(T &lateL, T &lateR, int injLag, T loopAPCoeff, T inGain, T extra) noexcept
One sample of the N-line FDN (compile-time N so the per-line stages vectorize): allpass-interpolated ...
std::array< T, kMaxLines > loopAPCur_
gliding lengths after a size change
static constexpr std::array< double, 2 > earlyWindow(Type type) noexcept
The early reflections' window of a type, in ms (none: both zero).
T getGateRelease() const noexcept
std::array< T, kMaxLines > injGain_
sign / sqrt(lines)
std::array< std::array< Line, kInStages >, 2 > inAP_
static constexpr double kSecondShare
its share of the tail's energy at 1
void setLateLevel(T dB) noexcept
Late tail level in dB (-60 to +6). Changes glide over about 20 ms.
void setModulationStyle(ModulationStyle style) noexcept
How the line lengths wander: Smooth (the default) is the smooth random modulation of every line; Segm...
DecayShape
Shape of a band of the decay equalizer (setDecayBand()).
void snapTone() noexcept
Puts the tone filters at their targets at once (prepare, reset).
SpaceLayout
How the line lengths are laid out (setSpaceLayout()).
void setToneLowCut(T hz) noexcept
Sets a post-reverb low-cut filter on the wet signal (12 dB/oct).
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
std::array< T, kMaxLines > bassA1_
static double springBaseMs(int s) noexcept
std::array< T, kMaxLines > bassB1_
WidthLaw
How the output width acts (setWidthLaw()).
T getLateLevel() const noexcept
Late tail level in dB (as set, or the preset's).
void snapAbsorption() noexcept
The absorption at its design at once (no glide).
bool airInUse_
any line's b, designed, gliding or in use, above 0
std::array< int, kDecayBands > dqList_
std::atomic< bool > toneDirty_
void setPostEqBand(int index, const typename KeyEqualizer< T, 2 >::Band &band) noexcept
One band of the wet signal's equalizer (KeyEqualizer bands).
void designPlate(double decay, double t60H, double crossoverHz) noexcept
The plate tank's decay and damping. A branch takes its gain once a pass, from its own length; the dam...
static constexpr int kPostBands
Bands of the wet equalizer.
std::array< T, kMaxLines > bassB0_
std::array< int, kMaxLines > loopAPTo_
static constexpr double kMaxErMs
double noteMs(int note, int feel) const noexcept
A note value's time at the tempo, in ms.
static constexpr int kERGroups
absorption groups (early -> late)
void setDamping(T amount) noexcept
Sets high-frequency damping (0 = bright, 1 = dark).
std::array< std::array< T, kMaxLines >, kDecayBands > dqZ1_
static T glideTo(T cur, T target, T amount) noexcept
void setErToLateDelay(T ms) noexcept
Extra gap between the early reflections and the late tail, in ms (0 - 200).
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an audio block in place with zero allocations.
T getAirAbsorption() const noexcept
static constexpr double kAirMaxDepth
void markUserParam(uint32_t bit) noexcept
std::array< std::array< int, kOutStages >, 2 > outAPLen_
static constexpr double kRotRateHz
std::atomic< uint32_t > userParamMask_
void setSize(T size) noexcept
Room size (0.01 - 1). Scales the delay lines from 36% to 100% of their base lengths....
double heardTailEnergy(double decay, double t60H, double t60B, double Kh, double Kb) const noexcept
The energy of the tail for a unit of energy injected, as heard. At each frequency the first pass leav...
void designSecondSlope(double decay, double t60H, double Kh) noexcept
The second slope's absorption and shares. Fed and summed as the tank is (unit energy in,...
bool getPostEqLoudness() const noexcept
bool isPlateTank() const noexcept
std::array< std::array< int, kERGroups+1 >, 2 > erGroupStart_
slot index per side
std::atomic< bool > presetDirty_
void commitPreset(const PresetValues &p) noexcept
std::array< SmoothRandomLFO, kMaxLines/2 > rotLfo_
static constexpr double kSubsonicHz
wet-output high-pass (2nd order): no room rings below it
void setDoubleSlope(T amount) noexcept
A second slope, 0 to 1 (0, the default, is off): beside the tank, four lines of its own decay in 0....
void setModRate(T hz) noexcept
Modulation rate in Hz (0.1 - 5); each line wanders at its own multiple.
int numERTaps_
reflections per output side
void stepAbsorption() noexcept
One sample of the loop gains' ramp.
std::array< std::array< int, kMaxERSlots >, 2 > erTap_
NoteFeel
The feel of a note value.
static constexpr double kSizeFadeOver
a length change beyond this share cross-fades two read heads
static constexpr int kSprings
std::array< SmoothRandomLFO, kMaxLines > lfo_
void updateDecayParams() noexcept
Per-line absorption: Jot mid/high shelf and bass shelf.
SpaceLayout getSpaceLayout() const noexcept
std::array< std::array< T, kMaxERSlots >, 2 > erGainTarget_
gains for the current size/decay
std::array< std::array< T, kMaxLines >, 6 > absStep_
void setDecayBand(int index, const DecayBand &band) noexcept
One band of the decay equalizer: the decay time in a band of frequencies, as a multiple of what the o...
void applyDecayBands(T *r) noexcept
The decay bands in the loop, one TDF-II biquad per line and band (the per-line arithmetic runs across...
static constexpr double kSoundSpeed
void setWidth(T width) noexcept
Sets stereo width of the late reverb tail.
@ Chamber
Recording studio chamber, warm, balanced.
@ Spring
Spring reverb, bouncy vintage character.
@ Cathedral
Large cathedral, immense decay, vast space.
@ Hall
Concert hall, spacious, long smooth tail.
@ Plate
Metal plate, dense shimmer, no early reflections.
@ Room
Small room, short decay, dense close reflections.
double levelRelease_
Tank leveling: the reduction (dB) and its release.
void setAirTaps(std::size_t l) noexcept
static constexpr double kShimmerMinMs
Shortest window of the shimmer's heads.
T getDiffusion() const noexcept
KeyEqualizer< T, 2 >::Band getPostEqBand(int index) const noexcept
std::array< std::array< T, kMaxLines >, 3 > jotGoal_
void setHighDecayMultiplier(T mult) noexcept
Sets HF decay as a multiplier of mid decay time.
T getDoubleSlope() const noexcept
std::array< std::array< T, kMaxLines >, kDecayBands > dqZ2_
std::array< Line, 2 > preDelay_
void setPlateTank(bool on) noexcept
The plate's own tank (off by default; Type::Plate only): the figure-eight of Dattorro's plate instead...
void generateERTaps(double minMs, double maxMs, int numTaps) noexcept
Velvet-noise early field (Valimaki et al.): numTaps sparse +-1 impulses per side between minMs and ma...
std::array< Line, 2 > ring_
allpass-diffused input, feeds the late field
void setPostEqLoudness(bool on) noexcept
Keeps the loudness of the wet signal through its equalizer (off by default; see KeyEqualizer::setLoud...
static T allpassCoeff(double d) noexcept
static constexpr double kCoherenceHz
side high-pass of the late field (2nd order, Q 0.74)
std::array< std::array< T, kMaxLines >, kDecayBands > dqB1_
std::atomic< Quality > quality_
static constexpr int kAirTaps
static void addTap(T *acc, const Line &l, int lag0, T gain, int count) noexcept
void refreshTopology() noexcept
Line count of the active engine: the springs, or the FDN size.
static constexpr int kMaxDiscreteER
std::array< T, kMaxLines > jotX1_
void applyHoldCoeffs() noexcept
The absorption and decay bands in use: the designed ones moved toward unity by the tail hold.
void setHighCrossover(T hz) noexcept
Frequency where the HF decay transition is centered.
static constexpr double kModMaxMs
void prepare(const AudioSpec &spec)
Prepares the reverberation engine and allocates required memory.
std::array< T, kMaxLines > jotY1_
std::array< T, kMaxLines > jotB0_
WidthLaw getWidthLaw() const noexcept
void setDecay(T seconds) noexcept
Mid-frequency reverberation time in seconds (0.1 - 30).
static constexpr double kShadowHF
high-frequency gain of a shadowed (far-ear) tap
void designDecayBands(double decay, double t60H, double t60B, double Kh, double Kb) noexcept
Designs the decay bands per line (audio thread at the drain, or prepare()): each band's gain from the...
static constexpr int kEcoLines
int numERSlots_
tap slots per output side (see kMaxERSlots)
double fadeStep_
the fade, 0 to 1, and its step per sample
std::array< double, 2 > shimPhase_
static void writeSpan(Line &l, const T *src, int count) noexcept
Pushes count samples into a line, in pieces that stop at its end.
ModulationStyle
How the lines' lengths wander (setModulationStyle()).
std::array< T, kMaxLines > apY2_
static double airAttenuationDbPerMetre(double hz) noexcept
The air's attenuation in dB per metre at 20 degrees C, 50 % relative humidity and one atmosphere (ISO...
void applyTopology(Type type) noexcept
void advanceTone(T amount, T &hp0, T &lp0) noexcept
std::array< double, 2 > shimLen_
std::array< std::array< std::array< T, kMaxLines >, kDecayBands >, 5 > dqFrom_
NoteValue getGateHoldNote() const noexcept
bool toneLPActive_
filter running (on, or still fading out)
static constexpr int kOutSignL_[kMaxLines]
void setBassDecayMultiplier(T mult) noexcept
Sets bass decay as a multiplier of mid decay time.
std::atomic< bool > qualityDirty_
std::array< int, kMaxLines > injTap_
static constexpr T kSoftLimit
in-loop safety limiter threshold
static PresetValues presetValues(Type type) noexcept
The parameter values of each preset.
std::atomic< int > preDelaySamples_
T getBandLimit() const noexcept
static constexpr double kGlideMs
size-change glide time constant
void setTempo(T bpm) noexcept
Tempo for the note values, 20 to 400 BPM (default 120).
static constexpr double kRotMaxRad
peak rotation angle at modulation 1 (rad)
void advanceSizeFade() noexcept
One sample of a size fade; at its end the second heads become the first.
static constexpr double kMaxLoopApMs
static constexpr int kEcoERTaps
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
void reset() noexcept
Clears the memory of every node. Coefficients and ramps are kept.
Biquad filter using Transposed Direct Form II (TDF-II) with thread-safe updates.
Definition Biquad.h:853
void setCoeffsNow(const BiquadCoeffs &c) noexcept
Stream-owner direct set: makes c the active set immediately.
Definition Biquad.h:963
void reset() noexcept
Resets all per-channel filter states to zero to avoid ringing/clicks.
Definition Biquad.h:1003
T processSample(T input, int channel) noexcept
Processes a single sample for a specific channel.
Definition Biquad.h:1029
double processSampleCore(double input, int channel) noexcept
One recursion step in the core's own precision (double).
Definition Biquad.h:1049
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
Definition DryWetMixer.h:83
static AnalogCascade ellipticHighCut(double hz, int order=12, double rippleDb=0.05, double stopDb=100.0) noexcept
Elliptic high cut: flat to the corner within the ripple, then a wall down to the stop level.
static BiquadCoeffs bilinear(const AnalogSection &section, double sampleRate, double exactHz) noexcept
The bilinear transform of a section, with one frequency mapped exactly.
Six bands of cuts, bells, shelves and tilts over the key of a dynamics processor.
void setLoudnessCompensation(bool on) noexcept
Keeps the loudness (off by default): the bands' change of the K-weighted level of pink noise (as BS....
bool getLoudnessCompensation() const noexcept
void writeState(StateWriter &w, const char *prefix) const
Writes the bands under keys that start with a prefix ("<prefix><band>.shape", ".freq",...
bool sync() noexcept
Takes the settings published since the last call.
void processFrame(T *frame, int channels) noexcept
One frame of the key, every channel of it, in place.
void advance(int samples) noexcept
Moves the equalizer on in time: the coefficients between two designs, the bands on the move to their ...
void reset() noexcept
Clears the memory of the filters (settings and glides are kept).
void readState(const StateReader &r, const char *prefix) noexcept
Reads the bands writeState() wrote (a band that is missing reads as Off, a placement that is missing ...
Band getBand(int band) const noexcept
The published settings of a band (a band out of range reads as Off).
void setBand(int band, const Band &settings) noexcept
Publishes the settings of a band.
void prepare(double sampleRate) noexcept
Prepares the equalizer for a sample rate and clears its memory.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
A dip and a relative gate driven by the dry signal.
Definition TailShaper.h:50
void addWithGain(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, float gain, int count) noexcept
Adds source samples scaled by a gain factor into a destination buffer.
Definition SimdOps.h:302
Main namespace for the DSPark framework.
T decibelsToGain(T dB, T minusInfinityDb=T(-100)) noexcept
Converts a value in decibels to linear gain.
Definition DspMath.h:77
T fastSin(T x) noexcept
Fast sine approximation (degree-9 odd minimax polynomial).
Definition DspMath.h:340
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
Block-cached copies of the atomics read in the sample loop.
One band of the decay equalizer.
T q
Width of a bell, 0.1 to 10 (the shelves ignore it).
T multiplier
Decay time in the band against the rest, 0.1 to 4.
T frequency
Centre or corner, 20 Hz to 20 kHz.
Equal-size delay lines in one contiguous buffer sharing a write index (every line is written once per...
void prepare(int numLines, int maxDelay)
T at(int i, int k) const noexcept
Power-of-two circular delay line: at(k) is the sample pushed k samples ago.
static constexpr std::array< int, 2 > kAp1
static constexpr double kExcursion
Of the modulated all-passes at full modulation.
static constexpr std::array< int, 2 > kD2
double scale
The rate over Dattorro's.
static constexpr std::array< int, 2 > kAp2
static constexpr std::array< int, 2 > kD1
int at(double samples29k) const noexcept
T keep
its share of the output, what the tank keeps (targets)
T keepNow
where they are now (they glide)
Modulation by segments: a straight move toward the other side, a random share (0.3 to 0....
void prepare(uint32_t seed) noexcept
double next(int stride, double rateHz, double sr) noexcept
void setRate(T rate, double sr) noexcept
void prepare(double sr, T rate, uint32_t seed) noexcept
Hermite-interpolated random noise generator for organic modulation.
void retarget(double want) noexcept
The corner wanted now (0 = off); a fade under way finishes first.
void frame(T &l, T &r) noexcept
Up to kMaxSections analog sections in series.
std::array< AnalogSection, kMaxSections > sections
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
Stores normalised biquad coefficients (b0, b1, b2, a1, a2), always double.
Definition Biquad.h:107
static BiquadCoeffs makeHighPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
High-pass filter.
Definition Biquad.h:143
static BiquadCoeffs makePeak(double sampleRate, double freq, double Q, double gainDb) noexcept
Peak (parametric EQ) filter.
Definition Biquad.h:201
static BiquadCoeffs makeLowPass(double sampleRate, double freq, double Q=0.7071067811865476) noexcept
Low-pass filter.
Definition Biquad.h:119
static BiquadCoeffs makeLowShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
Low-shelf filter.
Definition Biquad.h:417
static BiquadCoeffs makeHighShelf(double sampleRate, double freq, double gainDb, double slope=1.0) noexcept
High-shelf filter.
Definition Biquad.h:447
The settings of one band.