Skip to content

Modulation: ring mod, sample & hold, envelope follower, slew limiter - #60

Merged
danigb merged 5 commits into
mainfrom
modulation
Sep 12, 2026
Merged

danigb merged 5 commits into
mainfrom
modulation

Conversation

@danigb

@danigb danigb commented Sep 12, 2026

Copy link
Copy Markdown
Owner

Modulation: four primitives from Parts 10–17

Four new packages — the whole modulation folder, Tier 1 of the Synth Secrets
research. They are not four unrelated utilities: Part 16's Figure 6 is noise →
S&H → filter and Part 15's Figure 8 is follower → slew, so three of them exist
to be patched into each other. The fourth settles how a second audio signal
reaches a synthlet module at all.

What changed

  • Ring modulator —
    @synthlet/ring-mod: carrier × (offset + modulator) with a 5 Hz DC blocker
    on each input (packages/ring-mod/src/worklet.ts), offset spanning RM to
    AM. The modulator arrives as an a-rate AudioParam — the decision the rest of
    the library inherits, since connectParams wires params and nothing else.
  • Sample and hold —
    @synthlet/sample-hold, with track-and-hold as type. Both modes read the
    shared _gate.ts: Track takes its level from the detector's own open state,
    so nothing in the package compares to zero itself.
  • Envelope follower —
    @synthlet/envelope-follower: one mono control signal out, peak or RMS,
    attack/release as 99 % of a step. createFollower stays a closure in
    dsp.ts, so a vocoder's bank is reachable later.
  • Slew limiter —
    @synthlet/slew-limiter: exponential and linear, rise/fall separate.
    Linear arrives, so a gate through one still closes.
  • scripts/_smooth.ts — the folder's extract-or-copy question, answered
    extract with two instances in hand. One function and one constant, copied
    into the two packages that turn a time into a coefficient. What is shared is
    the library's definition of a second, not three lines of arithmetic; adsr
    and ad keep their own variants and are not retrofitted.

Deviations

Six success criteria did not survive contact with the arithmetic. Each is
reasoned in its plan and commit, and replaced by a test that pins the real
number: ring-mod bypass is bit-exact only when DC-coupled (a 5 Hz blocker has
1.00029 gain at 300 Hz) and Case 1's DC is 0.4991; SampleHold.trigger is
a-rate, because automation-rate ticket 03 moved every event param in the
library after that ticket was written; Rms needed two stages, since the
ticket's one-line formula ratchets to the peak and reads 0.93 for a unit sine;
peak unity gain needs attack: 0; ripple at the defaults is 0.6 dB, not 0.5.

Verification

origin/main moved under this branch (the instrument module, #59, changed
scripts/_worklet.ts), so it is merged in and the shared-file copies re-synced.
After that merge: 100 suites, 3249 tests, all passing. npm run build clean
with every generated processor in sync; check:rates and format:check pass.
Nothing was run in a browser — the four site examples are unexercised.

Next steps

  • Split into four branches and PRs if the folder README's one-PR-per-ticket rule
    is to be honoured; today this is four commits on one modulation branch.
  • Listen to the examples, especially SlewLimiter's, whose linear mode is
    deliberately unusable in cents.
  • The deferred voltage quantiser (Part 17) — S&H's other half; arp's
    scales.js already holds the tables.
  • The deferred Modulation guide page. All four modules now exist, which was
    its precondition.

https://claude.ai/code/session_01XGpZZMUoV3b3V9bFYW9PMm

`carrier × (offset + modulator)`, with a DC blocker on each input. `offset: 0`
is ring modulation, `offset: 1` is amplitude modulation — the ARP 2600's AC/DC
switch as a knob.

The multiply is four lines of stock Web Audio and does not justify a package.
The AC coupling does: a `GainNode` multiplies DC too, so an offset on either
input leaks the *other* signal straight through at full amplitude, and that leak
is the whole difference between a ring modulator and a VCA. Both inputs pass a
5 Hz one-pole blocker whose pole is computed from the sample rate, so 44.1 and
48 kHz block the same corner; `coupling: 0` turns them off to get Part 11's
"lesser RM" deliberately.

The **output** is not blocked. Reid's Case 1 — carrier and modulator at the same
frequency — puts the difference tone at 0 Hz, and the offset is signal.

Settles how a second *audio* signal reaches a synthlet module: as an a-rate
`AudioParam`. `connectParams` wires parameters and nothing else, so
`RingMod(ac, { modulator: osc })` needs no change to the module contract. The
two costs — an `AudioParam` input is down-mixed to mono, and an a-rate one is
clamped, which is why `modulator` declares ±10 — are in the README rather than
left to be discovered.

