Skip to content

Automation rate improvements - #48

Merged
danigb merged 9 commits into
mainfrom
chore/automation-rate-benchmark
Sep 7, 2026
Merged

danigb merged 9 commits into
mainfrom
chore/automation-rate-benchmark

Conversation

@danigb

@danigb danigb commented Sep 7, 2026

Copy link
Copy Markdown
Owner

Made with Claude

Answers ticket 00. Zero-dependency harness: OfflineAudioContext for
timings, Chrome's remote-debugging endpoint driven over Node's global
WebSocket, no SharedArrayBuffer and no reliance on `performance`
existing in AudioWorkletGlobalScope.

Chrome 152 findings: declaring a param costs ~0.30 us/node/block and
the rate is free - k-rate and a-rate are indistinguishable when
nothing is connected. Reading a param is 5x cheaper than declaring
it. Chrome collapses a constant sum to length 1, not just absent
automation, so an a-rate param fed a ConstantSourceNode still arrives
as length 1; only a varying value forces 128. With a real modulator
connected, a-rate is no more expensive than k-rate - k-rate just
discards the samples. Change detection removes 24% of a per-sample
coefficient recompute when the value is static.

Includes probe.js, which reports delivered length alongside
within-block spread - length alone cannot distinguish 'constant' from
'decimated'.
`worklet.ts` built its generator with `createLfo(sampleRate, false)`, so every
`Lfo` in the library emitted one value per render quantum - a 344 Hz staircase
at 44.1 kHz, whatever it was patched into. `generateAudioRate` has been
complete, correct and unreachable since it was written. Flip the argument.

Since #45 made `PolyblepOscillator.frequency` a-rate, this was the only thing
still quantising `MonoSynth`'s vibrato.

The block-constant generator was also not a decimation of the right signal: it
advanced the phase by a whole block and evaluated `gen(phase, nextPhase)` once,
so the two-endpoint shapes read a block-averaged value and an `Impulse` LFO
emitted a 128-sample pulse. It stays reachable through the argument, which stays
in place and unexposed per the folder's decision table, and it is tested.

`generateAudioRate`'s loop now hoists its generator, increment and scalars. All
five were read from the closure 128 times and all five are fixed for the block -
`read()` runs once and every parameter `Lfo` declares is k-rate. Worth 34% of
the function; output bit-identical, asserted sample-for-sample.

No parameter changed its automation rate.

Tests are new - the package had none. 19 assertions in `dsp.test.ts`, 13 of
which fail against the block-constant generator, and 5 in `worklet.test.ts`, 2
of which do. Energy at the render-quantum rate and its first three harmonics
goes from 37-49 dB below the fundamental to 146-158 dB, which is the
`Float32Array`'s own noise floor. `lfo` opts into `_spectrum.ts` to measure it.

`benchmarks/lfo-rate/` measures the generator side that ticket 00 could only
extrapolate: 0.66-1.67 us/block against a predicted 0.3-0.6. Optimistic by 3x,
and still 0.06% of one core.

Ticket: thoughts/tickets/automation-rate/01-give-the-lfo-a-signal.md
`input` and `mod` become a-rate, and the processor reads them per sample.

`Param` implements the library's central bet - numbers and nodes are
interchangeable at every parameter - and its whole `process()` was seven reads
at `[0]` and a `fill()`. Anything routed through it was decimated to one value
per render quantum, including the vision document's own headline example,
`Param(ac, { input: 1, mod: lfo })`.

It also included every instrument's note timing. All eleven drum voices build
their trigger inlet from a `Param` and `MonoSynth` builds its gate from one, so
a gate edge was quantised here before it reached an envelope that could already
read a-rate - which is why ticket 03 depends on this one. `_gate.ts:11-15`
promises the contract is "invariant under `Param`"; it was invariant in value
and not in time.

The `fill()` stays as the fast path and it is the common one: benchmark finding
3 measured Chrome collapsing a constant *sum* to length 1, so an unconnected
param and a constant-connected one both take it. A test spies on `fill` rather
than timing anything.

`this.c` and the four coefficients are hoisted out of the loop - `scale` is
k-rate so the converter is fixed for the block, and this is the
most-instantiated node in the library, sixteen of them in an eight-voice pool.
Length tests hoisted and spelled `length > 1`, ticket 05's form, so 05 has
nothing to normalise here.

