Skip to content

Virtual Analog Filter improvements - #52

Merged
danigb merged 10 commits into
mainfrom
vaf
Sep 7, 2026
Merged

danigb merged 10 commits into
mainfrom
vaf

Conversation

@danigb

@danigb danigb commented Sep 7, 2026 •

Copy link
Copy Markdown
Owner

Made with Claude

There was no test of what any of the nine filters *does*. `worklet.test.ts`
is 402 lines and every assertion in it is about the segment renderer, change
detection or stability - which is why eight of the nine models have been tuned
about two decades low since the package shipped and four of them have never
filtered the input at all. The sweep-stability test asserts `Number.isFinite`
and a magnitude bound, and being wrong is extremely stable.

`src/filters.test.ts` drives the five circuit modules directly. `src/test-utils.ts`
carries the I/Q demodulation from `state-variable-filter/src/allpass.test.ts:13-42`,
unchanged apart from the block-by-block render this package needs, plus a
bisecting corner search and a log-grid peak/notch finder.

Nine groups, every tolerance justified in place and none of them compared
against a captured output of today's code:

  passing   the skirt matches the order of the topology (and separates the
            two 4-pole models from the three 2-pole ones, which the existing
            "own model" test cannot do)
  passing   the highpass, bandpass and bandstop taps are what they say
  passing   passband gain against resonance - the Moog ducks by exactly
            1/(1+4r), the diode ladder is 30 dB hot
  passing   bounded at maximum resonance
  FAILING   the measured corner tracks the requested one          -> 03
  FAILING   the corner does not move with the sample rate         -> 03
  FAILING   the response does not depend on the block size        -> 02
  FAILING   recovers from a poisoned state                        -> 05
  FAILING   survives a cutoff past Nyquist                        -> 04

The five defect groups are written with `it.failing`, so the suite is green
while the defect is recorded, and each names the ticket that flips it back.
`MOOG_LADDER` is a plain `it` in the two corner groups: its transcription is
stale and already linear in Hz, so it passes them today.
`src/oberheim.ts:39` read `input[0]` inside a loop indexed by `i`. Four of the
nine models the README advertises - OBERHEIM_LPF, _HPF, _BPF and _BSF - were
therefore filtering a DC value re-latched once per render quantum, and have
never filtered audio. Under the 0.13.0 segment renderer it was worse than it
looks: an automated block is rendered in up to 128 `from`/`to` segments and
every one of them read index 0, the first sample of the block rather than of
the segment.

The Faust Rust reference reads the iterator's current sample
(`dsp/oberheim.rs:165`) and every other generated body in this package reads
`input[i]`. The correctness argument here is that codegen plus the
measurement in `filters.test.ts` - `ve.oberheim` derives from Pirkle §7.2,
which nobody here owns, so no source was consulted and none is implied.

Regenerating `oberheim.rs` from the unchanged `.dsp` with the locally
installed Faust 2.85.9 reproduces the 2.72.14 `compute` body exactly, modulo
Rust boilerplate and casts, so `vaeffects.lib`'s oberheim has not moved and
this ships ahead of ticket 03's pin.

Two smaller things in the same loop, because it was open:

  * `type = type;`, transcription residue Faust did not emit, deleted.
  * The four-way ternary on `type`, evaluated per sample to choose between
    four values all computed unconditionally, resolved once at construction.
    `type` is fixed for the life of the instance, and the four taps are
    combinations of the same temporaries, so three hoisted weights cover all
    of them without four copies of the loop. Not a performance change - the
    Oberheim measures 0.09% of realtime static.

`dsp/compile.txt` now records the Faust version and the two divergences the
hand transcriptions are allowed to carry, which is what would have caught
this: the `.ts` files are transcriptions of the `.rs` files and the only
intended edits are the `from`/`to` bounds and this module's single-output
collapse.

The block-size group in `filters.test.ts` goes from `it.failing` to `it` for
all four models, and the `blockSize: 1` workaround the other groups needed to
measure the Oberheim at all is deleted.
BREAKING CHANGE: `frequency` changes meaning on eight of the nine models.

