Skip to content

Polyblep improvements - #45

Merged
danigb merged 12 commits into
mainfrom
feat/polyblep
Sep 6, 2026
Merged

danigb merged 12 commits into
mainfrom
feat/polyblep

Conversation

@danigb

@danigb danigb commented Sep 6, 2026

Copy link
Copy Markdown
Owner

Made with Claude

The triangle is an integrated BLEP-corrected square, so its integrator gain
is `4 * increment`. The code had `4 / frequency` - inverted, and off by
`sampleRate / frequency^2`: measured peak 17.7 at 20 Hz and 0.0006 at 7 kHz
against a nominal 1.0. It also read the pre-detune frequency, leaving the
detuned increment unused.

The same division made `frequency = 0` fatal. `4 / 0` is Infinity, which
drove the accumulator to -Infinity and the output to NaN, permanently -
101 healthy blocks after one poisoned one still yielded NaN. `connectParams`
writes `param.value = 0` before connecting a node to a param, so every
MonoSynth hit this on its first render quantum. Using the increment removes
the division; zero frequency now holds.

Alongside it, the rest of the degenerate inputs:

- clamp the increment to 0.25 cycles/sample (Stages' kMaxFrequency), above
  which polyblep()'s two branches overlap - reachable at 20000 Hz with
  +1200 cents of detune, measured DC offset 0.2176
- wrap with `phase -= Math.floor(phase)`, which survives an increment of 1
  or more (phase reached 96 in 64 samples at 8 kHz / 20 kHz) and wraps a
  phase landing exactly on 1.0 on the same sample
- round and clamp `type`, so a fractional AudioParam value selects the
  nearest waveform instead of falling back to a sawtooth
- reset the integrator and DC blocker when the waveform changes
- replace `(phase + 0.5) % 1` with a branch matching the `phase < 0.5` test
  that picks the base level. For the double just below 0.5 the sum rounds up
  to exactly 1.0 and wraps to 0, applying the rising edge's correction with
  the falling edge's sign: a -2 sample on a +/-1 square, reachable at
  2205 Hz at 44.1 kHz and visible in the old snapshot
- drop the unmotivated `* 0.8` on the triangle's output, which left it 2 dB
  below the saw and square

All four waveform tests were mislabeled against the enum - `generates sine`
ran the sawtooth, `generates triangle` ran it again via `GENS[3] ?? GENS[0]`,
and the snapshot named `generates square` was really the triangle recorded at
1.6x full scale. They are renamed to the waveform they run, the fourth is
deleted, and the snapshot file is regenerated from scratch. Three regression
tests cover the finite output at frequency 0, the fractional type and the
phase wrap; each one fails against the previous code.

Triangle peak is now 0.978 at 440 Hz and 0.909 at 4186 Hz. The remaining
low-end loss (0.201 at 20 Hz) is the 63 Hz DC blocker, left alone here.
The band-limiting kernel was written inline in polyblep-oscillator's dsp.ts and
nowhere else, while three packages generate waveforms with discontinuities. It
is now one file alongside scripts/_gate.ts, copied by scripts/copy_files.sh
under the same rule - only into a package that already carries it, so adding a
package does not silently give it an unused file.

Four pure functions, two correction orders: blepResidual2/blampResidual2 (the
linear B-spline, support 1 sample) and blepResidual4/blampResidual4 (the cubic
B-spline, support 2 samples, which Valimaki, Pekonen and Nam recommend). One
contract for all four: `t` is the signed distance in samples from the
discontinuity, `d` is |t|, a BLEP residual is for a unit rising step and is
scaled by the step height, a BLAMP residual is scaled by the slope change per
sample. Every function returns 0 outside its support, so a caller can evaluate
it unconditionally.

The residuals are derived, not transcribed. The audit could not land the
higher-order kernels because two prototypes taken from the PDF-to-markdown
conversions performed worse than naive, which is impossible for a correct
implementation; docs/papers/polyblep/README.md records the cause - the
conversion dropped or scrambled every typeset equation. Integrating the
centered cardinal B-spline once gives the BLEP residual (subtracting the naive
step), twice gives the BLAMP residual, and the file states that derivation
rather than citing coefficients nobody can check. Nothing here or in the tests
reads docs/papers-md/.

blep.test.ts is what makes the derivation checkable, asserting the properties
the true integrals have and a mistyped coefficient does not: zero outside the
support (exactly +0, which is why the guards come before the arithmetic), C2
continuity across the joins at -1, 0 and 1, a jump of exactly -1 across the
step being corrected, the BLAMP peaks 1/6 and 7/30, zero net area over the
support by Simpson at 20000 intervals per piece (measured 1.1e-15 and
-1.5e-15), and R' = r by central differences. Spot-checked by mutation: no
single perturbed coefficient escapes fewer than two of the six tests.

The drift test in @synthlet/synthlet gets a third block, asserting the list of
packages carrying src/_blep.ts is exactly ["polyblep-oscillator"] and that each
copy is byte-identical to the original. lfo and wavetable-oscillator are the
intended next consumers; each opts in by carrying the file.

No audio changes. Nothing imports _blep.ts yet - dsp.ts keeps its inline
polyblep() until the discontinuity-scheduler rewrite adopts these - so the
worklet bundle, the parameter descriptors and every waveform snapshot are
untouched. The kernels land with their proofs attached rather than buried in
that rewrite's diff.
Split test:ci into 'npm run build' and 'npm run test' in the workflow and
diff the regenerated bundles in between. CI already rebuilt every
src/processor.ts on each pull request and threw the result away, so a commit
that changed worklet.ts or dsp.ts without regenerating the bundle passed
silently while the published package shipped stale DSP.

The pathspec also covers packages/*/src/_processor.ts: level-meter inverts the
convention, bundling its hand-written src/processor.ts into src/_processor.ts,
so watching only processor.ts would have watched that package's source and
ignored its generated file.
The package's only output tests were four snapshots, and the audit showed
exactly what that buys: they ran on every CI job for a year while the triangle
was recorded at 1.6x full scale under the name "square". Snapshots assert
stability, not correctness.

src/spectrum.ts ports the audit's alias-SNR metric into the package - a
32768-point FFT, a 4-term Blackman-Harris window, energy within +-10 bins of
each harmonic counted as signal and everything else as noise - plus peak() and
a render() that discards 8192 samples of warm-up before capturing 32768 in
128-sample blocks, which is what the worklet is actually called with. Test-only
and imported by nothing, like lookahead-limiter/src/true-peak-oracle.ts; it is
a measuring instrument, not a runtime contract, so it lives in the package
rather than in scripts/.

spectrum.test.ts calibrates it. The metric is the audit's own, so its absolute
values mean nothing outside this repository - what makes them usable is that
they are reproducible, and the two sawtooth rows are what pin them down:
30.2 / 19.1 / 15.6 / 12.5 / 9.1 / 5.0 dB uncorrected and
67.0 / 35.4 / 32.0 / 29.5 / 24.7 / 18.3 dB through createPolyblep, at
110 / 440 / 1000 / 2000 / 4000 / 8000 Hz. Both reproduce order-harness.js and
the audit to the decimal, through a Float32Array in 128-sample blocks rather
than the harness's Float64 single buffer. If either drifts, every floor below
is meaningless.

dsp.test.ts is what the package promises, driven by two exported tables so the
rewrite edits data rather than code:

- ALIAS_FLOORS, the measured 2-point figures minus 1.5 dB at five frequencies
  per waveform: saw 33.9 / 30.5 / 28.0 / 23.2 / 16.8, square
  35.4 / 31.8 / 31.5 / 28.9 / 16.6, triangle 64.2 / 53.6 / 48.6 / 39.4 / 38.1
- PEAK_BOUNDS, [min, max] per waveform and frequency, max 1.02 throughout and
  min the measured warm peak minus 0.02. A band-limited waveform does not peak
  at 1.0 - the saw reaches 0.670 at 8 kHz - so a flat bound would fail a
  correct implementation. The triangle's 20-110 Hz rows (0.181 / 0.504 / 0.775)
  record the 63 Hz DC blocker's loss, not band-limiting
- finite and bounded over the whole declared range, read from PARAMS rather
  than from literals: two sample rates x five type values including the
  half-integers a ramp passes through x {0, 20000} Hz x {-1200, 0, +1200}
  cents, then a second block at 440 Hz proving no state was poisoned
- element-wise identical rendering 4096 samples in one call and in 32 of 128
- no overshoot at 735 / 1470 / 2205 / 3675 Hz, where an exact integer of
  samples per cycle lands the accumulated phase on the double just below 0.5

Every floor is one-sided, and every one is today's 2-point figure: the suite is
green the moment it lands, so the discontinuity-scheduler rewrite can raise
them and have the diff show the improvement rather than needing a test edit to
record it.

Reverting any one of the triangle-gain commit's fixes fails this suite -
4/freq nine tests, the * 0.8 eight, the increment clamp the declared-range
test, the type rounding throws, halfPhase the overshoot test. The one exception
is the floor-based phase wrap, which is unobservable alone: under the 0.25
increment clamp `phase -= Math.floor(phase)` and `if (phase >= 1) phase -= 1`
are identical for every reachable input. It becomes load-bearing once the phase
can run backwards.

worklet.test.ts keeps its snapshots at sampleRate 40, with a header saying what
they are for and where the package's promises now live. No audio changes, no
API changes; processor.ts was regenerated and diffed to prove it is unchanged.
One primitive replaces three hand-written per-waveform branches. A phase
accumulator, an edge detector and addDiscontinuity(d, stepHeight, slopeChange)
writing the 4-point B-spline residuals of _blep.ts backwards into a four-slot
pending ring carried across render quanta. Every waveform is now a naive
function plus a list of where its discontinuities fall.

The structure is Mutable Instruments' this_sample/next_sample scheme from
stages/oscillator.h (MIT), generalised from one pending sample to two because
the 4-point kernel's support is +/-2. The kernels are deliberately not
stmlib's: at 4-point order the B-spline residuals beat them by 10-20 dB.
Recorded in THIRD-PARTY-LICENSES.md, whose reading-list statement no longer
claims that nothing derives from stmlib.

Measured alias SNR at 440/1000/2000/4000/8000 Hz, 44.1 kHz:

  sawtooth  35.4/32.0/29.5/24.7/18.3  ->  45.5/42.3/40.1/34.5/26.8
  square    36.9/33.3/33.0/30.4/18.1  ->  46.8/43.2/45.1/43.8/26.6
  triangle  65.7/55.1/50.1/40.9/-     ->  80.7/70.2/67.0/60.6/36.2

The triangle is corrected directly with a BLAMP: the integrator, its 4*inc gain
and the 63 Hz DC blocker are deleted together. Peak at 20 Hz goes from 0.201 to
0.999, and with the recursive state goes the cold-start transient - a render
from silence peaked at 1.777 while the integrator settled and now peaks at
exactly 1.000, so the cold and warm bounds are the same number.

Breaking: PolyblepOscillatorType renumbers in brightness order (Sine 0,
Triangle 1, Sawtooth 2, Square 3, default unchanged), the square's polarity
flips to +1 for the first half of the cycle per the Web Audio spec, the sine is
restored, and frequency and detune become a-rate - read per sample instead of
once per 128-frame quantum. A type change is scheduled as a step, so switching
waveform mid-note no longer clicks.

The output lags by two samples, about 45 us: the correction spans +/-2 samples
around a discontinuity, so it is written into samples already computed but not
yet emitted. That is what places it exactly under fast modulation, where a
predictive correction lands wrong.

dsp.ts holds exactly one division by the increment, reachable only from inside a
crossing branch, which a zero increment cannot produce.
One a-rate `width` parameter, 0..1, default 0.5, routed through the
discontinuity scheduler rather than around it: moving `width` moves where the
second discontinuity sits, and nothing else changes. The square becomes a pulse
wave and the triangle a continuous morph to a rising or falling ramp; the sine
and the sawtooth ignore it, because a skewed sawtooth is the triangle at
`width -> 1`.

The waveform table's `slope0`/`slopeH` become the corner's *sign* and the
scheduler scales them by `(2/w + 2/(1 - w)) * inc`, which is ticket 04's
`8 * inc` at `width = 0.5`, exactly. `width = 0.5` reproduces the previous
square and triangle bit for bit, verified against af9c00c over four waveforms,
seventeen frequencies and two sample rates.

Measured alias SNR at 44.1 kHz, DC removed for the pulse rows, at 440 / 1000 /
2000 / 4000 / 8000 Hz: a 25% pulse 46.4 / 43.7 / 44.7 / 32.3 / 36.8, a 10%
pulse 42.6 / 37.4 / 36.8 / 39.4 / 36.8. A skewed triangle at 440 / 1661 /
4186 Hz: 79.2 / 60.1 / 48.9 at width 0.75 and 65.6 / 59.6 / 53.6 at 0.95,
against 56.6 / 38.8 / 26.5 and 44.4 / 28.4 / 13.7 naive. A pulse's peak is
1.000 at every width and frequency measured and its mean is `2 * width - 1`,
which is signal and not an offset to remove.

The moving edge is the part that needed care. `high ^ (phase < width)` fires
both when the phase advances past the width and when the width retreats past
it, so the correction carries a sign, and its sub-sample age is measured
against `inc - deltaWidth` - the speed at which `phase - width` closes, which
is `inc` to the bit when the width is held. Getting that wrong corrects one
edge twice; the new test drives a width step at every sample over 42 width
pairs at three frequencies and holds the result to one band-limited edge of
height 2 (1.2), measured 1.1979 against 2.0000 uncorrected.

`width` is clamped to `[2|inc|, 1 - 2|inc|]` per sample, floored at 1e-3. Two
samples is the 4-point kernel's support; the same bound also caps the
triangle's corner at `1 + 2|inc|`, which is what keeps a heavily skewed
triangle finite. `Math.abs` rather than the raw increment, for ticket 07.
`frequency` is declared `-20000…20000` instead of `0…20000`, the increment
clamps to `[-0.25, 0.25]`, and a negative frequency runs the phase backwards.
A modulator connected to `frequency` is no longer half-wave rectified at the
bottom - and rectifying it did not merely limit the sound, it produced a
different, wrong spectrum. `AudioParam` sums its inputs with the intrinsic
value, so connecting a node there is linear FM by construction.

The scheduler needed one branch, not a second code path: a backward crossing is
the same `addCrossing` call with its signed quantities negated. The ages do not
flip - below zero the overshoot and the rate are both negative and the quotient
is the same `d` in `[0, 1)`. Nor does the corner need a second sign: `corner`
carries the sign of `inc`, so `-slope0 * corner` comes out positive for a
negative increment, which is right, because phase 0 is the triangle's minimum
and a minimum in time stays a minimum however the phase reaches it.

Two degenerate ages needed guarding, both measured rather than imagined. An age
of exactly 1 puts a discontinuity on the previous sample, whose naive value is
the pre-jump one - the one arrangement `blepResidual4(0)` cannot express. Going
backwards it is reachable three ways: a cold start at any negative frequency
(measured -2.000), the `connectParams` path where an oscillator holds at phase 0
until its modulator's first sample arrives negative (2.000), and the width edge
at every `|frequency| >= sampleRate / 4`, where the clamp pins `width` to 0.5
and the phase lattice lands exactly on it (1.917). Reading such an age as 0
places the same band-limited step on the sample that does carry the post-jump
value; the crossing instant is genuinely ambiguous in all three.

Measured, 44.1 kHz: alias SNR at a negative frequency equals the positive figure
to the decimal in every cell of `ALIAS_FLOORS`, and peaks match to four
decimals, so the tests assert the negative side against the same tables rather
than a second set. The sine at `-f` negates the sine at `+f` to 2.1e-13, the
sawtooth and square to 3.0e-8 and 3.3e-12, and the symmetric triangle at `-f`
equals the triangle at `+f` exactly. A linear sweep through zero and an
audio-rate `200 + 3000*sin(2pi*220t)` both peak at 1.0000 for every waveform and
width. `width` driven at Nyquist with negative frequencies included peaks at
1.2109, below ticket 05's 1.281.

A positive-frequency render is bit-for-bit what a0a99b5 produced: 452 of 452
fingerprints identical, covering every waveform, seventeen frequencies, five
widths, the cold degenerate grid and a-rate frequency and width arrays.

The example moves its LFO from `detune` to `frequency` and gains FM depth and
rate sliders, ranged wide enough to cross zero.
An a-rate `sync` gate whose rising edge restarts the phase at a sub-sample
instant, and a `phase` construction option that says where it restarts to.
Audit F3 and F4, which turn out to be one piece of plumbing.

The reset goes through `addDiscontinuity` like every other discontinuity: a
step height and a slope change at an age in [0, 1). That is why the triangle
ships with the others rather than being deferred as the audit expected - its
reset produces a corner as well as a jump, and the primitive takes both in the
same call.

A sample that carries a reset is two sub-advances, not one. The phase runs to
the reset instant, jumps, and runs on to the sample, so a wrap or a pulse edge
on either side of the reset is corrected exactly once and at its own age.
Advancing once and resetting afterwards schedules crossings the reset
pre-empted and never walks the ones it really makes: measured over 432
settings that peaks at 2.6190 against 1.0037 for the version here.

An age of exactly 1 is the common case, not a corner case: a gate written with
`setValueAtTime` steps 0 -> 1 between two samples, which interpolates to the
previous sample - the one age the residual's convention cannot express, and
ticket 07's +/-2.000. It reads as 0, which is also the right answer for a
stepped gate.

Measured: the sample after the edge is `naive(phase + d*inc) +
h*blepResidual4(d)` to within 2.0e-3 at 440 Hz; the integer reading's error
grows monotonically with the fraction, 0.039 to 0.403. Against an uncorrected
reset, +0.94 to +23.82 dB of alias SNR with a non-integer master, and +0.85 to
+13.71 dB against the same phase trajectory with only the correction missing.
A reset every 1-32 samples peaks at 1.1667 and a noise-driven gate at 1.0875.

`phase` is a construction option rather than an AudioParam - a one-time
initial condition. `"random"` draws once per instance, so stacked detuned
oscillators stop combing at the attack.

`sync` declares the shared gate shape at a-rate, and `descriptors.test.ts`
asserts the shape whole with the rate per module rather than being weakened.

Nothing that does not use `sync` changes: 3584 of 3584 fingerprinted no-sync
renders are bit-for-bit identical to e336dcd, and a gate that never goes
positive produces the same samples as no gate at all.
The last of the polyblep tickets, describing the parameter surface the other
eight froze.

**Attribution.** The quadratic PolyBLEP residual is credited to Välimäki &
Huovilainen 2007, not to Brandt 2001 — Brandt's paper contains no polynomial at
all, and is cited instead for hard sync and MinBLEP. THIRD-PARTY-LICENSES.md now
separates the five papers the package cites from the one source it derives from,
states that the residuals in `src/_blep.ts` were obtained by integrating the
cardinal B-spline rather than transcribed from any table, and retires the sndkit
credit with its reason: the 2-point correction it described was deleted by the
discontinuity-scheduler rewrite, and The Unlicense owed no notice anyway. Ticket
04's stmlib MIT entry is untouched.

**README.** It used to open with a citation matching no paper and a usage example
that was literally `import {} from "@synthlet/polyblep-oscillator"`. It now has a
pasteable example, a parameter table matching `src/params.ts` cell for cell, the
`phase` construction option, sections for through-zero FM and hard sync, and the
four conventions a user cannot guess — phase 0 at the step and at the triangle's
minimum, the square `+1` first per the Web Audio spec, `frequency = 0` holds and
negative runs backwards, and two samples of output latency.

The measured alias SNR figures are in it with the metric described in one
sentence and scoped to this repository, and every one of them is a floor
`src/dsp.test.ts` asserts at the measured value minus 1.5 dB. There is
deliberately no dB number for the comparison against `OscillatorNode`: nobody has
measured the native node with the same metric.

**Docs page and demo.** `polyblep.mdx` compiles, lists the four types once with
their numbers, and documents `width`, `sync` and `phase`. The example is rebuilt
around the comparison the README declines to put a number on: a PolyblepOscillator
and a native OscillatorNode at the same pitch, taking the same waveform and the
same modulation, with a spectrum analyser on each and a switch for which one is
audible. Each analyser sits before its own mute, so both keep drawing.

New `site/examples/components/Spectrum.tsx` — an AnalyserNode plus a
requestAnimationFrame loop, on a linear frequency axis because a log axis reads a
mix better and a linear one reads aliasing better. It takes an analyser rather
than creating one, so the node stays inside the Compound and is torn down with it.

The vibrato demonstration that ticket 07 lost when it moved the LFO from `detune`
to `frequency` is restored as a second LFO, which is also what makes the linear-FM
point legible: one LFO shape doing two different things depending on the inlet.

**Metadata.** `package.json` gains `repository` (with `directory`) and `homepage`.
Three changes to the site example, none of them to the DSP.

`Audible` was a two-entry `<select>`, which is a lot of ceremony for a
binary. It is now one button carrying the name of the side you are
hearing, tinted with that spectrum's own colour so the control and the
graph it refers to are visibly the same thing.

Sliders take an optional `defaultValue` and render a small reset button
beside their readout when they get one, dimmed when already there. It is
opt-in precisely so the other twenty examples render exactly as before -
`Slider` is shared. The example passes one for all seven of its sliders,
which matters most for FM depth and Sync: both are easy to leave
somewhere unrecognisable while chasing a sound, and neither has an
obvious home position by ear.

Volume gains a mute button and starts muted. The mute is a separate gain
*after* the volume gain, so it never writes to the volume param -
unmuting returns to whatever level was dialled in - and it sits after
both analysers, so the spectra keep drawing while the page is silent and
a muted example is still a working demonstration. A "Unmute to hear"
note appears next to the button while it is, since two live spectra and
no sound is otherwise a bug report waiting to happen. Unmuting also
resumes the audio context: it is a click, which is the user gesture the
autoplay policy wants, and the context is a module-level singleton that
may well have been created suspended.
It was a 10px glyph in a hairline chip - legible as a decoration, not as
something to click. It now uses the same `border px-2 py-1 rounded
bg-fd-secondary` as every other button in the examples, and value and
button sit in an inline flex so the readout keeps its own baseline
instead of the button dragging it around.
# Conflicts:
#	packages/synthlet/src/descriptors.test.ts
#	packages/synthlet/src/worklet-copies.test.ts
#	scripts/copy_files.sh
@danigb
danigb merged commit c155243 into main Sep 6, 2026
1 check passed
@danigb
danigb deleted the feat/polyblep branch September 6, 2026 17:00
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