`gain`, `offset`, `min`, `max` stay k-rate as coefficients; `scale` stays
structural. All seven now carry their reason, and `params.ts` says that k-rate
is an opt-out of the spec default.

New `worklet.test.ts`: 21 assertions, 10 of which fail against the old `fill()`.
`index.test.ts` gains the check the ticket asked for - that no factory variant
touches the signal path's rate.

Ticket: thoughts/tickets/automation-rate/02-let-param-carry-a-signal.md
Six descriptors flip: `adsr.gate`, `ad.trigger`, `karplus-strong.trigger`,
`impulse.trigger`, `arp.trigger`, `euclid.clock`.

**Note placement moves**, which is the one audible break in the folder. A note
used to land at the top of the next render quantum - up to 2.9 ms late at
44.1 kHz, and by a different amount for every event, so a repeated pattern did
not swing consistently. Pre-1.0 this is free; after 1.0 it would not be.

Three of the six already read rate-agnostically, behind an opt-in that was
invisible in `X.descriptors`, unreachable through a compound, and verified on
headless Chrome and nothing else. They needed the descriptor and a comment
rewrite. The other three needed the read:

- `impulse` - the detector consumes every sample. This fixes a *dropped* event,
  not just a late one: reading one sample per block meant a pulse that rose and
  fell inside a quantum produced no impulse at all. The impulse still goes at
  index 0, deliberately and deferred, so two edges in one block still yield one.
- `arp` - the note changes at the trigger's sample. `createArpeggiator` memoises
  the note-to-frequency conversion so the per-sample call is a comparison rather
  than a `Math.pow`.
- `euclid` - `clock` is a phase ramp, so a step boundary lands on its own sample.
  `generate` splits into a per-sample `step()` and a hoisted `length > 1` check.

Depends on 02: a compound's gate goes `caller -> Param.input -> Adsr.gate`, and
declaring the envelope a-rate while the conduit filled a block constant would
have changed nothing for `MonoSynth` or the drums.
`packages/synthlet/src/gate-path.test.ts` asserts the two meet.

`descriptors.test.ts`'s trigger table said k-rate for seven of nine entries and
carried an argument for why. Both are now the other way round, so a new module
declaring a k-rate trigger fails there.

Nothing costs more. Every processor takes a hoisted `length > 1` fast path when
the parameter arrives unautomated, and benchmark finding 2 measured k-rate
saving nothing when a node is connected.

`gatePulse` and the `Clock`/`Euclid` producers are untouched. Relaxing the pulse
width is deferred.

Ticket: thoughts/tickets/automation-rate/03-declare-the-event-params-a-rate.md
`Math.floor(params.type)` reads the whole `Float32Array`. It has been correct
since the day it was written, by accident: `Math.floor` coerces, a
`Float32Array` stringifies through `join`, and a length-1 array stringifies to
its single value - and `type` is k-rate, so the array is always length 1.

Give it more than one value and it stringifies to "3,3,3", `Number("3,3,3")` is
`NaN`, and `bank[NaN] || bank[0]` selects the Moog ladder for every type. No
error, no warning, and audio that still sounds like a filter.

No behaviour changes. This lands on its own, before the rate half of the ticket,
because a one-character correctness fix should not wait on a rate decision and
should be reviewable without one.

The test that pins it forces a length-3 `type` and asserts each of the nine
models still selects itself - the shape that breaks the old code.

Ticket: thoughts/tickets/automation-rate/04-the-missing-index-then-filter-parity.md
The library has two filters and they gave opposite answers about rate.
`state-variable-filter` has declared `frequency` a-rate since it was written and
is the origin of the house read idiom; this one declared `frequency`, `detune`
and `resonance` k-rate with no stated reason. So `MonoSynth` gets a smooth
envelope sweep through `Svf` and the same patch built on `VirtualAnalogFilter`
got a 344 Hz staircase - and a 200 Hz modulator was not quantised but aliased,
to 144 Hz.

There was no cost argument either: benchmark finding 2 measured k-rate saving
nothing when a node is connected, which is the configuration a filter cutoff is
in whenever anyone cares about it.

