Просмотр исходного кода

Facet EQ: dynamic EQ bands, natural / linear phase modes, solo; analyser tap and live meters for Facet EQ / LYNX Tune

Ka1-S 1 месяц назад
Родитель
Сommit
fe8a5d1680
6 измененных файлов с 762 добавлено и 40 удалено
  1. 56 0
      docs/analise/REA_rodada103.md
  2. 2 0
      src/core/Effects.cpp
  3. 598 27
      src/core/FacetEq.cpp
  4. 59 7
      src/core/FacetEq.h
  5. 31 4
      src/core/RackRenderer.cpp
  6. 16 2
      src/core/RackRenderer.h

+ 56 - 0
docs/analise/REA_rodada103.md

@@ -0,0 +1,56 @@
+# REA round 103 — Facet EQ editor, dynamic EQ and phase modes; LYNX Tune live pitch display
+
+Branch `feature/facet103`. English-first; clean-room. The reference EQ (FabFilter Pro-Q 4, official trial installed by
+the user) was only **hosted** with `tools/fxmeasure` (VST3 parameters in, audio out) — no disassembly, no strings, no
+graphics or manual text. Raw captures stay in `tmp/r103` (never in git). Scripts: `tools/fxmeasure/py/pqdyn.py`.
+
+## 1. Goal
+1. Facet EQ (core/FacetEq.*, round 99): a dedicated interactive editor (analyser, draggable nodes, add / remove bands,
+   Q on the wheel, shape menu, solo), per-band dynamic EQ (threshold / range, sidechain-able) and phase modes (zero
+   latency / natural / linear, latency reported to PDC).
+2. LYNX Tune (round 95): the live pitch display (detected pitch, target note, correction, scrolling pitch graph).
+
+## 2. Measurements of the reference's dynamic EQ [EXEC]
+Setup: one Bell band, 1 kHz, Q 1, gain 0 dB, Zero Latency, 48 kHz; 1 kHz sine stair −60 … 0 dBFS (sine peak), 2 dB
+steps of 0.6 s, level read over the last 0.3 s of each step; bursts −50 → −6 → −50 dBFS for timing.
+
+### 2.1 Static curve
+- The per-band switch whose texts read "Dynamics Auto" (normalized < 0.5) / "Dynamics Manual" (≥ 0.5) behaves the
+  other way round from its text: only with "Auto" (< 0.5) is the **threshold knob** used; with "Manual" (the default)
+  the threshold is set automatically from the signal (−60 / −30 / −10 dB thresholds all gave the same curve). The
+  measurements below use the knob.
+- With threshold T and range R (−12 dB): gain change at T−4: −0.1 dB, T−2: −0.5, T: −1.3, T+2: −2.5, T+4: −4.1,
+  T+6: −6.0, T+8: −8.0, T+10: −10.0, T+12: −12.0 (= R, then flat). So: **1 dB of gain per dB over the threshold (an
+  infinite ratio), a ≈10 dB soft knee centred on T, clamped at the range**. A quadratic knee of width 10 dB
+  ((x+5)²/20 for |x| < 5, x = level − T) reproduces every step within 0.1 dB [fit].
+- Positive range mirrors it (+0.1 … +12.0 dB at the same levels): the band is boosted as the level rises.
+- The static gain adds to it (gain +6, range −12: +6.0 below, −6.0 above).
+- An off-centre tone (500 Hz, one octave below) starts acting ≈ 6 dB later and reaches the bell's −5.7 dB there: the
+  detector listens through a band filter around the band (a 2nd-order band pass with the band's Q gives −5.1 dB one
+  octave away) [fit, approximate].
+
+### 2.2 Timing (gain envelope = |analytic(out)| / |analytic(in)|)
+- Attack % → time to 63 % of the 12 dB move: 0 %: 1.2 ms, 25 %: 1.4 ms, 50 %: 3.5 ms, 75 %: 13 ms, 100 %: 38 ms
+  (≈ 0.4 ms · 96^p, the bottom limited by the detector).
+- Release % → exponential recovery time constant (from the dB curve after the drop): 0 %: ≈ 115 ms, 25 %: ≈ 160 ms,
+  50 %: ≈ 270 ms, 75 %: ≈ 440 ms, 100 %: ≈ 720 ms.
+
+### 2.3 Phase modes (from round 99, MEASURE_fabfilter §1.3)
+Zero latency 0; natural phase 320 samples at 48 kHz (analog magnitude and phase); linear phase (medium) 5120.
+
+## 3. LYNX's design (own) [model]
+- Parameters appended at 42 … 63 (older projects load with every new control at the old behaviour: range 0 dB =
+  static band, phase = zero latency, solo off, detector = input).
+- Dynamic band (bell, shelves, tilt with range ≠ 0): detector = mid of the EQ input, or of the slot's sidechain
+  when "Detector: Sidechain" is chosen and a sidechain track is routed (mixer slot menu "Sidechain from"); filtered
+  by an RBJ band pass at the band frequency / Q (low pass for low shelf, high pass for high shelf), mean square
+  over max(1 ms, 1.5 periods), level in sine-peak dB; gain law of §2.1; gain smoothed with attack 0.25 … 50 ms
+  (default 3.5 ms) and release 20 ms … 4 s (default 283 ms). Zero-latency mode re-designs the band's sections every
+  32 samples when the dynamic gain moved more than 0.01 dB.
+- Natural phase: FIR (8192 taps at 48 kHz) of the analog prototype's complex response delayed by 192 samples,
+  windowed by a half-Hann rise before the delay and a half-Hann decay after it, run as a uniformly partitioned FFT
+  convolution with 128-sample blocks → latency 320 at 48 kHz (×2 up to 96 kHz, ×4 above).
+- Linear phase: FIR of the analog magnitude, delay 4096, Hann window, 512-sample blocks → latency 4608 at 48 kHz.
+- In the FIR modes the kernel is redesigned at most every 1024 samples (parameter changes, dynamic movement
+  > 0.05 dB) and cross-faded over one convolution block.
+- Solo: the band's region alone (the detector filter on the input), delayed by the mode's latency.

+ 2 - 0
src/core/Effects.cpp

@@ -2924,6 +2924,8 @@ std::unique_ptr<Effect> makeEffect (const EffectSlot& slot)
         return std::make_unique<ParametricEq> (slot.params);
     if (slot.kind == EffectKind::frequencySplitter)
         return fsplit::make (slot.params);
+    if (slot.kind == EffectKind::facetEq) // its phase mode (latency) known before the first block
+        return facet::make (&slot.params);
     if (slot.kind == EffectKind::hyperChorus)
         return hyperchorusfx::make (hyperchorusfx::instanceOf (slot.state));
     if (slot.kind == EffectKind::vintageChorus)

+ 598 - 27
src/core/FacetEq.cpp

@@ -1,9 +1,11 @@
 #include "core/FacetEq.h"
 
 #include <algorithm>
+#include <atomic>
 #include <cmath>
 #include <complex>
 #include <cstdio>