`vaeffects.lib` is uniform: every function this package uses takes a
normalised *logarithmic* control and maps it back to Hz itself,
`cf = 2*(10^(3*normFreq+1))`, i.e. 20 Hz..20 kHz over 0..1. All six `.dsp`
wrappers handed it `cutoffHz / nyquist`, a linear fraction of Nyquist.
`2*10^(3*0.0417+1)` is 26.7 Hz, which is where a 1 kHz request at 48 kHz was
going. The exponential map was being applied to a quantity that had never been
normalised for it.

Faust folds the division into a constant - `fConst2 = 6.0/SR` is `3*(2/SR)` -
so the generated bodies show an arbitrary constant and the `.dsp` shows a
slider labelled "Hz" divided by Nyquist. Neither file shows the bug on its own,
which is how it survived three audits.

The fix is the inverse of the library's own map, in the wrappers:

    cutoffNorm = max(0, min(1, (log10(cutoffHz / 2) - 1) / 3));

Measured -3 dB corner at 48 kHz, resonance 0.2, asking for 1000 Hz:
MOOG_LADDER 907 -> 907, MOOG_HALF_LADDER 30 -> 1163, KORG35_LPF 24 -> 870,
DIODE_LADDER 13 -> 502, OBERHEIM_LPF 41 -> 1542. What is left is the
topology - a four-section cascade crosses -3 dB at 0.435 of its design cutoff -
and it is now asserted per model rather than left to be discovered.

`frequency: 20000` reaches 20 kHz instead of 3.2 kHz, and the corner no longer
drifts with the sample rate: under 0.1% across 44.1/48/96 kHz on four models
and 1.9% on the diode ladder, against the ~20% the Nyquist-fraction bug gave.

MOOG_LADDER is unchanged to the digit, which is the check that the
regeneration did not move the one model that was right. Its transcription was
stale - `tan(PI*f/SR)`, from a revision whose `moogLadder` really did take a
fraction of Nyquist - so its wrapper happened to match its body. New:
`tan(2*PI/SR * 10^(3n+1))` with `10^(3n+1) = f/2` is the same number, now
written in the convention all six share.

The diode ladder's second reading of the cutoff follows automatically:
`17 - 9.7*(2f/SR)^10` becomes `17 - 9.7*normFreq^10`, the library's
cutoff-dependent feedback term, confirmed in the regenerated Rust rather than
assumed.

`dsp/compile.txt` now pins the toolchain: FAUST 2.85.9 and vaeffects.lib 1.5.0
at git blob 3aa5fe85, with the command to check it. That is half this change.
Recording the commands without the library version is what let two circuit
files generated from revisions with incompatible conventions be checked in
side by side.

The clamped map is a named function, `src/norm-freq.ts`, rather than five
inlined copies of one logarithm - a fourth recorded divergence from the
codegen. Its clamp is the library's own 20 Hz..20 kHz domain, and it
incidentally bounds `detune`'s +/-127 semitones, so `filters.test.ts`'s
past-Nyquist group passes on all nine models now. Ticket 04 still replaces the
hard breakpoint with a continuous prewarp, because a discontinuity in dg/df is
audible when a cutoff is swept through it.

The corner, sample-rate and past-Nyquist groups in `filters.test.ts` go from
`it.failing` to `it`.
`worklet.ts` folds `detune` into the cutoff with no bound, and `detune` is
declared +/-127 semitones. `frequency: 1000, detune: 127` - both inside their
declared ranges - asked for 1.54 MHz. One block of noise there returned
`Infinity` on the diode ladder and a peak of 5.6e21 on the Moog, which is not
a distinction that means anything to somebody with speakers connected.

Ticket 03's `normFreq` clamp moved that cliff without removing it. 20 kHz is
above Nyquist below 40 kHz, and `new AudioContext({ sampleRate: 22050 })` is
legal, `OfflineAudioContext` is routinely constructed low, and this package's
own worklet tests run at 8000. And a hard breakpoint is the wrong shape
anyway: `dg/df` drops to zero at the ceiling, and Zavalishin says exactly what
that costs - "a sudden change of the perceived modulation speed as the cutoff
traverses through the prewarping breakpoint". An a-rate cutoff being swept is
this package's entire point.

