Răsfoiți Sursa

Merge perf7_190px (8bc7ea11c) into wip/rollup032

Ka1-S 1 săptămână în urmă
părinte
comite
c19bc989f5

+ 3 - 1
src/Main.cpp

@@ -16264,7 +16264,9 @@ private:
                     // round 190ok (P24): Settings › Audio › "Safe overloads" (core/OverloadGuard.h), since the start
                     const auto& guard = app.engine->getOverloadGuard();
                     text << "    safe overloads " << (guard.isEnabled() ? "on" : "off") << ": engaged " << (juce::int64) guard.timesEngaged()
-                         << " times" << (guard.engaged() ? " (now)" : "") << ", yielded " << juce::String (guard.yieldedMs(), 0) << " ms";
+                         << " times" << (guard.engaged() ? " (now)" : "") << ", yielded " << juce::String (guard.yieldedMs(), 0) << " ms"
+                         // round 190px: the render-ahead thread's catch-up paced while the UI starved
+                         << ", render-ahead paced " << (juce::int64) guard.timesPaced() << " times (" << juce::String (guard.pacedMs(), 0) << " ms)";
                     // round 190os: the last release in this step — why, and how long after the callbacks kept their
                     // deadline again
                     if (const auto at = guard.lastReleaseAtMs(); at >= wallStart && guard.lastReleaseReason() != lynx::OverloadGuard::notReleased)

+ 122 - 29
src/core/EchoSuite.cpp

@@ -1,5 +1,6 @@
 #include "core/EchoSuite.h"
 #include "core/FastMath.h"
+#include "core/LazyFloats.h"
 
 #include <atomic>
 #include <algorithm>
@@ -37,47 +38,139 @@ bool on (float v) noexcept { return v >= 0.5f; }
 
 // Circular delay line (power-of-two size). at (d) is x[n − d] for the sample about to be written (d ≥ 2), read with
 // 4-point cubic (Catmull-Rom / Hermite) interpolation.
-struct Line
+//
+// Round 190px (perf 7, RAM of Live sets): a long line (Echoform's 20.6 s, the tape / hybrid / spiral lines) keeps
+// its full size as its LOGICAL size (maxDelay(), the clamps and every decision made from them are unchanged), but its
+// ring runs over a power-of-two CAPACITY that starts at `lazyStart` samples (about 3 s at 44.1 kHz) and doubles, in
+// place, the first time a read reaches past it (LazyFloats: the pages past the capacity are reserved, never touched).
+// Bit-identical to the full ring whenever no sample a read needs was overwritten before the line grew: always with a
+// delay that stays put (a project's settings), that changes no faster than the audio runs (a turned or automated time
+// knob gliding, tempo changes), and in every line's first `capacity` samples (the start of a song). Only a jump of the
+// delay to more than the capacity, after the ring has wrapped, reads silence there where the full ring still held
+// audio from before the jump (as a line that was just made). Short lines (Line: diffusion, shifters) are a plain vector
+// with no check at all, as before; the long ones are LongLine.
+template <bool Grows>
+struct DelayLine
 {
-    std::vector<float> buf;
-    int mask = 0;
-    int w = 0;
+    static constexpr int lazyStart = 1 << 17;
 
     void allocate (double samples)
     {
         int size = 16;
         while ((double) size < samples + 8.0)
             size <<= 1;
-        buf.assign ((std::size_t) size, 0.0f);
-        mask = size - 1;
+        logicalMask = size - 1;
         w = 0;
+        // (LYNX_LONGLINES_FULL=1: every line its whole ring, as before round 190px — the null test of the gate)
+        static const bool full = std::getenv ("LYNX_LONGLINES_FULL") != nullptr;
+        if (Grows && ! full && size > lazyStart && lazy.reserve ((std::size_t) size) && lazy.commit ((std::size_t) lazyStart))
+        {
+            plain.clear();
+            plain.shrink_to_fit();
+            buf = lazy.data();
+            mask = lazyStart - 1;
+            growAt = (unsigned) (lazyStart - growMargin);
+            readHi = (double) (lazyStart - growMargin - 2);
+            std::fill (buf, buf + lazyStart, 0.0f); // (touched here, off the audio thread: no page faults while it plays)
+            return;
+        }
+        lazy = {};
+        plain.assign ((std::size_t) size, 0.0f);
+        buf = plain.data();
+        mask = size - 1;
+        growAt = ~0u;
+        readHi = maxDelay();
     }
+    bool empty() const noexcept { return buf == nullptr; }
     void clear() noexcept
     {
-        std::fill (buf.begin(), buf.end(), 0.0f);
+        if (buf != nullptr)
+            std::fill (buf, buf + mask + 1, 0.0f);
         w = 0;
     }
-    double maxDelay() const noexcept { return (double) mask - 4.0; }
+    double maxDelay() const noexcept { return (double) logicalMask - 4.0; }
     void push (float x) noexcept
     {
         buf[(std::size_t) w] = x;
         w = (w + 1) & mask;
     }
-    float tap (int d) const noexcept { return buf[(std::size_t) ((w - d) & mask)]; } // x[n − d], d ≥ 1
+    // x[n − d], d ≥ 1 (d ≤ 0 or past the logical size: as the full ring, which wraps)
+    float tap (int d) const noexcept
+    {
+        if constexpr (Grows)
+            if ((unsigned) (d - 1) >= growAt) [[unlikely]]
+                grow (d);
+        return buf[(std::size_t) ((w - d) & mask)];
+    }
     float at (double d) const noexcept
     {
-        if (buf.empty())
+        if (buf == nullptr)
             return 0.0f;
-        d = std::clamp (d, 2.0, maxDelay());
+        if constexpr (Grows)
+        {
+            // (the clamp's upper compare doubles as the check: `readHi` is maxDelay() once the ring is whole, else
+            // what the capacity can read now; std::clamp's arithmetic otherwise, NaN included)
+            d = std::max (d, 2.0);
+            if (d > readHi) [[unlikely]]
+            {
+                d = std::min (d, maxDelay());
+                grow ((int) d + 2);
+            }
+        }
+        else
+            d = std::clamp (d, 2.0, maxDelay());
         const auto i = (int) d;
         const auto t = (float) (d - (double) i);
-        const auto xm1 = tap (i - 1), x0 = tap (i), x1 = tap (i + 1), x2 = tap (i + 2);
+        const auto xm1 = raw (i - 1), x0 = raw (i), x1 = raw (i + 1), x2 = raw (i + 2);
         const auto c1 = 0.5f * (x1 - xm1);
         const auto c2 = xm1 - 2.5f * x0 + 2.0f * x1 - 0.5f * x2;
         const auto c3 = 0.5f * (x2 - xm1) + 1.5f * (x0 - x1);
         return ((c3 * t + c2) * t + c1) * t + x0;
     }
+    // the samples the ring holds in RAM now (tests, the memory figures)
+    std::size_t capacity() const noexcept { return buf == nullptr ? 0 : (std::size_t) mask + 1; }
+
+private:
+    static constexpr int growMargin = 8; // (grows a little before a read reaches the ring's oldest sample)
+    float raw (int d) const noexcept { return buf[(std::size_t) ((w - d) & mask)]; }
+    // The ring's capacity made the next power of two that holds `d` back (d ≤ 0: the whole logical size), in place: the
+    // older part of the ring, [w, capacity), moves to the end of the new one, so every delay up to the old capacity
+    // reads what it read before; the part in between was never touched (zeros). Audio thread (no allocation).
+    void grow (int d) const noexcept
+    {
+        const auto oldCap = mask + 1, full = logicalMask + 1;
+        auto cap = oldCap;
+        if (d <= 0 || d >= full - growMargin)
+            cap = full;
+        else
+            while (cap < full && cap - growMargin <= d)
+                cap <<= 1;
+        if (cap <= oldCap || ! lazy.commit ((std::size_t) cap))
+        {
+            growAt = ~0u; // (already whole, or the system refused the memory: the ring stays as it is)
+            readHi = maxDelay();
+            return;
+        }
+        const auto tail = oldCap - w;
+        std::memmove (buf + w + (cap - oldCap), buf + w, (std::size_t) tail * sizeof (float));
+        std::fill (buf + w, buf + oldCap, 0.0f);
+        mask = cap - 1;
+        growAt = cap >= full ? ~0u : (unsigned) (cap - growMargin);
+        readHi = cap >= full ? maxDelay() : (double) (cap - growMargin - 2);
+    }
+
+    // (mutable: a read may grow the ring; one instance is only ever used by one thread)
+    mutable float* buf = nullptr;
+    mutable int mask = 0;
+    mutable unsigned growAt = ~0u; // a read of d with d − 1 ≥ this grows the ring first
+    mutable double readHi = 0.0;   // at (d) with d above this grows the ring first (or clamps at maxDelay())
+    int logicalMask = 0;
+    int w = 0;
+    mutable LazyFloats lazy;
+    std::vector<float> plain; // (short lines, or when the system refuses the reservation)
 };