+#include <vector>
 
 namespace lynx::facet
 {
@@ -127,11 +129,11 @@ int butterworthQs (int n, double* qs) noexcept
 }
 
 // analog sections of one band (normalized to the band frequency); returns the count
-int analogSections (const EffectParams& p, int b, Analog* out) noexcept
+int analogSections (const EffectParams& p, int b, Analog* out, double extraDb = 0.0, bool keepFlat = false) noexcept
 {
     const auto sh = shape (p[(std::size_t) param (b, 0)]);
     const double scale = gainScale (p[(std::size_t) scaleParam]);
-    const double g = gainDb (p[(std::size_t) param (b, 2)]) * scale;
+    const double g = (gainDb (p[(std::size_t) param (b, 2)]) + extraDb) * scale;
     const double Q = bandQ (p, b);
     const int slope = slopeDb (p[(std::size_t) param (b, 4)]);
 
@@ -141,7 +143,7 @@ int analogSections (const EffectParams& p, int b, Analog* out) noexcept
         case Shape::bell:
         {
             // symmetric bell: (s² + s·A/Qb + 1) / (s² + s/(A·Qb) + 1), Qb = Q/√2 (measured convention)
-            if (std::abs (g) < 1e-9) return 0;
+            if (std::abs (g) < 1e-9 && ! keepFlat) return 0;
             const double A = std::pow (10.0, g / 40.0), qb = Q / std::sqrt (2.0);
             out[0] = { 1.0, A / qb, 1.0, 1.0, 1.0 / (A * qb), 1.0 };
             return 1;
@@ -150,7 +152,7 @@ int analogSections (const EffectParams& p, int b, Analog* out) noexcept
         case Shape::highShelf:
         case Shape::tiltShelf:
         {
-            if (std::abs (g) < 1e-9) return 0;
+            if (std::abs (g) < 1e-9 && ! keepFlat) return 0;
             const bool tilt = sh == Shape::tiltShelf;
             const double gg = tilt ? 2.0 * g : g;
             const double A = std::pow (10.0, gg / 40.0), sa = std::sqrt (A);
@@ -200,41 +202,451 @@ int analogSections (const EffectParams& p, int b, Analog* out) noexcept
     return 0;
 }
 
+
 cd evalDigital (const Section& s, double w) noexcept
 {
     const cd z1 = std::polar (1.0, -w), z2 = z1 * z1;
     return (s.b0 + s.b1 * z1 + s.b2 * z2) / (1.0 + s.a1 * z1 + s.a2 * z2);
 }
 
+// the analog response (complex) of one band at hz, with its dynamic movement
+cd analogBand (const EffectParams& p, int b, double f, double extraDb) noexcept
+{
+    Analog a[maxSections];
+    const int n = analogSections (p, b, a, extraDb);
+    const double w = f / hz (p[(std::size_t) param (b, 1)]);
+    cd h (1.0, 0.0);
+    for (int k = 0; k < n; ++k) h *= evalAnalog (a[k], w);
+    return h;
+}
+
+// the factor of the sine-rate grid of a phase mode: 1 up to 48 kHz, 2 up to 96 kHz, 4 above
+int rateFactor (double sr) noexcept { return sr <= 50000.0 ? 1 : sr <= 100000.0 ? 2 : 4; }
+constexpr int naturalBlock = 128, naturalDelay = 192, linearBlock = 512, firTaps = 8192;
+
+// --- FFT and the partitioned convolver (the FIR phase modes) ------------------------------------------------------
+
+struct Fft
+{
+    int n = 0;
+    std::vector<cd> tw;
+    std::vector<int> rev;
+
+    void init (int size)
+    {
+        n = size;
+        tw.resize ((std::size_t) n / 2);
+        for (int k = 0; k < n / 2; ++k) tw[(std::size_t) k] = std::polar (1.0, -2.0 * pi * k / n);
+        rev.resize ((std::size_t) n);
+        int bits = 0;
+        while ((1 << bits) < n) ++bits;
+        for (int i = 0; i < n; ++i)
+        {
+            int r = 0;
+            for (int b = 0; b < bits; ++b) r |= ((i >> b) & 1) << (bits - 1 - b);
+            rev[(std::size_t) i] = r;
+        }
+    }
+
+    // in place, unscaled (the inverse is n times too large)
+    void run (cd* a, bool inverse) const noexcept
+    {
+        for (int i = 0; i < n; ++i)
+            if (i < rev[(std::size_t) i]) std::swap (a[i], a[rev[(std::size_t) i]]);
+        for (int len = 2; len <= n; len <<= 1)
+        {
+            const int half = len / 2, step = n / len;
+            for (int i = 0; i < n; i += len)
+                for (int j = 0; j < half; ++j)
+                {
+                    const double wr = tw[(std::size_t) (j * step)].real(), wi = inverse ? -tw[(std::size_t) (j * step)].imag() : tw[(std::size_t) (j * step)].imag();
+                    const double xr = a[i + j + half].real(), xi = a[i + j + half].imag();
+                    const cd u = a[i + j], v (xr * wr - xi * wi, xr * wi + xi * wr);
+                    a[i + j] = u + v;
+                    a[i + j + half] = u - v;
+                }
+        }
+    }
+};
+
+// Uniformly partitioned overlap-save convolution of a stereo signal (left + j·right) with a real FIR; block P, latency
+// P. Buffers are sized once for the largest configuration; a new kernel is cross-faded in over one block.
+class Convolver
+{
+public:
+    void allocate (int maxTaps, int maxBlock)
+    {
+        fdl.assign ((std::size_t) maxTaps * 2, {});
+        kern[0].assign ((std::size_t) maxTaps * 2, {});
+        kern[1].assign ((std::size_t) maxTaps * 2, {});
+        timeBuf.assign ((std::size_t) maxBlock * 2, {});
+        acc.assign ((std::size_t) maxBlock * 2, {});
+        acc2.assign ((std::size_t) maxBlock * 2, {});
+        in.assign ((std::size_t) maxBlock, {});
+        out.assign ((std::size_t) maxBlock, {});
+    }
+
+    // P must be a power of two whose FFT (2P) is `fft`
+    void configure (const Fft& f, int blockSize, int taps) noexcept
+    {
+        fft = &f;
+        P = blockSize;
+        K = taps / blockSize;
+        reset();
+    }
+
+    void reset() noexcept
+    {
+        std::fill (fdl.begin(), fdl.end(), cd {});
+        std::fill (timeBuf.begin(), timeBuf.end(), cd {});
+        std::fill (in.begin(), in.end(), cd {});
+        std::fill (out.begin(), out.end(), cd {});
+        pos = head = 0;
+        pending = -1;
+    }
+
+    // a new FIR (K·P taps); the first one is used at once, later ones fade in over the next block
+    void load (const double* h, bool immediate) noexcept
+    {
+        const int next = immediate ? active : 1 - active;
+        auto* frame = acc2.data();
+        for (int k = 0; k < K; ++k)
+        {
+            for (int i = 0; i < P; ++i) frame[i] = cd (h[k * P + i], 0.0);
+            for (int i = P; i < 2 * P; ++i) frame[i] = {};
+            fft->run (frame, false);
+            std::copy (frame, frame + 2 * P, kern[(std::size_t) next].begin() + (std::ptrdiff_t) k * 2 * P);
+        }
+        pending = immediate ? -1 : next;
+    }
+
+    bool fading() const noexcept { return pending >= 0; }
+
+    void step (float& l, float& r) noexcept
+    {
+        in[(std::size_t) pos] = cd (l, r);
+        const auto y = out[(std::size_t) pos];
+        l = (float) y.real();
+        r = (float) y.imag();
+        if (++pos == P) block();
+    }
+
+private:
+    void accumulate (int which, cd* dst) noexcept
+    {
+        const int n2 = 2 * P;
+        std::fill (dst, dst + n2, cd {});
+        const auto* kr = kern[(std::size_t) which].data();
+        for (int k = 0; k < K; ++k)
+        {
+            const auto* x = fdl.data() + (std::ptrdiff_t) (((head - k + K) % K) * n2);
+            const auto* hk = kr + (std::ptrdiff_t) k * n2;
+            // plain products (std::complex's operator* checks for infinities, several times slower)
+            for (int i = 0; i < n2; ++i)
+            {
+                const double xr = x[i].real(), xi = x[i].imag(), hr = hk[i].real(), hi = hk[i].imag();
+                dst[i] += cd (xr * hr - xi * hi, xr * hi + xi * hr);
+            }
+        }
+        fft->run (dst, true);
+    }
+
+    void block() noexcept
+    {
+        const int n2 = 2 * P;
+        auto* tb = timeBuf.data();
+        std::copy (tb + P, tb + n2, tb);
+        std::copy (in.begin(), in.begin() + P, tb + P);
+        auto* x = fdl.data() + (std::ptrdiff_t) head * n2;
+        std::copy (tb, tb + n2, x);
+        fft->run (x, false);
+        const double scale = 1.0 / n2;
+        accumulate (active, acc.data());
+        if (pending >= 0)
+        {
+            accumulate (pending, acc2.data());
+            for (int i = 0; i < P; ++i)
+            {
+                const double t = (i + 0.5) / P;
+                out[(std::size_t) i] = (acc[(std::size_t) (P + i)] * (1.0 - t) + acc2[(std::size_t) (P + i)] * t) * scale;
+            }
+            active = pending;
+            pending = -1;
+        }
+        else
+            for (int i = 0; i < P; ++i) out[(std::size_t) i] = acc[(std::size_t) (P + i)] * scale;
+        head = (head + 1) % K;
+        pos = 0;
+    }
+
+    const Fft* fft = nullptr;
+    int P = 128, K = 1, pos = 0, head = 0, active = 0, pending = -1;
+    std::vector<cd> fdl, kern[2], timeBuf, acc, acc2, in, out;
+};
+
+// a biquad on doubles (detector / solo filters)
+struct Biquad
+{
+    double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0;
+    double z1[2] {}, z2[2] {};
+    double run (double x, int ch) noexcept
+    {
+        const double y = b0 * x + z1[ch];
+        z1[ch] = b1 * x - a1 * y + z2[ch];
+        z2[ch] = b2 * x - a2 * y;
+        return y;
+    }
+    void clear() noexcept { z1[0] = z1[1] = z2[0] = z2[1] = 0.0; }
+};
+
+// the band's region: band pass at its frequency and Q (low pass / high pass for the shelves and cuts)
+void regionFilter (Biquad& f, const EffectParams& p, int b, double sr) noexcept
+{
+    const auto sh = shape (p[(std::size_t) param (b, 0)]);
+    const double f0 = std::min (hz (p[(std::size_t) param (b, 1)]), 0.45 * sr);
+    const double w0 = 2.0 * pi * f0 / sr, cw = std::cos (w0), sw = std::sin (w0);
+    const bool low = sh == Shape::lowShelf || sh == Shape::highCut;
+    const bool high = sh == Shape::highShelf || sh == Shape::lowCut;
+    const double Q = low || high ? std::sqrt (0.5) : std::clamp (q (p[(std::size_t) param (b, 3)]), 0.1, 40.0);
+    const double alpha = sw / (2.0 * Q), a0 = 1.0 + alpha;
+    if (low) { f.b0 = (1.0 - cw) * 0.5 / a0; f.b1 = (1.0 - cw) / a0; f.b2 = f.b0; }
+    else if (high) { f.b0 = (1.0 + cw) * 0.5 / a0; f.b1 = -(1.0 + cw) / a0; f.b2 = f.b0; }
+    else { f.b0 = alpha / a0; f.b1 = 0.0; f.b2 = -alpha / a0; }
+    f.a1 = -2.0 * cw / a0;
+    f.a2 = (1.0 - alpha) / a0;
+}
+
 class FacetEqEffect final : public Effect
 {
 public:
-    void prepare (double sr) noexcept override { sampleRate = sr; cached.fill (-1.0f); reset(); }
+    explicit FacetEqEffect (const EffectParams* initial)
+    {
+        if (initial != nullptr) mode = phase ((*initial)[(std::size_t) phaseParam]);
+    }
+
+    void prepare (double sr) noexcept override
+    {
+        sampleRate = sr;
+        const int fct = rateFactor (sr);
+        taps = firTaps * fct;
+        fftNatural.init (2 * naturalBlock * fct);
+        fftLinear.init (2 * linearBlock * fct);
+        fftDesign.init (taps);
+        conv.allocate (taps, linearBlock * fct);
+        spec.assign ((std::size_t) taps, {});
+        fir.assign ((std::size_t) taps, 0.0);
+        delayLen = latencyFor (Phase::linear, sr) + 1;
+        delay[0].assign ((std::size_t) delayLen, 0.0f);
+        delay[1].assign ((std::size_t) delayLen, 0.0f);
+        cached.fill (-1.0f);
+        configureMode (mode);
+        reset();
+    }
+
     void reset() noexcept override
     {
         for (auto& band : state)
             for (auto& st : band)
                 st = {};
+        for (auto& d : det) { d.filter.clear(); d.ms = 0.0; d.gain = 0.0; }
+        solo.clear();
+        conv.reset();
+        firLoaded = false;
+        for (auto& d : delay) std::fill (d.begin(), d.end(), 0.0f);
+        delayPos = 0;
+        dynUsed.fill (0.0);
+        for (auto& m : meters) m.store (0.0f, std::memory_order_relaxed);
+    }
+
+    void setSidechain (const float* left, const float* right) noexcept override
+    {
+        sideL = left;
+        sideR = right;
+        sideGiven = true;
     }
 
+    float controlOutput (int o) const noexcept override
+    {
+        return o >= 0 && o < bands ? meters[(std::size_t) o].load (std::memory_order_relaxed) / 60.0f : 0.0f;
+    }
+
+    int latencySamples() const noexcept override { return latencyNow.load (std::memory_order_relaxed); }
+
     void process (float* left, float* right, int n, const EffectParams& params, double) noexcept override
     {
         bool changed = false;
         for (int i = 0; i < paramCount; ++i)
             if (params[(std::size_t) i] != cached[(std::size_t) i]) { changed = true; break; }
         if (changed)
+            update (params);
+
+        // the detector: the slot's sidechain when asked for and routed (nullptr = a silent source), else the input
+        const bool useSide = sideGiven && sidechainDetector (params[(std::size_t) detectorParam]);
+        const float* dl = useSide ? sideL : left;
+        const float* dr = useSide ? (sideR != nullptr ? sideR : sideL) : right;
+        sideGiven = false;
+        sideL = sideR = nullptr;
+
+        constexpr int chunk = 32;
+        for (int off = 0; off < n; off += chunk)
         {
-            for (int i = 0; i < paramCount; ++i) cached[(std::size_t) i] = params[(std::size_t) i];
-            for (int b = 0; b < bands; ++b)
+            const int m = std::min (chunk, n - off);
+            if (anyDynamic)
+                detect (dl != nullptr ? dl + off : nullptr, dr != nullptr ? dr + off : nullptr, left + off, right + off, m, useSide);
+
+            if (soloOn)
+            {
+                runSolo (left + off, right + off, m);
+                continue;
+            }
+            if (mode == Phase::zeroLatency)
+            {
+                if (anyDynamic) redesignDynamic();
+                runIir (left + off, right + off, m);
+            }
+            else
             {
-                const int before = counts[(std::size_t) b];
-                counts[(std::size_t) b] = design (params, b, sampleRate, sections[(std::size_t) b]);
-                if (counts[(std::size_t) b] != before) // the structure changed: start this band clean
-                    for (auto& st : state[(std::size_t) b]) st = {};
+                sinceDesign += m;
+                if (! firLoaded || (sinceDesign >= updateEvery && ! conv.fading() && (firDirty || (anyDynamic && dynamicMoved()))))
+                    loadFir();
+                for (int i = 0; i < m; ++i) conv.step (left[off + i], right[off + i]);
             }
-            outGain = (float) std::pow (10.0, outputDb (params[(std::size_t) outputParam]) / 20.0);
         }
 
+        if (outGain != 1.0f)
+            for (int i = 0; i < n; ++i) { left[i] *= outGain; right[i] *= outGain; }
+        for (int b = 0; b < bands; ++b) meters[(std::size_t) b].store ((float) det[(std::size_t) b].gain, std::memory_order_relaxed);
+    }
+
+private:
+    struct State { double z1[2] {}, z2[2] {}; };
+    struct Detector
+    {
+        Biquad filter;
+        double ms = 0.0, gain = 0.0, msCoef = 0.0, threshold = -20.0, range = 0.0;
+        bool on = false;
+    };
+
+    void configureMode (Phase p) noexcept
+    {
+        mode = p;
+        const int fct = rateFactor (sampleRate);
+        if (p == Phase::natural) conv.configure (fftNatural, naturalBlock * fct, taps);
+        else if (p == Phase::linear) conv.configure (fftLinear, linearBlock * fct, taps);
+        updateEvery = std::max (1024 * fct, p == Phase::linear ? linearBlock * fct : naturalBlock * fct);
+        firLoaded = false;
+        latencyNow.store (latencyFor (p, sampleRate), std::memory_order_relaxed);
+    }
+
+    void update (const EffectParams& params) noexcept
+    {
+        for (int i = 0; i < paramCount; ++i) cached[(std::size_t) i] = params[(std::size_t) i];
+        current = params;
+        const auto newMode = phase (params[(std::size_t) phaseParam]);
+        if (newMode != mode)
+        {
+            configureMode (newMode);
+            conv.reset();
+            for (auto& d : delay) std::fill (d.begin(), d.end(), 0.0f);
+        }
+        anyDynamic = false;
+        for (int b = 0; b < bands; ++b)
+        {
+            auto& d = det[(std::size_t) b];
+            const bool was = d.on;
+            d.on = isDynamic (params, b);
+            d.threshold = thresholdDb (params[(std::size_t) (thresholdParam0 + b)]);
+            d.range = rangeDb (params[(std::size_t) (rangeParam0 + b)]);
+            if (d.on)
+            {
+                regionFilter (d.filter, params, b, sampleRate);
+                const double f0 = hz (params[(std::size_t) param (b, 1)]);
+                d.msCoef = 1.0 - std::exp (-1.0 / (std::max (0.001, 1.5 / f0) * sampleRate));
+                anyDynamic = true;
+                if (! was) { d.filter.clear(); d.ms = 0.0; }
+            }
+            else
+                d.gain = 0.0;
+
+            const int before = counts[(std::size_t) b];
+            counts[(std::size_t) b] = facet::design (params, b, sampleRate, sections[(std::size_t) b], d.gain);
+            if (d.on && counts[(std::size_t) b] == 0) // a dynamic band at 0 dB keeps its (flat) section to move it later
+                counts[(std::size_t) b] = designKeep (b, d.gain);
+            if (counts[(std::size_t) b] != before) // the structure changed: start this band clean
+                for (auto& st : state[(std::size_t) b]) st = {};
+            dynUsed[(std::size_t) b] = d.gain;
+        }
+        attackCoef = 1.0 - std::exp (-1.0 / (attackMs (params[(std::size_t) attackParam]) * 0.001 * sampleRate));
+        releaseCoef = 1.0 - std::exp (-1.0 / (releaseMs (params[(std::size_t) releaseParam]) * 0.001 * sampleRate));
+        outGain = (float) std::pow (10.0, outputDb (params[(std::size_t) outputParam]) / 20.0);
+
+        const int sb = soloBand (params[(std::size_t) soloParam]);
+        const bool wasSolo = soloOn;
+        soloOn = sb >= 0 && shape (params[(std::size_t) param (sb, 0)]) != Shape::off;
+        if (soloOn) regionFilter (solo, params, sb, sampleRate);
+        if (soloOn && ! wasSolo) solo.clear();
+        firDirty = true;
+    }
+
+    int designKeep (int b, double extra) noexcept
+    {
+        Analog a[maxSections];
+        const int n = analogSections (current, b, a, extra, true);
+        const double f0 = std::min (hz (current[(std::size_t) param (b, 1)]), 0.4999 * sampleRate);
+        const double w0 = 2.0 * pi * f0 / sampleRate;
+        for (int k = 0; k < n; ++k) sections[(std::size_t) b][(std::size_t) k] = matched (a[k], w0);
+        return n;
+    }
+
+    // detector levels and the dynamic gains, sample by sample over one chunk
+    void detect (const float* dl, const float* dr, const float* inL, const float* inR, int m, bool side) noexcept
+    {
+        for (int b = 0; b < bands; ++b)
+        {
+            auto& d = det[(std::size_t) b];
+            if (! d.on) continue;
+            for (int i = 0; i < m; ++i)
+            {
+                double x = 0.0;
+                if (side) x = dl != nullptr ? 0.5 * ((double) dl[i] + (double) dr[i]) : 0.0;
+                else x = 0.5 * ((double) inL[i] + (double) inR[i]);
+                if (! std::isfinite (x)) x = 0.0;
+                const double y = d.filter.run (x, 0);
+                d.ms += d.msCoef * (y * y - d.ms);
+                const double level = 10.0 * std::log10 (2.0 * d.ms + 1e-20);
+                const double target = dynamicGainDb (level, d.threshold, d.range);
+                d.gain += (std::abs (target) > std::abs (d.gain) ? attackCoef : releaseCoef) * (target - d.gain);
+            }
+            if (std::abs (d.ms) < 1e-30) d.ms = 0.0;
+        }
+    }
+
+    void redesignDynamic() noexcept
+    {
+        for (int b = 0; b < bands; ++b)
+        {
+            const auto& d = det[(std::size_t) b];
+            if (! d.on || std::abs (d.gain - dynUsed[(std::size_t) b]) < 0.01) continue;
+            const int before = counts[(std::size_t) b];
+            const int c = designKeep (b, d.gain);
+            if (c != before)
+            {
+                for (auto& st : state[(std::size_t) b]) st = {};
+                counts[(std::size_t) b] = c;
+            }
+            dynUsed[(std::size_t) b] = d.gain;
+        }
+    }
+
+    bool dynamicMoved() const noexcept
+    {
+        for (int b = 0; b < bands; ++b)
+            if (det[(std::size_t) b].on && std::abs (det[(std::size_t) b].gain - dynUsed[(std::size_t) b]) > 0.05) return true;
+        return false;
+    }
+
+    void runIir (float* left, float* right, int n) noexcept
+    {
         for (int b = 0; b < bands; ++b)
             for (int k = 0; k < counts[(std::size_t) b]; ++k)
             {
@@ -257,22 +669,109 @@ public:
                     st.z2[ch] = std::abs (z2) < 1e-30 ? 0.0 : z2;
                 }
             }
+    }
 
-        if (outGain != 1.0f)
-            for (int i = 0; i < n; ++i) { left[i] *= outGain; right[i] *= outGain; }
+    // solo: the band's region alone (delayed like the FIR modes so switching does not jump)
+    void runSolo (float* left, float* right, int n) noexcept
+    {
+        const int lat = mode == Phase::zeroLatency ? 0 : latencyFor (mode, sampleRate);
+        for (int i = 0; i < n; ++i)
+        {
+            const float yl = (float) solo.run (left[i], 0), yr = (float) solo.run (right[i], 1);
+            if (lat == 0) { left[i] = yl; right[i] = yr; continue; }
+            delay[0][(std::size_t) delayPos] = yl;
+            delay[1][(std::size_t) delayPos] = yr;
+            const int rd = (delayPos - lat + delayLen) % delayLen;
+            left[i] = delay[0][(std::size_t) rd];
+            right[i] = delay[1][(std::size_t) rd];
+            delayPos = (delayPos + 1) % delayLen;
+        }
+    }
+
+    // the FIR of the current response (analog magnitude; analog phase in natural mode), windowed around its delay
+    void loadFir() noexcept
+    {
+        const int M = taps;
+        const bool natural = mode == Phase::natural;
+        const int fct = rateFactor (sampleRate);
+        const int D = natural ? naturalDelay * fct : M / 2;
+        // every band's analog sections once, then the product of their responses on the FFT grid
+        Analog a[bands * maxSections];
+        double f0[bands * maxSections];
+        int used = 0;
+        for (int b = 0; b < bands; ++b)
+        {
+            if (shape (current[(std::size_t) param (b, 0)]) == Shape::off) continue;
+            const int c = analogSections (current, b, a + used, det[(std::size_t) b].on ? det[(std::size_t) b].gain : 0.0);
+            for (int k = 0; k < c; ++k) f0[used + k] = hz (current[(std::size_t) param (b, 1)]);
+            used += c;
+        }
+        const cd rot = std::polar (1.0, -2.0 * pi * D / M);
+        cd phasor (1.0, 0.0);
+        for (int k = 0; k <= M / 2; ++k)
+        {
+            const double f = std::max ((double) k * sampleRate / M, 0.01);
+            double hr = 1.0, hi = 0.0;
+            for (int j = 0; j < used; ++j)
+            {
+                const auto& s = a[j];
+                const double w = f / f0[j], w2 = w * w;
+                const double nr = s.n0 - s.n2 * w2, ni = s.n1 * w, dr = s.d0 - s.d2 * w2, di = s.d1 * w;
+                const double dd = dr * dr + di * di;
+                const double qr = (nr * dr + ni * di) / dd, qi = (ni * dr - nr * di) / dd;
+                const double tr = hr * qr - hi * qi;
+                hi = hr * qi + hi * qr;
+                hr = tr;
+            }
+            cd h = natural ? cd (hr, hi) : cd (std::sqrt (hr * hr + hi * hi), 0.0);
+            h = cd (h.real() * phasor.real() - h.imag() * phasor.imag(), h.real() * phasor.imag() + h.imag() * phasor.real());
+            if ((k & 255) == 255) phasor = std::polar (1.0, -2.0 * pi * (double) (k + 1) * D / M); // no drift
+            else phasor *= rot;
+            if (k == M / 2 || k == 0) h = cd (h.real(), 0.0);
+            spec[(std::size_t) k] = h;
+            if (k > 0 && k < M / 2) spec[(std::size_t) (M - k)] = std::conj (h);
+        }
+        fftDesign.run (spec.data(), true);
+        for (int i = 0; i < M; ++i)
+        {
+            const double w = i < D ? 0.5 * (1.0 - std::cos (pi * (i + 0.5) / D)) : 0.5 * (1.0 + std::cos (pi * (i - D) / (double) (M - D)));
+            fir[(std::size_t) i] = spec[(std::size_t) i].real() / M * w;
+        }
+        conv.load (fir.data(), ! firLoaded);
+        firLoaded = true;
+        firDirty = false;
+        sinceDesign = 0;
+        for (int b = 0; b < bands; ++b) dynUsed[(std::size_t) b] = det[(std::size_t) b].gain;
     }
 
-private:
-    struct State { double z1[2] {}, z2[2] {}; };
     double sampleRate = 48000.0;
+    Phase mode = Phase::zeroLatency;
+    EffectParams current {};
     std::array<float, paramCount> cached {};
     std::array<std::array<Section, maxSections>, bands> sections {};
     std::array<std::array<State, maxSections>, bands> state {};
     std::array<int, bands> counts {};
+    std::array<Detector, bands> det {};
+    std::array<double, bands> dynUsed {};
+    std::array<std::atomic<float>, bands> meters {};
+    double attackCoef = 0.1, releaseCoef = 0.001;
     float outGain = 1.0f;
+    bool anyDynamic = false, soloOn = false, firLoaded = false, firDirty = true, sideGiven = false;
+    Biquad solo;
+    const float* sideL = nullptr;
+    const float* sideR = nullptr;
+    Fft fftNatural, fftLinear, fftDesign;
+    Convolver conv;
+    int taps = firTaps, updateEvery = 1024, sinceDesign = 0;
+    std::vector<cd> spec;
+    std::vector<double> fir;
+    std::vector<float> delay[2];
+    int delayLen = 1, delayPos = 0;
+    std::atomic<int> latencyNow { 0 };
 };
 } // namespace
 