So `src/prewarp.ts` is *continuous-speed* bounded prewarping, section 3.8
eq. 3.23 and the derivative on p.70: the tangent below 0.72 of Nyquist, its
tangent line above. Finite, positive and strictly increasing from 0.013 Hz to
1.54 MHz at 8000, 22050, 44100, 48000 and 96000 Hz, and bit-identical to the
`Math.tan` it replaces below the ceiling - every measured corner reproduces to
the digit (906.55, 1163.25, 870.24, 502.21, 1542.26 Hz).

0.72 is ours, not Zavalishin's - he gives no numeric prescription beyond
"around 16kHz" - and it is the same 0.72 as `state-variable-filter`, because a
cutoff that meant one thing in `Svf` and another here would be its own bug.
`prewarp.ts` is a deliberate second copy of that package's `createPrewarp`:
where a shared DSP core lives is a repo-wide question three ticket folders
have now deferred, and twenty duplicated lines is the cheaper mistake.

Two things collapse into `prewarp(f)`. The library's `cf = 2*10^(3*normFreq+1)`
and `normFreq = (log10(f/2)-1)/3` are inverses, so the round trip is the
identity and `tan(2*PI/SR * 10^(3*normFreq(f)+1))` was `tan(PI*f/SR)` with two
transcendental calls in front of it - per coefficient update, which on a
per-sample sweep is per sample. What survives of `normFreq()` is the *domain*
of the diode ladder's `17 - 9.7*normFreq^10` feedback scaling, which the
library designs over 0..1 and which is the term that actually returned
`Infinity`: past 1 the tenth power runs away and flips the coefficient's sign.
It is easy to miss because it is not the prewarp.

`detune` keeps its +/-127 range. The range was never the bug.
One non-finite input sample killed the filter permanently, on all nine models.
Injecting a single `NaN` and then feeding 300 blocks of clean noise: never
recovers, every model. What makes it permanent is arithmetic rather than a
missing guard - every recursive state update is `state = state + k * something`
and `NaN + anything` is `NaN` - and the two saturating models do not help,
because `Math.max(-1, Math.min(1, NaN))` is `NaN` as well. Web Audio has no
recovery path: the node emits `NaN` or silence for the life of the graph and
the only fix a user has is to rebuild it.

Five three-line `reset()`s, and one scan in `worklet.ts`. After a channel is
rendered - both the static path and the segmented one - its output block is
scanned once; if anything is non-finite, that channel's *active* filter is
reset, the block is zeroed and the change-detection slot is invalidated.

Three decisions worth stating:

  * Scanned on the output, not the input. The input is not the only route in:
    before the cutoff was bounded, the diode ladder produced `Infinity` from
    two in-range parameters.
  * In `worklet.ts`, not at the end of `process()` where `state-variable-filter`
    puts its check. That package's `filter()` is called once a block. This
    one's `process()` takes `from`/`to` bounds and the segment renderer calls
    it up to 128 times a block, so a check there would be a per-sample check
    wearing a per-block disguise.
  * The active filter only. Each channel keeps all nine models so that
    switching `type` mid-note resumes where that model left off
    (`worklet.test.ts` asserts it), and only the filter that rendered can have
    been poisoned. `reset()` clears the sliders too, so the slot has to be
    invalidated or the next block skips `update()` and renders at a cutoff of
    zero.

Cost of the scan, measured in V8 over 200k blocks of 128 samples: +4.0% on the
Moog ladder, +5.4% on the Oberheim. Against 0.09-0.35% of realtime for one
voice that is about 0.015% of realtime. Stated rather than rounded to zero.
(Benchmarked in node, not in jest: jest's VM realm makes `Number.isFinite` a
cross-realm call and reports +444%, which is an artifact of the harness.)

`filters.test.ts`'s recovery group becomes the circuit-level contract - poison
the model, confirm no input clears it, `reset()`, confirm it is alive - and the
end-to-end recovery is asserted in `worklet.test.ts`, where the guard lives:
finite on the next block for one model per circuit, silence rather than `NaN`
on the offending block, on the automated path as well as the static one, and
neither the other channel nor the other types in the bank disturbed.
BREAKING CHANGE: output level changes on all nine models, and `DIODE_LADDER`
changes character completely.

Two level defects, opposite in sign, both invisible because nothing measured
gain.

