diff --git a/CMakeLists.txt b/CMakeLists.txt index ecfed7e..e770077 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -995,15 +995,16 @@ target_link_libraries(curve_popup PUBLIC editor_geometry) add_library(master_gain STATIC src/core/instrument/engine/master_gain.cpp) target_include_directories(master_gain PUBLIC src) -# filter — the per-voice 2-pole resonant low/high-pass, ported from Daniel's Cortex-M4 filter -# with its virtual FilterBase/Filter/Biquad hierarchy flattened away (that hierarchy dispatched -# virtually per channel per sample, which the per-voice per-sample path forbids). Control -# mapping, RBJ coefficient math, feedback saturation, and the filter type each get their own -# file; VoiceFilter::process is header-inline so the biquad kernel still inlines at the call -# site. Standard library only. NEITHER SDK. +# filter — the per-voice TPT/SVF with a continuous HP->BP->LP morph and an in-loop drive stage. +# The Cortex-M4 source's virtual FilterBase/Filter/Biquad hierarchy dispatched per channel per +# sample, which the per-voice per-sample path forbids, so none of it came across. Control +# mapping, SVF coefficients, morph weights, and the filter type each get their own file; +# VoiceFilter::process is header-inline so the kernel still inlines at the call site. Standard +# library only. NEITHER SDK. add_library(filter STATIC src/core/instrument/engine/filter/filter_params.cpp src/core/instrument/engine/filter/filter_coeffs.cpp + src/core/instrument/engine/filter/filter_morph.cpp src/core/instrument/engine/filter/voice_filter.cpp) target_include_directories(filter PUBLIC src) @@ -1107,9 +1108,10 @@ add_executable(master_gain_tests tests/test_master_gain.cpp) target_link_libraries(master_gain_tests PRIVATE master_gain) add_test(NAME master_gain_tests COMMAND master_gain_tests) -# filter: the per-voice resonant filter. Pins the RBJ coefficients against an independent -# textbook cos/sin derivation, asserts the cutoff/Q control mappings at their anchors, and -# measures the resonant peak both analytically and by driving real sines. NEITHER SDK. +# filter: the per-voice resonant filter. Pins the SVF coefficients against an independent +# derivation, asserts the cutoff/Q control mappings at their anchors, holds the morph endpoints +# to the analytic 2-pole targets, and measures rate/level invariance and drive stability by +# driving real sines. NEITHER SDK. add_executable(filter_tests tests/test_filter.cpp) target_link_libraries(filter_tests PRIVATE filter) add_test(NAME filter_tests COMMAND filter_tests) diff --git a/src/core/instrument/engine/filter/CLAUDE.md b/src/core/instrument/engine/filter/CLAUDE.md index 97f5b21..3c09ce2 100644 --- a/src/core/instrument/engine/filter/CLAUDE.md +++ b/src/core/instrument/engine/filter/CLAUDE.md @@ -2,19 +2,22 @@ ## Scope -The pure 2-pole resonant low/high-pass a sounding voice runs. No REAPER, no VST3, no -allocation, no I/O. Everything here lives in `reasampler::instrument::engine::filter`, -nested per the directory-mirrors-namespace convention — this keeps `FilterMode` and -friends out of `reasampler::instrument::engine` proper, where `zone_params.h` lives, since -this module has no call site yet to force the collision into the open at compile time. -Four files, one responsibility each: +The pure per-voice filter a sounding voice runs: a Zavalishin TPT/SVF with a continuous +HP→BP→LP morph and a drive stage. No REAPER, no VST3, no allocation, no I/O. Everything +here lives in `reasampler::instrument::engine::filter`, nested per the +directory-mirrors-namespace convention — this keeps `FilterSettings` and friends out of +`reasampler::instrument::engine` proper, where `zone_params.h` lives, since this module has +no call site yet to force a collision into the open at compile time. Five files, one +responsibility each: -- `filter_params` — the control domain: `FilterMode`, normalized [0,1] knob position → - cutoff Hz and Q, and the exact inverses. -- `filter_coeffs` — the DSP domain: `BiquadCoeffs` and the RBJ coefficient computation - from (mode, cutoff Hz, Q, sample rate). -- `filter_saturate` — the high-pass feedback saturator (`tanhSaturate` / - `feedbackSaturate`). Header-only inline; it sits on the per-sample path. +- `filter_params` — the control domain: normalized [0,1] knob position → cutoff Hz, Q, and + drive depth, plus the exact inverses for cutoff and Q. +- `filter_coeffs` — the DSP domain: `SvfCoeffs` and the TPT coefficient solve from + (cutoff Hz, Q, sample rate). +- `filter_morph` — the morph domain: normalized position → per-tap weights, and the fold of + those weights into the three multipliers the kernel applies. +- `filter_saturate` — `softLimit`, the drive stage's shaper. Header-only inline; it sits + inside the per-sample recursion. - `voice_filter` — `FilterSettings` and `VoiceFilter`, the concrete per-voice type. `process()` is defined in the header. @@ -22,39 +25,102 @@ Four files, one responsibility each: ### No vtable on the per-sample path -This is a **port, not a relocation**. The Cortex-M4 source was a virtual hierarchy -(`FilterBase` → `Filter` → `Biquad` → `{BiquadHP, BiquadLP}`) whose base class routed the -channel loop through pure-virtual `process_channel_frame` / `filter` / `update_feedback` -so a `FilterDecorator` chain could wrap it. **None of that came across, and none of it may -come back.** `VoiceFilter` is concrete: mode is a member branch inside an inlined -`process()`, predicted perfectly because it cannot change within a note. There is no -`IFilter`, no decorator seam, no virtual `tick()`, and no allocation in `process()` — root -`CLAUDE.md`'s structural heuristic 3 names this class of dispatch blowout directly. +The Cortex-M4 source this began as was a virtual hierarchy (`FilterBase` → `Filter` → +`Biquad` → `{BiquadHP, BiquadLP}`) whose base class routed the channel loop through +pure-virtual `process_channel_frame` / `filter` / `update_feedback` so a `FilterDecorator` +chain could wrap it. **None of that came across, and none of it may come back.** +`VoiceFilter` is concrete, `process()` is inlined, and there is no `IFilter`, no decorator +seam, no virtual `tick()`, and no allocation in `process()` — root `CLAUDE.md`'s structural +heuristic 3 names this class of dispatch blowout directly. -A non-type template parameter for the mode was considered and rejected: mode is a -runtime-settable user parameter, so templating would only relocate the same branch to the -call site and force the voice to hold two instances or switch over them. +### The rate enters ONLY through `g = tan(pi*fc/sr)` -### Two modes, and only two +There is no reference sample rate, calibration rate, or fallback rate anywhere in this +module, and introducing one is the specific regression to guard against. An earlier design +carried a `kFilterFeedbackDelaySeconds = 1/48000` tuning constant for a feedback tap; that +tap, its ring buffer, and the constant are all deleted. A non-positive rate yields `g == 0` +and a bypass mix (signal passes through) — never an invented rate. -2-pole high-pass and 2-pole low-pass. The source's `Biquad1PoleLP` is struck and was not -ported. Further modes are deferred — **do not build a mode-extension framework** for them. +### Why the high-pass feedback tap was right on Q15 hardware and wrong here + +The ported firmware fed a saturated share of an earlier output back into the high-pass +input. Its stated rationale — that the HP numerator collapses toward zero at low cutoff, +taking the resonance with it — is **inverted**, and the comment asserting it has been +removed rather than carried forward. Measurement: the HP `b0` approaches **1** as cutoff +falls (0.99987 at 20 Hz); it is the **low-pass** `b0` that collapses (1.7e−06 at 20 Hz). + +The tap was a Q15 fixed-point workaround. At 16-bit fixed point the low-cutoff biquad loses +a ~17-bit cancellation and the resonance really does die; the feedback injected it back by +another route. float32 survives that cancellation with 7 bits to spare, so on this target +the tap did not restore character — it *reduced* it (HP landed 0.4% off the analytic RBJ +target with the tap disabled, and 25% off with it enabled), and it introduced both level +dependence and rate dependence. + +Daniel's ruling on the level-dependent resonance bloom it produced: *"was a feature on the +hardware (one knob colorful HP for master FX), wrong choice for this approach."* Drive is +now an explicit user-controlled stage instead of an emergent side effect. + +### The morph is a blend of taps, never a coefficient switch + +An SVF produces high, band, and low from the same state, which is the reason this topology +was chosen. `FilterMode` as a discrete enum is retired. HP at 0.0, BP at 0.5, LP at 1.0, +continuous throughout, and the three endpoints are exact. + +The crossfade is **equal-power between adjacent taps**, and both halves of that are forced +by the topology rather than picked by ear: + +- At the corner the taps are `HP = jQ`, `BP = Q`, `LP = -jQ` — adjacent taps in exact + quadrature, which the bilinear transform preserves exactly at the prewarped corner. A + `cos`/`sin` pair therefore holds the corner magnitude at exactly `Q*sqrt(cos² + sin²) = Q` + at every morph position. A linear crossfade of a quadrature pair would sag to `Q/sqrt(2)` + mid-leg — a 3 dB hole that reads as a defect, not as character. +- **Adjacent only.** HP and LP are exactly antiphase at the corner, so any law giving both + simultaneous weight cancels there and cuts a notch. That notch is the Oberheim SEM's + centre tap. This control's centre is a band-pass, per the explicit HP/BP/LP enumeration — + do not "simplify" the two legs into one three-way weighting, which silently builds the SEM. + +### Drive is a contraction inside the loop, which is what makes it unconditionally stable + +`softLimit(u, depth) = u / sqrt(1 + (depth*u)²)` shapes the **band-pass integrator state**. +Three properties carry the design: + +- `depth == 0` makes it algebraically the identity (`x / sqrt(1) == x`, exact in IEEE), so + drive 0 is **bit-exact** linear with no branch and no special case on the hot path. The + test asserts bit-identity against the same kernel with the limiter deleted. +- `|softLimit(u, d)| <= |u|` for every depth, so the state update can only shrink the state. + The filter cannot gain energy from the drive stage: stability at any Q and any cutoff is + structural, and self-oscillation is impossible. This is why the shaper must keep unit slope + at the origin — a shaper with gain above 1 there turns the resonator into an oscillator. +- It shapes the **state**, not the zero-delay loop. A nonlinearity inside the loop would + break the closed-form `a1`/`a2`/`a3` solve and need per-sample Newton iteration. + +Placement is the resonance path because that is where the firmware's character came from, +and because the band-pass state sits at zero in the passband and at DC — so drive colours +the resonance and leaves the passband transparent (measured 0.98 at max drive). It is not a +distortion box in series with the signal; a caller wanting that has every other plugin. + +**Drive × resonance interact by design.** What reaches the shaper is the resonance state, +already multiplied by roughly `2*Q`, so the same drive setting bites harder the more +resonance is dialled in — and harder on a hotter input. That level dependence is the +*point* of an explicit drive control; what Daniel rejected was level dependence nobody +asked for. At drive 0 there is none, to 0.0004% over a 1000:1 level range. + +`kFilterDriveDepthMax` (4.0) was set against measurement, not feel: at max drive, full-scale +input and max resonance the resonant peak lands ~10 dB under the passband — plainly +crushed, which is the asked-for "extreme". Raising it further inverts the filter's shape +(21 dB under passband at depth 64), turning the peak the user dialled in into a notch. +There is deliberately **no makeup gain** — any law for it would be invented rather than +derived, and drive is due an ear pass against the radial dial. ### The cutoff control is sample-rate-free; the clamp is not -`filterCutoffHzFromNorm` sweeps a fixed 20 Hz – 20 kHz (three exact decades, so norm 1/3 -is 200 Hz and 2/3 is 2 kHz) and takes no sample rate. The persisted value is the -normalized knob position, so a rate-derived endpoint would make one preset sound different -at 44.1k and 96k. The Nyquist clamp (`kFilterNyquistFraction`, 0.48) is a property of the -bilinear transform — `tan(pi*fc/sr)` diverges at Nyquist — so it lives in `biquadCoeffs` -where the rate is already a parameter. 20 kHz is under 0.48·sr at 44.1k and above, so the -clamp never eats live knob travel there; the source's hardcoded 23 kHz endpoint did exactly -that at 44.1k. Below 44.1k (e.g. 32k, 22.05k) the clamp still handles the math correctly — -it just legitimately eats the top of the knob travel at those rates. - -`biquadCoeffs` with a non-positive sample rate returns pass-through coefficients. It does -**not** fall back to 44100 — that would breach the standing no-hardcoded-sample-rates -ruling. +`filterCutoffHzFromNorm` sweeps a fixed 20 Hz – 20 kHz (three exact decades, so norm 1/3 is +200 Hz and 2/3 is 2 kHz) and takes no sample rate. The persisted value is the normalized +knob position, so a rate-derived endpoint would make one preset sound different at 44.1k and +96k. The Nyquist clamp (`kFilterNyquistFraction`, 0.48) is a property of the bilinear +transform — `tan(pi*fc/sr)` diverges at Nyquist — so it lives in `svfCoeffs` where the rate +is already a parameter. 20 kHz is under 0.48·sr at 44.1k and above, so the clamp never eats +live knob travel there; the source's hardcoded 23 kHz endpoint did exactly that at 44.1k. ### Q spans 0.1 → 10 with √2 at the center @@ -62,70 +128,33 @@ Settled by Daniel. The source's `Q = M_SQRT1_2 + resonance` mapping (floored at center anchor) was **rewritten, not ported**. The curve is quadratic in log Q through the three anchors rather than two spliced log segments — same anchors either way, but no slope kink at the center detent. The quadratic term is nonzero only because √2 is not the -geometric mean of 0.1 and 10; `filterNormFromQ` divides by it. +geometric mean of 0.1 and 10; `filterNormFromQ` divides by it. The SVF consumes it as +`k = 1/Q`. -### The high-pass input feedback is load-bearing +### Denormal flushing tests the envelope, not one sample -`kHighPassFeedbackShare` (0.24) times the raw **normalized** resonance, not Q — Q reaches -10 and scaling the feedback by it would push loop gain past unity. The high-pass numerator -collapses toward zero as cutoff falls, taking the resonance with it; the saturated -feedback restores the character down there. Ported behavior; the constant is the tuning -knob if the feel needs adjusting. `audio_saturate` and `H()` from the source were unused -by the biquads and were not ported. - -### The feedback tap is a fixed TIME, and 48 kHz is the calibration anchor - -`kFilterFeedbackDelaySeconds` (1/48000 s) is the interval the feedback tap reaches back, -resolved to a sample offset at `prepare()` and read with linear interpolation between two -whole taps. It is **not** a fallback sample rate and does not breach the -no-hardcoded-sample-rates ruling: nothing here ever substitutes it for the host's rate, -which still arrives as a parameter and is the only thing the coefficients are computed -from. It is a tuning constant of the filter, in the same sense as an attack time. - -The firmware ran one fixed rate, so a tap that reached back one *sample* and one that -reached back a fixed *interval* were indistinguishable there. On a variable-rate host they -are not: the loop closes once per sample, so a one-sample tap made the loop's phase at the -cutoff — and with it the resonant emphasis and the stability margin — a function of the -rate. Measured peak/passband at fc=4 kHz, res=1.0 ran 5.02 at 48k against 8.52 at 192k. - -Two consequences worth knowing before touching this: - -- **48 kHz is the reference and must stay bit-identical.** It is the rate the constants - were voiced at. The interval resolves to exactly one sample there, so 48k reproduces the - firmware kernel sample-for-sample; `testFortyEightKilohertzBehaviorIsUnchanged` pins that - with literals captured before the tap became a time. -- **44.1 kHz cannot be corrected and is deliberately left alone.** One sample there is - already *longer* than the interval, and the loop must contain at least one sample of - delay or it is algebraic and uncomputable. So 44.1k keeps the firmware's single tap and - sits up to ~6% off 48k at the top of the cutoff range — exactly where it has always been. - Everything at or above 48k lands within the bilinear discretization difference of 48k. - -The tap line is written with the **flushed** `y1`, so it drains to exact zero behind a -flushed recursion rather than circulating denormals; `isSilent()` therefore has to scan the -whole line, not just the newest entry. - -### Denormal flushing - -`process()` flushes the **y** history to exact zero below `kFilterDenormalFloor` (1e-30). -Only the recursive half needs it: a denormal in `y` self-sustains and stalls the FPU for -thousands of samples on a ringing-out voice, while the `x` history is an FIR tail that -shifts out within two samples. `isSilent()` reports the flushed state and is the honest -signal that a voice's filter can no longer contribute output. +`process()` flushes **both** integrators to exact zero once both are below +`kFilterDenormalFloor` (1e-30). Testing both is required, not tidy: `ic1` and `ic2` are in +quadrature, so a resonator swings each of them through zero twice a cycle. Flushing on a +single integrator injects a step in phase with the resonance, which the resonance then +amplifies — the filter limit-cycles at the floor forever instead of going quiet. This was +re-verified for TPT rather than assumed to transfer from the retired Direct Form I state. ## Gotchas -- **The tan pre-warp is not a different filter.** By the half-angle identity - `cos(w0) = (1-w²)/(1+w²)` and `sin(w0) = 2w/(1+w²)` with `w = tan(pi*fc/sr)`, these are - the textbook RBJ cos/sin coefficients exactly — just computed in a form that stays - conditioned at low cutoff where `cos(w0) → 1`. `tests/test_filter.cpp` asserts the - equivalence against an independent derivation. Don't "simplify" it back to `std::cos`. -- **`prepare()` deliberately does not clear history** — a live parameter move must glide, - not click. Call `reset()` at note-on. -- **`a1`/`a2` are stored for a subtracting difference equation** (`y = ... - a1*y1 - - a2*y2`), so the transfer denominator is `1 + a1*z^-1 + a2*z^-2`. A sign convention slip - here inverts the poles. +- **TPT is what fixed the low-cutoff conditioning defect** — this is a topology change, not + a relocation. Direct Form I encoded pole proximity in `a1 → -2`, `a2 → +1` and cancelled + them against each other every sample, which at `fc/sr ≈ 1e-4` cost ~17 bits and put the + measured peak **15% low** at 20 Hz / 192 kHz. TPT encodes the same proximity in `a1`'s + small deviation from 1, which float32 resolves: measured 10.0160 against the analytic + 10.0125, +0.034%. Do not reintroduce a direct-form kernel. +- **`prepare()` deliberately does not clear state** — a live parameter move must glide, not + click. Call `reset()` at note-on. +- **The morph endpoints are asserted on the folded mix, exactly.** `morphWeights` snaps the + leg endpoints instead of trusting `cos`/`sin` to land on 0 and 1, which they miss by ~1e-17 + — enough to leave a -324 dB neighbour tap in what is specified as a pure response. - **No call site yet.** Wiring the filter into the voice path is a separate track; nothing in `sampler_core` references this module today. -- **Decay to the denormal floor is a fixed wall-clock time (~0.21 s), not a sample count.** - A test budget expressed in samples is therefore itself a rate assumption — a fixed 20000 - samples is ample at 48k and expires mid-decay at 96k and above. +- **Decay to the denormal floor is a fixed wall-clock time, not a sample count.** A test + budget expressed in samples is therefore itself a rate assumption — a fixed 20000 samples + is ample at 48k and expires mid-decay at 96k and above. diff --git a/src/core/instrument/engine/filter/filter_coeffs.cpp b/src/core/instrument/engine/filter/filter_coeffs.cpp index 8baa29c..65598e2 100644 --- a/src/core/instrument/engine/filter/filter_coeffs.cpp +++ b/src/core/instrument/engine/filter/filter_coeffs.cpp @@ -12,31 +12,28 @@ double clampd(double v, double lo, double hi) { return v < lo ? lo : (v > hi ? h } // namespace -BiquadCoeffs biquadCoeffs(FilterMode mode, float cutoffHz, float q, double sampleRate) { - if (!(sampleRate > 0.0)) return BiquadCoeffs{}; - - const double nyquistCeiling = kFilterNyquistFraction * sampleRate; - const double fc = clampd(cutoffHz, kFilterCutoffMinHz, nyquistCeiling); +SvfCoeffs svfCoeffs(float cutoffHz, float q, double sampleRate) { const double qq = clampd(q, kFilterQMin, kFilterQMax); + const double k = 1.0 / qq; - const double w = std::tan(kPi * fc / sampleRate); - const double w2 = w * w; - const double cosw = (1.0 - w2) / (1.0 + w2); - const double sinw = 2.0 * w / (1.0 + w2); - const double alpha = sinw / (2.0 * qq); - const double norm = 1.0 / (1.0 + alpha); + double g = 0.0; + if (sampleRate > 0.0) { + const double fc = clampd(cutoffHz, kFilterCutoffMinHz, kFilterNyquistFraction * sampleRate); + g = std::tan(kPi * fc / sampleRate); + } - // Both modes share the denominator; only the numerator's sign on cosw differs, and b1 is - // always +/-2*b0 — folding that in keeps the two branches from drifting apart. - const double b0 = (mode == FilterMode::HighPass ? (1.0 + cosw) : (1.0 - cosw)) * 0.5 * norm; - const double b1 = (mode == FilterMode::HighPass ? -2.0 : 2.0) * b0; + // Solved in double and narrowed once. The intermediate g*(g+k) is the term that carries the + // pole proximity, so forming it in float would throw away the conditioning TPT just bought. + const double a1 = 1.0 / (1.0 + g * (g + k)); + const double a2 = g * a1; + const double a3 = g * a2; - BiquadCoeffs c; - c.b0 = static_cast(b0); - c.b1 = static_cast(b1); - c.b2 = static_cast(b0); - c.a1 = static_cast(-2.0 * cosw * norm); - c.a2 = static_cast((1.0 - alpha) * norm); + SvfCoeffs c; + c.g = static_cast(g); + c.k = static_cast(k); + c.a1 = static_cast(a1); + c.a2 = static_cast(a2); + c.a3 = static_cast(a3); return c; } diff --git a/src/core/instrument/engine/filter/filter_coeffs.h b/src/core/instrument/engine/filter/filter_coeffs.h index c4d5a66..0a483d7 100644 --- a/src/core/instrument/engine/filter/filter_coeffs.h +++ b/src/core/instrument/engine/filter/filter_coeffs.h @@ -1,7 +1,7 @@ -// filter_coeffs.h — RBJ Audio EQ Cookbook Direct Form I biquad coefficients for the 2-pole -// low/high-pass. Computed via the tan half-angle substitution w = tan(pi*fc/sr): by the -// identity cos(w0) = (1-w^2)/(1+w^2), sin(w0) = 2w/(1+w^2) these ARE the textbook cos/sin -// coefficients, in a form that stays conditioned at low cutoff where cos(w0) -> 1. +// filter_coeffs.h — Zavalishin topology-preserving-transform state-variable coefficients. +// The rate enters ONLY through g = tan(pi*fc/sr); there is no reference or calibration rate +// anywhere in this module, and reintroducing one would restore the rate-dependent resonance +// the TPT rewrite exists to remove. #pragma once @@ -9,23 +9,29 @@ namespace reasampler::instrument::engine::filter { -// Already normalized by a0. The denominator is 1 + a1*z^-1 + a2*z^-2, so the difference -// equation SUBTRACTS the a terms: y = b0*x + b1*x1 + b2*x2 - a1*y1 - a2*y2. -struct BiquadCoeffs { - float b0 = 1.0f; - float b1 = 0.0f; - float b2 = 0.0f; - float a1 = 0.0f; +// The two-integrator SVF's per-sample constants. a1/a2/a3 are the algebraic solution of the +// zero-delay feedback loop, so the kernel needs no iteration. +struct SvfCoeffs { + float g = 0.0f; // tan(pi*fc/sr) — the ONLY place the sample rate appears + float k = 1.0f; // 1/Q, the damping term + float a1 = 1.0f; float a2 = 0.0f; + float a3 = 0.0f; }; // Highest fraction of the sample rate the pre-warp stays well-conditioned at: tan() diverges -// as fc approaches sr/2. Ported unchanged from the firmware, where it was already the ceiling. +// as fc approaches sr/2. inline constexpr double kFilterNyquistFraction = 0.48; // cutoffHz is clamped into [kFilterCutoffMinHz, kFilterNyquistFraction*sampleRate] and q into -// [kFilterQMin, kFilterQMax]. A non-positive sampleRate yields pass-through coefficients — the -// no-hardcoded-sample-rates ruling means we refuse to invent a rate rather than assume 44.1k. -BiquadCoeffs biquadCoeffs(FilterMode mode, float cutoffHz, float q, double sampleRate); +// [kFilterQMin, kFilterQMax]. A non-positive sampleRate yields g == 0 — we refuse to invent a +// rate rather than assume 44.1k. +// +// Float storage is safe HERE in a way it was not for the retired Direct Form I path. DF1 encoded +// pole proximity in a1 -> -2, a2 -> +1 and cancelled them against each other every sample, which +// at fc/sr ~ 1e-4 cost ~17 bits and moved the resonant peak -15%. TPT encodes the same proximity +// in a1's small DEVIATION from 1, which float resolves. Measured 20 Hz/192 kHz peak is 10.0160 +// against the analytic 10.0125, +0.034%. +SvfCoeffs svfCoeffs(float cutoffHz, float q, double sampleRate); } // namespace reasampler::instrument::engine::filter diff --git a/src/core/instrument/engine/filter/filter_morph.cpp b/src/core/instrument/engine/filter/filter_morph.cpp new file mode 100644 index 0000000..e06ad69 --- /dev/null +++ b/src/core/instrument/engine/filter/filter_morph.cpp @@ -0,0 +1,54 @@ +#include "core/instrument/engine/filter/filter_morph.h" + +#include + +namespace reasampler::instrument::engine::filter { +namespace { + +constexpr double kPi = 3.14159265358979323846; + +struct Pair { + double a, b; +}; + +// Equal-power crossfade, EXACT at both ends by construction rather than by rounding: cos and sin +// of the leg's quarter turn are only 1e-17 from 0/1 at the endpoints, and the endpoints have to +// be pure taps, not a pure tap plus a -324 dB neighbour. +Pair equalPower(double t) { + if (!(t > 0.0)) return {1.0, 0.0}; + if (t >= 1.0) return {0.0, 1.0}; + const double theta = 0.5 * kPi * t; + return {std::cos(theta), std::sin(theta)}; +} + +} // namespace + +MorphWeights morphWeights(float norm) { + const double n = norm < 0.0 ? 0.0 : (norm > 1.0 ? 1.0 : static_cast(norm)); + + MorphWeights w; + if (n <= 0.5) { + const Pair p = equalPower(2.0 * n); // HP -> BP + w.hp = static_cast(p.a); + w.bp = static_cast(p.b); + w.lp = 0.0f; + } else { + const Pair p = equalPower(2.0 * n - 1.0); // BP -> LP + w.hp = 0.0f; + w.bp = static_cast(p.a); + w.lp = static_cast(p.b); + } + return w; +} + +MorphMix morphMix(const MorphWeights& w, float k) { + MorphMix m; + m.m0 = w.hp; + m.m1 = w.bp - w.hp * k; + m.m2 = w.lp - w.hp; + return m; +} + +MorphMix bypassMix() { return MorphMix{1.0f, 0.0f, 0.0f}; } + +} // namespace reasampler::instrument::engine::filter diff --git a/src/core/instrument/engine/filter/filter_morph.h b/src/core/instrument/engine/filter/filter_morph.h new file mode 100644 index 0000000..d622a30 --- /dev/null +++ b/src/core/instrument/engine/filter/filter_morph.h @@ -0,0 +1,48 @@ +// filter_morph.h — the continuous HP -> BP -> LP morph: normalized position to tap weights, +// and the fold of those weights into the three multipliers the kernel actually applies. An SVF +// produces all three taps from one state, so the morph is a blend, never a coefficient switch. + +#pragma once + +namespace reasampler::instrument::engine::filter { + +// Weight on each SVF tap. Exactly one of hp/lp is nonzero at a time — the morph crossfades +// between ADJACENT taps only, never HP against LP. +struct MorphWeights { + float hp = 0.0f; + float bp = 0.0f; + float lp = 1.0f; +}; + +// HP at 0.0, BP at 0.5, LP at 1.0. Out-of-range norm clamps to the endpoints. +// +// Equal-power (cos/sin) rather than linear, and that choice is forced by the topology rather +// than picked by ear. At the corner frequency the three taps are HP = jQ, BP = Q, LP = -jQ, so +// adjacent taps are in exact QUADRATURE there (and the bilinear transform preserves that exactly +// at the prewarped corner). Under a cos/sin pair the corner magnitude is therefore +// Q*sqrt(cos^2 + sin^2) = Q at every morph position — algebraically flat across the whole sweep. +// A linear crossfade of the same quadrature pair would sag to Q/sqrt(2), a 3 dB hole mid-leg. +// +// Crossfading adjacent taps only is the other half of it: HP and LP are exactly ANTIPHASE at the +// corner, so any law giving both simultaneous weight cancels there and cuts a notch. That notch +// is the Oberheim SEM's center tap; this control's center is a band-pass, per the explicit +// HP/BP/LP enumeration. +MorphWeights morphWeights(float norm); + +// The kernel applies out = m0*v0 + m1*v1 + m2*v2, where v0 is the input and v1/v2 are the SVF's +// band and low outputs. Folding hp = v0 - k*v1 - v2 into the weights here keeps the per-sample +// path at three multiplies and spares it ever forming the high tap. +struct MorphMix { + float m0 = 0.0f; + float m1 = 0.0f; + float m2 = 1.0f; +}; + +MorphMix morphMix(const MorphWeights& w, float k); + +// Passes the input through untouched, whatever the morph position asks for. Reserved for a +// sample rate we cannot form a filter from: silencing an instrument is a worse failure than +// ignoring the morph, and at g == 0 a low-pass tap is analytically silent. +MorphMix bypassMix(); + +} // namespace reasampler::instrument::engine::filter diff --git a/src/core/instrument/engine/filter/filter_params.cpp b/src/core/instrument/engine/filter/filter_params.cpp index ead4ca0..927d194 100644 --- a/src/core/instrument/engine/filter/filter_params.cpp +++ b/src/core/instrument/engine/filter/filter_params.cpp @@ -43,6 +43,11 @@ float filterQFromNorm(float norm) { return static_cast(std::exp(k.a + n * (k.b + k.c * n))); } +float filterDriveDepthFromNorm(float norm) { + const double n = clamp01(norm); + return static_cast(kFilterDriveDepthMax * n * n); +} + float filterNormFromQ(float q) { if (!(q > kFilterQMin)) return 0.0f; if (q >= kFilterQMax) return 1.0f; diff --git a/src/core/instrument/engine/filter/filter_params.h b/src/core/instrument/engine/filter/filter_params.h index f5faf91..94485f8 100644 --- a/src/core/instrument/engine/filter/filter_params.h +++ b/src/core/instrument/engine/filter/filter_params.h @@ -1,14 +1,12 @@ // filter_params.h — control-domain mapping for the voice filter: normalized [0,1] knob -// positions to cutoff Hz and Q, plus the two-mode enum. Deliberately sample-rate-free — -// the Nyquist clamp is a property of the bilinear transform and lives in filter_coeffs, -// so the persisted normalized cutoff means the same frequency at every project rate. +// positions to cutoff Hz, Q, and drive depth. Deliberately sample-rate-free — the Nyquist +// clamp is a property of the bilinear transform and lives in filter_coeffs, so the persisted +// normalized cutoff means the same frequency at every project rate. #pragma once namespace reasampler::instrument::engine::filter { -enum class FilterMode { LowPass, HighPass }; - // The audio band the cutoff control sweeps: three exact decades, so norm 1/3 is 200 Hz and // norm 2/3 is 2 kHz. NOT derived from the sample rate — a rate-dependent endpoint would make // one saved preset sound different at 44.1k and 96k, and at 44.1k the top of the travel would @@ -23,6 +21,14 @@ inline constexpr float kFilterQMin = 0.1f; inline constexpr float kFilterQMax = 10.0f; inline constexpr float kFilterQCenter = 1.41421356f; +// Depth at the top of the drive control. The limiter's knee is at 1/depth, and the resonance +// swings the state to roughly 2*Q*level, so this is the range over which drive bites. Chosen +// against measurement rather than by feel: at max drive, full-scale input and max resonance the +// resonant peak lands ~10 dB under the passband — plainly crushed, which is the asked-for +// "extreme". Raising it further inverts the filter's shape (measured 21 dB under passband at +// depth 64), turning the peak the user dialled in into a notch. +inline constexpr float kFilterDriveDepthMax = 4.0f; + // Out-of-range norm clamps to the endpoints. float filterCutoffHzFromNorm(float norm); @@ -37,4 +43,10 @@ float filterQFromNorm(float norm); // Exact inverse of filterQFromNorm; out-of-range Q clamps to 0 or 1. float filterNormFromQ(float q); +// Drive depth for the in-loop limiter. Square law, not linear: the knee is 1/depth, so a linear +// depth would spend most of the audible travel in the first tenth of the knob. Exactly 0 at +// norm 0 — the limiter is then algebraically the identity, which is what makes drive=0 bit-exact +// linear rather than merely close. +float filterDriveDepthFromNorm(float norm); + } // namespace reasampler::instrument::engine::filter diff --git a/src/core/instrument/engine/filter/filter_saturate.h b/src/core/instrument/engine/filter/filter_saturate.h index a6fd8b8..b78fc95 100644 --- a/src/core/instrument/engine/filter/filter_saturate.h +++ b/src/core/instrument/engine/filter/filter_saturate.h @@ -1,27 +1,32 @@ -// filter_saturate.h — the high-pass feedback-path saturator, ported from the Cortex-M4 -// filter. Header-inline: it sits on the per-voice per-sample path, and a rational -// approximation is here precisely to avoid a transcendental tanh() call there. +// filter_saturate.h — the drive stage's soft limiter. Header-inline: it sits inside the +// per-voice per-sample recursion. #pragma once +#include + namespace reasampler::instrument::engine::filter { -// Rational tanh approximation inside +/-threshold, continued past it with a gentle 0.1 slope -// anchored at the threshold value so the curve stays continuous rather than hard-clipping. -inline float tanhSaturate(float x, float threshold, float a, float b) { - if (x > threshold) { - const float satAtThreshold = threshold * a / (a + b + threshold * threshold); - return satAtThreshold + (x - threshold) * 0.1f; - } - if (x < -threshold) { - const float satAtThreshold = -threshold * a / (a + b + threshold * threshold); - return satAtThreshold + (x + threshold) * 0.1f; - } - return x * a / (a + b + x * x); +// Odd, smooth, strictly monotone, bounded by 1/depth, with unit slope at the origin. +// +// Three properties are load-bearing and none of them are tuning: +// - depth == 0 makes this ALGEBRAICALLY the identity (x / sqrt(1) == x, exact in IEEE), so +// drive = 0 is bit-exact linear with no branch and no special case on the hot path. +// - |softLimit(x, d)| <= |x| for every d, so dropping it into the resonance state update can +// only ever shrink the state. The filter therefore cannot gain energy from the drive stage: +// stability at any Q and any cutoff is structural, not a tuned margin, and it can never +// self-oscillate. +// - Unit slope at the origin, so the shaper adds no gain of its own at any depth. What reaches +// it is the resonance state, already multiplied by roughly 2*Q, which is why drive and +// resonance interact: the same drive setting bites harder the more resonance is dialled in. +// +// The retired feedbackSaturate() is deliberately not carried forward: it had 0.75 slope at the +// origin, a fixed +/-2.0 threshold calibrated for firmware excursion levels, and turned over +// (non-monotone) past x = 6. That absolute threshold is the origin of the level-dependent +// resonance this rewrite removes — do not reintroduce it. +inline float softLimit(float x, float depth) { + const float s = depth * x; + return x / std::sqrt(1.0f + s * s); } -// TB-303-style hard feedback saturation. Tuned for the large excursions a resonant feedback -// path produces, not for audio-level signals — do not reuse it as a general waveshaper. -inline float feedbackSaturate(float x) { return tanhSaturate(x, 2.0f, 27.0f, 9.0f); } - } // namespace reasampler::instrument::engine::filter diff --git a/src/core/instrument/engine/filter/voice_filter.cpp b/src/core/instrument/engine/filter/voice_filter.cpp index 7cefa2d..69088ec 100644 --- a/src/core/instrument/engine/filter/voice_filter.cpp +++ b/src/core/instrument/engine/filter/voice_filter.cpp @@ -3,26 +3,10 @@ namespace reasampler::instrument::engine::filter { void VoiceFilter::prepare(const FilterSettings& settings, double sampleRate) { - mode_ = settings.mode; - const float cutoffHz = filterCutoffHzFromNorm(settings.cutoffNorm); - coeffs_ = biquadCoeffs(settings.mode, cutoffHz, filterQFromNorm(settings.resonanceNorm), - sampleRate); - const float res = settings.resonanceNorm < 0.0f - ? 0.0f - : (settings.resonanceNorm > 1.0f ? 1.0f : settings.resonanceNorm); - fbAmount_ = res * kHighPassFeedbackShare; - - // The calibrated feedback interval, expressed in samples at THIS rate. Floored at one sample - // because the loop must hold at least that much delay or it is algebraic and not computable - // — which is also why 44.1k, whose sample period already exceeds the interval, keeps the - // firmware's single tap. A non-positive rate lands on that same floor rather than on an - // invented rate. Clamped as a double before the narrowing cast so a wild rate cannot - // overflow the integer part. - double taps = kFilterFeedbackDelaySeconds * sampleRate; - if (!(taps > 1.0)) taps = 1.0; - if (taps > kFilterFeedbackTaps - 1) taps = kFilterFeedbackTaps - 1; - fbDelay_ = static_cast(taps); - fbDelayFrac_ = static_cast(taps - fbDelay_); + coeffs_ = svfCoeffs(filterCutoffHzFromNorm(settings.cutoffNorm), + filterQFromNorm(settings.resonanceNorm), sampleRate); + mix_ = (sampleRate > 0.0) ? morphMix(morphWeights(settings.morphNorm), coeffs_.k) : bypassMix(); + driveDepth_ = filterDriveDepthFromNorm(settings.driveNorm); } void VoiceFilter::reset() { @@ -31,11 +15,7 @@ void VoiceFilter::reset() { bool VoiceFilter::isSilent() const { for (const State& s : state_) { - if (s.x1 != 0.0f || s.x2 != 0.0f || s.y1 != 0.0f || s.y2 != 0.0f) return false; - // The whole tap line, not just the newest entry: an older tap still reaches the input. - for (float v : s.fb) { - if (v != 0.0f) return false; - } + if (s.ic1 != 0.0f || s.ic2 != 0.0f) return false; } return true; } diff --git a/src/core/instrument/engine/filter/voice_filter.h b/src/core/instrument/engine/filter/voice_filter.h index ba1d491..5c91474 100644 --- a/src/core/instrument/engine/filter/voice_filter.h +++ b/src/core/instrument/engine/filter/voice_filter.h @@ -1,6 +1,6 @@ -// voice_filter.h — per-voice 2-pole resonant low/high-pass. Concrete type, no vtable: this -// sits on the per-voice per-sample path, so process() is header-inline and mode is a member -// branch. No allocation, no virtual dispatch, no I/O anywhere in process(). +// voice_filter.h — per-voice TPT state-variable filter with a continuous HP->BP->LP morph and +// an in-loop drive stage. Concrete type, no vtable: this sits on the per-voice per-sample path, +// so process() is header-inline. No allocation, no virtual dispatch, no I/O in process(). #pragma once @@ -8,6 +8,7 @@ #include #include "core/instrument/engine/filter/filter_coeffs.h" +#include "core/instrument/engine/filter/filter_morph.h" #include "core/instrument/engine/filter/filter_params.h" #include "core/instrument/engine/filter/filter_saturate.h" @@ -15,62 +16,29 @@ namespace reasampler::instrument::engine::filter { // Normalized control positions, as the editor moves them and the persisted state carries them. struct FilterSettings { - FilterMode mode = FilterMode::LowPass; float cutoffNorm = 1.0f; float resonanceNorm = 0.0f; + float morphNorm = 1.0f; // 0 = high-pass, 0.5 = band-pass, 1 = low-pass + float driveNorm = 0.0f; }; -// Share of the last output fed back into the high-pass input at full resonance. Driven by the -// raw control position rather than by Q: Q reaches 10, and scaling the feedback by it would -// push the loop gain past unity at the top of the range. -// -// The HP/LP resonance asymmetry this produces is a known ear call reserved for Daniel, not a -// bug: measured peak/passband at res=1.0, fc=1kHz/sr=48k is LP 9.98 (flat at every input level) -// vs HP 7.44 (input 0.001-0.1), 7.59 (0.3), 8.52 (1.0) — HP resonance is level-dependent because -// feedbackSaturate's threshold (+/-2.0) is an absolute level, not a fraction of the signal. -// Retuning this constant alone cannot make the two modes track, since it does not touch that -// level-dependence. -inline constexpr float kHighPassFeedbackShare = 0.24f; - -// The feedback tap is a fixed TIME, not a fixed sample count. The loop closes once per sample -// through it, so tapping the immediately previous sample makes the loop's phase at the cutoff -- -// and with it the resonant emphasis -- a function of the sample rate: measured peak/passband at -// fc=4 kHz, res=1.0 was 5.02 at 48k against 8.52 at 192k while this was one sample. The source -// firmware ran a single fixed rate and could not see it. 1/48000 s is the interval the constants -// above were voiced at, so 48k resolves to exactly the one-sample tap the firmware used and is -// bit-identical to it; 44.1k, where one sample already exceeds the interval, is held at that -// same single tap by the floor in prepare() and is likewise unchanged. -inline constexpr double kFilterFeedbackDelaySeconds = 1.0 / 48000.0; - -// Depth of the tap line, a power of two so the index wraps with a mask. Sixteen holds delays 1 -// through 16, and the interpolating read needs one tap beyond the whole part, so rates up to -// 15/kFilterFeedbackDelaySeconds = 720 kHz resolve exactly — past REAPER's 384 kHz ceiling. -// Beyond that the delay clamps and the rate dependence creeps back, which is the pre-fix -// behavior rather than a new failure. -inline constexpr int kFilterFeedbackTaps = 16; -static_assert((kFilterFeedbackTaps & (kFilterFeedbackTaps - 1)) == 0, "mask indexing needs 2^n"); - -// Below this the recursion has decayed past -600 dB. Flushing keeps the history out of the +// Below this the recursion has decayed past -600 dB. Flushing keeps the state out of the // subnormal range, where a ringing-out voice would otherwise stall the FPU for thousands of // samples. Chosen well above FLT_MIN so a flushed state can never re-enter that range. inline constexpr float kFilterDenormalFloor = 1e-30f; class VoiceFilter { public: - // The instrument's output bus is permanently stereo; one history line per channel. + // The instrument's output bus is permanently stereo; one integrator pair per channel. static constexpr int kMaxChannels = 2; struct State { - float x1 = 0.0f; - float x2 = 0.0f; - float y1 = 0.0f; - float y2 = 0.0f; - float fb[kFilterFeedbackTaps]{}; // output history the high-pass feedback tap reads back - unsigned fbWrite = 0; // slot the NEXT output goes into + float ic1 = 0.0f; // band-pass integrator + float ic2 = 0.0f; // low-pass integrator }; - // Recomputes coefficients from the control positions. History is deliberately preserved so - // a live parameter move glides instead of clicking; call reset() at note-on. + // Recomputes coefficients from the control positions. State is deliberately preserved so a + // live parameter move glides instead of clicking; call reset() at note-on. void prepare(const FilterSettings& settings, double sampleRate); void reset(); @@ -80,50 +48,32 @@ public: assert(channel >= 0 && channel < kMaxChannels); State& s = state_[channel]; - // The high-pass numerator collapses toward zero as cutoff falls, taking the resonance - // with it; feeding a saturated share of an earlier output back into the input restores - // the character the coefficients alone stop producing down there. The 0.9f pre-scale is - // carried from the source firmware, uncalibrated here — no derivation is known for it. - // fbDelay_/fbDelayFrac_ are resolved at prepare(), so the tap stays a rate-free index - // here and the whole arm is evaluated only in high-pass mode. The interpolation between - // adjacent taps is exactly a no-op wherever the rate is a whole multiple of the - // calibration rate (fbDelayFrac_ is then exactly 0), so it costs no accuracy at 48/96/192k - // and only engages at the rates a whole tap would have rounded. - const float in = - (mode_ == FilterMode::HighPass) ? x - fbAmount_ * feedbackSaturate(fbTap(s) * 0.9f) : x; + const float v3 = x - s.ic2; + const float v1 = coeffs_.a1 * s.ic1 + coeffs_.a2 * v3; + const float v2 = s.ic2 + coeffs_.a2 * s.ic1 + coeffs_.a3 * v3; - const float y = coeffs_.b0 * in + coeffs_.b1 * s.x1 + coeffs_.b2 * s.x2 - - coeffs_.a1 * s.y1 - coeffs_.a2 * s.y2; + // The drive stage, and the only nonlinearity. It shapes the BAND-PASS integrator state + // rather than the input because that state IS the resonance: in the passband and at DC + // it sits at zero, so drive colours the resonance and leaves the passband transparent. + // Placing it on the state rather than inside the zero-delay loop keeps a1/a2/a3 an exact + // algebraic solve — a nonlinearity inside the loop would need per-sample Newton + // iteration. softLimit is a contraction, so this cannot destabilize the filter. + s.ic1 = softLimit(2.0f * v1 - s.ic1, driveDepth_); + s.ic2 = 2.0f * v2 - s.ic2; - s.x2 = s.x1; - s.x1 = in; - s.y2 = s.y1; - s.y1 = y; - - // Snap the RECURSIVE half of the state once it has decayed past -600 dB. Only y1/y2 - // are flushed (and only they are tested) — x1/x2 is an FIR tail that shifts out within - // two samples on its own, and a high-pass has an exact DC null (b1 == -2*b0 bit-exactly), - // so under a constant/DC-biased input y decays to zero while x1/x2 sit at the input - // level; clearing x1/x2 too would discard that history and the next sample would - // recompute a full-amplitude step from b0*in alone, re-ringing forever (a click train). - // Zeroing individual samples instead of the pair does not work either: a resonator - // swings through zero twice a cycle, so a per-sample flush injects a step in phase with - // the resonance, which the resonance then amplifies — the filter limit-cycles at the - // floor forever rather than going quiet. Testing y1 AND y2 tests the envelope, not one - // sample. - if (s.y1 > -kFilterDenormalFloor && s.y1 < kFilterDenormalFloor && - s.y2 > -kFilterDenormalFloor && s.y2 < kFilterDenormalFloor) { - s.y1 = 0.0f; - s.y2 = 0.0f; + // Snap the state once the whole resonator has decayed past -600 dB. Testing BOTH + // integrators is testing the ENVELOPE rather than one sample, and that is required, not + // tidy: ic1 and ic2 are in quadrature, so a resonator swings each of them through zero + // twice a cycle. Flushing on a single integrator would inject a step in phase with the + // resonance, which the resonance then amplifies — the filter limit-cycles at the floor + // forever instead of going quiet. + if (s.ic1 > -kFilterDenormalFloor && s.ic1 < kFilterDenormalFloor && + s.ic2 > -kFilterDenormalFloor && s.ic2 < kFilterDenormalFloor) { + s.ic1 = 0.0f; + s.ic2 = 0.0f; } - // Pushes the FLUSHED y1, so the tap line drains to exact zero behind a flushed recursion - // instead of feeding denormals back in. Stored unconditionally even in LP mode, where - // nothing reads it: the mode branch above already exists, but gating this store on it - // buys nothing a dead-store-eliminating compiler doesn't already do for free, at the - // cost of a second branch on the mode. - s.fb[s.fbWrite & (kFilterFeedbackTaps - 1)] = s.y1; - ++s.fbWrite; - return y; + + return mix_.m0 * x + mix_.m1 * v1 + mix_.m2 * v2; } void processFrame(float* samples, int channelCount) { @@ -131,7 +81,7 @@ public: for (int c = 0; c < channelCount; ++c) samples[c] = process(c, samples[c]); } - // True once every history line has flushed to exact zero — the voice's filter has stopped + // True once every integrator has flushed to exact zero — the voice's filter has stopped // ringing and cannot contribute further output. bool isSilent() const; @@ -139,23 +89,13 @@ public: assert(channel >= 0 && channel < kMaxChannels); return state_[channel]; } - const BiquadCoeffs& coeffs() const { return coeffs_; } + const SvfCoeffs& coeffs() const { return coeffs_; } + const MorphMix& mix() const { return mix_; } private: - // The feedback tap, fbDelay_ + fbDelayFrac_ samples back. Not named near/far: those are - // legacy Windows macros, and this header is bound for translation units that see windows.h. - float fbTap(const State& s) const { - constexpr unsigned mask = kFilterFeedbackTaps - 1; - const float recent = s.fb[(s.fbWrite - fbDelay_) & mask]; - const float older = s.fb[(s.fbWrite - fbDelay_ - 1u) & mask]; - return recent + fbDelayFrac_ * (older - recent); - } - - BiquadCoeffs coeffs_{}; - FilterMode mode_ = FilterMode::LowPass; - float fbAmount_ = 0.0f; - float fbDelayFrac_ = 0.0f; - unsigned fbDelay_ = 1; + SvfCoeffs coeffs_{}; + MorphMix mix_{}; + float driveDepth_ = 0.0f; State state_[kMaxChannels]{}; }; diff --git a/tests/test_filter.cpp b/tests/test_filter.cpp index c8914ec..839525d 100644 --- a/tests/test_filter.cpp +++ b/tests/test_filter.cpp @@ -1,9 +1,11 @@ -// Standalone tests for the per-voice filter — no VST3, no REAPER, no framework. Same fast -// assert loop as the sibling pure tests. The coefficient pins are literals so a refactor that -// changes the DSP fails loudly; they are cross-checked in-test against a textbook RBJ -// derivation (std::cos/std::sin) that shares no code with the implementation. +// Standalone tests for the per-voice TPT/SVF filter — no VST3, no REAPER, no framework. Same +// fast assert loop as the sibling pure tests. The coefficient pins are literals so a refactor +// that changes the DSP fails loudly; they are cross-checked in-test against a derivation that +// shares no code with the implementation, and the responses against the analog 2-pole prototype +// evaluated at the bilinear-warped frequency. #include "../src/core/instrument/engine/filter/filter_coeffs.h" +#include "../src/core/instrument/engine/filter/filter_morph.h" #include "../src/core/instrument/engine/filter/filter_params.h" #include "../src/core/instrument/engine/filter/filter_saturate.h" #include "../src/core/instrument/engine/filter/voice_filter.h" @@ -25,8 +27,59 @@ static int g_fail = 0; static constexpr double kPi = 3.14159265358979323846; +// Morph positions of the three pure taps. +static constexpr float kHighPass = 0.0f; +static constexpr float kBandPass = 0.5f; +static constexpr float kLowPass = 1.0f; + +// The rates the invariance claims are made over. +static const double kRates[] = {44100.0, 48000.0, 88200.0, 96000.0, 192000.0}; +static constexpr int kRateCount = 5; + +// The measurement pass's bar, and the bar the rewrite exists to hold: peak and passband agree +// with the analytic target to better than this at every rate, level, and morph position. +static constexpr double kAgreement = 0.004; + // --------------------------------------------------------------------------- -// Cutoff mapping +// Independent references +// --------------------------------------------------------------------------- + +// The analog 2-pole prototype |H(jW)| evaluated at the bilinear-warped frequency. The TPT maps +// the digital frequency onto the prototype EXACTLY at the prewarped corner, so this is the exact +// digital magnitude — derived from the continuous-time prototype and the transform rather than +// from anything filter_coeffs computes. +static double analyticMag(float morph, double freq, double fc, double q, double sr) { + const double w = std::tan(kPi * freq / sr) / std::tan(kPi * fc / sr); + const double dRe = 1.0 - w * w, dIm = w / q; + const double den = std::sqrt(dRe * dRe + dIm * dIm); + if (morph == kHighPass) return w * w / den; + if (morph == kBandPass) return w / den; + return 1.0 / den; +} + +// Steady-state gain of the running filter at one frequency. Windows are wall-clock, not sample +// counts, so every rate integrates the same amount of signal. +static double measuredGain(const FilterSettings& fs, double sr, double freq, double amp = 0.25, + double settleSec = 0.15, double measureSec = 0.10) { + VoiceFilter f; + f.prepare(fs, sr); + f.reset(); + const int settle = static_cast(sr * settleSec); + const int measure = static_cast(sr * measureSec); + double sumSq = 0.0; + for (int i = 0; i < settle + measure; ++i) { + const float y = f.process(0, static_cast(amp * std::sin(2.0 * kPi * freq * i / sr))); + if (i >= settle) sumSq += static_cast(y) * y; + } + return std::sqrt(sumSq / measure) / (amp / std::sqrt(2.0)); +} + +static FilterSettings at(double fcHz, float res, float morph, float drive = 0.0f) { + return {filterNormFromCutoffHz(static_cast(fcHz)), res, morph, drive}; +} + +// --------------------------------------------------------------------------- +// Control mappings (carried over — the cutoff and Q laws are unchanged) // --------------------------------------------------------------------------- static void testCutoffMapsThreeDecadesLogarithmically() { @@ -51,16 +104,10 @@ static void testCutoffNormRoundTrips() { CHECK_NEAR(filterNormFromCutoffHz(filterCutoffHzFromNorm(n)), n, 1e-6); } CHECK_NEAR(filterNormFromCutoffHz(200.0f), 1.0 / 3.0, 1e-6); - CHECK_NEAR(filterNormFromCutoffHz(2000.0f), 2.0 / 3.0, 1e-6); CHECK(filterNormFromCutoffHz(1.0f) == 0.0f); - CHECK(filterNormFromCutoffHz(0.0f) == 0.0f); CHECK(filterNormFromCutoffHz(48000.0f) == 1.0f); } -// --------------------------------------------------------------------------- -// Q mapping -// --------------------------------------------------------------------------- - static void testQSpansPointOneToTenWithRootTwoAtCenter() { CHECK_NEAR(filterQFromNorm(0.0f), 0.1, 1e-6); CHECK_NEAR(filterQFromNorm(0.5f), std::sqrt(2.0), 1e-5); @@ -88,327 +135,127 @@ static void testQNormRoundTrips() { CHECK(filterNormFromQ(1000.0f) == 1.0f); } -// --------------------------------------------------------------------------- -// Coefficients — pinned literals plus an independent textbook derivation -// --------------------------------------------------------------------------- +static void testDriveDepthIsZeroAtRestAndRisesMonotonically() { + // Exactly zero, not nearly: the limiter is the identity only at depth 0. + CHECK(filterDriveDepthFromNorm(0.0f) == 0.0f); + CHECK(filterDriveDepthFromNorm(-1.0f) == 0.0f); + CHECK_NEAR(filterDriveDepthFromNorm(1.0f), kFilterDriveDepthMax, 1e-6); + CHECK_NEAR(filterDriveDepthFromNorm(2.0f), kFilterDriveDepthMax, 1e-6); -// Textbook RBJ Audio EQ Cookbook, computed straight from cos(w0)/sin(w0). Shares no code with -// filter_coeffs, which reaches the same numbers through the tan half-angle substitution. -static void rbjReference(bool highPass, double fc, double q, double sr, double out[5]) { - const double w0 = 2.0 * kPi * fc / sr; - const double c = std::cos(w0); - const double s = std::sin(w0); - const double alpha = s / (2.0 * q); - const double a0 = 1.0 + alpha; - const double n = highPass ? (1.0 + c) : (1.0 - c); - out[0] = n / 2.0 / a0; // b0 - out[1] = (highPass ? -n : n) / a0; // b1 - out[2] = n / 2.0 / a0; // b2 - out[3] = -2.0 * c / a0; // a1 - out[4] = (1.0 - alpha) / a0; // a2 + float prev = -1.0f; + for (int i = 0; i <= 100; ++i) { + const float d = filterDriveDepthFromNorm(static_cast(i) / 100.0f); + CHECK(d > prev); + prev = d; + } } -static void testCoefficientsMatchPinnedRbjValues() { - const double sr = 48000.0, fc = 1000.0, q = std::sqrt(2.0); +// --------------------------------------------------------------------------- +// SVF coefficients — pinned literals plus an independent derivation +// --------------------------------------------------------------------------- - const BiquadCoeffs lp = biquadCoeffs(FilterMode::LowPass, static_cast(fc), - static_cast(q), sr); - const BiquadCoeffs hp = biquadCoeffs(FilterMode::HighPass, static_cast(fc), - static_cast(q), sr); +static void testSvfCoefficientsMatchPinnedValues() { + const double sr = 48000.0, fc = 1000.0, q = std::sqrt(2.0); + const SvfCoeffs c = svfCoeffs(static_cast(fc), static_cast(q), sr); // Pinned literals: change the math and these fail. - CHECK_NEAR(lp.b0, 0.0040888771, 2e-6); - CHECK_NEAR(lp.b1, 0.0081777542, 2e-6); - CHECK_NEAR(lp.b2, 0.0040888771, 2e-6); - CHECK_NEAR(lp.a1, -1.8954199076, 2e-6); - CHECK_NEAR(lp.a2, 0.9117754318, 2e-6); + CHECK_NEAR(c.g, 0.0655434653, 2e-9); + CHECK_NEAR(c.k, 0.7071067691, 2e-9); + CHECK_NEAR(c.a1, 0.9517988563, 2e-9); + CHECK_NEAR(c.a2, 0.0623841919, 2e-9); + CHECK_NEAR(c.a3, 0.0040888758, 2e-9); - CHECK_NEAR(hp.b0, 0.9517988338, 2e-6); - CHECK_NEAR(hp.b1, -1.9035976676, 2e-6); - CHECK_NEAR(hp.b2, 0.9517988338, 2e-6); - CHECK_NEAR(hp.a1, -1.8954199076, 2e-6); - CHECK_NEAR(hp.a2, 0.9117754318, 2e-6); - - // Independent derivation — proves the pinned literals are RBJ and not just "what we emit". - double ref[5]; - rbjReference(false, fc, q, sr, ref); - CHECK_NEAR(lp.b0, ref[0], 1e-6); - CHECK_NEAR(lp.b1, ref[1], 1e-6); - CHECK_NEAR(lp.b2, ref[2], 1e-6); - CHECK_NEAR(lp.a1, ref[3], 1e-6); - CHECK_NEAR(lp.a2, ref[4], 1e-6); - - rbjReference(true, fc, q, sr, ref); - CHECK_NEAR(hp.b0, ref[0], 1e-6); - CHECK_NEAR(hp.b1, ref[1], 1e-6); - CHECK_NEAR(hp.b2, ref[2], 1e-6); - CHECK_NEAR(hp.a1, ref[3], 1e-6); - CHECK_NEAR(hp.a2, ref[4], 1e-6); + // Independent derivation — proves the pins are the TPT solve and not just "what we emit". + const double g = std::tan(kPi * fc / sr); + const double k = 1.0 / q; + const double denom = 1.0 + g * g + g * k; // written out rather than factored as g*(g+k) + CHECK_NEAR(c.g, g, 1e-7); + CHECK_NEAR(c.k, k, 1e-7); + CHECK_NEAR(c.a1, 1.0 / denom, 1e-7); + CHECK_NEAR(c.a2, g / denom, 1e-7); + CHECK_NEAR(c.a3, g * g / denom, 1e-7); } -static void testCoefficientsTrackSampleRateAndClampBelowNyquist() { - // Same fc at a different rate must give the RBJ answer for THAT rate, not a cached one. - double ref[5]; - rbjReference(false, 1000.0, 2.0, 44100.0, ref); - const BiquadCoeffs at441 = biquadCoeffs(FilterMode::LowPass, 1000.0f, 2.0f, 44100.0); - CHECK_NEAR(at441.a1, ref[3], 1e-6); - CHECK_NEAR(at441.a2, ref[4], 1e-6); +static void testTheSampleRateEntersOnlyThroughG() { + // k and the cutoff mapping are rate-free; only g moves with the rate. A reference rate + // creeping back into the module would break this. + const SvfCoeffs a = svfCoeffs(1000.0f, 2.0f, 48000.0); + const SvfCoeffs b = svfCoeffs(1000.0f, 2.0f, 96000.0); + CHECK(a.k == b.k); + CHECK(a.g != b.g); + CHECK_NEAR(b.g, std::tan(kPi * 1000.0 / 96000.0), 1e-7); // Requesting above 0.48*sr clamps rather than diverging through tan(). - const BiquadCoeffs clamped = biquadCoeffs(FilterMode::LowPass, 20000.0f, 1.0f, 32000.0); - rbjReference(false, 0.48 * 32000.0, 1.0, 32000.0, ref); - CHECK_NEAR(clamped.b0, ref[0], 1e-6); - CHECK(std::isfinite(clamped.a1) && std::isfinite(clamped.a2)); + const SvfCoeffs clamped = svfCoeffs(20000.0f, 1.0f, 32000.0); + CHECK_NEAR(clamped.g, std::tan(kPi * 0.48), 1e-5); + CHECK(std::isfinite(clamped.a1) && std::isfinite(clamped.a3)); - // A non-positive rate passes through instead of inventing 44.1k. - const BiquadCoeffs bypass = biquadCoeffs(FilterMode::LowPass, 1000.0f, 1.0f, 0.0); - CHECK(bypass.b0 == 1.0f && bypass.b1 == 0.0f && bypass.b2 == 0.0f); - CHECK(bypass.a1 == 0.0f && bypass.a2 == 0.0f); + // A non-positive rate yields g == 0 instead of inventing 44.1k. + CHECK(svfCoeffs(1000.0f, 1.0f, 0.0).g == 0.0f); + CHECK(svfCoeffs(1000.0f, 1.0f, -48000.0).g == 0.0f); } -// DC gain of a lowpass and Nyquist gain of a highpass are both exactly unity — an independent -// structural check on the coefficient set that a sign slip would break. -static void testPassbandGainIsUnity() { - for (double q : {0.1, std::sqrt(2.0), 10.0}) { - const BiquadCoeffs lp = - biquadCoeffs(FilterMode::LowPass, 1000.0f, static_cast(q), 48000.0); - CHECK_NEAR((lp.b0 + lp.b1 + lp.b2) / (1.0 + lp.a1 + lp.a2), 1.0, 1e-4); - - const BiquadCoeffs hp = - biquadCoeffs(FilterMode::HighPass, 1000.0f, static_cast(q), 48000.0); - CHECK_NEAR((hp.b0 - hp.b1 + hp.b2) / (1.0 - hp.a1 + hp.a2), 1.0, 1e-4); +// An invalid rate must pass the signal, not silence the instrument, whatever the morph asks for. +static void testNonPositiveRatePassesSignalThroughAtEveryMorph() { + for (float morph : {kHighPass, kBandPass, kLowPass}) { + VoiceFilter f; + f.prepare({0.5f, 0.5f, morph, 0.0f}, 0.0); + f.reset(); + for (int i = 0; i < 64; ++i) { + const float x = static_cast(std::sin(0.1 * i)); + CHECK(f.process(0, x) == x); + } } } // --------------------------------------------------------------------------- -// Resonance +// Morph // --------------------------------------------------------------------------- -// |H(e^jw)| for y = b0*x + b1*x1 + b2*x2 - a1*y1 - a2*y2. -static double magnitudeAt(const BiquadCoeffs& c, double freqHz, double sr) { - const double w = 2.0 * kPi * freqHz / sr; - const double nRe = c.b0 + c.b1 * std::cos(w) + c.b2 * std::cos(2 * w); - const double nIm = -(c.b1 * std::sin(w) + c.b2 * std::sin(2 * w)); - const double dRe = 1.0 + c.a1 * std::cos(w) + c.a2 * std::cos(2 * w); - const double dIm = -(c.a1 * std::sin(w) + c.a2 * std::sin(2 * w)); - return std::sqrt(nRe * nRe + nIm * nIm) / std::sqrt(dRe * dRe + dIm * dIm); +// The endpoints are pure taps EXACTLY, not to within a rounding of cos/sin. Asserted on the +// folded mix, where "pure" is an exact statement about three floats. +static void testMorphEndpointMixesAreExactlyPureTaps() { + const float k = 1.0f / filterQFromNorm(0.5f); + + const MorphMix hp = morphMix(morphWeights(kHighPass), k); + CHECK(hp.m0 == 1.0f && hp.m1 == -k && hp.m2 == -1.0f); // v0 - k*v1 - v2 + + const MorphMix bp = morphMix(morphWeights(kBandPass), k); + CHECK(bp.m0 == 0.0f && bp.m1 == 1.0f && bp.m2 == 0.0f); // v1 + + const MorphMix lp = morphMix(morphWeights(kLowPass), k); + CHECK(lp.m0 == 0.0f && lp.m1 == 0.0f && lp.m2 == 1.0f); // v2 + + // Out-of-range clamps to the endpoints rather than extrapolating. + CHECK(morphWeights(-1.0f).hp == 1.0f); + CHECK(morphWeights(2.0f).lp == 1.0f); } -static void testHighQPeaksAtCutoffInBothModes() { +// HP and LP never carry weight at the same time. That is what keeps the centre a band-pass +// instead of the Oberheim SEM's notch: the two are antiphase at the corner and would cancel. +static void testMorphNeverBlendsHighAgainstLowPass() { + for (int i = 0; i <= 200; ++i) { + const MorphWeights w = morphWeights(static_cast(i) / 200.0f); + CHECK(w.hp == 0.0f || w.lp == 0.0f); + CHECK(w.hp >= 0.0f && w.bp >= 0.0f && w.lp >= 0.0f); + // Equal power: the active pair sums in quadrature to unity. + CHECK_NEAR(w.hp * w.hp + w.bp * w.bp + w.lp * w.lp, 1.0, 1e-6); + } +} + +static void testMorphEndpointsMatchTheAnalyticTwoPoleTargets() { const double sr = 48000.0, fc = 1000.0; - const float qHigh = filterQFromNorm(1.0f); // 10 - const float qLow = filterQFromNorm(0.0f); // 0.1 - - for (FilterMode mode : {FilterMode::LowPass, FilterMode::HighPass}) { - const BiquadCoeffs hi = biquadCoeffs(mode, static_cast(fc), qHigh, sr); - - // Scan a log grid and locate the maximum. - double peakMag = 0.0, peakFreq = 0.0; - for (int i = 0; i <= 600; ++i) { - const double f = 20.0 * std::pow(1000.0, static_cast(i) / 600.0); - const double m = magnitudeAt(hi, f, sr); - if (m > peakMag) { peakMag = m; peakFreq = f; } - } - // The peak is at the cutoff, not at a band edge — within a quarter octave. - CHECK(peakFreq > fc / 1.19 && peakFreq < fc * 1.19); - // An RBJ 2-pole peaks at Q; assert most of that emphasis is really there. - CHECK(peakMag > 8.0); - - // The emphasis is relative to the passband, not just a loud filter. - const double passband = magnitudeAt(hi, mode == FilterMode::LowPass ? 20.0 : 20000.0, sr); - CHECK_NEAR(passband, 1.0, 0.05); - CHECK(peakMag / passband > 8.0); - - // At the bottom of the Q control there is no peak at all: the response is monotone - // over the band, so high Q is genuinely doing the work. - const BiquadCoeffs lo = biquadCoeffs(mode, static_cast(fc), qLow, sr); - double prev = magnitudeAt(lo, 20.0, sr); - bool monotone = true; - for (int i = 1; i <= 600; ++i) { - const double f = 20.0 * std::pow(1000.0, static_cast(i) / 600.0); - const double m = magnitudeAt(lo, f, sr); - if (mode == FilterMode::LowPass ? (m > prev + 1e-9) : (m < prev - 1e-9)) { - monotone = false; - } - prev = m; - } - CHECK(monotone); - } -} - -// Drive real sines through VoiceFilter and measure steady-state RMS. Unlike the analytic -// check above this also exercises the high-pass input-feedback path, which is outside the -// coefficient transfer function. The settle and measure windows are wall-clock, not sample -// counts, so every rate integrates the same amount of signal. -static double measuredRms(FilterMode mode, float cutoffNorm, float resNorm, double freqHz, - double sr, double amp = 1.0) { - VoiceFilter f; - f.prepare({mode, cutoffNorm, resNorm}, sr); - f.reset(); - - const int settle = static_cast(sr * 0.15); - const int measure = static_cast(sr * 0.10); - double sumSq = 0.0; - for (int i = 0; i < settle + measure; ++i) { - const float x = static_cast(amp * std::sin(2.0 * kPi * freqHz * i / sr)); - const float y = f.process(0, x); - if (i >= settle) sumSq += static_cast(y) * y; - } - return std::sqrt(sumSq / measure); -} - -static void testMeasuredResponsePeaksAtCutoffInBothModes() { - const double sr = 48000.0; - const float cutoffNorm = filterNormFromCutoffHz(1000.0f); - - for (FilterMode mode : {FilterMode::LowPass, FilterMode::HighPass}) { - double peakRms = 0.0, peakFreq = 0.0; - for (int i = 0; i <= 40; ++i) { - const double f = 100.0 * std::pow(100.0, static_cast(i) / 40.0); - const double r = measuredRms(mode, cutoffNorm, 1.0f, f, sr); - if (r > peakRms) { peakRms = r; peakFreq = f; } - } - CHECK(peakFreq > 1000.0 / 1.3 && peakFreq < 1000.0 * 1.3); - - const double passband = - measuredRms(mode, cutoffNorm, 1.0f, mode == FilterMode::LowPass ? 100.0 : 10000.0, sr); - CHECK(peakRms / passband > 3.0); - - // Same measurement at the bottom of the resonance control shows no such emphasis. - const double flatAtCutoff = measuredRms(mode, cutoffNorm, 0.0f, 1000.0, sr); - const double flatPassband = - measuredRms(mode, cutoffNorm, 0.0f, mode == FilterMode::LowPass ? 100.0 : 10000.0, sr); - CHECK(flatAtCutoff / flatPassband < 1.0); - } -} - -// --------------------------------------------------------------------------- -// Sample-rate invariance -// --------------------------------------------------------------------------- - -// The rates the invariance claim is made over. 88.2k is deliberately included: it is the rate -// whose calibrated feedback delay lands between two whole taps, so it is the one the -// interpolating read has to earn. -static const double kRates[] = {44100.0, 48000.0, 88200.0, 96000.0, 192000.0}; -static constexpr int kRateCount = 5; -static constexpr int kRef48k = 1; // index of the reference rate within kRates - -// Resonant emphasis: level at the cutoff over the passband level. Measured at the requested -// cutoff rather than at the scanned peak so no frequency-grid quantization leaks into the -// comparison. The passband reference is the same frequency at every rate, or the ratio would -// compare a different measurement at each rate -- and it must stay well clear of the LOWEST -// Nyquist tested, since a high-pass reference near 44.1k's band edge measures the bilinear -// warping rather than the resonance. -static double emphasisAtCutoff(FilterMode mode, double fcHz, float resNorm, double sr) { - const float cn = filterNormFromCutoffHz(static_cast(fcHz)); - const double refHz = (mode == FilterMode::LowPass) ? fcHz / 8.0 : fcHz * 8.0; - return measuredRms(mode, cn, resNorm, fcHz, sr, 0.25) / - measuredRms(mode, cn, resNorm, refHz, sr, 0.25); -} - -// The feedback loop's contribution alone: the measured closed-loop level at a frequency over the -// level the bare coefficients predict there. Dividing the coefficient response out removes the -// bilinear discretization difference between rates -- which is real, correct, and not something -// a feedback fix can or should touch -- leaving exactly the loop under audit. In low-pass mode -// there is no loop, so this is identically 1 at every rate. -static double feedbackContribution(FilterMode mode, double fcHz, float resNorm, double sr) { - const float cn = filterNormFromCutoffHz(static_cast(fcHz)); - VoiceFilter f; - f.prepare({mode, cn, resNorm}, sr); - const double openLoopRms = magnitudeAt(f.coeffs(), fcHz, sr) * 0.25 / std::sqrt(2.0); - return measuredRms(mode, cn, resNorm, fcHz, sr, 0.25) / openLoopRms; -} - -// Where the response actually peaks, as a multiple of the requested cutoff. -static double peakOverCutoff(FilterMode mode, double fcHz, float resNorm, double sr) { - const float cn = filterNormFromCutoffHz(static_cast(fcHz)); - double peak = 0.0, peakF = 0.0; - for (int i = 0; i <= 12; ++i) { - const double f = fcHz * std::pow(2.0, -0.5 + i / 12.0); - const double r = measuredRms(mode, cn, resNorm, f, sr, 0.25); - if (r > peak) { peak = r; peakF = f; } - } - return peakF / fcHz; -} - -// The defect these pin: the high-pass feedback loop closes once per sample, so while its tap was -// the immediately previous output the loop's phase at the cutoff -- and with it the resonant -// emphasis -- scaled with the sample rate. Against that one-sample tap, emphasisAtCutoff for -// fc=1 kHz, res=1.0 measured 5.46 at 48k rising monotonically to 6.04 at 192k (10.5%), and -// feedbackContribution for fc=4 kHz, res=1.0 ran 0.443 at 48k against 0.506 at 192k (14.4%). -// Both now sit inside the bounds below. -// -// The two tolerances split on the reference rate, and the split is load-bearing rather than -// convenient. At or above 48k the calibrated interval is at least one sample, so the tap -// reproduces it and only the bilinear discretization difference remains. Below it -- 44.1k -- -// one sample is ALREADY longer than the interval, so the delay cannot be shortened to match -// without a sub-sample delay the loop cannot contain; 44.1k is left exactly where it has always -// been, which is up to 6% off 48k at the top of the cutoff range. -static constexpr double kAtOrAboveReferenceTolerance = 0.02; -static constexpr double kBelowReferenceTolerance = 0.08; - -static void checkInvariant(const char* what, FilterMode mode, double fcHz, float resNorm, - double (*measure)(FilterMode, double, float, double)) { - const double reference = measure(mode, fcHz, resNorm, kRates[kRef48k]); - for (int r = 0; r < kRateCount; ++r) { - const double v = measure(mode, fcHz, resNorm, kRates[r]); - const double deviation = std::fabs(v - reference) / reference; - const double tolerance = kRates[r] >= kRates[kRef48k] ? kAtOrAboveReferenceTolerance - : kBelowReferenceTolerance; - if (!(deviation <= tolerance)) { - std::printf("FAIL line %d: %s %s fc=%.0f res=%.2f at %.0f Hz: %.5f vs 48k %.5f " - "(%.2f%% > %.2f%%)\n", - __LINE__, what, mode == FilterMode::LowPass ? "LP" : "HP", fcHz, resNorm, - kRates[r], v, reference, deviation * 100.0, tolerance * 100.0); - ++g_fail; - } - } -} - -// End-to-end: the emphasis a listener hears, coefficients and feedback together. Held to cutoffs -// whose passband reference (8x the cutoff) stays well below 44.1k's band edge -- higher cutoffs -// are covered by the isolated test below, which does not need a passband reference at all. -static void testHighPassResonanceIsRateInvariant() { - for (float res : {0.2f, 0.5f, 1.0f}) { - checkInvariant("emphasis", FilterMode::HighPass, 250.0, res, emphasisAtCutoff); - checkInvariant("emphasis", FilterMode::HighPass, 1000.0, res, emphasisAtCutoff); - } -} - -// The low-pass has no feedback path, so it was already invariant. Pinning it is the control: it -// proves the measurement detects what it claims to, and it keeps a future feedback path on the -// low-pass from acquiring the same defect unnoticed. -static void testLowPassResonanceIsRateInvariant() { - for (float res : {0.2f, 0.5f, 1.0f}) { - checkInvariant("emphasis", FilterMode::LowPass, 250.0, res, emphasisAtCutoff); - checkInvariant("emphasis", FilterMode::LowPass, 1000.0, res, emphasisAtCutoff); - checkInvariant("emphasis", FilterMode::LowPass, 4000.0, res, emphasisAtCutoff); - } -} - -// The precise form of the same claim, with the discretization difference divided out, so it also -// holds at the top of the cutoff range where a passband reference cannot sit clear of 44.1k's -// band edge. -static void testFeedbackLoopContributionIsRateInvariant() { - for (float res : {0.2f, 0.5f, 1.0f}) { - for (double fc : {250.0, 1000.0, 4000.0}) { - checkInvariant("loop", FilterMode::HighPass, fc, res, feedbackContribution); - checkInvariant("loop", FilterMode::LowPass, fc, res, feedbackContribution); - } - } -} - -static void testResonantPeakTracksCutoffAtEveryRate() { - for (FilterMode mode : {FilterMode::LowPass, FilterMode::HighPass}) { - for (double fc : {250.0, 1000.0, 4000.0}) { - for (int r = 0; r < kRateCount; ++r) { - // At full resonance there is a real peak to find; a quarter octave either side - // of the requested cutoff is the same window the 48k-only test uses. - const double ratio = peakOverCutoff(mode, fc, 1.0f, kRates[r]); - if (!(ratio > 1.0 / 1.19 && ratio < 1.19)) { - std::printf("FAIL line %d: %s peak at %.3f x fc (fc=%.0f, sr=%.0f)\n", - __LINE__, mode == FilterMode::LowPass ? "LP" : "HP", ratio, fc, - kRates[r]); + for (float res : {0.0f, 0.5f, 1.0f}) { + const double q = filterQFromNorm(res); + for (float morph : {kHighPass, kBandPass, kLowPass}) { + for (double f : {125.0, 500.0, 1000.0, 2000.0, 8000.0}) { + const double got = measuredGain(at(fc, res, morph), sr, f); + const double want = analyticMag(morph, f, fc, q, sr); + if (!(std::fabs(got / want - 1.0) <= kAgreement)) { + std::printf("FAIL line %d: morph %.1f res %.1f at %.0f Hz: %.6f vs analytic " + "%.6f (%.3f%%)\n", + __LINE__, morph, res, f, got, want, + (got / want - 1.0) * 100.0); ++g_fail; } } @@ -416,116 +263,289 @@ static void testResonantPeakTracksCutoffAtEveryRate() { } } -// 48k is the rate the feedback constants were voiced at, and the rate Daniel's ear judgments -// were made against, so making the other rates match it must not move it. These literals were -// captured from the build BEFORE the fixed-time feedback tap landed; the tap resolves to -// exactly one sample at 48k, so they must reproduce bit-for-bit rather than merely closely. -static void testFortyEightKilohertzBehaviorIsUnchanged() { - struct Pin { - FilterMode mode; - double y1, y7, y31, y127, energy, sineRms; - }; - const Pin pins[2] = { - {FilterMode::LowPass, 0.016871979, 0.098936319, -0.084338546, -0.044524558, 0.652648822, - 1.767755710}, - {FilterMode::HighPass, -0.184770823, -0.082661532, 0.057580549, -0.008336116, 1.427662234, - 0.895141269}, - }; - - for (const Pin& p : pins) { - VoiceFilter f; - f.prepare({p.mode, filterNormFromCutoffHz(1000.0f), 1.0f}, 48000.0); - f.reset(); - double energy = 0.0; - for (int i = 0; i < 4096; ++i) { - const float y = f.process(0, i == 0 ? 1.0f : 0.0f); - energy += static_cast(y) * y; - if (i == 1) CHECK_NEAR(y, p.y1, 1e-7); - if (i == 7) CHECK_NEAR(y, p.y7, 1e-7); - if (i == 31) CHECK_NEAR(y, p.y31, 1e-7); - if (i == 127) CHECK_NEAR(y, p.y127, 1e-7); +// The reason the blend is equal-power rather than linear. At the corner the three taps are +// HP = jQ, BP = Q, LP = -jQ — adjacent taps in exact quadrature — so a cos/sin pair holds the +// corner magnitude at exactly Q the whole way across. A linear crossfade would sag to Q/sqrt(2) +// mid-leg, a 3 dB hole that would read as a defect rather than as character. +static void testCornerMagnitudeIsFlatAcrossTheWholeMorphSweep() { + const double sr = 48000.0, fc = 1000.0; + for (float res : {0.0f, 0.5f, 1.0f}) { + const double q = filterQFromNorm(res); + for (int i = 0; i <= 16; ++i) { + const float m = static_cast(i) / 16.0f; + const double got = measuredGain(at(fc, res, m), sr, fc); + if (!(std::fabs(got / q - 1.0) <= kAgreement)) { + std::printf("FAIL line %d: morph %.4f res %.1f corner gain %.6f, expected Q " + "%.6f (%.3f%%)\n", + __LINE__, m, res, got, q, (got / q - 1.0) * 100.0); + ++g_fail; + } } - CHECK_NEAR(energy, p.energy, 1e-7); - - VoiceFilter g; - g.prepare({p.mode, filterNormFromCutoffHz(1000.0f), 1.0f}, 48000.0); - g.reset(); - double sumSq = 0.0; - for (int i = 0; i < 28800; ++i) { - const float x = static_cast(0.25 * std::sin(2.0 * kPi * 1000.0 * i / 48000.0)); - const float y = g.process(0, x); - if (i >= 14400) sumSq += static_cast(y) * y; - } - CHECK_NEAR(std::sqrt(sumSq / 14400.0), p.sineRms, 1e-7); } } -// The tap is a fixed INTERVAL, so the sample offset it resolves to scales with the rate. Read -// out of the filter's behavior, not its internals: run an impulse through the high-pass and -// alongside it the bare difference equation on the SAME coefficients with no feedback at all. -// The tap reads y[n-D], and every earlier history slot is zero, so the first sample at which the -// two can possibly diverge is exactly D. Against the pre-fix one-sample tap this reports 1 at -// every rate; it must now report 1, 1, 1, 2, 4. -static void testFeedbackTapOffsetScalesWithSampleRate() { - const int expected[kRateCount] = {1, 1, 1, 2, 4}; - for (int r = 0; r < kRateCount; ++r) { - VoiceFilter f; - f.prepare({FilterMode::HighPass, filterNormFromCutoffHz(1000.0f), 1.0f}, kRates[r]); - f.reset(); - const BiquadCoeffs c = f.coeffs(); - - float x1 = 0.0f, x2 = 0.0f, y1 = 0.0f, y2 = 0.0f; - int firstDivergence = -1; - for (int i = 0; i < 64 && firstDivergence < 0; ++i) { - const float x = (i == 0) ? 1.0f : 0.0f; - const float actual = f.process(0, x); - const float noFeedback = c.b0 * x + c.b1 * x1 + c.b2 * x2 - c.a1 * y1 - c.a2 * y2; - x2 = x1; - x1 = x; - y2 = y1; - y1 = noFeedback; - if (actual != noFeedback) firstDivergence = i; +// Continuity as a control, not just at the corner: no step between adjacent morph positions at +// any fixed frequency. A coefficient switch at the centre — the thing an enum would have forced — +// shows up here as a jump. +static void testMorphSweepHasNoDiscontinuity() { + const double sr = 48000.0, fc = 1000.0; + constexpr int kSteps = 40; + for (float res : {0.0f, 0.5f, 1.0f}) { + for (double f : {250.0, 1000.0, 4000.0}) { + double prev = -1.0; + for (int i = 0; i <= kSteps; ++i) { + const float m = static_cast(i) / kSteps; + const double got = measuredGain(at(fc, res, m), sr, f); + if (prev >= 0.0) { + // Scaled by the response's own magnitude at this setting — the passband is + // unity and the corner is Q, so below Q=1 the passband is what a step has to + // be small against, not Q. + const double scale = std::fmax(1.0, filterQFromNorm(res)); + // One step is 1/40 of the travel; the steepest leg moves well under a tenth + // of that scale over one step (measured worst case is 0.03). + const double jump = std::fabs(got - prev) / scale; + if (!(jump < 0.1)) { + std::printf("FAIL line %d: morph %.4f res %.1f at %.0f Hz jumps %.4f\n", + __LINE__, m, res, f, jump); + ++g_fail; + } + } + prev = got; + } } - if (firstDivergence != expected[r]) { - std::printf("FAIL line %d: sr=%.0f feedback first reaches the output at sample %d, " - "expected %d\n", - __LINE__, kRates[r], firstDivergence, expected[r]); + } +} + +// --------------------------------------------------------------------------- +// Drive +// --------------------------------------------------------------------------- + +// The hard acceptance criterion, in its strongest form: at drive 0 the kernel is BIT-IDENTICAL +// to the same kernel with the limiter deleted. softLimit(x, 0) is x / sqrt(1) == x exactly, so +// this holds by algebra rather than by tolerance. +static void testDriveZeroIsBitIdenticalToTheLinearKernel() { + for (float morph : {kHighPass, kBandPass, kLowPass}) { + VoiceFilter f; + f.prepare(at(1000.0, 1.0f, morph, 0.0f), 48000.0); + f.reset(); + const SvfCoeffs c = f.coeffs(); + const MorphMix mix = f.mix(); + + float ic1 = 0.0f, ic2 = 0.0f; + unsigned rng = 0x13579bdfu; + for (int i = 0; i < 4096; ++i) { + rng = rng * 1664525u + 1013904223u; + const float x = static_cast(static_cast(rng >> 9) - (1 << 22)) / + static_cast(1 << 22); + + const float v3 = x - ic2; + const float v1 = c.a1 * ic1 + c.a2 * v3; + const float v2 = ic2 + c.a2 * ic1 + c.a3 * v3; + ic1 = 2.0f * v1 - ic1; // no limiter at all + ic2 = 2.0f * v2 - ic2; + if (ic1 > -kFilterDenormalFloor && ic1 < kFilterDenormalFloor && + ic2 > -kFilterDenormalFloor && ic2 < kFilterDenormalFloor) { + ic1 = 0.0f; + ic2 = 0.0f; + } + CHECK(f.process(0, x) == mix.m0 * x + mix.m1 * v1 + mix.m2 * v2); + } + } +} + +// The complaint the rewrite answers: resonance must not track how hard the sample hits the +// filter unless the user asked for it. At drive 0 the response is identical over a 1000:1 level +// range; the tap this replaced moved by 14% over the same span. +static void testDriveZeroResponseIsLevelInvariant() { + const double sr = 48000.0, fc = 1000.0; + for (float morph : {kHighPass, kBandPass, kLowPass}) { + const double q = filterQFromNorm(1.0f); + const double want = analyticMag(morph, fc, fc, q, sr); + for (double amp : {0.001, 0.01, 0.1, 1.0}) { + const double got = measuredGain(at(fc, 1.0f, morph), sr, fc, amp); + if (!(std::fabs(got / want - 1.0) <= kAgreement)) { + std::printf("FAIL line %d: morph %.1f amp %g gain %.6f vs analytic %.6f " + "(%.3f%%)\n", + __LINE__, morph, amp, got, want, (got / want - 1.0) * 100.0); + ++g_fail; + } + } + } +} + +// Drive is bounded by construction, not by tuning: softLimit is a contraction, so the state +// update can only ever shrink the state and the filter cannot gain energy from it. This sweeps +// the corners that would expose a tuned margin instead. +static void testFullDriveStaysBoundedAtEveryCutoffResonanceAndRate() { + unsigned rng = 0x2468aceu; + auto noise = [&rng]() { + rng = rng * 1664525u + 1013904223u; + return static_cast(static_cast(rng >> 9) - (1 << 22)) / + static_cast(1 << 22); + }; + + for (int r = 0; r < kRateCount; ++r) { + const double sr = kRates[r]; + for (int ci = 0; ci <= 8; ++ci) { + for (int mi = 0; mi <= 4; ++mi) { + for (float res : {0.0f, 0.5f, 1.0f}) { + VoiceFilter f; + f.prepare({ci / 8.0f, res, mi / 4.0f, 1.0f}, sr); + f.reset(); + for (int i = 0; i < 4000; ++i) { + const float y = f.process(0, noise()); + if (!std::isfinite(y) || std::fabs(y) > 8.0f) { + std::printf("FAIL line %d: sr=%.0f cutoff=%.2f morph=%.2f res=%.1f " + "full drive produced %g\n", + __LINE__, sr, ci / 8.0, mi / 4.0, res, y); + ++g_fail; + return; + } + } + } + } + } + } +} + +// Full drive at full resonance with no input must still go quiet. A nonlinearity in the loop is +// exactly where a self-oscillator would hide, and softLimit's sub-unit slope is what forbids it. +static void testFullDriveDoesNotSelfOscillate() { + for (int r = 0; r < kRateCount; ++r) { + const double sr = kRates[r]; + for (float morph : {kHighPass, kBandPass, kLowPass}) { + VoiceFilter f; + f.prepare(at(1000.0, 1.0f, morph, 1.0f), sr); + f.reset(); + const int excite = static_cast(sr * 0.01); + for (int i = 0; i < excite; ++i) { + f.process(0, static_cast(std::sin(2.0 * kPi * 1000.0 * i / sr))); + } + for (int i = 0; i < static_cast(sr * 0.5); ++i) f.process(0, 0.0f); + CHECK(f.isSilent()); + } + } +} + +// Drive has to actually do something at the top of its travel, and do it monotonically — the +// brief's "extreme, not politely warm". Measured at the corner, where the resonance state is +// what the limiter sees. +static void testDriveCompressesTheResonantPeakMonotonically() { + const double sr = 48000.0, fc = 1000.0; + double prev = 1e30; + for (int i = 0; i <= 8; ++i) { + const double got = measuredGain(at(fc, 1.0f, kLowPass, i / 8.0f), sr, fc, 1.0); + CHECK(got < prev); + prev = got; + } + // Full drive against no drive: a large, unmistakable reduction of the resonant peak. + CHECK(prev < 0.5 * filterQFromNorm(1.0f)); + + // And the passband is left alone at every drive setting — drive colours the resonance, it + // is not a distortion box in series with the signal. + for (int i = 0; i <= 4; ++i) { + CHECK_NEAR(measuredGain(at(fc, 1.0f, kLowPass, i / 4.0f), sr, 100.0, 1.0), 1.0, 0.05); + } +} + +static void testSoftLimitIsOddMonotoneBoundedAndExactAtZeroDepth() { + for (double x : {-3.0, -0.5, 0.0, 1e-9, 0.25, 7.0}) { + // Depth 0 is the identity by algebra, so drive 0 needs no special case on the hot path. + CHECK(softLimit(static_cast(x), 0.0f) == static_cast(x)); + } + CHECK_NEAR(softLimit(1.5f, 2.0f), -softLimit(-1.5f, 2.0f), 1e-9); + + for (float depth : {0.5f, 4.0f, 64.0f}) { + // The two properties the stability argument rests on, over the whole excursion range a + // resonating state can reach. Monotonicity is NOT asserted here: far past the knee the + // curve is asymptotically flat, so the true increment between adjacent samples falls + // below float epsilon and rounding can walk it backwards by an ulp. + for (int i = -400; i <= 400; ++i) { + const float x = static_cast(i) * 0.05f; + const float y = softLimit(x, depth); + CHECK(std::fabs(y) <= std::fabs(x)); // a contraction — the stability argument + CHECK(std::fabs(y) < 1.0f / depth + 1e-6f); // bounded by the knee + } + // Strictly increasing across the knee, which is where the shaping actually happens. + const float knee = 1.0f / depth; + float prev = -1e30f; + for (int i = -20; i <= 20; ++i) { + const float y = softLimit(static_cast(i) * 0.1f * knee, depth); + CHECK(y > prev); + prev = y; + } + } +} + +// --------------------------------------------------------------------------- +// Sample-rate invariance +// --------------------------------------------------------------------------- + +// The rate must enter only through g = tan(pi*fc/sr), so the response at a given cutoff and Q is +// the same filter at every rate. The retired feedback tap made this false: it closed the loop +// once per SAMPLE, so emphasis ran 5.02 at 48k against 8.52 at 192k. +static void testResponseIsRateInvariantAtEveryMorph() { + for (float morph : {kHighPass, kBandPass, kLowPass}) { + for (float res : {0.2f, 0.5f, 1.0f}) { + const double q = filterQFromNorm(res); + for (double fc : {250.0, 1000.0, 4000.0}) { + for (int r = 0; r < kRateCount; ++r) { + const double got = measuredGain(at(fc, res, morph), kRates[r], fc); + const double want = analyticMag(morph, fc, fc, q, kRates[r]); + if (!(std::fabs(got / want - 1.0) <= kAgreement)) { + std::printf("FAIL line %d: morph %.1f res %.1f fc %.0f at %.0f Hz: %.6f " + "vs analytic %.6f (%.3f%%)\n", + __LINE__, morph, res, fc, kRates[r], got, want, + (got / want - 1.0) * 100.0); + ++g_fail; + } + } + } + } + } +} + +// The conditioning corner: fc/sr ~ 1e-4. Float32 Direct Form I encoded pole proximity in +// a1 -> -2, a2 -> +1 and cancelled them every sample, costing ~17 bits and putting the measured +// peak 15% LOW at 20 Hz / 192 kHz. TPT encodes the same proximity in a1's small deviation from +// 1, which float resolves; this pins that the defect is gone at every rate. +static void testLowCutoffHighRateCornerHoldsTheAnalyticPeak() { + const double q = filterQFromNorm(1.0f); + // A 2-pole low-pass peaks at W = sqrt(1 - 1/(2Q^2)), where |H| = Q / sqrt(1 - 1/(4Q^2)). + const double wPeak = std::sqrt(1.0 - 1.0 / (2.0 * q * q)); + const double want = q / std::sqrt(1.0 - 1.0 / (4.0 * q * q)); + CHECK_NEAR(want, 10.012516, 1e-5); // the figure the measurement pass quoted + + for (int r = 0; r < kRateCount; ++r) { + const double sr = kRates[r]; + const double fPeak = sr / kPi * std::atan(wPeak * std::tan(kPi * 20.0 / sr)); + // Q=10 at 20 Hz rings for ~0.16 s, so the settle window has to be seconds, not samples. + const double got = measuredGain(at(20.0, 1.0f, kLowPass), sr, fPeak, 0.25, 3.0, 1.0); + if (!(std::fabs(got / want - 1.0) <= kAgreement)) { + std::printf("FAIL line %d: 20 Hz peak at %.0f Hz is %.6f vs analytic %.6f (%.3f%%)\n", + __LINE__, sr, got, want, (got / want - 1.0) * 100.0); ++g_fail; } } } -// The floor is load-bearing, not defensive: below 48k one sample is ALREADY longer than the -// calibrated interval, so the offset cannot shrink to match without a sub-sample delay the loop -// cannot contain -- it would be algebraic and uncomputable. A rate at or below the reference -// therefore keeps the firmware's single tap, and a non-positive rate lands on the same floor -// rather than on an invented rate. -static void testFeedbackTapNeverFallsBelowOneSample() { - for (double sr : {-48000.0, 0.0, 1000.0, 22050.0, 44100.0, 48000.0}) { - VoiceFilter f; - f.prepare({FilterMode::HighPass, filterNormFromCutoffHz(1000.0f), 1.0f}, sr); - f.reset(); - for (int i = 0; i < 512; ++i) CHECK(std::isfinite(f.process(0, i == 0 ? 1.0f : 0.0f))); - } -} - // --------------------------------------------------------------------------- -// Stability +// Stability, denormals, and state // --------------------------------------------------------------------------- static void testFullRangeCutoffSweepAtAudioRateStaysBounded() { - // Deterministic pseudo-noise; a fixed sine would miss the resonant frequency on most steps. unsigned rng = 0x13579bdfu; auto noise = [&rng]() { rng = rng * 1664525u + 1013904223u; - return static_cast(static_cast(rng >> 9) - (1 << 22)) / static_cast(1 << 22); + return static_cast(static_cast(rng >> 9) - (1 << 22)) / + static_cast(1 << 22); }; for (int r = 0; r < kRateCount; ++r) { const double sr = kRates[r]; - for (FilterMode mode : {FilterMode::LowPass, FilterMode::HighPass}) { - for (float res : {0.0f, 0.5f, 1.0f}) { - for (int direction = 0; direction < 2; ++direction) { + for (float morph : {kHighPass, kBandPass, kLowPass}) { + for (float res : {0.0f, 1.0f}) { + for (float drive : {0.0f, 1.0f}) { VoiceFilter f; f.reset(); // A fixed WALL-CLOCK sweep: the same cutoff travel per second at every rate, @@ -533,8 +553,7 @@ static void testFullRangeCutoffSweepAtAudioRateStaysBounded() { const int n = static_cast(sr * 0.25); for (int i = 0; i < n; ++i) { const float t = static_cast(i) / static_cast(n - 1); - // Per-sample coefficient update across the whole cutoff travel. - f.prepare({mode, direction == 0 ? t : 1.0f - t, res}, sr); + f.prepare({t, res, morph, drive}, sr); const float y = f.process(0, noise()); CHECK(std::isfinite(y)); CHECK(std::fabs(y) < 100.0f); @@ -546,142 +565,124 @@ static void testFullRangeCutoffSweepAtAudioRateStaysBounded() { } } -// The decay to the floor is a fixed WALL-CLOCK time (~0.21 s at these settings), not a fixed -// sample count -- so the budget has to scale with the rate. A fixed 20000-sample budget is itself -// a rate assumption: it is ample at 48k and expires mid-decay at 96k and above. +// The flush tests the ENVELOPE — both integrators — not one sample. ic1 and ic2 are in +// quadrature, so a resonator swings each through zero twice a cycle; flushing on a single one +// injects a step in phase with the resonance, which the resonance amplifies, and the filter +// limit-cycles at the floor forever instead of going quiet. Re-verified for TPT rather than +// assumed to carry over from the retired Direct Form I state. static void testStateFlushesToZeroWithoutStallingInDenormals() { for (int r = 0; r < kRateCount; ++r) { const double sr = kRates[r]; + // The decay to the floor is a fixed WALL-CLOCK time, so the budget scales with the rate. const int budget = static_cast(sr * 0.5); - for (FilterMode mode : {FilterMode::LowPass, FilterMode::HighPass}) { - VoiceFilter f; - f.prepare({mode, filterNormFromCutoffHz(1000.0f), 1.0f}, sr); - f.reset(); + for (float morph : {kHighPass, kBandPass, kLowPass}) { + for (float drive : {0.0f, 1.0f}) { + VoiceFilter f; + f.prepare(at(1000.0, 1.0f, morph, drive), sr); + f.reset(); - // Excite, then hard-cut to silence the way a released voice does. - const int excite = static_cast(sr * 0.01); - for (int i = 0; i < excite; ++i) { - f.process(0, 0.5f * static_cast(std::sin(2.0 * kPi * 1000.0 * i / sr))); - } + // Excite, then hard-cut to silence the way a released voice does. + const int excite = static_cast(sr * 0.01); + for (int i = 0; i < excite; ++i) { + f.process(0, 0.5f * static_cast(std::sin(2.0 * kPi * 1000.0 * i / sr))); + } - int subnormalSamples = 0; - int silentAt = -1; - for (int i = 0; i < budget; ++i) { - f.process(0, 0.0f); - const VoiceFilter::State& s = f.state(0); - bool subnormal = false; - for (float v : {s.x1, s.x2, s.y1, s.y2}) { - if (v != 0.0f && std::fabs(v) < FLT_MIN) subnormal = true; + int subnormalSamples = 0, silentAt = -1; + for (int i = 0; i < budget; ++i) { + f.process(0, 0.0f); + const VoiceFilter::State& s = f.state(0); + if ((s.ic1 != 0.0f && std::fabs(s.ic1) < FLT_MIN) || + (s.ic2 != 0.0f && std::fabs(s.ic2) < FLT_MIN)) { + ++subnormalSamples; + } + if (silentAt < 0 && f.isSilent()) silentAt = i; } - for (float v : s.fb) { - if (v != 0.0f && std::fabs(v) < FLT_MIN) subnormal = true; - } - if (subnormal) ++subnormalSamples; - if (silentAt < 0 && f.isSilent()) silentAt = i; + // Without the flush the state grinds down through the subnormal range for + // thousands of samples; a stray sample or two at a zero crossing is not a stall. + CHECK(subnormalSamples <= 2); + CHECK(silentAt >= 0); + CHECK(silentAt < budget); + // And it stays silent — a flush that perturbs the loop would re-excite it. + for (int i = 0; i < 1000; ++i) CHECK(f.process(0, 0.0f) == 0.0f); + CHECK(f.isSilent()); } - // Without the flush the state grinds down through the subnormal range for thousands - // of samples; a stray sample or two at a zero crossing is not a stall. The feedback - // tap line holds copies of the flushed y, so it drains behind it rather than feeding - // subnormals back into the loop. - CHECK(subnormalSamples <= 2); - CHECK(silentAt >= 0); - CHECK(silentAt < budget); - // And it stays silent — a flush that perturbs the feedback loop would re-excite it. - for (int i = 0; i < 1000; ++i) CHECK(f.process(0, 0.0f) == 0.0f); - CHECK(f.isSilent()); } } } -// A high-pass has an exact DC null (b1 == -2*b0 bit-exactly), so under sustained DC the -// recursive y decays to zero while x1/x2 sit pinned at the DC level -- the case the zero-input -// test above cannot see, since there x1/x2 are zero anyway. A flush that clears x1/x2 along -// with y1/y2 discards that pinned history; the next sample then recomputes a full-amplitude -// step from b0*in alone, which re-rings and repeats forever (a click train). This must fail -// against a flush that also clears x1/x2. -// Run at full resonance as well as none: at res=0 the feedback share is zero and the tap line is -// inert, so that case alone would never notice the tap line failing to drain behind a flush. +// A high-pass under sustained DC must settle to zero and STAY there. Sampling only the final +// value is not enough: a resonator swings through zero twice a cycle, so a single late sample +// can land near zero while the envelope still rings well above it. This regressed a click train +// on the retired topology, where flushing the FIR history discarded the pinned DC and the next +// sample recomputed a full-amplitude step. TPT has no FIR history to discard, so the hazard is +// structural rather than a tuning — but the assertion is cheap and pins the outcome. static void testHighPassSustainedDCDoesNotReRing() { for (int r = 0; r < kRateCount; ++r) { - for (float res : {0.0f, 1.0f}) { - const double sr = kRates[r]; + const double sr = kRates[r]; + for (float drive : {0.0f, 1.0f}) { VoiceFilter f; - f.prepare({FilterMode::HighPass, filterNormFromCutoffHz(1000.0f), res}, sr); + f.prepare(at(1000.0, 1.0f, kHighPass, drive), sr); f.reset(); - const int settle = static_cast(sr * 0.05); float worstAfterSettle = 0.0f; for (int i = 0; i < static_cast(sr * 0.5); ++i) { const float y = f.process(0, 1.0f); - if (i >= settle) { - const float a = std::fabs(y); - if (a > worstAfterSettle) worstAfterSettle = a; - } + if (i >= settle) worstAfterSettle = std::fmax(worstAfterSettle, std::fabs(y)); } - // A correct flush leaves the settled output pinned near zero. The click train this - // regresses against recurs every ~4760 samples at 48k at a magnitude around 0.6 -- - // nowhere near this tolerance. CHECK(worstAfterSettle < 1e-3f); } } } -// --------------------------------------------------------------------------- -// Impulse / step sanity and saturation -// --------------------------------------------------------------------------- - -static void testImpulseResponseMatchesDifferenceEquation() { - const double sr = 48000.0; +static void testImpulseResponseMatchesTheKernel() { VoiceFilter f; - f.prepare({FilterMode::LowPass, filterNormFromCutoffHz(1000.0f), 0.5f}, sr); + f.prepare(at(1000.0, 0.5f, kLowPass), 48000.0); f.reset(); - const BiquadCoeffs c = f.coeffs(); + const SvfCoeffs c = f.coeffs(); + // From a cleared state the first sample reduces to the coefficients alone: v1 == a2, v2 == a3. + CHECK_NEAR(f.process(0, 1.0f), c.a3, 1e-7); - // First three impulse-response taps follow directly from the coefficients. - const float h0 = f.process(0, 1.0f); - const float h1 = f.process(0, 0.0f); - const float h2 = f.process(0, 0.0f); - CHECK_NEAR(h0, c.b0, 1e-6); - CHECK_NEAR(h1, c.b1 - c.a1 * c.b0, 1e-6); - CHECK_NEAR(h2, c.b2 - c.a1 * h1 - c.a2 * h0, 1e-6); + VoiceFilter bp; + bp.prepare(at(1000.0, 0.5f, kBandPass), 48000.0); + bp.reset(); + CHECK_NEAR(bp.process(0, 1.0f), c.a2, 1e-7); + + VoiceFilter hp; + hp.prepare(at(1000.0, 0.5f, kHighPass), 48000.0); + hp.reset(); + CHECK_NEAR(hp.process(0, 1.0f), 1.0 - c.k * c.a2 - c.a3, 1e-7); } -static void testLowpassStepSettlesToUnity() { +static void testLowpassStepSettlesToUnityAndHighpassRejectsDC() { const double sr = 48000.0; VoiceFilter f; - f.prepare({FilterMode::LowPass, filterNormFromCutoffHz(1000.0f), 0.0f}, sr); + f.prepare(at(1000.0, 0.0f, kLowPass), sr); f.reset(); float y = 0.0f; for (int i = 0; i < 48000; ++i) y = f.process(0, 1.0f); CHECK_NEAR(y, 1.0, 1e-3); // DC passes a lowpass at unity - // A DC step through a highpass should settle to (and STAY AT) zero. Sampling only the - // final value is not enough to prove that: a resonator swings through zero twice a cycle, - // so a single late sample can land near zero while the envelope is still ringing well - // above it elsewhere in the same run -- track the worst case over the settled region. VoiceFilter hp; - hp.prepare({FilterMode::HighPass, filterNormFromCutoffHz(1000.0f), 0.0f}, sr); + hp.prepare(at(1000.0, 0.0f, kHighPass), sr); hp.reset(); - const int settle = 200; float worstAfterSettle = 0.0f; for (int i = 0; i < 48000; ++i) { y = hp.process(0, 1.0f); - if (i >= settle) { - const float a = std::fabs(y); - if (a > worstAfterSettle) worstAfterSettle = a; - } + if (i >= 200) worstAfterSettle = std::fmax(worstAfterSettle, std::fabs(y)); } - CHECK(worstAfterSettle < 1e-3f); // fully rejected by a highpass, not just at one instant + CHECK(worstAfterSettle < 1e-3f); } -static void testResetClearsHistoryButPrepareKeepsIt() { +static void testResetClearsStateButPrepareKeepsIt() { VoiceFilter f; - f.prepare({FilterMode::LowPass, 0.5f, 0.5f}, 48000.0); + f.prepare({0.5f, 0.5f, kLowPass, 0.0f}, 48000.0); f.process(0, 1.0f); CHECK(!f.isSilent()); - // A live parameter move must not zero the history — that is what would click. - f.prepare({FilterMode::LowPass, 0.6f, 0.5f}, 48000.0); + // A live parameter move must not zero the state — that is what would click. + f.prepare({0.6f, 0.5f, kLowPass, 0.0f}, 48000.0); + CHECK(!f.isSilent()); + f.prepare({0.6f, 0.5f, kBandPass, 1.0f}, 48000.0); CHECK(!f.isSilent()); f.reset(); @@ -690,55 +691,52 @@ static void testResetClearsHistoryButPrepareKeepsIt() { static void testChannelStateIsIndependent() { VoiceFilter f; - f.prepare({FilterMode::LowPass, 0.5f, 0.5f}, 48000.0); + f.prepare({0.5f, 0.5f, kLowPass, 0.0f}, 48000.0); f.reset(); f.process(0, 1.0f); - CHECK(f.state(0).x1 == 1.0f); - CHECK(f.state(1).x1 == 0.0f); + CHECK(f.state(0).ic2 != 0.0f); + CHECK(f.state(1).ic2 == 0.0f); float frame[2] = {1.0f, -1.0f}; f.processFrame(frame, 2); - CHECK(f.state(1).x1 == -1.0f); + CHECK(f.state(1).ic2 < 0.0f); CHECK(frame[0] != frame[1]); } -static void testFeedbackSaturationIsContinuousWithGentleLinearTail() { - CHECK_NEAR(feedbackSaturate(0.0f), 0.0, 1e-9); - // Odd symmetry. - CHECK_NEAR(feedbackSaturate(1.5f), -feedbackSaturate(-1.5f), 1e-6); - // Continuous across the threshold at +/-2. - CHECK_NEAR(feedbackSaturate(2.0f - 1e-4f), feedbackSaturate(2.0f + 1e-4f), 1e-4); - // Past the threshold the curve continues on a 0.1 slope rather than hard-clipping -- it is - // NOT bounded, so this pins the linear continuation's shallow slope, not a ceiling. - CHECK(std::fabs(feedbackSaturate(100.0f)) < 12.0f); - CHECK(feedbackSaturate(100.0f) > feedbackSaturate(50.0f)); -} - int main() { testCutoffMapsThreeDecadesLogarithmically(); testCutoffNormRoundTrips(); testQSpansPointOneToTenWithRootTwoAtCenter(); testQNormRoundTrips(); - testCoefficientsMatchPinnedRbjValues(); - testCoefficientsTrackSampleRateAndClampBelowNyquist(); - testPassbandGainIsUnity(); - testHighQPeaksAtCutoffInBothModes(); - testMeasuredResponsePeaksAtCutoffInBothModes(); - testHighPassResonanceIsRateInvariant(); - testLowPassResonanceIsRateInvariant(); - testFeedbackLoopContributionIsRateInvariant(); - testResonantPeakTracksCutoffAtEveryRate(); - testFortyEightKilohertzBehaviorIsUnchanged(); - testFeedbackTapOffsetScalesWithSampleRate(); - testFeedbackTapNeverFallsBelowOneSample(); + testDriveDepthIsZeroAtRestAndRisesMonotonically(); + + testSvfCoefficientsMatchPinnedValues(); + testTheSampleRateEntersOnlyThroughG(); + testNonPositiveRatePassesSignalThroughAtEveryMorph(); + + testMorphEndpointMixesAreExactlyPureTaps(); + testMorphNeverBlendsHighAgainstLowPass(); + testMorphEndpointsMatchTheAnalyticTwoPoleTargets(); + testCornerMagnitudeIsFlatAcrossTheWholeMorphSweep(); + testMorphSweepHasNoDiscontinuity(); + + testDriveZeroIsBitIdenticalToTheLinearKernel(); + testDriveZeroResponseIsLevelInvariant(); + testFullDriveStaysBoundedAtEveryCutoffResonanceAndRate(); + testFullDriveDoesNotSelfOscillate(); + testDriveCompressesTheResonantPeakMonotonically(); + testSoftLimitIsOddMonotoneBoundedAndExactAtZeroDepth(); + + testResponseIsRateInvariantAtEveryMorph(); + testLowCutoffHighRateCornerHoldsTheAnalyticPeak(); + testFullRangeCutoffSweepAtAudioRateStaysBounded(); testStateFlushesToZeroWithoutStallingInDenormals(); testHighPassSustainedDCDoesNotReRing(); - testImpulseResponseMatchesDifferenceEquation(); - testLowpassStepSettlesToUnity(); - testResetClearsHistoryButPrepareKeepsIt(); + testImpulseResponseMatchesTheKernel(); + testLowpassStepSettlesToUnityAndHighpassRejectsDC(); + testResetClearsStateButPrepareKeepsIt(); testChannelStateIsIndependent(); - testFeedbackSaturationIsContinuousWithGentleLinearTail(); if (g_fail == 0) std::printf("filter_tests: all passed\n"); else std::printf("filter_tests: %d FAILED\n", g_fail);