+
 Shape shape (float v) noexcept { return (Shape) std::clamp ((int) std::lround (v * (shapeCount - 1)), 0, shapeCount - 1); }
 float shapeValue (Shape s) noexcept { return (float) (int) s / (float) (shapeCount - 1); }
 double hz (float v) noexcept { return 10.0 * std::pow (3000.0, (double) std::clamp (v, 0.0f, 1.0f)); }
@@ -314,6 +813,19 @@ const EffectInfo& info()
             }
         e.params.push_back ({ "Output", 0.5f });
         e.params.push_back ({ "Gain Scale", 0.5f });
+        static std::array<std::array<char, 24>, bands * 2> dynNames {};
+        for (int k = 0; k < bands * 2; ++k)
+        {
+            auto& n = dynNames[(std::size_t) k];
+            std::snprintf (n.data(), n.size(), k < bands ? "%d Range" : "%d Threshold", k % bands + 1);
+            e.params.push_back ({ n.data(), k < bands ? 0.5f : thresholdValue (-20.0) });
+        }
+        e.params.push_back ({ "Attack", 0.5f });
+        e.params.push_back ({ "Release", 0.5f });
+        e.params.push_back ({ "Phase", 0.0f });
+        e.params.push_back ({ "Solo", 0.0f });
+        e.params.push_back ({ "Detector", 0.0f });
+        e.params.push_back ({ "Analyzer", 1.0f });
         return e;
     }();
     return i;