Opening the resonance ducked the signal. MOOG_LADDER measured exactly
1/(1+4*resonance) at DC - 0 dB, -5.1, -9.5, -13.3 at resonance 0, 0.2, 0.5,
0.9 - which is a ladder's uncompensated feedback attenuation. Every filter
people compare this to applies makeup gain; this one applied none. And
OBERHEIM_BPF had the same defect upwards: its peak gain *is* Q, rising from
0.707 to 28.6, so resonance was a 32 dB volume control there.

Passband gain is now flat across the whole resonance range on every model,
measured to within 0.005 dB. Per topology, and every one of them measured
before it was written:

  MOOG_LADDER          1 + 4r   Huovilainen 2004, Zavalishin section 5
  MOOG_HALF_LADDER     1 + 2r   the same, half the ladder
  KORG35_*, OBERHEIM   1        measured flat to 3e-4, not a citation
    LPF/HPF/BSF
  OBERHEIM_BPF         1/Q      what state-variable-filter settled on
  DIODE_LADDER         solved from its own DC steady state

The two ladders' k is exactly 4r and 2r, from the files' own constants:
0.1646572 * 24.293 = 4.0000 and 0.0823286 * 24.293 = 2.0000. The Korg 35 and
three Oberheim taps scale their feedback back into the forward path and need
nothing - and that is a measurement, deliberately not a citation, because
`ve.oberheim` derives from Pirkle section 7.2 and that book is not on disk
here.

The diode ladder has no closed form in resonance alone: the slope of 1/gain
against resonance moves with the cutoff, because fSlow15 = 17 - 9.7*normFreq^10
scales the feedback. So it is derived instead. At DC every fTemp5..fTemp8 is
zero, which leaves a 4x4 that substitutes forward in about twenty flops.
Checked against measurement at five cutoffs and four resonances: agrees to
0.25%, and the residual is the cubic clipper rather than the algebra.

The second defect: the diode ladder was a fuzzbox. It clipped `100 * input[i]`
with no way to turn it down, so above an input of about 0.01 the output
fundamental was constant at 0.265 and only the zero crossings survived - a
distortion box with a filter after it. That is faustlibraries #214, open
upstream since February 2025, which reports needing -41 dB of trim.

`drive` is that gain, a-rate, default 1, range 0..100. At 1 the diode ladder
is clean - a 0.5-amplitude sine comes through within 1 dB of its small-signal
gain - and at 100 it is the fuzzbox it used to be, on purpose, which is also
the check that `drive` reaches the saturator rather than sitting in front of
it as an output gain.

`drive` is applied at the *input* of every model rather than folded into the
output gain. On the three linear models the two are algebraically identical
and folding would save a multiply, but the Oberheim and the diode have
saturators inside the loop and ticket 07 puts one in both ladders. On those
three it is input gain and nothing more, and the parameter's comment says so
rather than implying otherwise.

Wired through the segment renderer, not read as `drive[0]`: a moving drive
splits the block the way a moving cutoff does, which `worklet.test.ts` now
asserts by instrumenting the calls. `packages/synthlet`'s filter-parity test
learns the new parameter too.
BREAKING CHANGE: `resonance` changes meaning on MOOG_LADDER and
MOOG_HALF_LADDER.

The README sold "the nonlinearity and the resonance behaviour that make it
recognisable" and five of the nine models had no nonlinearity of any kind,
including the flagship. `moog.ts` was Zavalishin's *linear* TPT ladder;
`vaeffects.lib` says "no nonlinearities" in its own doc comment and the README
did not. So nothing self-oscillated. MOOG_LADDER at resonance 1.0 held a
constant amplitude because k = 4*resonance landed on exactly 4.0, the analytic
threshold: a marginally stable linear resonator ringing at whatever the last
impulse left it with, one rounding error either side of silence and
divergence. A linear ladder has one loop gain for every amplitude, so it can
only decay, hold, or diverge - never settle into a note.