Eleven tests on the real processor, measured with the shared `_spectrum.ts`:
Figure 10's two sidebands with nothing within 60 dB at either input frequency,
Equation 6's halves at `offset: 1`, the leak appearing and disappearing with
`coupling`, Case 1's surviving DC, bit-exact bypass when DC-coupled, channel
independence, and 60 s of silence with no NaN.

Two success criteria in the ticket moved, with the arithmetic in the tests:
bit-exact bypass holds for `coupling: 0` but not for `coupling: 1` (a 5 Hz
blocker has a passband gain of 1.00029 and a 0.017 rad phase shift at 300 Hz),
and Case 1's DC is 0.4991 rather than 0.5 because both inputs carry that loss.

Claude-Session: https://claude.ai/code/session_01XGpZZMUoV3b3V9bFYW9PMm
Latch the input on a trigger's rising edge and hold it, plus the MS-20/Buchla
track-and-hold mode on the same latch. Two lines of DSP; the rest is contract.

The library had a `Clock`, a `Noise` and every filter you could point a random
voltage at, and nothing to connect them. Web Audio has no equivalent and neither
does the host side — an S&H is a sample-rate latch, not something a
`setValueAtTime` loop can fake without knowing the input signal.

Detection comes from the shared `_gate.ts`, which this is the first new package
to adopt since the wavetable oscillator. Both modes read it: `Track` takes its
level from the detector's own open state rather than comparing to zero itself,
so exactly one place in the package decides what positive means. The detector
advances once per *frame* and fills a scratch array of latch decisions, so a
stereo input samples at the same instant a mono one does.

No droop: the held value is bit-identical after 60 s, asserted. A droop
parameter would be a slew limiter pointing the wrong way.

One deviation from the ticket, and the reason is in the plan and in
`descriptors.test.ts`: `trigger` is declared **a-rate**, not k-rate. The ticket
cited the `ad`/`adsr` pattern from the envelopes folder, but automation-rate
ticket 03 has since moved every event param in the library to a-rate, and the
list that pins it says a new module declaring a k-rate trigger should fail
there. The ticket's own argument agrees, and harder: 2.9 ms on an envelope is a
late start, but on an S&H fed noise it is a *different* random value. A k-rate
caller still works — both cases are tested.

Fourteen tests: ten steps per second at the edge sample, 60 s without droop, the
whole retrigger table (0.001 fires, 0 and −1 do not), track mode's transparency
and its 50/50 split, a one-sample pulse making T&H identical to S&H, channel
independence, and the a-rate/k-rate pair on a mid-block edge.

Claude-Session: https://claude.ai/code/session_01XGpZZMUoV3b3V9bFYW9PMm
Rectify, then charge and discharge at different rates — Part 15's module, and
the missing half of the library's signal flow. `AdsrEnv` makes an envelope from
a gate; `LevelMeter` measures amplitude and posts it to the main thread. Nothing
took audio in and produced something an `AudioParam` could be driven by, so
nothing in synthlet could respond to the loudness of anything else.

`attack` and `release` are the time to cover 99 % of a step — the library's one
meaning for a time in seconds since the envelopes folder settled it. The README
gives `t = τ × 4.605` for porting from a plugin that labels time constants,
rather than admitting a second meaning. `0` is instantaneous, not a division by
zero, and the coefficient comes from `sampleRate` so 44.1 and 48 kHz agree.

`createFollower` stays a small closure over a sample rate, `createAdsr`'s shape,
so the whole test file drives it with no worklet stub — and so a bank of them is
reachable when the vocoder lands. Nothing is extracted to `scripts/`; ticket 04
makes that call with two instances in hand.

Three of the ticket's success criteria moved, each because the arithmetic says
so rather than because the tolerance was inconvenient. All three are in the plan
and in the tests:

- **`Rms` is two stages.** Running the asymmetric filter straight on the squared
  signal is not RMS: a rectified sine's square swings 0…1 at twice the signal
  frequency, so a fast attack and a slow release ratchet it towards its *peak*
  and a unit sine reads 0.93 rather than 0.707. A mean needs a symmetric filter,
  so the averaging stage uses `release` in both directions and the asymmetric
  stage shapes the result — a compressor's RMS detector. Sine reads 0.707,
  square reads 1.0.
- **Peak unity gain needs `attack: 0`.** A one-pole covers a fraction of the gap
  per sample and a sine's peak is instantaneous, so at 1 kHz `attack: 0.01`
  settles at 0.952. Both numbers are asserted; the second is the fact the docs
  page points at.