@@ -324,6 +836,14 @@ std::string paramText (int p, float v)
     char t[48];
     if (p == outputParam) { std::snprintf (t, sizeof (t), "%+.2f dB", outputDb (v)); return t; }
     if (p == scaleParam) { std::snprintf (t, sizeof (t), "%.0f%%", gainScale (v) * 100.0); return t; }
+    if (p >= rangeParam0 && p < rangeParam0 + bands) { std::snprintf (t, sizeof (t), "%+.2f dB", rangeDb (v)); return t; }
+    if (p >= thresholdParam0 && p < thresholdParam0 + bands) { std::snprintf (t, sizeof (t), "%.1f dB", thresholdDb (v)); return t; }
+    if (p == attackParam) { std::snprintf (t, sizeof (t), attackMs (v) < 10.0 ? "%.2f ms" : "%.1f ms", attackMs (v)); return t; }
+    if (p == releaseParam) { const auto ms = releaseMs (v); std::snprintf (t, sizeof (t), ms < 1000.0 ? "%.0f ms" : "%.2f s", ms < 1000.0 ? ms : ms / 1000.0); return t; }
+    if (p == phaseParam) return phaseName (phase (v));
+    if (p == soloParam) { const auto b = soloBand (v); if (b < 0) return "Off"; std::snprintf (t, sizeof (t), "Band %d", b + 1); return t; }
+    if (p == detectorParam) return sidechainDetector (v) ? "Sidechain" : "Input";
+    if (p == analyzerParam) { static const char* a[] = { "Off", "Pre", "Post", "Pre + Post" }; return a[(int) analyzer (v)]; }
     switch (p % fieldsPerBand)
     {
         case 0: return shapeName (shape (v));
@@ -334,10 +854,10 @@ std::string paramText (int p, float v)
     }
 }
 