+using Line = DelayLine<false>;
+using LongLine = DelayLine<true>;
 
 // one-pole low-pass (impulse invariant); hp() = input − low-pass
 struct OnePole
@@ -1225,7 +1318,7 @@ public:
 
     void process (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept override
     {
-        if (ch[0].line.buf.empty())
+        if (ch[0].line.empty())
             prepare (sr);
         float inPeak = 0.0f;
         for (int i = 0; i < n; ++i)
@@ -1827,7 +1920,7 @@ private:
 
     struct Channel
     {
-        Line line;
+        LongLine line;
         PitchShifter pitch;
         Shifter shifter;
         std::array<Allpass, 4> diff;
@@ -2087,7 +2180,7 @@ private:
     static constexpr int hybridFirMax = 96; // round 190lf: LoFi's FIR, up to 192 kHz
     struct HybridState
     {
-        Line a, b;
+        LongLine a, b;
         double ga = 1.0, gb = 1.0, aPrev = 0.0, bPrev = 0.0;
         Biquad tilt;
         bool dirty = true;
@@ -2159,9 +2252,9 @@ private:
             hybridLaw1 (l, r, n, p, bpm);
             return;
         }
-        if (hyb.a.buf.empty() || hyb.dirty)
+        if (hyb.a.empty() || hyb.dirty)
         {
-            if (hyb.a.buf.empty())
+            if (hyb.a.empty())
             {
                 hyb.a.allocate (sr * 3.6 + 8.0);
                 hyb.b.allocate (sr * 3.6 + 8.0);
@@ -2230,9 +2323,9 @@ private:
     void hybridLaw1 (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept
     {
         const auto need = sr * 3.6 * 1.6 + 8.0; // the longest time and its swing
-        if (hyb.a.buf.empty() || hyb.dirty || hyb.a.maxDelay() < need - 16.0)
+        if (hyb.a.empty() || hyb.dirty || hyb.a.maxDelay() < need - 16.0)
         {
-            if (hyb.a.buf.empty() || hyb.a.maxDelay() < need - 16.0)
+            if (hyb.a.empty() || hyb.a.maxDelay() < need - 16.0)
             {
                 hyb.a.allocate (need);
                 hyb.b.allocate (need);
@@ -2384,12 +2477,12 @@ private:
     }
     struct TapeState
     {
-        Line in[2], z[2];
+        LongLine in[2], z[2];
         double passX[2][2][3] {}, passY[2][2][3] {}, loopX[2][3] {}, loopY[2][3] {};
         bool dirty = true;
         // round 148: the ping-pong's measured kernels (first pass and loop per side) and the lines their output is read from
         BlockConvolver first[2], loop[2];
-        Line firstOut[2], loopOut[2];
+        LongLine firstOut[2], loopOut[2];
         double kernelRate = 0.0;
     } tape;
 
@@ -2451,11 +2544,11 @@ private:
     void tapeProcess (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept
     {
         const auto& v = tapeData (tapeVoicingOf (p[tapeVoicing]));
-        if (tape.in[0].buf.empty() || tape.dirty)
+        if (tape.in[0].empty() || tape.dirty)
         {
             for (int c = 0; c < 2; ++c)
             {
-                if (tape.in[c].buf.empty())
+                if (tape.in[c].empty())
                 {
                     tape.in[c].allocate (sr * 4.6 + 1300.0);
                     tape.z[c].allocate (sr * 4.6 + 1300.0);
@@ -2634,7 +2727,7 @@ private:
     // pair tone
     struct SecondLoop
     {
-        Line line;
+        LongLine line;
         std::array<Allpass, 4> diff;
         OnePole lowCut, highCut;
     };
@@ -2802,7 +2895,7 @@ public:
 
     void process (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept override
     {
-        if (ch[0].line.buf.empty())
+        if (ch[0].line.empty())
             prepare (sr);
         const auto wet = clamp01 (p[mix]), dry = 1.0f - wet; // linear crossfade (REA_rodada101 §4)
         const auto beats = syncBeats (syncIndex (p[sync]));
@@ -2917,7 +3010,7 @@ private:
 
     struct Channel
     {
-        Line line;
+        LongLine line;
         Shifter shifter;
         OnePole lo, hi;
         Biquad band, ap; // round 190do: the measured loop's filters
@@ -3040,7 +3133,7 @@ public:
 
     void process (float* l, float* r, int n, const EffectParams& p, double) noexcept override
     {
-        if (ch[0].line.buf.empty())
+        if (ch[0].line.empty())
             prepare (sr);
         float dryGain = 1.0f, wetGain = 0.0f;
         equalPowerMix (p[mix], dryGain, wetGain);
@@ -3597,7 +3690,7 @@ public:
 
     void process (float* l, float* r, int n, const EffectParams& p, double bpm) noexcept override
     {
-        if (ch[0].line.buf.empty())
+        if (ch[0].line.empty())
             prepare (sr);
         float dryGain = 1.0f, wetGain = 0.0f;
         equalPowerMix (p[mix], dryGain, wetGain);
@@ -3749,7 +3842,7 @@ public:
 private:
     struct Channel
     {
-        Line line;
+        LongLine line;
         std::array<Allpass, 4> diff;
         std::array<RandomLfo, 16> detune;
         RandomLfo diffLfo;

+ 114 - 0
src/core/LazyFloats.h

@@ -0,0 +1,114 @@
+#pragma once
+
+// Round 190px (perf 7): a block of floats whose address range is reserved at once but whose memory is only made real
+// (committed on Windows, touched everywhere) as far as it is used. A delay line sized for its longest possible delay
+// (Echoform: 20.6 s per line) then holds in RAM only what its actual delay reaches: the pages past that stay
+// untouched, so they are neither in the working set nor (Windows) in the commit charge.
+//
+// The memory of a fresh block reads as zeros. commit() may be called from the audio thread (no allocation, no lock of
+// LYNX's; on Windows one VirtualAlloc(MEM_COMMIT) call on a range already reserved). Header-only, no windows.h: the two
+// Win32 functions are declared here with their exact Win64 signatures.
+
+#include <cstddef>
+#include <cstdint>
+
+#if defined(_WIN32)
+extern "C" __declspec (dllimport) void* __stdcall VirtualAlloc (void* address, unsigned long long size, unsigned long type, unsigned long protect);
+extern "C" __declspec (dllimport) int __stdcall VirtualFree (void* address, unsigned long long size, unsigned long type);
+#else
+ #include <sys/mman.h>
+#endif
+
+namespace lynx
+{
+class LazyFloats
+{
+public:
+    LazyFloats() = default;
+    ~LazyFloats() { release(); }
+    LazyFloats (const LazyFloats&) = delete;
+    LazyFloats& operator= (const LazyFloats&) = delete;
+    LazyFloats (LazyFloats&& o) noexcept { take (o); }
+    LazyFloats& operator= (LazyFloats&& o) noexcept
+    {
+        if (this != &o)
+        {
+            release();
+            take (o);
+        }
+        return *this;
+    }
+
+    // Reserves `count` floats (off the audio thread). False: the system refused (the caller falls back to a vector).
+    bool reserve (std::size_t count) noexcept
+    {
+        release();
+        if (count == 0)
+            return false;
+        const auto bytes = count * sizeof (float);
+#if defined(_WIN32)
+        void* at = VirtualAlloc (nullptr, (unsigned long long) bytes, 0x2000u /* MEM_RESERVE */, 0x01u /* PAGE_NOACCESS */);
+        if (at == nullptr)
+            return false;
+#else
+        void* at = mmap (nullptr, bytes, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS
+ #if defined(MAP_NORESERVE)
+                                                                     | MAP_NORESERVE
+ #endif
+                         , -1, 0);
+        if (at == MAP_FAILED)
+            return false;
+#endif
+        data_ = static_cast<float*> (at);
+        reserved = count;
+        committed = 0;
+        return true;
+    }
+
+    // Makes the first `count` floats usable (they read as zeros the first time). False: the system refused (Windows:
+    // the commit limit); what was usable stays usable.
+    bool commit (std::size_t count) noexcept
+    {
+        if (count > reserved)
+            count = reserved;
+        if (count <= committed)
+            return true;
+#if defined(_WIN32)
+        if (VirtualAlloc (data_, (unsigned long long) (count * sizeof (float)), 0x1000u /* MEM_COMMIT */, 0x04u /* PAGE_READWRITE */) == nullptr)
+            return false;
+#endif
+        committed = count;
+        return true;
+    }
+
+    float* data() const noexcept { return data_; }
+    std::size_t size() const noexcept { return reserved; }
+    std::size_t usable() const noexcept { return committed; }
+
+private:
+    void release() noexcept
+    {
+        if (data_ != nullptr)
+        {
+#if defined(_WIN32)
+            VirtualFree (data_, 0, 0x8000u /* MEM_RELEASE */);
+#else
+            munmap (data_, reserved * sizeof (float));
+#endif
+        }
+        data_ = nullptr;
+        reserved = committed = 0;
+    }
+    void take (LazyFloats& o) noexcept
+    {
+        data_ = o.data_;
+        reserved = o.reserved;
+        committed = o.committed;
+        o.data_ = nullptr;
+        o.reserved = o.committed = 0;
+    }
+
+    float* data_ = nullptr;
+    std::size_t reserved = 0, committed = 0;
+};
+} // namespace lynx

+ 31 - 5
src/core/MinPhaseBand.h

@@ -19,6 +19,7 @@
 
 #include <algorithm>
 #include <array>
+#include <limits>
 #include <cmath>
 #include <complex>
 #include <vector>
@@ -303,10 +304,17 @@ public:
             for (int k = 0; k < order; ++k)
                 out[(std::size_t) k0++] = std::polar (radius, pi * (2.0 * k + order + 1.0) / (2.0 * order));
         };
-        if (wh > 0.0)
-            butterworth (wh, poles, np, nh);
-        if (wl > 0.0)
-            butterworth (wl, poles, np, nl);
+        // round 190px (perf 7): the poles, and so their sections, depend on the crossovers and their orders only, not on
+        // g: Prism's dynamic bands design again at every gain step, so they are worked out once per (wl, wh, nl, nh) and
+        // kept (the same doubles: the comparison is exact, and the sections come from the same roots)
+        const bool polesKept = poleKey[0] == wl && poleKey[1] == wh && poleOrders[0] == nl && poleOrders[1] == nh;
+        if (! polesKept)
+        {
+            if (wh > 0.0)
+                butterworth (wh, poles, np, nh);
+            if (wl > 0.0)
+                butterworth (wl, poles, np, nl);
+        }
         if (wl > 0.0 && wh > 0.0 && nl != nh)
             mixedZeros (wl, wh, nl, nh, g, zeros, nz);
         else if (wl <= 0.0)
@@ -337,7 +345,20 @@ public:
         // sections: conjugate pairs, then the real roots two by two, a last real root alone
         std::array<Analog, 4> num {}, den {};
         const int sn = sections (zeros.data(), nz, num);
-        const int sd = sections (poles.data(), np, den);
+        int sd = 0;
+        if (polesKept)
+        {
+            den = keptDen;
+            sd = keptSections;
+        }
+        else
+        {
+            sd = sections (poles.data(), np, den);
+            keptDen = den;
+            keptSections = sd;
+            poleKey = { wl, wh };
+            poleOrders = { nl, nh };
+        }
         const int m = std::max (sn, sd);
         for (int k = 0; k < m; ++k)
             c[(std::size_t) k] = bilinear (k < sn ? num[(std::size_t) k] : Analog {}, k < sd ? den[(std::size_t) k] : Analog {});
@@ -553,5 +574,10 @@ private:
     std::array<std::array<double, 2>, maxSections> state {};
     int count = 0;
     double gain = 1.0;
+    // round 190px: the last design's pole sections and what they were made from (NaN: none yet)
+    std::array<double, 2> poleKey { std::numeric_limits<double>::quiet_NaN(), std::numeric_limits<double>::quiet_NaN() };
+    std::array<int, 2> poleOrders { 0, 0 };
+    std::array<Analog, 4> keptDen {};
+    int keptSections = 0;
 };
 } // namespace lynx::minphase

+ 42 - 0
src/core/MixSuite.cpp

@@ -1,4 +1,5 @@
 #include "core/MixSuite.h"
+#include "core/CpuFeatures.h"
 #include "core/FastMath.h"
 #include "core/RenDynamics.h"
 #include "core/VitaminLaw.h"
@@ -253,8 +254,49 @@ namespace
 {
 // acc[k] = Σ coef[j] · lin[L − 1 + k − j] over j = 0 … L − 1, summed in that order from 0 (as up and down sum one
 // output), for k in [0, count): eight and four outputs side by side in SSE lanes, the rest one by one
+void halfBandBlock (const float* coef, int L, const float* lin, int count, float* acc) noexcept;
+
+#if LYNX_CPU_DISPATCH
+// Round 190px (perf 7): sixteen and eight outputs side by side in AVX lanes. Each lane does what an SSE lane does — a
+// multiply, then an add, tap after tap in the same order (AVX has no fused multiply-add) — so every output is the same
+// float; the outputs left over go to the SSE / scalar loops (lin and acc moved by the outputs done).
+LYNX_TARGET_AVX void halfBandBlockAvx (const float* coef, int L, const float* lin, int count, float* acc) noexcept
+{
+    const int P = L - 1;
+    int k = 0;
+    for (; k + 16 <= count; k += 16)
+    {
+        auto a0 = _mm256_setzero_ps(), a1 = _mm256_setzero_ps();
+        for (int j = 0; j < L; ++j)
+        {
+            const auto c = _mm256_set1_ps (coef[j]);
+            a0 = _mm256_add_ps (a0, _mm256_mul_ps (c, _mm256_loadu_ps (lin + P + k - j)));
+            a1 = _mm256_add_ps (a1, _mm256_mul_ps (c, _mm256_loadu_ps (lin + P + k + 8 - j)));
+        }
+        _mm256_storeu_ps (acc + k, a0);
+        _mm256_storeu_ps (acc + k + 8, a1);
+    }
+    for (; k + 8 <= count; k += 8)
+    {
+        auto a0 = _mm256_setzero_ps();
+        for (int j = 0; j < L; ++j)
+            a0 = _mm256_add_ps (a0, _mm256_mul_ps (_mm256_set1_ps (coef[j]), _mm256_loadu_ps (lin + P + k - j)));
+        _mm256_storeu_ps (acc + k, a0);
+    }
+    if (k < count)
+        halfBandBlock (coef, L, lin + k, count - k, acc + k);
+}
+#endif
+
 void halfBandBlock (const float* coef, int L, const float* lin, int count, float* acc) noexcept
 {
+#if LYNX_CPU_DISPATCH
+    if (count >= 8 && cpu::hasAvx())
+    {
+        halfBandBlockAvx (coef, L, lin, count, acc);
+        return;
+    }
+#endif
     const int P = L - 1;
     int k = 0;
 #if defined(LYNX_X86)

+ 28 - 0
src/core/OggVorbis.cpp

@@ -111,6 +111,27 @@ struct Link
 };
 } // namespace
 
+namespace
+{
+// Round 190px (perf 7): the last Ogg page's granule position (the stream's length in samples per channel for a
+// stream that starts at 0), or 0 when there is none to trust. Only a size hint for the decoded vectors: they used to
+// grow by doubling, so a long stem ended with up to twice its samples' memory reserved (Thief's vocal: 77.7 MB of
+// audio in 128 MB) and was copied at every doubling.
+std::size_t lengthHint (const std::uint8_t* bytes, std::size_t size) noexcept
+{
+    for (std::size_t at = size >= 27 ? size - 27 : 0; at-- > 0;)
+        if (bytes[at] == 'O' && bytes[at + 1] == 'g' && bytes[at + 2] == 'g' && bytes[at + 3] == 'S' && bytes[at + 4] == 0)
+        {
+            std::uint64_t g = 0;
+            for (int k = 7; k >= 0; --k)
+                g = (g << 8) | bytes[at + 6 + (std::size_t) k];
+            // (−1: no packet ends on that page; anything beyond 24 hours at 384 kHz: not a length)
+            return g == ~std::uint64_t { 0 } || g > 384000ull * 86400ull ? 0 : (std::size_t) g;
+        }
+    return 0;
+}
+} // namespace
+
 bool decode (const std::uint8_t* bytes, std::size_t size, Decoded& out)
 {
     out = {};
@@ -163,6 +184,9 @@ bool decode (const std::uint8_t* bytes, std::size_t size, Decoded& out)
             out.channels = channels;
             out.sampleRate = (int) link.info.rate;
             out.data.assign ((std::size_t) channels, {});
+            if (const auto hint = lengthHint (bytes, size); hint > 0)
+                for (auto& d : out.data)
+                    d.reserve (hint + 8192); // (the last packets may run a little past the last granule)
         }
 
         if (vorbis_synthesis_init (&link.dsp, &link.info) != 0)
@@ -204,6 +228,10 @@ bool decode (const std::uint8_t* bytes, std::size_t size, Decoded& out)
         }
     }
 
+    // (round 190px: no large slack kept — a hint too small left the doubling's spare room, a chained file's more)
+    for (auto& d : out.data)
+        if (d.capacity() - d.size() > 16384)
+            d.shrink_to_fit();
     return out.channels > 0;
 }
 } // namespace lynx::oggvorbis

+ 23 - 0
src/core/OverloadGuard.h

@@ -55,6 +55,9 @@ public:
         // 190os: the stop now lets go at once, and the processing time it judges does not include the yield, so the
         // windows above see the same; each probe starved the screen for its 250 ms (perf190os/HANDOFF.md)
         double probeEveryMs = 0.0, probeMs = 250.0;
+        // round 190px: how late the pulse is when render-ahead starts pacing its catch-up ("ralate"; 50 = uiLateMs's
+        // default). Pacing costs the audio nothing while the ring holds blocks, so it may act earlier than the yield.
+        double aheadLateMs = 50.0;
     };
     const Params& params() const noexcept { return p; }
     // "key=value,…" (missing keys keep their value; any thread before the device starts)
@@ -85,6 +88,7 @@ public:
             else if (key == "probe") p.probeMs = v;
             else if (key == "probeevery") p.probeEveryMs = v;
             else if (key == "stopgrace") p.stopGraceMs = v;
+            else if (key == "ralate") p.aheadLateMs = v;
             at = end;
             while (*at != 0 && *at != ',')
                 ++at;
@@ -100,6 +104,24 @@ public:
     // Message thread: its 30 Hz pulse (the engine's timer), `nowMs` on the callbacks' clock.
     void uiPulse (double nowMs) noexcept { lastUiMs.store (nowMs, std::memory_order_relaxed); }
 
+    // Round 190px (perf 7): the UI starves right now — "Safe overloads" on and the 30 Hz pulse late by aheadLateMs. Any
+    // thread (the render-ahead thread paces its catch-up with it: after an overload, the callbacks keep their deadline
+    // while render-ahead refills its window with the workers on both CPUs of a small PC, which the callbacks' windows
+    // above never see; 190os measured 90-130 ms frame gaps there).
+    bool uiStarving (double nowMs) const noexcept
+    {
+        const auto ui = lastUiMs.load (std::memory_order_relaxed);
+        return enabled.load (std::memory_order_relaxed) && ui > 0.0 && nowMs - ui > p.aheadLateMs;
+    }
+    // what the render-ahead thread gave up that way (for --uiperf and the tests)
+    void notePaced (double ms) noexcept
+    {
+        pacedUs.fetch_add ((std::uint64_t) (ms * 1000.0), std::memory_order_relaxed);
+        pacedCount.fetch_add (1, std::memory_order_relaxed);
+    }
+    double pacedMs() const noexcept { return (double) pacedUs.load (std::memory_order_relaxed) / 1000.0; }
+    std::uint64_t timesPaced() const noexcept { return pacedCount.load (std::memory_order_relaxed); }
+
     // Audio thread, after every device callback (its output written): `usedMs` its processing time, `budgetMs` its
     // deadline, `playing` whether the transport runs (round 190os). Returns how long to yield now (ms, 0 = none). No
     // lock, no allocation.
@@ -244,6 +266,7 @@ private:
     std::atomic<double> releaseAt { 0.0 }, releaseLag { 0.0 };
     std::atomic<double> lastUiMs { 0.0 };
     std::atomic<std::uint64_t> engagements { 0 }, yieldedUs { 0 };
+    std::atomic<std::uint64_t> pacedUs { 0 }, pacedCount { 0 }; // (round 190px)
     // audio thread only
     double windowStartMs = 0.0, lastOverloadMs = -1.0e12;
     int windowCalls = 0, windowOver = 0;

+ 17 - 1
src/core/RenderAhead.cpp

@@ -1,4 +1,5 @@
 #include "core/RenderAhead.h"
+#include "core/OverloadGuard.h"
 
 #include <algorithm>
 #include <cmath>
@@ -810,7 +811,9 @@ void RenderAhead::threadLoop (std::function<void()> onStart)
         // (the workers when the window runs thin, or for good while one thread can't keep up — a serial block now and
         // then, with the window comfortable, measures that again)
         const auto heavy = serialLoad >= serialLimit && ! (jobsSinceSerial >= 256 && fill >= targetFill / 2);
-        const auto useWorkers = pool != nullptr && (fill < std::max (1, targetFill / 3) || heavy);
+        // round 190px: while the UI starves ("Safe overloads"), the workers only when the ring is about to run dry
+        const auto starving = uiGuard != nullptr && uiClock != nullptr && uiGuard->uiStarving (uiClock());
+        const auto useWorkers = pool != nullptr && (starving ? fill < 2 : (fill < std::max (1, targetFill / 3) || heavy));
        #endif
         const auto jobStart = ProcessTimes::now();
         const auto jobCpu = WorkerPool::threadCpuNs();
@@ -835,6 +838,19 @@ void RenderAhead::threadLoop (std::function<void()> onStart)
             pool->park(); // (the window is full: the workers sleep instead of spinning)
         writeIndex.store (w + 1, std::memory_order_release);
         owner.store (0, std::memory_order_release);
+       #if ! defined(__APPLE__)
+        // round 190px (perf 7, fluidity): the UI starving while two or more blocks wait in the ring — the callbacks are
+        // served — the thread gives the screen as long as the block took (0.5 … 4 ms), so a window refilled after an
+        // overload no longer keeps both CPUs of a small PC busy (the samples rendered are the same; only when)
+        if (starving && fill + 1 >= 2 && ! sb.last)
+        {
+            const auto ms = std::clamp ((double) jobNs * 1.0e-6, 0.5, 4.0);
+            if (useWorkers)
+                pool->park();
+            OverloadGuard::sleepFor (ms);
+            uiGuard->notePaced (ms);
+        }
+       #endif
     }
 }
 

+ 12 - 0
src/core/RenderAhead.h

@@ -52,6 +52,7 @@ namespace lynx
 {
 class WorkerPool;
 class OsSemaphore;
+class OverloadGuard;
 
 // Options › Audio settings › "Render ahead (lower CPU at small buffers)": on by default (O22). App-wide, kept in
 // ui-options.txt ("renderAhead=0/1").
@@ -193,6 +194,15 @@ public:
     // render-ahead thread; `onThreadStart` raises its priority (as the workers'). Once, before playback.
     void setWorkerPool (WorkerPool* pool, std::function<void()> onThreadStart = {});
     void setLiveInput (LiveInput* input) noexcept { liveInput = input; }
+    // Round 190px (perf 7, fluidity): the engine's "Safe overloads" guard and its clock (ms, the callbacks' clock). While
+    // the guard says the UI starves, the render-ahead thread refills its window without the workers (unless the ring is
+    // about to run dry) and gives up a slice of the CPU after each block it renders while two or more wait in the ring.
+    // Only when blocks are rendered changes, never what they hold. Once, before playback; nullptr = never paced.
+    void setUiGuard (OverloadGuard* guard, double (*clockMs)() noexcept) noexcept
+    {
+        uiGuard = guard;
+        uiClock = clockMs;
+    }
     void setTargets (const renderahead::Targets* t) noexcept { targets = t; }
     // the window in samples (default about 23 ms; tests use other values)
     void setWindowSamples (int samples) noexcept { windowSamples = samples; }
@@ -316,6 +326,8 @@ private:
     std::unique_ptr<MeterBank> aheadMeters; // its meters, taken into the ring and replayed when the block is heard
     std::unique_ptr<HostTimeline> aheadTimeline;
     const renderahead::Targets* targets = nullptr;
+    OverloadGuard* uiGuard = nullptr; // (round 190px)
+    double (*uiClock)() noexcept = nullptr;
     renderahead::Stats counters;
 
     // the partition in use and the one being worked out (the renderers hold pointers into `current`)

+ 2 - 0
src/engine/AudioEngine.cpp

@@ -758,6 +758,8 @@ void AudioEngine::buildInitialGraph()
     if (rackProcessor != nullptr)
     {
         rackProcessor->setRenderAheadTargets (&renderAheadTargets); // (round 190gq)
+        // round 190px: the render-ahead thread sees the "Safe overloads" guard's view of the UI (the guard's own clock)
+        rackProcessor->setUiGuard (&overloadGuard, [] () noexcept { return juce::Time::getMillisecondCounterHiRes(); });
         rackProcessor->setLiveInput (&liveInput);
         rackProcessor->setHardwareOutput (&hwOutput);
         rackProcessor->setPerformance (performanceLive.get());

+ 2 - 0
src/engine/ChannelRackProcessor.h

@@ -80,6 +80,8 @@ public:
     void setProfiling (bool on) noexcept { ahead->setProfiling (on); }
     bool renderAheadOwnsWorkers() const noexcept { return ahead->ownsWorkers(); }
     void haltRenderAhead() noexcept { ahead->halt(); }
+    // round 190px: render-ahead paces its catch-up while the UI starves (core/RenderAhead.h setUiGuard)
+    void setUiGuard (OverloadGuard* guard, double (*clockMs)() noexcept) noexcept { ahead->setUiGuard (guard, clockMs); }
     void resumeRenderAhead() noexcept { ahead->resume(); } // (round 190jb: after an export's hold)
     void setRenderAheadAlways (bool always) noexcept { ahead->setAlwaysEngage (always); }
     const renderahead::Stats& renderAheadStats() const noexcept { return ahead->stats(); }

+ 98 - 20
src/engine/SampleLibrary.cpp

@@ -189,6 +189,9 @@ public:
         return true;
     }
 
+    // round 190px: the decoded channels themselves (SampleLibrary::decode takes them instead of copying them twice)
+    oggvorbis::Decoded& decodedData() noexcept { return decoded; }
+
 private:
     oggvorbis::Decoded decoded;
 };
@@ -309,6 +312,10 @@ namespace
 // a changed algorithm never reuses an old copy. The floats are stored as computed: what plays is bit for bit the same.
 constexpr char stretchMagic[8] = { 'L', 'Y', 'N', 'X', 'S', 'T', 'R', '1' };
 constexpr int stretchHeader = 32;
+// round 190px (perf 7): the header's channel count for a stereo copy whose two channels are the same samples — one
+// channel is stored, both read it (Thief: the stretched copies of its four long stems, 67 MB of the 229 MB locked in
+// RAM). An older LYNX refuses the file (channels other than 1 / 2) and stretches again.
+constexpr std::int32_t stretchStereoSame = -2;
 constexpr juce::int64 stretchCacheLimit = 1024LL * 1024 * 1024; // pruned (oldest first) to 3/4 of it when exceeded
 
 std::uint64_t fnv (const void* data, std::size_t bytes, std::uint64_t h = 1469598103934665603ULL) noexcept
@@ -553,7 +560,8 @@ std::shared_ptr<SampleData> mapStretched (const juce::File& file, double rate, j
     auto copy = std::make_shared<LockedCopy>();
     copy->file = std::make_unique<juce::MemoryMappedFile> (file, juce::MemoryMappedFile::readOnly);
     const auto* d = static_cast<const char*> (copy->file->getData());
-    const auto bytes = (std::size_t) (frames * channels) * sizeof (float);
+    const auto stored = channels == stretchStereoSame ? 1 : channels;
+    const auto bytes = (std::size_t) (frames * stored) * sizeof (float);
     if (d == nullptr || copy->file->getSize() != (std::size_t) stretchHeader + bytes || std::memcmp (d, stretchMagic, 8) != 0)
         return nullptr;
     const auto* samples = d + stretchHeader;
@@ -565,7 +573,8 @@ std::shared_ptr<SampleData> mapStretched (const juce::File& file, double rate, j
     out->sampleRate = rate;
     out->mappedFrames = (std::size_t) frames;
     out->mappedLeft = reinterpret_cast<const float*> (samples);
-    out->mappedRight = channels == 2 ? reinterpret_cast<const float*> (samples) + frames : nullptr;
+    out->mappedRight = channels == 2 ? reinterpret_cast<const float*> (samples) + frames
+                       : channels == stretchStereoSame ? out->mappedLeft : nullptr;
     {
         const std::scoped_lock l (lockedCopiesLock());
         auto& list = lockedCopies();
@@ -591,8 +600,8 @@ std::shared_ptr<SampleData> readStretched (const juce::File& file)
                 std::memcpy (&rate, header + 8, 8);
                 std::memcpy (&frames, header + 16, 8);
                 std::memcpy (&channels, header + 24, 4);
-                if (frames > 0 && (channels == 1 || channels == 2) && rate > 0.0
-                    && file.getSize() == stretchHeader + frames * channels * (juce::int64) sizeof (float))
+                if (frames > 0 && (channels == 1 || channels == 2 || channels == stretchStereoSame) && rate > 0.0
+                    && file.getSize() == stretchHeader + frames * (channels == stretchStereoSame ? 1 : channels) * (juce::int64) sizeof (float))
                     if (auto mapped = mapStretched (file, rate, frames, channels))
                     {
                         file.setLastModificationTime (juce::Time::getCurrentTime()); // (recently used: pruned last)
@@ -613,8 +622,8 @@ std::shared_ptr<SampleData> readStretched (const juce::File& file)
     std::memcpy (&rate, d + 8, 8);
     std::memcpy (&frames, d + 16, 8);
     std::memcpy (&channels, d + 24, 4);
-    if (frames <= 0 || (channels != 1 && channels != 2) || ! (rate > 0.0)
-        || (juce::int64) block.getSize() != stretchHeader + frames * channels * (juce::int64) sizeof (float))
+    if (frames <= 0 || (channels != 1 && channels != 2 && channels != stretchStereoSame) || ! (rate > 0.0)
+        || (juce::int64) block.getSize() != stretchHeader + frames * (channels == stretchStereoSame ? 1 : channels) * (juce::int64) sizeof (float))
         return nullptr;
     auto out = std::make_shared<SampleData>();
     out->sampleRate = rate;
@@ -622,6 +631,8 @@ std::shared_ptr<SampleData> readStretched (const juce::File& file)
     out->left.assign (samples, samples + frames);
     if (channels == 2)
         out->right.assign (samples + frames, samples + 2 * frames);
+    else if (channels == stretchStereoSame) // (not mapped: the two channels in RAM, as a stereo copy read this way was)
+        out->right = out->left;
     file.setLastModificationTime (juce::Time::getCurrentTime()); // (recently used: pruned last)
     return out;
 }
@@ -653,7 +664,9 @@ void writeStretched (const juce::File& file, const SampleData& data)
         if (out.failedToOpen())
             return;
         const auto frames = (juce::int64) data.left.size();
-        const std::int32_t channels = data.right.empty() ? 1 : 2;
+        std::int32_t channels = data.right.empty() ? 1 : 2;
+        if (channels == 2 && std::memcmp (data.left.data(), data.right.data(), data.left.size() * sizeof (float)) == 0)
+            channels = stretchStereoSame;
         char header[stretchHeader] {};
         std::memcpy (header, stretchMagic, 8);
         std::memcpy (header + 8, &data.sampleRate, 8);
@@ -878,23 +891,55 @@ std::shared_ptr<const SampleData> SampleLibrary::loadStreamed (const juce::File&
                                                     .hashCode64());
     const auto leftFile = cacheFolder().getChildFile (key + ".L.pcm");
     const auto rightFile = cacheFolder().getChildFile (key + ".R.pcm");
+    // round 190px (perf 7): a stereo file whose two channels decode to the same samples keeps one channel on disk and in
+    // memory; this marker says so (Thief's four long stems: 67 MB of the 211 MB its streamed samples map)
+    const auto sameFile = cacheFolder().getChildFile (key + ".R.same");
+    bool rightIsLeft = channels > 1 && sameFile.existsAsFile() && leftFile.existsAsFile();
 
     prunePcmCacheLater();
     if (leftFile.existsAsFile())
     {
         markUsed (leftFile);
-        if (channels > 1)
+        if (channels > 1 && ! rightIsLeft)
             markUsed (rightFile);
     }
     auto mapped = std::make_shared<Mapped>();
     mapped->left = mapChannel (leftFile, reader.sampleRate, frames);
-    mapped->right = channels > 1 ? mapChannel (rightFile, reader.sampleRate, frames) : nullptr;
+    mapped->right = channels > 1 && ! rightIsLeft ? mapChannel (rightFile, reader.sampleRate, frames) : nullptr;
 
-    if (mapped->left == nullptr || (channels > 1 && mapped->right == nullptr))
+    // a cache written before round 190px holds both channels: compared once (a read of what is mapped, cheaper than
+    // decoding again), and the answer kept beside it (.R.same: the right file goes; .R.diff: both stay)
+    const auto diffFile = cacheFolder().getChildFile (key + ".R.diff");
+    if (mapped->left != nullptr && mapped->right != nullptr && ! diffFile.existsAsFile())
+    {
+        const auto* a = static_cast<const char*> (mapped->left->getData()) + cacheHeader;
+        const auto* b = static_cast<const char*> (mapped->right->getData()) + cacheHeader;
+        if (std::memcmp (a, b, (std::size_t) frames * sizeof (float)) == 0)
+        {
+            mapped->right = nullptr; // (unmapped before it is deleted: Windows keeps a mapped file)
+            if (sameFile.create().wasOk() && rightFile.deleteFile())
+                rightIsLeft = true;
+            else
+            {
+                sameFile.deleteFile();
+                mapped->right = mapChannel (rightFile, reader.sampleRate, frames);
+            }
+        }
+        else
+            diffFile.create();
+    }
+
+    if (mapped->left == nullptr || (channels > 1 && ! rightIsLeft && mapped->right == nullptr))
     {
         // decode once, in chunks, straight into the cache files
+        mapped->left = nullptr;
+        mapped->right = nullptr;
         leftFile.deleteFile();
         rightFile.deleteFile();
+        sameFile.deleteFile();
+        diffFile.deleteFile();
+        rightIsLeft = false;
+        bool same = channels > 1;
         {
             juce::FileOutputStream outL (leftFile);
             std::unique_ptr<juce::FileOutputStream> outR;
@@ -916,18 +961,31 @@ std::shared_ptr<const SampleData> SampleLibrary::loadStreamed (const juce::File&
                 outL.write (buffer.getReadPointer (0), (size_t) n * sizeof (float));
 
                 if (outR != nullptr)
+                {
                     outR->write (buffer.getReadPointer (1), (size_t) n * sizeof (float));
+                    same = same && std::memcmp (buffer.getReadPointer (0), buffer.getReadPointer (1), (size_t) n * sizeof (float)) == 0;
+                }
             }
 
             outL.flush();
             if (outR != nullptr)
                 outR->flush();
         }
+        // (the right file is written as it decodes — whether the channels match is only known at the end — and dropped
+        // then; the marker is made once the left file is complete)
+        if (same && sameFile.create().wasOk() && rightFile.deleteFile())
+            rightIsLeft = true;
+        else
+        {
+            sameFile.deleteFile();
+            if (channels > 1)
+                diffFile.create();
+        }
 
         mapped->left = mapChannel (leftFile, reader.sampleRate, frames);
-        mapped->right = channels > 1 ? mapChannel (rightFile, reader.sampleRate, frames) : nullptr;
+        mapped->right = channels > 1 && ! rightIsLeft ? mapChannel (rightFile, reader.sampleRate, frames) : nullptr;
 
-        if (mapped->left == nullptr || (channels > 1 && mapped->right == nullptr))
+        if (mapped->left == nullptr || (channels > 1 && ! rightIsLeft && mapped->right == nullptr))
             return nullptr;
     }
 
@@ -939,7 +997,7 @@ std::shared_ptr<const SampleData> SampleLibrary::loadStreamed (const juce::File&
     data->mappedLeft = reinterpret_cast<const float*> (static_cast<const char*> (mapped->left->getData()) + cacheHeader);
     data->mappedRight = mapped->right != nullptr
                             ? reinterpret_cast<const float*> (static_cast<const char*> (mapped->right->getData()) + cacheHeader)
-                            : nullptr;
+                            : (rightIsLeft ? data->mappedLeft : nullptr); // (stereo, the same samples: isStereo() stays true)
     data->mapping = mapped;
 
     // the first seconds already in memory: the clip start doesn't wait for the disk
@@ -1081,7 +1139,7 @@ std::int64_t heldBytes (const SampleData& d)
 }
 std::int64_t mappedBytesOf (const SampleData& d)
 {
-    return d.isMapped() ? (std::int64_t) d.mappedFrames * (d.mappedRight != nullptr ? 2 : 1) * (std::int64_t) sizeof (float) : 0;
+    return d.isMapped() ? (std::int64_t) d.mappedFrames * (d.mappedRight != nullptr && d.mappedRight != d.mappedLeft ? 2 : 1) * (std::int64_t) sizeof (float) : 0;
 }
 } // namespace
 
@@ -1179,14 +1237,36 @@ std::shared_ptr<const SampleData> SampleLibrary::decode (const juce::String& pat
     const auto frames = (int) juce::jmin<juce::int64> (reader->lengthInSamples, (juce::int64) (reader->sampleRate * 600.0));
     const auto channels = juce::jmin (2, (int) reader->numChannels);
 
-    juce::AudioBuffer<float> buffer (channels, frames);
-    reader->read (&buffer, 0, frames, 0, true, channels > 1);
-
     auto data = std::make_shared<SampleData>();
     data->sampleRate = reader->sampleRate;
     data->bitsPerSample = (int) reader->bitsPerSample;
     data->floatData = reader->usesFloatingPointData;
-    data->left.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + frames);
+    // round 190px (perf 7): FL's Ogg samples are decoded whole already; their channels move into the sample (the same
+    // floats AudioFormatReader::read copies, without the two copies of every sample that made the open's peak)
+    juce::AudioBuffer<float> buffer;
+    if (auto* ogg = dynamic_cast<DecodedReader*> (reader.get());
+        ogg != nullptr && (int) ogg->decodedData().data.size() >= channels && (juce::int64) ogg->decodedData().data[0].size() >= frames)
+    {
+        auto& d = ogg->decodedData().data;
+        data->left = std::move (d[0]);
+        data->left.resize ((std::size_t) frames);
+        if (channels > 1)
+        {
+            data->right = std::move (d[1]);
+            data->right.resize ((std::size_t) frames, 0.0f); // (as the reader's zeros past a shorter channel)
+        }
+        for (auto* v : { &data->left, &data->right }) // (cut at the 10-minute limit: no large spare room kept)
+            if (v->capacity() - v->size() > 16384)
+                v->shrink_to_fit();
+    }
+    else
+    {
+        buffer.setSize (channels, frames);
+        reader->read (&buffer, 0, frames, 0, true, channels > 1);
+        data->left.assign (buffer.getReadPointer (0), buffer.getReadPointer (0) + frames);
+        if (channels > 1)
+            data->right.assign (buffer.getReadPointer (1), buffer.getReadPointer (1) + frames);
+    }
     // the file's own loop (WAV smpl, first loop; JUCE gives the end frame inclusive)
     {
         const auto& meta = reader->metadataValues;
@@ -1199,8 +1279,6 @@ std::shared_ptr<const SampleData> SampleLibrary::decode (const juce::String& pat
         }
     }
 
-    if (channels > 1)
-        data->right.assign (buffer.getReadPointer (1), buffer.getReadPointer (1) + frames);
     readWavExtras (file, *data);
 
     return data;

+ 141 - 0
tests/Perf190pxTests.inc

@@ -0,0 +1,141 @@
+// Round 190px (0.1.32 perf round 7): exact speed-ups and memory cuts — the AVX half-band oversampler (mixsuite), the
+// kept pole sections of the minimum-phase band filters (Prism's dynamic bands), FL's Ogg samples decoded without spare
+// room, and the "Safe overloads" guard's view of a starving UI that paces render-ahead's catch-up.
+// (Echoform's lazily grown delay lines: the gold renders and perf190px/s/linebench, the old ring against the new.)
+
+#include "core/CpuFeatures.h"
+#include "core/MinPhaseBand.h"
+#include "core/MixSuite.h"
+#include "core/OggVorbis.h"
+#include "core/OverloadGuard.h"
+
+#include <cstring>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+
+namespace
+{
+std::uint64_t fnv190px (const std::vector<std::vector<float>>& channels)
+{
+    std::uint64_t h = 1469598103934665603ULL;
+    for (const auto& v : channels)
+    {
+        const auto* p = reinterpret_cast<const unsigned char*> (v.data());
+        for (std::size_t i = 0; i < v.size() * sizeof (float); ++i)
+            h = (h ^ p[i]) * 1099511628211ULL;
+    }
+    return h;
+}
+} // namespace
+
+TEST (perf190px_oversampler_avx_renders_the_sse_samples_bit_for_bit)
+{
+    using namespace lynx;
+    std::vector<float> in (5000);
+    std::uint32_t s = 0x2468aceu;
+    for (auto& x : in)
+    {
+        s = s * 1664525u + 1013904223u;
+        x = (float) ((double) (s >> 8) / 16777216.0 * 2.0 - 1.0);
+    }
+    const auto curve = [] (float v) noexcept { return v - 0.25f * v * v * v; };
+    for (int factor : { 2, 4, 8 })
+        // (blocks of every length the stages split into: whole AVX groups, the SSE and scalar remainders)
+        for (int block : { 1, 7, 8, 15, 16, 17, 64, 100, 256 })
+        {
+            std::vector<float> a = in, b = in;
+            mixsuite::Oversampler oa, ob;
+            oa.setFactor (factor);
+            ob.setFactor (factor);
+            cpu::setLevelForTest (cpu::sse41);
+            for (int at = 0; at < (int) a.size(); at += block)
+                oa.process (a.data() + at, std::min (block, (int) a.size() - at), curve);
+            cpu::setLevelForTest (-1); // (the hardware's: AVX where there is one)
+            for (int at = 0; at < (int) b.size(); at += block)
+                ob.process (b.data() + at, std::min (block, (int) b.size() - at), curve);
+            CHECK (std::memcmp (a.data(), b.data(), a.size() * sizeof (float)) == 0);
+        }
+    cpu::setLevelForTest (-1);
+}
+
+TEST (perf190px_minphase_band_kept_poles_design_as_a_fresh_band)
+{
+    using namespace lynx::minphase;
+    // a gain sweep as Prism's dynamic bands make it (every step a new design of the same band), and the crossovers moved
+    // half way: each design against a band that never designed before, response and samples bit for bit
+    struct Case { double wl, wh; int ml, mh; };
+    const Case cases[] { { 0.0, 0.31, 0, 4 }, { 0.12, 0.0, 4, 0 }, { 0.05, 0.4, 4, 4 }, { 0.05, 0.4, 2, 8 }, { 0.2, 0.9, 8, 8 }, { 0.08, 0.6, 2, 2 } };
+    for (const auto& c : cases)
+    {
+        Band kept;
+        for (int step = 0; step < 60; ++step)
+        {
+            const double g = std::pow (10.0, (-24.0 + 0.8 * step) / 20.0);
+            const auto wl = step < 30 ? c.wl : c.wl * 1.1, wh = step < 30 ? c.wh : c.wh * 0.9;
+            Band fresh;
+            kept.designM (wl, wh, c.ml, c.mh, g);
+            fresh.designM (wl, wh, c.ml, c.mh, g);
+            bool same = true;
+            for (double w : { 0.01, 0.1, 0.5, 1.0, 2.0, 3.0 })
+            {
+                const auto a = kept.response (w), b = fresh.response (w);
+                same = same && a.real() == b.real() && a.imag() == b.imag();
+            }
+            Band k2 = kept, f2 = fresh;
+            k2.reset();
+            f2.reset();
+            for (int i = 0; i < 64; ++i)
+            {
+                const double x = i == 0 ? 1.0 : std::sin (0.37 * i);
+                same = same && k2.process (x) == f2.process (x);
+            }
+            CHECK (same);
+        }
+    }
+}
+
+TEST (perf190px_guard_sees_the_ui_starving)
+{
+    lynx::OverloadGuard g;
+    CHECK (! g.uiStarving (1000.0)); // (no pulse yet)
+    g.uiPulse (1000.0);
+    CHECK (! g.uiStarving (1049.0));
+    CHECK (g.uiStarving (1051.0));
+    g.setEnabled (false); // ("Safe overloads" off: never)
+    CHECK (! g.uiStarving (1200.0));
+    g.setEnabled (true);
+    g.uiPulse (1200.0);
+    CHECK (! g.uiStarving (1220.0));
+    // ("ralate": render-ahead's own threshold, for an A/B)
+    lynx::OverloadGuard h;
+    h.configure ("ralate=30");
+    h.uiPulse (1000.0);
+    CHECK (! h.uiStarving (1029.0) && h.uiStarving (1031.0));
+    g.notePaced (1.5);
+    g.notePaced (0.5);
+    CHECK (g.timesPaced() == 2 && std::abs (g.pacedMs() - 2.0) < 1e-9);
+}
+
+TEST (perf190px_fl_ogg_samples_decode_the_same_floats_without_spare_room)
+{
+    if (realFlpDir.empty())
+        return;
+    const auto packs = std::filesystem::path (realFlpDir) / "Patches" / "Packs" / "Drums";
+    // the samples' FNV-1a 64 of the planar floats, as the decoder before round 190px made them (perf190px/perf/ogg-base.txt)
+    const std::pair<const char*, std::uint64_t> files[] { { "Cymbals/Broken Crash.wav", 0xa9dbd74be1a16257ull },
+                                                          { "Kicks/Grv Kick 27.wav", 0x08919d4b317dd9c5ull },
+                                                          { "Snares/808 Snare.wav", 0xc410014a2627fb33ull } };
+    for (const auto& [name, hash] : files)
+    {
+        std::ifstream in (packs / name, std::ios::binary);
+        const std::vector<std::uint8_t> bytes { std::istreambuf_iterator<char> (in), {} };
+        lynx::oggvorbis::Decoded d;
+        if (bytes.empty())
+            continue;
+        CHECK (lynx::oggvorbis::decode (bytes.data(), bytes.size(), d) && ! d.data.empty());
+        CHECK (fnv190px (d.data) == hash);
+        for (const auto& v : d.data)
+            CHECK (v.capacity() - v.size() <= 16384);
+    }
+}

+ 1 - 0
tests/tests.cpp

@@ -18096,6 +18096,7 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "FlParity190prTests.inc" // round 190pr: Harmor automation, FL song-start values of Harmor / Sytrus / FL effects
 #include "PatcherXyz190ptTests.inc" // round 190pt: Patcher Control Surface / X-Y-Z links, Vocodex controls under automation
 #include "Perf190osTests.inc" // round 190os: the safe-overload guard lets go at the stop and within 1 s of the overload's end
+#include "Perf190pxTests.inc" // round 190px: AVX half-band, kept minimum-phase poles, Ogg samples without spare room, render-ahead paced
 #include "Tracker190omTests.inc" // round 190om (0.1.31): tracker stage 2 (pattern events, pitch curves, Bxx / Vxx), SimSynth velocity
 #include "Rollup031s6Tests.inc" // rollup 0.1.31 step 6: gold sweep for 190om decisions 4-5 (LYNX_SWEEP_DIR)
 #include "TrackStates190opTests.inc" // round 190op (0.1.31): Hide / Deactivate tracks (P4), Capture automation (P7)