- **The ripple bound is 0.6 dB at the defaults**, measured, not the 0.5 dB the
  ticket guessed — and under 0.2 dB at `release: 0.5`. The test pins both ends,
  which turns the docs page's guidance into something that fails if it stops
  being true.

One mono output whatever the input carries, declared with `outputChannelCount`:
a stereo control signal would be two inconsistently timed copies of one
decision. Channels fold into the detector instead — `Peak` by maximum, `Rms` by
mean square.

Twenty tests, and a line in each of the two READMEs saying why this and
`LevelMeter` are not the same module.

Claude-Session: https://claude.ai/code/session_01XGpZZMUoV3b3V9bFYW9PMm
Rate-limit a control signal — portamento, and the smoother Part 16 puts after
an S&H and Part 15 after the envelope follower. One module, referenced twice by
the book, missing from the library both times. `setTargetAtTime` is not a
substitute: it is host-side automation on one `AudioParam`, so it cannot sit in
a signal path or smooth a signal arriving from another node.

Both laws ship as `type`, and they are different modules wearing one name.
`Linear` is what the name strictly means — a rate cap, so a step becomes a
straight ramp that *arrives*. `Exponential` is what the book depicts and is the
default, for a reason about units rather than taste: a linear rate is per unit
of the signal, so 1 unit/second is a lifetime on a [0,1] CV and imperceptible on
a frequency in Hz, while a proportional move takes the same time whatever the
step and whatever the unit.

That leaves `rise`/`fall` with two meanings — 99 % of a step in exponential,
seconds per unit in linear — which is a real wart, deliberately accepted: a rate
limiter has no notion of a step, and a second parameter inert in the other mode
would be worse. Both rows are in the README and on the docs page, and the site
example demonstrates the cost rather than describing it.

Linear reaches exactly zero, so a gate through one still closes; the test drives
`createGateDetector` over the output to prove it. Exponential gets no matching
assertion, because that is the documented warning rather than a supported use —
and the gates page's existing callout now names the module and its one safe mode.

State is `Float64`: the linear law accumulates 4410 steps for a 100 ms ramp, and
in single precision the drift exceeds the 1e-6 the ramp is asserted against.

**The extract-or-copy decision: extract.** `scripts/_smooth.ts` now holds one
function and one constant — the coefficient of a one-pole covering 99 % of a
step, and ln(100) — copied into this package and `envelope-follower`, added to
`copy_files.sh`, and asserted by name in `worklet-copies.test.ts`.

The thing being kept in one place is not "a one-pole", it is the library's
definition of a time in seconds. If the two drifted, `0.1` would mean 99 % of a
step in one module and something else in the one beside it, and a caller moving
a setting between them would get a different move with no error and no clue why
— the class of silence `_gate.ts` exists to prevent. `karplus-strong` declined
`_delay.ts` because adopting it would have changed its behaviour; nothing
changed here, and the follower's twenty tests pass untouched.

Not dragged in to justify the file: the direction choice, the follower's
rectifier and RMS stage, the linear branch, and `adsr`'s TCO machinery. `adsr`
and `ad` keep their own variants, so the file covers two of the library's four
smoothers — which the header says rather than overstating.

Claude-Session: https://claude.ai/code/session_01XGpZZMUoV3b3V9bFYW9PMm
The instrument module (#59) landed after this branch started and changed
`scripts/_worklet.ts` — `Connector` and `createWorkletConstructor` now take a
`BaseAudioContext` — so the four new packages carried a stale copy that
`worklet-copies.test.ts` would have failed on. Re-ran `scripts/copy_files.sh`.

Two textual conflicts, both additive:

- `packages/synthlet/src/index.ts`: the explicit enum re-exports, where
  `StealMode` and `RingModType`/`SampleHoldType`/`SlewType` were added at the
  same place. Both kept.
- `scripts/copy_files.sh`: `_smooth.ts` against `_voices.ts`/`_traversal.ts`.
  Both kept, and the header sentence rewritten to name all eight shared files
  rather than either branch's subset.

`registerAllWorklets` is 28 and the count in `registrars.test.ts` matches:
instrument registers through its own registrar, so main's 24 plus this branch's
four is right.

Full suite after the merge: 100 suites, 3249 tests, all passing. Build clean
with every generated processor in sync; `check:rates` and `format:check` pass.

Claude-Session: https://claude.ai/code/session_01XGpZZMUoV3b3V9bFYW9PMm
@danigb
danigb merged commit 239fb73 into main Sep 12, 2026
6 checks passed
@danigb
danigb deleted the modulation branch September 12, 2026 16:42
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