Both ladders now saturate in the feedback path, and the delay-free loop that
creates is resolved rather than delayed away. Measured at 48 kHz, frequency
1000: silence below resonance 0.95, and above it a stable oscillation settling
at 0.96 (full ladder) and 0.58 (half ladder) at resonance 1.0, at a frequency
that tracks `frequency`. `resonance` is rescaled so the threshold sits at 0.95
instead of at the very top - which is the breaking part - and below the
saturation knee the filter is the one it was: the solver's initial estimate
*is* the linear closed form it replaces, so every corner, skirt, sample-rate
and passband measurement is unchanged.

The saturator is Huovilainen's differential pair (DAFx 2004, eq. 1-6): the two
transistors' collector currents differ by a tanh, and that sits exactly where
the input meets the feedback. The loop is resolved by the discrete-time method
from Chowdhury's review (section 4), which his conclusion recommends for
purely digital systems - "forming continuous-time equations often adds
unnecessary complexity". It fits this filter without adaptation: Chowdhury's
`h0` is the ladder's input-to-output gain, G^4 for the full ladder and
G^2(2G-1) for the half, and his `H_n` is the state sum the linear code already
formed. Four Newton iterations from the linear solution; worst-case residual
9.0e-11 over every (A, B, k, x) the parameter ranges permit, asserted in
`saturate.test.ts`.

Huovilainen's own answer is to put a unit delay in the feedback path and not
resolve the loop at all - his eq. (13) reads `yd(n-1)` - and his sections
5.2-5.3 are then entirely about compensating the tuning error that causes,
with a half-sample delay and a residual "less than 10% for f < Fs/4". Taking
that would have retuned the filter, and not retuning it was the point.

His four *per-stage* tanhs are deliberately not here. They shape harmonics
rather than create the oscillation; they would turn a scalar solve into a
four-dimensional one, which Chowdhury singles out as the expensive case; and
he is explicit that they need oversampling, which is the next ticket.

Two numbers the ticket asked for, and neither is good:

  Aliasing, unit sine in, 48 kHz, no oversampling: worst non-harmonic partial
  -179 dB at drive 1 and a 1 kHz probe, -41 dB at 3.7 kHz with drive 10, -30
  dB at 7.9 kHz with drive 10 and resonance 0.9. That is the baseline
  oversampling has to improve.

  Cost: MOOG_LADDER is 11x what it was. 13.6 -> 151 ns a sample, 0.065% ->
  0.73% of realtime for one voice at 48 kHz, measured in node against the
  previous commit's linear body. The other seven models are unchanged. The
  iteration count is nearly free - 82, 103 and 112 ns a call for two, three
  and four - because the cost is the fixed setup and the first tanh.

The bounded-at-maximum-resonance group was rewritten *before* the
nonlinearity, as the ticket asks: an absolute bound for all nine rather than a
relative one (a self-oscillating filter is supposed to grow), a settling
assertion for the two ladders, and a new full-range a-rate sweep at maximum
resonance with a full-scale deterministic noise - the combination a filter
tuned by ear at one setting will not have been tried at.

KORG35_* stays linear by decision. `moog.ts` and `moog-half.ts` stop being
generated files: their linear TPT cores are still upstream's and still
attributed, the nonlinearity and the solver are ours and transcribed from two
papers rather than from anyone's code, and THIRD-PARTY-LICENSES.md and
dsp/compile.txt both say which is which.
A saturating nonlinearity generates harmonics without bound and everything
above Nyquist folds back down as inharmonic aliasing - the "digital" sound
virtual-analog modelling exists to avoid. Huovilainen is explicit that his
ladder needs oversampling. The two models that already saturated, the diode
ladder and the four Oberheim taps, had the same problem since the package
shipped and nobody had measured it.

Measured with `aliasSnr` from `scripts/_spectrum.ts`, which this package now
opts into so its numbers are comparable with the two oscillator packages'. The
probe is 3.7 kHz, deliberately not a sub-multiple of 48 kHz: at 1 kHz every
alias folds onto a harmonic and the metric reads a meaningless 97 dB whatever
the filter is doing, which is how a first attempt at this measurement reported
-245 dB of aliasing from a filter that was obviously aliasing.

                            before    after
  MOOG_LADDER                39.5      51.0
  MOOG_LADDER (7.9 kHz)      26.6      35.3
  MOOG_HALF_LADDER           44.6      54.4
  DIODE_LADDER               14.8      31.6
  DIODE_LADDER drive 100     12.5      23.4
  OBERHEIM_LPF                7.3      43.4
  OBERHEIM_LPF drive 100     -9.3      23.6