**The mechanism is runs, not a per-sample `update()`.** The nine models are
Faust-generated and `update()` only stores its arguments - every coefficient,
the `Math.tan` and korg35's `Math.pow`, is computed at the top of `process()`.
So updating per sample without splitting the render would apply the *last*
sample's coefficients to the whole block: worse than today, and just as quiet
about it. Instead the block is rendered in runs of constant coefficients. One
run when nothing is automated, which is exactly what it cost before; 128 when a
modulator genuinely moves every sample, which is the recompute the smooth sweep
needs. Change detection then skips even the one update when nothing has moved -
finding 4 measured that at 24%.

`Filter.process` takes a `from`/`to` range so a run needs no `subarray` and the
audio thread allocates nothing. The generated Faust bodies are untouched apart
from the loop bounds - six sites across five files.

Change-detection state is per channel, alongside the per-channel filter bank.
One shared pair of locals would report "unchanged" for every channel after the
first and leave their coefficients stale; the ticket flagged this and there is a
test for it.

`type` stays k-rate: an index into a bank of nine circuits, and switching it
mid-block is a discontinuity rather than a feature. Its selection is asserted
again with `type` forced a-rate, which is the condition that would have
detonated the missing `[0]` fixed in the previous commit.

`packages/synthlet/src/filter-parity.test.ts` asserts the thing the ticket is
named for: a sweep through either filter is comparably smooth.

Ticket: thoughts/tickets/automation-rate/04-the-missing-index-then-filter-parity.md
The library had one rule for reading an `AudioParam` array, three spellings of
it, and none of them written anywhere a package author would look.

**The idiom now lives next to `ParamDescriptor` in `scripts/_worklet.ts`**,
which `copy_files.sh` already puts in all 23 packages - so the convention
travels with the type it constrains, the way the gate contract travels next to
`createGateDetector`. It says what a-rate delivery actually looks like (length 1
*or* one value per sample, per the spec's MAY, and Chrome collapses a connected
constant to 1, so length 1 is the common case rather than a corner), the hoisted
`length > 1` form, and why not `length === n`.

`length === n` agrees with `length > 1` whenever the block being rendered is a
whole render quantum, and is silently wrong the moment a DSP renders a
sub-block. `karplus-strong` splits a block at each trigger edge; ticket 04 made
`virtual-analog-filter` render one segment per distinct cutoff. In a 40-sample
segment a 128-sample parameter has `length !== n` and would be read once and
held - audio that still sounds like audio.

Converted: `state-variable-filter`, `lookahead-limiter` (where it was already
`length === blockSize && blockSize > 1`, the same test the long way round),
`polyblep-oscillator`, `wavetable-oscillator`. Variant C stays in
`karplus-strong`: its `typeof` is about a union type, not about rate.

`wavetable-oscillator` gets a real improvement out of it. Its barrier comment
argued that a one-element stand-in *is* a-rate when the block is one sample
long, so the stochastic stage could engage on an input nobody supplied. Under
`> 1` a stand-in is never a-rate and the hazard is gone; the comment says so
rather than being carried over. Its block-size test now references a two-sample
render rather than a one-sample one, because at a block of one the two
deliveries are byte-identical and no rule can tell them apart.

**`scripts/check-param-rates.mjs` is the durable half.** It reads each package's
`params.ts` and its processor together - the only thing that would have caught
`Math.floor(params.type)`, correct by accident for its whole life with no test
that could have failed. `npm run check:rates`, and a CI step next to the
generated-bundle guard. A deliberate `[0]` read declares itself with
`rate-ok: <reason>`; there is no silent exemption, and a `params.ts` the guard
cannot parse is reported rather than passing quietly.

`.mjs` and not the `.ts` the ticket named: the workspace has no TypeScript
runner and one guard is not a reason to add a dependency.
`benchmarks/automation-rate/run-chrome.mjs` is the same shape for the same
reason.

`packages/synthlet/src/param-rates.test.ts` watches the guard fail - both shapes
it exists to catch, four it must not flag, and the library itself.
`karplus-strong` gains the sub-block assertion the ticket asked for: a pluck
whose block is split at the trigger keeps its pitch when `frequency` arrives
length 1, and takes the segment's own value when it arrives per sample.

No behaviour changes in any shipped configuration.