-int design (const EffectParams& params, int band, double sampleRate, std::array<Section, maxSections>& out) noexcept
+int design (const EffectParams& params, int band, double sampleRate, std::array<Section, maxSections>& out, double extraDb) noexcept
 {
     Analog a[maxSections];
-    const int n = analogSections (params, band, a);
+    const int n = analogSections (params, band, a, extraDb);
     const double f0 = std::min (hz (params[(std::size_t) param (band, 1)]), 0.4999 * sampleRate);
     const double w0 = 2.0 * pi * f0 / sampleRate;
     for (int k = 0; k < n; ++k)
@@ -345,28 +865,79 @@ int design (const EffectParams& params, int band, double sampleRate, std::array<
     return n;
 }
 
-double analogDb (const EffectParams& params, int band, double f) noexcept
+double analogDb (const EffectParams& params, int band, double f, double extraDb) noexcept
 {
     Analog a[maxSections];
-    const int n = analogSections (params, band, a);
+    const int n = analogSections (params, band, a, extraDb);
     const double w = f / hz (params[(std::size_t) param (band, 1)]);
     double m = 1.0;
     for (int k = 0; k < n; ++k) m *= std::sqrt (mag2 (a[k], w));
     return 20.0 * std::log10 (std::max (m, 1e-15));
 }
 
-double responseDb (const EffectParams& params, double sampleRate, double f) noexcept
+double bandResponseDb (const EffectParams& params, int band, double sampleRate, double f, double extraDb) noexcept
 {
-    const double w = 2.0 * pi * f / sampleRate;
+    if (phase (params[(std::size_t) phaseParam]) != Phase::zeroLatency)
+        return analogDb (params, band, f, extraDb);
+    std::array<Section, maxSections> s;
+    const int n = design (params, band, sampleRate, s, extraDb);
+    const double w = 2.0 * pi * std::min (f, 0.5 * sampleRate) / sampleRate;
     double m = 1.0;
+    for (int k = 0; k < n; ++k) m *= std::abs (evalDigital (s[(std::size_t) k], w));
+    return 20.0 * std::log10 (std::max (m, 1e-15));
+}
+
+double responseDb (const EffectParams& params, double sampleRate, double f, const float* dynamicDb) noexcept
+{
+    double db = outputDb (params[(std::size_t) outputParam]);
     for (int b = 0; b < bands; ++b)
+        db += bandResponseDb (params, b, sampleRate, f, dynamicDb != nullptr && isDynamic (params, b) ? (double) dynamicDb[b] : 0.0);
+    return db;
+}
+
+bool hasGain (Shape s) noexcept { return s == Shape::bell || s == Shape::lowShelf || s == Shape::highShelf || s == Shape::tiltShelf; }
+double rangeDb (float v) noexcept { return ((double) std::clamp (v, 0.0f, 1.0f) - 0.5) * 60.0; }
+float rangeValue (double db) noexcept { return (float) std::clamp (db / 60.0 + 0.5, 0.0, 1.0); }
+double thresholdDb (float v) noexcept { return -80.0 + 80.0 * (double) std::clamp (v, 0.0f, 1.0f); }
+float thresholdValue (double db) noexcept { return (float) std::clamp ((db + 80.0) / 80.0, 0.0, 1.0); }
+double attackMs (float v) noexcept { return 0.25 * std::pow (200.0, (double) std::clamp (v, 0.0f, 1.0f)); }
+double releaseMs (float v) noexcept { return 20.0 * std::pow (200.0, (double) std::clamp (v, 0.0f, 1.0f)); }
+Phase phase (float v) noexcept { return (Phase) std::clamp ((int) std::lround (v * (phaseCount - 1)), 0, phaseCount - 1); }
+float phaseValue (Phase p) noexcept { return (float) (int) p / (float) (phaseCount - 1); }
+int soloBand (float v) noexcept { return std::clamp ((int) std::lround (v * bands), 0, bands) - 1; }
+float soloValue (int band) noexcept { return band < 0 ? 0.0f : (float) (band + 1) / (float) bands; }
+bool sidechainDetector (float v) noexcept { return v >= 0.5f; }
+Analyzer analyzer (float v) noexcept { return (Analyzer) std::clamp ((int) std::lround (v * 3.0f), 0, 3); }
+float analyzerValue (Analyzer a) noexcept { return (float) (int) a / 3.0f; }
+const char* phaseName (Phase p) noexcept
+{
+    static const char* names[] = { "Zero Latency", "Natural Phase", "Linear Phase" };
+    return names[(int) p];
+}
+
+bool isDynamic (const EffectParams& p, int b) noexcept
+{
+    return hasGain (shape (p[(std::size_t) param (b, 0)])) && std::abs (rangeDb (p[(std::size_t) (rangeParam0 + b)])) > 0.01;
+}
+
+double dynamicGainDb (double level, double threshold, double range) noexcept
+{
+    const double x = level - threshold;
+    constexpr double knee = 10.0; // fitted to the reference (REA_rodada103 §2.1)
+    const double over = x <= -0.5 * knee ? 0.0 : x < 0.5 * knee ? (x + 0.5 * knee) * (x + 0.5 * knee) / (2.0 * knee) : x;
+    return range < 0.0 ? -std::min (-range, over) : std::min (range, over);
+}
+
+int latencyFor (Phase p, double sampleRate) noexcept
+{
+    const int f = rateFactor (sampleRate);
+    switch (p)
     {
-        std::array<Section, maxSections> s;
-        const int n = design (params, b, sampleRate, s);
-        for (int k = 0; k < n; ++k) m *= std::abs (evalDigital (s[(std::size_t) k], w));
+        case Phase::natural: return (naturalBlock + naturalDelay) * f;
+        case Phase::linear: return linearBlock * f + firTaps * f / 2;
+        default: return 0;
     }
-    return 20.0 * std::log10 (std::max (m, 1e-15)) + outputDb (params[(std::size_t) outputParam]);
 }
 
-std::unique_ptr<Effect> make() { return std::make_unique<FacetEqEffect>(); }
+std::unique_ptr<Effect> make (const EffectParams* initial) { return std::make_unique<FacetEqEffect> (initial); }
 } // namespace lynx::facet

