T-016 — Parameter changes while playing: recompute coefficients off the audio thread and swap them in without a lock or a free
Status: done — D1–D7 accepted as proposed (maintainer, 2026-12-02) · Area: rust, piano · Depends on: T-008, T-009
Read for that: Piano 13 (Changing parameters while playing: the three control classes), T-008 (Outcome: CoeffSet, Bank, Span), T-009 (how the plugin drives the engine, the gain parameter and its state), Plugin formats (audio-thread rules), crates/dsp/src/piano/{coeffs,resonator,engine}.rs, crates/piano/src/{audio,params}.rs.
Why: today everything that depends on the model is computed once, in prepare at activate. Piano 13’s recompute class (tuning, decay scale, inharmonicity scale, later the model and the quality level) needs a path that builds a new coefficient set while the piano plays and hands it to the audio thread, which must not wait, allocate or free. Every later control of that class (T-018 tuning, T-029 quality levels, T-030 model files) uses this path, so it is built once, here, with real controls that exercise it.
Measured for this page: PianoEngine::prepare (a full CoeffSet for the committed model, 7,904 modes) takes 0.37 ms in release on this VM, at 44.1, 48 and 96 kHz. A recompute is therefore cheap; the latency of a change is set by how the worker is woken (D4), not by the computation.
What
- Split state from coefficients in
crates/dsp: the modes’ complex states (zr,zi) move out ofBankinto the engine; everything rate- and setting-dependent (delta coefficients, gains, excitation table, spans,gain_abs) is the swappableCoeffSet, built byCoeffSet::new(model, rate, &Settings). Settings: the recompute-class values, with defaults that reproduce today’s coefficients bit for bit (the golden test is unchanged). First members per D1.- Exchange (D3) and worker (D4): a request (new
Settings) is written by the main thread or the audio thread; a worker thread builds the set and sends it; the audio thread takes it between blocks (D5) and sends the old one back; the worker frees it. - The plugin: the two parameters of D1 (ids, ranges, automation and state per D7), applied through this path.
- Pages: Piano 13’s table names what exists; Plugin formats gets the rule “recompute-class parameters apply at a block boundary, ~10 ms after the change”.
Decisions (accepted as proposed)
| Question | Options | Proposal | |
|---|---|---|---|
| D1 | Which controls exercise the path now (format v1 holds only fitted frequencies, decays, gains) | (a) two controls v1 can express: Sustain (a factor on the free decay times, ×0.25 … ×4, default ×1) and A4 (reference pitch 415–466 Hz, default 440: one frequency ratio for every mode); stretch, temperaments and MTS-ESP stay with T-018, which then builds on this path; (b) the mechanism only, exercised by tests, the first plugin controls with T-018/T-025; (c) (a) plus switching to another model file | (a): the path is tested end to end in a host, and both are in Spec 001’s first set of controls. (b) leaves the plugin side untested until a later task; (c) is a layout change (D6) |
| D2 | What Sustain and A4 do to the modes | (a) Sustain : free decay ; damped rate unchanged but kept the new free rate (the format’s invariant), so a released key still stops as fitted. A4: every freq_hz × A4/440; the set’s layout (which modes exist) stays the one built at prepare; a mode tuned to or above Nyquist gets zero coefficients and gains and its state is zeroed at the swap; modes culled at prepare stay culled when tuning down (they are above 20 kHz at 44.1 kHz). (b) scale the damped rate with Sustain too; (c) rebuild the layout on every tuning change (a layout change, D6) | (a): the layout never changes for these controls, so ringing keys carry over (D5); a mode muted at the top of the spectrum is inaudible |
| D3 | How sets travel between threads | (a) two wait-free single-producer single-consumer rings (rtrb): new sets worker → audio (capacity 1), retired sets audio → worker (capacity 2), carrying Box<CoeffSet>; no unsafe in our code (crates/dsp stays deny(unsafe_code)); (b) a hand-written single slot on AtomicPtr (Box::into_raw/from_raw: unsafe, ours to get right); (c) basedrop (reference-counted pointers whose last drop is deferred to a collector) | (a): the smallest safe primitive; check rtrb’s real API in ~/.cargo/registry/src/ before use. The audio thread pops a new set only if the retire ring has room, so it never has to keep or drop the old one |
| D4 | Where the recompute runs and how it learns about a request | (a) a worker thread per engine, started at activate, stopped and joined at deactivate (both main thread); requests are atomics (the values plus a generation counter) that the main thread, the GUI and the audio thread write; the worker polls them every 5 ms, builds a set when the generation moved (the latest values win, so a slider drag coalesces), and frees retired sets. Framework-free, in crates/dsp, so the standalone app (T-026) reuses it; (b) the CLAP main thread through request_callback (no thread of ours, but plugin-specific and it stalls the GUI for the build); (c) as (a), but the audio thread wakes the worker with Thread::unpark (a futex syscall on the audio thread) | (a): the audio thread only stores atomics; ≤ 5 ms polling + 0.4 ms build ≈ 6 ms to the swap, a few ms more until the next block. Idle cost: one wake-up per 5 ms per instance |
| D5 | When and how the audio thread swaps | (a) at the start of render, once per call: take a waiting set, keep the states, send the old set back; no crossfade — the states are continuous, so a step in decay or pitch between two blocks does not click; (b) crossfade the outputs of old and new set over 10 ms (two coefficient sets live, double cost while fading, and the two would diverge in state) | (a): one pointer swap per change. Changes are block-accurate, not sample-accurate (D7) |
| D6 | Changes of layout (another model, T-019/T-030; quality levels that add or drop modes, T-029) | (a) out of scope, the rule written down here: the new set carries its own state arrays; the engine fades the old output out over ~20 ms, then swaps both (old set and states go back to the worker); built and tested with its first user; (b) build it now with a synthetic second model | (a): nothing in the plugin can trigger it yet, and its first user decides details (e.g. whether ringing keys may finish on the old set) |
| D7 | Automation, ids and state | (a) ids 2 (Sustain) and 3 (A4), stable forever; automatable, not modulatable (CLAP’s per-note modulation makes no sense for a whole coefficient set); host automation applies at the next swap, so ramps become steps of ~10 ms; the plugin state becomes version 2 (gain, sustain, A4), version 1 still loads with the new parameters at their defaults; (b) not automatable (only GUI/host edits) | (a): hosts expect a parameter to be automatable, and steps of ~10 ms in a decay or tuning change are inaudible as steps. The parameters follow params.rs’s pattern; T-025 moves all of them into crates/params |
D7 follow-up. T-025 moved the parameters into the shared store. The plugin now saves id-keyed v3 and still loads v1 and v2. Host automation and editor edits update the store, and the coefficient worker receives its applied settings. Piano parameter state
Done when
Tests first.
- dsp: with default
Settingsthe golden test passes unchanged at block sizes 1, 64, 513; a swap to an identical set mid-note gives bit-identical output to no swap; after a swap to Sustain ×2 the envelope of a held C4 partial decays at half the rate from the next block on (closed form, as T-008’s damper test), with no click (the largest sample-to-sample difference around the swap is no larger than elsewhere in the note); A4 466 Hz moves a partial’s measured frequency by the ratio (≤ 0.1 cent), and a mode pushed above Nyquist at 44.1 kHz is silent and finite; the damped rate stays ≥ the free rate at Sustain ×4. - Real-time:
renderwith swaps happening allocates and frees nothing (assert_no_alloccatches both); with the retire ring full,renderleaves the new set waiting and swaps on a later call; a stress test (one thread renders, another requests changes as fast as it can, for a few seconds) ends with every set freed on the worker (counted) and finite output. - Worker: a request is applied within 20 ms; a burst of 100 requests produces far fewer builds than requests, and the last values win;
deactivatejoins the worker and frees everything. - Plugin (
crates/piano/tests/host.rs): a host parameter event for Sustain lengthens a held note’s tail; A4 changes the pitch of a struck key; state version 2 round-trips, version 1 loads with defaults;clap-validatorpasses (35 / 0 / 9 or better), and the GUI smoke test passes. - Gates green; the default sound is unchanged (golden test), so the demo renders need no refresh.
Pages: this page’s Outcome, Piano 13’s Changing parameters while playing (what is built), Plugin formats (block-accurate recompute parameters), backlog rows of T-016 and T-018 (A4 moved here if D1 (a)), Status.
Out of scope: stretch, temperaments and MTS-ESP (T-018), layout changes (D6: T-019/T-029/T-030), crates/params (T-025), GUI controls for the new parameters (T-020; until then the host’s generic parameter view shows them).
Outcome (done, 2026-12-02)
Implemented by Codex (gpt-6.2-sol) from this page; reviewed by Mistral Large 4 (no defects; static only, its sandbox refused cargo) and by the maintainer’s session.
- dsp (
crates/dsp/src/piano/):ModeState(zr,ziand the pending contact stateur,ui) lives in the engine;Bankholds only coefficients and gains.CoeffSet::new(model, rate, &Settings)withSettings { sustain, a4_hz }(coeffs.rs): free decay rate ÷ Sustain, damped ratemax(damped, free), every frequency × A4/440; the layout comes from the untuned frequencies (D2), a mode tuned to or above Nyquist ismuted(zero coefficients and gains, no excitation, state zeroed at the swap). DefaultSettingsreproduce the old coefficients exactly (golden test unchanged: 3.70e-5 / 4.75e-5 of the peak at block sizes 1, 64, 513). - Exchange and worker (
exchange.rs):SettingsRequests(atomics plus a generation counter, clamped, NaN → default) is written by any thread;Worker(threadpiano-coefficients, started byPianoEngine::activate, stopped and joined at deactivate or drop) polls every 5 ms, builds with the latest values when the generation moved, and frees retired sets; at shutdown it also takes the current set and drains both rings.AudioExchange::swap(twortrbrings, new 1, retired 2) runs inbegin_block: it takes a waiting set only when the retire ring has room.render=begin_block+render_segment; the plugin callsbegin_blockonce per host block andrender_segmentper event batch, so a block keeps one set. - Plugin: parameters 2 Sustain (×0.25 … ×4) and 3 A4 (415–466 Hz), automatable; the host’s events reach
SettingsRequestsfromprocess, bothflushes and state load. State version 2 =[2][gain][sustain][a4](little-endian f32); version 1 loads with both at their defaults. - Tests (
crates/dsp/src/piano/engine/tests.rs,crates/piano/tests/host.rs,no_alloc.rs): identical swap mid-note bit-identical (with hammer contact pending); Sustain ×2 → held C4 partial’s decay rate ratio 0.4999989 from the next block, no larger step at the swap; A4 466 Hz → +0.000024 cent off the ratio, a mode above Nyquist silent and finite; damped ≥ free at ×4; a full retire ring defers the swap without allocating or freeing; one host block keeps one set when split by events; worker latency 7.7 ms (bound 20 ms), a burst of 100 requests → 1 build, last values win; 2 s stress (one thread renders, one requests): 393 builds, all 393 freed on the worker, finite output. Plugin: Sustain lengthens a held tail, A4 moves a struck key’s pitch, state v2 round-trips and v1 loads with defaults, ids/ranges/flags; the plugin’s no-alloc test sends Sustain and A4 and swaps underassert_no_alloc. - Gates: fmt, clippy, nextest 88 passed / 1 skipped;
clap-validator35 / 0 / 9; GUI smoke test passed. The default sound is unchanged, so no demo refresh. - Left as they are: re-
activatedrops the previous set on the main thread (never the audio thread);PianoEngine::prepare(used by the demos) stops a worker and builds default settings.