Ticket: thoughts/tickets/automation-rate/05-one-idiom-and-a-guard.md
125 parameters across 23 packages, and every one now carries a ground for its
automation rate. Before this pass 69 did - and 30-odd of those were written by
tickets 02, 03 and 04 of this folder while the files were open.

Comments only. `git diff` on the 21 changed `params.ts` files, with comment
lines stripped, is empty; no `processor.ts` regenerates and no test changes.

Every header now says how many parameters the module declares, how many are
a-rate, and that `automationRate` defaults to `"a-rate"` in the spec - so a
`k-rate` is an explicit opt-out and reads as one. The count is the input to any
future `processorOptions` conversation: `karplus-strong` declares fifteen,
`dattorro-reverb` nine, the two delays eight each.

**The taxonomy is two grounds, not three.** The ticket documented (a)
structural, (b) block-consumed and (c) "nobody modulates it". Benchmark finding
1 says the rate is free when unautomated and finding 2 says k-rate saves nothing
when a node is connected - it renders the modulator and discards the samples.
So (c) was never a cost argument, only ever a claim that modulating the
parameter would be meaningless, which is (a) or (b) wearing different clothes.
`scripts/_worklet.ts` has said so since ticket 05; this pass applies it.

**Nineteen parameters across eleven packages are honestly (c)**, and each says
so in the word the ticket asked for - `**A bet**` - so the list is greppable
rather than only written down:

    grep -rn '\*\*A bet' packages/*/src/params.ts

Ranked, with the size of each fix, in
thoughts/plans/20260907_ar06_a_reason_for_every_rate.md. The first one is
`state-variable-filter.Q`: ticket 04 made `virtual-analog-filter.resonance`
a-rate, so the library's two filters now disagree about resonance in the same
way they disagreed about cutoff before this folder started. The best-value
bundle is the four output crossfades - `granite.wet`, `dattorro-reverb.dryWet`,
`analog-delay.mix`, `digital-delay.mix` - which are plain per-sample multiplies
that are k-rate only because they arrive through the same per-block `update()`
as the coefficients.

Ticket: thoughts/tickets/automation-rate/06-a-reason-for-every-rate.md
Brings in #46 (Granite improvements) and #47 (FlexAudioBufferSource ->
TimestretchAudioSource). Three conflicts, all in files this branch also
rewrote.

**`packages/granite/src/params.ts`** - main replaced the four-parameter engine
with an eighteen-parameter one, so ticket 06's pass on the old `wet`/`speed`/
`density`/`spread` had nothing left to describe. Took main's file and re-applied
the convention to it.

Its header carried a cost argument this branch disproves: "not worth 128 floats
per parameter per block". `benchmarks/automation-rate/` measured that and it is
wrong twice over - declaring a parameter costs ~0.30 us/node/block with the rate
free, and an a-rate parameter with nothing varying connected still arrives as a
single value, so the 128 floats only exist once somebody has patched something
in, at which point k-rate renders the modulator and discards the samples.
Replaced with the honest ground: fifteen of the eighteen are read once per grain
at activation, which is (b). `freeze` is (a). `wet` and `feedback` are applied
per sample and are marked **A bet**, joining the folder's candidate list.

**`packages/synthlet/src/descriptors.test.ts`** - main added
`["Granite", "freeze", "k-rate"]` to the trigger-like table, against this
branch's claim that every trigger-like param is now a-rate.

Kept `freeze` k-rate. It is not an event: it borrows the gate shape (`> 0`, so a
scaled control still opens it) to latch a *mode*, and `dsp.ts` crossfades 100
samples across each edge - so the splice is what a listener hears, not the
sample the edge landed on, and placing it exactly would buy nothing the fade
does not already cover. Narrowed the claim the test pins from "every
trigger-like param" to "every param that places an *event*", and said why
`freeze` is the exception.

**`packages/synthlet/src/worklet-copies.test.ts`** - both sides added a package
to `spectrumPackages`. Kept both: `granite`, `lfo`.

Verified on the merged tree: 60 suites, 1519 tests, 42 snapshots pass;
`npm run build` leaves every generated bundle unchanged; `npm run check:rates`
and `prettier --check` pass. The two lockfiles are byte-identical to main's.
@danigb
danigb merged commit 75e8ac9 into main Sep 7, 2026
1 check passed
@danigb
danigb deleted the chore/automation-rate-benchmark branch September 7, 2026 07:27
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