+ 59 - 7
src/core/FacetEq.h

@@ -9,7 +9,18 @@
 // slope law follow our black-box measurements of the reference EQ (docs/analise/MEASURE_fabfilter.md §1).
 //
 // Parameters (0..1, EffectKind::facetEq): band b uses [5b .. 5b+4] = shape, frequency, gain, Q, slope;
-// [40] output gain, [41] gain scale.
+// [40] output gain, [41] gain scale; (round 103, appended so older projects load unchanged — every default is the old
+// behaviour) [42 + b] dynamic range of band b (0.5 = 0 dB = a static band), [50 + b] its threshold, [58] attack,
+// [59] release, [60] phase mode (zero latency / natural / linear), [61] solo band (0 = none), [62] dynamics detector
+// (the EQ's input / the slot's sidechain), [63] analyser display (editor only: off, pre, post, pre + post).
+//
+// Dynamic EQ (docs/analise/REA_rodada103.md §2, measured on the reference): each band with a gain (bell, shelves,
+// tilt) whose range is not 0 listens to its own region of the detector signal (band pass at the band frequency and
+// Q; low pass / high pass for the shelves) and moves its gain by up to `range` dB as that level rises over the
+// threshold — 1 dB per dB above it (an infinite ratio) with a 10 dB soft knee, clamped at the range, smoothed by the
+// attack / release times. Phase modes: zero latency (the IIR sections), natural phase (the analog prototype's
+// magnitude and phase as an FIR, 320 samples at 48 kHz) and linear phase (the analog magnitude, zero phase, 4608
+// samples at 48 kHz), both run as a uniformly partitioned FFT convolution and reported to PDC.
 
 #include <array>
 #include <memory>
@@ -23,7 +34,15 @@ constexpr int bands = 8;
 constexpr int fieldsPerBand = 5;
 constexpr int outputParam = 40;
 constexpr int scaleParam = 41;
-constexpr int paramCount = 42;
+constexpr int rangeParam0 = 42;     // + band
+constexpr int thresholdParam0 = 50; // + band
+constexpr int attackParam = 58;
+constexpr int releaseParam = 59;
+constexpr int phaseParam = 60;
+constexpr int soloParam = 61;
+constexpr int detectorParam = 62;
+constexpr int analyzerParam = 63;
+constexpr int paramCount = 64;
 constexpr int maxSections = 8; // 96 dB/oct = 16th order
 
 enum class Shape { off, bell, lowShelf, highShelf, lowCut, highCut, notch, bandPass, tiltShelf };
@@ -45,6 +64,33 @@ float slopeValue (int dbPerOct) noexcept;
 double outputDb (float v) noexcept;    // ±24 dB
 double gainScale (float v) noexcept;   // 0 .. 200 %
 const char* shapeName (Shape s) noexcept;
+bool hasGain (Shape s) noexcept;       // bell, shelves, tilt: the shapes a gain (and dynamics) applies to
+
+enum class Phase { zeroLatency, natural, linear };
+constexpr int phaseCount = 3;
+enum class Analyzer { off, pre, post, both };
+
+double rangeDb (float v) noexcept;     // dynamic range ±30 dB (0.5 = 0 = static)
+float rangeValue (double db) noexcept;
+double thresholdDb (float v) noexcept; // −80 … 0 dB (sine peak)
+float thresholdValue (double db) noexcept;
+double attackMs (float v) noexcept;    // 0.25 … 50 ms
+double releaseMs (float v) noexcept;   // 20 … 4000 ms
+Phase phase (float v) noexcept;
+float phaseValue (Phase p) noexcept;
+int soloBand (float v) noexcept;       // −1 = none
+float soloValue (int band) noexcept;
+bool sidechainDetector (float v) noexcept;
+Analyzer analyzer (float v) noexcept;
+float analyzerValue (Analyzer a) noexcept;
+bool isDynamic (const EffectParams& params, int band) noexcept;
+const char* phaseName (Phase p) noexcept;
+
+// The dynamic gain (dB) a band applies for a detector level (dB, sine peak): 0 below the knee, then 1 dB per dB over the
+// threshold (10 dB soft knee), clamped at the range; the sign follows the range.
+double dynamicGainDb (double levelDb, double thresholdDb, double rangeDb) noexcept;
+// Latency (samples) of a phase mode at a sample rate
+int latencyFor (Phase p, double sampleRate) noexcept;
 
 const EffectInfo& info();
 std::string paramText (int param, float v);
@@ -53,11 +99,17 @@ std::string paramText (int param, float v);
 struct Section { double b0 = 1, b1 = 0, b2 = 0, a1 = 0, a2 = 0; };
 
 // The sections of one band at a sample rate; returns how many were written (0 = the band is off / flat).
-int design (const EffectParams& params, int band, double sampleRate, std::array<Section, maxSections>& out) noexcept;
+// `extraDb` is added to the band's gain (before the gain scale): the dynamic EQ's movement.
+int design (const EffectParams& params, int band, double sampleRate, std::array<Section, maxSections>& out, double extraDb = 0.0) noexcept;
 // The analog prototype's response of one band (dB) — the target the digital design matches.
-double analogDb (const EffectParams& params, int band, double hz) noexcept;
-// Response of the whole EQ (digital, dB) at hz.
-double responseDb (const EffectParams& params, double sampleRate, double hz) noexcept;
+double analogDb (const EffectParams& params, int band, double hz, double extraDb = 0.0) noexcept;
+// Response of the whole EQ (dB) at hz: the digital sections in zero-latency mode, the analog prototype in the FIR
+// modes. `dynamicDb` (optional, 8 values) are the bands' live dynamic gains.
+double responseDb (const EffectParams& params, double sampleRate, double hz, const float* dynamicDb = nullptr) noexcept;
+// One band's own response (dB) at hz, same rules
+double bandResponseDb (const EffectParams& params, int band, double sampleRate, double hz, double extraDb = 0.0) noexcept;
 
-std::unique_ptr<Effect> make();
+// The effect; with the slot's parameters its latency is known from the start (PDC plans it before the first block).
+std::unique_ptr<Effect> make (const EffectParams* initial = nullptr);
+// controlOutput (b), b = 0 … 7: band b's live dynamic gain in dB / 60 (signed: 0 = no movement, also when cleared)
 } // namespace lynx::facet

+ 31 - 4
src/core/RackRenderer.cpp

@@ -1045,6 +1045,12 @@ void RackRenderer::applyTrackEq (const MixerTrack& track, int t, float* l, float
     }
 }
 
+// effects whose controlOutput() an editor shows live
+static bool hasLiveMeters (EffectKind kind) noexcept
+{
+    return mixsuite::isSuiteKind (kind) || kind == EffectKind::lynxTune || kind == EffectKind::facetEq;
+}
+
 void RackRenderer::setSidechain (const RackState& state, const EffectSlot& slot, Effect& effect, int track) noexcept
 {
     // the source was already processed in this pass (earlier layer); silent = no signal in the detector
@@ -1102,7 +1108,7 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
 
         if (! slots[i].enabled || wet <= 0.0f)
         {
-            if (mixsuite::isSuiteKind (slots[i].kind))
+            if (hasLiveMeters (slots[i].kind))
                 clearMeters();
             continue;
         }
@@ -1130,7 +1136,7 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
                 sd.silentSamples = 0;
             else if (sd.silentSamples >= hold)
             {
-                if (mixsuite::isSuiteKind (slots[i].kind))
+                if (hasLiveMeters (slots[i].kind))
                     clearMeters();
                 continue;
             }
@@ -1138,6 +1144,16 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
                 sd.silentSamples += n;
         }
 
+        // the editor's spectrum analyser listens to this slot: its input
+        const auto tapped = times->analyzer.key.load (std::memory_order_relaxed) == (int) key;
+        if (tapped)
+        {
+            auto& tap = times->analyzer;
+            const auto w = tap.written.load (std::memory_order_relaxed);
+            for (int k = 0; k < n; ++k)
+                tap.pre[(std::size_t) ((w + (std::uint32_t) k) & (ProcessTimes::AnalyzerTap::size - 1))].store (0.5f * (l[k] + r[k]), std::memory_order_relaxed);
+        }
+
         // dry/wet: keep the dry signal to mix later
         const auto partial = wet < 0.999f;
 
@@ -1187,8 +1203,19 @@ void RackRenderer::runEffects (const RackState& state, int track, int n) noexcep
             }
         }
 
-        // live meters for the editor (the mixing suite's gain reduction)
-        if (mixsuite::isSuiteKind (slots[i].kind) && key < (std::size_t) maxMixerTracks * maxEffectSlots)
+        // ... and its output
+        if (tapped)
+        {
+            auto& tap = times->analyzer;
+            const auto w = tap.written.load (std::memory_order_relaxed);
+            for (int k = 0; k < n; ++k)
+                tap.post[(std::size_t) ((w + (std::uint32_t) k) & (ProcessTimes::AnalyzerTap::size - 1))].store (0.5f * (l[k] + r[k]), std::memory_order_relaxed);
+            tap.sampleRate.store (sampleRate, std::memory_order_relaxed);
+            tap.written.store (w + (std::uint32_t) n, std::memory_order_release);
+        }
+
+        // live meters for the editor (the mixing suite's gain reduction, LYNX Tune's pitch, Facet EQ's dynamic gains)
+        if (hasLiveMeters (slots[i].kind) && key < (std::size_t) maxMixerTracks * maxEffectSlots)
             for (int o = 0; o < ProcessTimes::meterOutputs; ++o)
                 times->effectMeters[key * ProcessTimes::meterOutputs + (std::size_t) o].store (effects[i]->controlOutput (o), std::memory_order_relaxed);
 

+ 16 - 2
src/core/RackRenderer.h

@@ -145,11 +145,25 @@ struct ProcessTimes
     std::array<std::atomic<std::uint64_t>, maxMixerTracks * maxEffectSlots> effectNs {}; // [track * maxEffectSlots + slot]
     std::atomic<std::uint64_t> audioNs { 0 };  // duration of the audio rendered while enabled
     std::atomic<std::uint64_t> wallNs { 0 };   // time the whole rack took for it
-    // Live meters of the effects that have them (the mixing suite's gain reduction, REA round 96), always published:
+    // Live meters of the effects that have them (the mixing suite's gain reduction, REA round 96; LYNX Tune's pitch and
+    // Facet EQ's dynamic gains, round 103), always published:
     // [(track * maxEffectSlots + slot) * meterOutputs + output] = Effect::controlOutput (output) after the last block.
-    static constexpr int meterOutputs = 2;
+    static constexpr int meterOutputs = 8;
     std::array<std::atomic<float>, (std::size_t) maxMixerTracks * maxEffectSlots * meterOutputs> effectMeters {};
 
+    // Audio of one effect slot for an editor's spectrum analyser (Facet EQ, round 103): the editor sets `key`
+    // (track * maxEffectSlots + slot, −1 = none); the audio thread then writes the slot's input (pre) and output
+    // (post), as mono mid samples, into the rings and advances `written`. Reads may tear; the analyser tolerates it.
+    struct AnalyzerTap
+    {
+        static constexpr int size = 16384; // power of two
+        std::atomic<int> key { -1 };
+        std::atomic<std::uint32_t> written { 0 };
+        std::atomic<double> sampleRate { 48000.0 };
+        std::array<std::atomic<float>, size> pre {}, post {};
+    };
+    AnalyzerTap analyzer;
+
     static std::uint64_t now() noexcept
     {
         return (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now().time_since_epoch()).count();