Two times, not four, and that is the measurement rather than a convention.
Four buys another 10-13 dB and costs another doubling: MOOG_LADDER is 0.78% of
realtime for one voice at 1x, 1.96% at 2x and 3.91% at 4x, the ladder being
expensive because its delay-free loop is solved per sample. Trading 2% of a
core for 12 dB is the trade antiderivative antialiasing exists to avoid, and
that is the follow-up.

KORG35_LPF and KORG35_HPF do not resample - no clipper and no tanh by the
library's design, nothing to band-limit, and they measure above 90 dB either
way. The bank is built heterogeneously: the seven at `sampleRate * 2` and the
Korg pair at `sampleRate`.

BREAKING in effect if not in semver: **this node now delays its output by 16
samples**, 0.33 ms at 48 kHz and 16 samples at any rate. It had none. Two
symmetric FIRs, one up and one down, each delaying by half its length. The
Korg pair is delayed to match, because a `type` change that also moved the
output by 16 samples would be a click. A polyphase IIR halfband would be near
zero-latency, but its allpass coefficients come out of an elliptic design, and
a table of constants copied from a library nobody here owns is the kind of
thing this package has already been bitten by. Declared in the README, in
`worklet.ts` as `LATENCY_SAMPLES`, and asserted in `oversample.test.ts` by
finding the peak of a round-tripped impulse.

The resampling brackets the *block*, not the run: the whole input is upsampled
once, the segment renderer's runs are rendered inside the oversampled domain as
`[from * 2, to * 2)`, and the whole output is downsampled once. Coefficient
updates therefore still happen at the base rate, one per output sample on a
genuine sweep, which `worklet.test.ts` still asserts - now against the
oversampled bounds.

The `NaN` guard moved with it, and got better in the process. It now scans the
filter's own output *before* the resampling rather than the block that leaves
the node: checking after the downsampler would let a `NaN` into its history,
and checking after the bypass delay hid it for a whole block and cost a block
of recovery - which is how this was found.

The resampler's kernel is a Kaiser-windowed sinc computed at construction
rather than a table, so the stopband is a consequence of two stated numbers.
Measured: the round trip is within 0.01% of unity to 15 kHz, droops in the top
octave because a finite linear-phase filter has a transition band and not an
edge, and rejects 36 kHz and 44 kHz by more than 70 dB.
The README sold "nine classic analog filter circuits, each with the
nonlinearity and the resonance behaviour that make it recognisable". There are
five circuits - the Oberheim SEM is one filter read at four taps - and three of
the nine responses have no nonlinearity at all. `vaeffects.lib`'s own doc
comment for `moogLadder` said "no nonlinearities" and the README said the
opposite. None of that was dishonest; it is what happens when the wrapper is
audited three times and the circuits never are.

It now says: five circuits and nine responses, with a table giving each one's
order and whether it saturates; `frequency` in Hz with the bounded prewarping
named; `drive`, including plainly that on KORG35_* it is input gain and nothing
more; the makeup gain, so nobody is surprised that resonance no longer ducks;
and where self-oscillation starts. The measured corner of each model is in
there too, because the corner sits where the topology puts it rather than
exactly on the request, and that is worth saying rather than leaving to be
discovered.

The a-rate section is kept verbatim. It is about `worklet.ts`, which is the
half of this package that had been audited, and every claim in it was true -
which is the shortest version of what this folder found.

Credits now distinguish the three circuit files that are still Faust
transcriptions from the two ladders, whose linear cores still are and whose
saturating feedback paths are not.

The demo was patching a 5 kHz sawtooth through the filter at `frequency: 2000`
- a source that high is what you end up choosing when you tune a demo by ear
against a filter whose corner is really 30 Hz. It is a 110 Hz sawtooth at an
800 Hz cutoff now, with a `drive` slider, and the type list says which models
saturate, which two are linear, and which four are taps of the same filter -
four that had never filtered audio, so nobody had heard them.
@danigb
danigb merged commit 8a98969 into main Sep 7, 2026
1 check passed
@danigb
danigb deleted the vaf branch September 7, 2026 14:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant