Piano 13 — Real-time implementation: from equations to a CLAP plugin
Builds on
all pages before. Cost and quality levels: Piano 14. Code lives in
crates/dsp(ADR-0002), the plugin on clack (ADR-0001), the GUI on egui (ADR-0006). Parameters come from the piano model file; how it is tested: Testing and evaluation.
Three numerical methods for the strings
| Method | How | Strengths | Weaknesses |
|---|---|---|---|
| Digital waveguide (02) | delay lines + loop filters | cheapest per string; cost independent of partial count | inharmonicity needs dispersion filter cascades; per-partial decays need high-order filters; fitting data to filters is indirect |
| Modal synthesis | one damped oscillator per partial, coupled to hammer and bridge through mode shapes | fitted , plug in directly; exact inharmonicity; trivially parallel (SIMD); differentiable in Julia with the same structure | cost ∝ number of partials (bass notes have many) |
| Finite differences (Bilbao; Chabassier et al.) | discretise the PDEs in space and time | most physical: nonlinear string, full coupling | expensive; stability conditions; hard to fit |
Choice: modal synthesis for the strings, as in Bank, Zambon & Fontana (2010). It matches how we fit (page 12): the Julia model and the Rust model are the same set of resonators, so golden vectors compare like with like.
88 key states, not a voice pool
A sample player allocates a voice per note-on and steals old ones. A piano has 88 fixed sets of strings, and that difference is audible: striking a key whose strings still vibrate hits a moving string — the new excitation adds to (or partly cancels) the existing vibration, and with the coupled hammer the felt meets a string that is already moving. Repeated notes, trills and pedalled passages depend on it.
So the engine holds one KeyState per key, created at activate and never allocated again:
KeyState
strings[1..3] per string: partials (complex states, coefficients) per polarisation
hammer position, velocity, in-contact flag (stage 2)
damper position 0..1 (key and pedals combined), current damping per partial
active false when every partial is below the cut-off → skipped entirely“Voice management” becomes activity tracking: a key is computed only while it is audible; a key at rest costs nothing. The worst case is bounded (88 keys) and needs no stealing; the benchmark must show it fits the CPU budget in pedalled passages (P-004).
The same key states serve sympathetic resonance (page 09): when the pedal lifts the dampers, the bridge signal drives the low partials of all undamped keys — no separate resonator bank, and a key excited sympathetically and then struck continues from that state.
Strings are represented separately
A note has one, two or three strings, each with two polarisations (page 07). Stage 1 could fold them into “mode pairs” per partial, but that loses what later stages need: una corda strikes only some strings; bridge coupling acts per string; unison detune is a per-string tuning. So the data and the engine keep the axis key × string × polarisation × partial from the start (model file); stage 1 simply fills it from the fitted mode pairs.
One partial as a resonator — and its precision
A damped mode with frequency and decay is computed as a complex one-pole (equivalently the coupled form): the state is a complex number rotated and shrunk each sample,
and the mode’s displacement is . That is 4 multiplies and 4 adds per sample in real arithmetic, and it maps well onto SIMD (real and imaginary parts as separate arrays).
Why not the textbook two-pole ? Its frequency hides in , which for low notes is extremely close to 1. For A0 (27.5 Hz) at 48 kHz, , and ; in f32 the nearest representable values near 2 are about apart, which moves by about — roughly 0.25 Hz, i.e. ~16 cents at 27.5 Hz. The complex one-pole stores with full relative precision, so the frequency stays exact; the decay ( for a 20 s T60) is accurate to well under 1 % in f32.
The decay needs one more step (measured in T-011): for that partial, and f32 resolves numbers near 1 only to , so storing moves the decay rate by up to 0.8 % (at 96 kHz) — 5 % of amplitude after 20 s. The delta form stores instead (small, so with full relative precision) and updates
which is as accurate as f64 (errors below 0.01 %) and costs the same with FMA ( is two FMAs). is computed without cancellation as with exp_m1.
Rule: complex one-pole in f32, delta form; a unit test checks a 27.5 Hz partial with a 20 s T60 for frequency (≤ 0.1 cent) and decay (≤ 1 %) after 20 s at 44.1, 48 and 96 kHz (crates/dsp/src/piano/resonator.rs, from the spike). No f64 octave is needed; it would cost 2× there.
Sample-rate independence: and are computed from the physical , at activate for the host’s sample rate — the same principle as the continuous-time SSMs in the Model pipeline.
Cost estimate
- Partials per string: everything below ~10 kHz and above the noise floor — a few in the top octave, up to a few hundred in the lowest bass.
- Typical load in pedalled music: tens of active keys, not 88; dead partials are culled as they fall 90+ dB below their peak.
- Order of magnitude without any savings: 50 active keys × 2 strings × 100 partials × 2 polarisations ≈ 20,000 complex one-poles × 48,000 samples × 8 flops ≈ 8 GFLOP/s — an upper bound. With culling, merged high partials and a frequency cap the estimate for the High quality level is ~1 GFLOP/s average, ~2.4 GFLOP/s peak: see Piano 14 for the cost breakdown and the quality levels.
- Measured (T-011): the SIMD kernel below advances one resonator by one sample in ~0.07 ns on an AVX-512 core (~0.1 ns with AVX2), about 300,000 resonators in real time per core. The 50-key case (8,840 resonators with realistic partial counts) takes 3–6 % of one core, Ultra’s worst case ~6–8 %. The CPU risk (P-004) is retired for the desktop; on the Raspberry Pi 3 (Standalone and remote) the same kernel measures ~2.25 ns (~33× the AVX-512 core, not the old ~5× projection): High and below fit one core, Ultra needs threads (T-011 §4).
SIMD on stable Rust
std::simd is still nightly-only, and the toolchain is pinned to stable (Toolchain). Decided by T-011: pulp, with its x86-v4 feature (AVX-512 where present, AVX2+FMA otherwise, NEON on aarch64), and an explicit kernel that keeps 4 vectors of partials in flight for the whole block (64 partials on AVX-512). It was 2.5–3× faster than plain loops or wide at the baseline target a plugin ships with, which cannot use AVX at all without runtime dispatch. The options that were compared:
| Option | For | Against |
|---|---|---|
| auto-vectorisation of plain loops over SoA slices | no dependency; often enough for simple recurrences across partials | fragile: a small change can silently de-vectorise; verify in the benchmark |
wide | simple portable f32x8 types | fixed width; no runtime dispatch |
pulp | runtime dispatch to AVX2/AVX-512/NEON from one source | more abstraction |
Layout regardless of option: structure of arrays, partials of a string contiguous, real/imag/coefficients in separate aligned arrays, active partials compacted so loops run over dense ranges.
Kernel shape (from the spike): the loop over samples runs inside the loop over partial groups, so a group’s states stay in registers for the block, and the output is accumulated per sample as vectors (one horizontal sum per sample per block). Every sample depends on the previous one, so one vector alone is latency-bound; several independent vectors fill the FMA pipelines. Two traps: helper code inside pulp’s with_simd must be generic #[inline(always)] functions, not closures, or it is not inlined into the #[target_feature] context and every SIMD op becomes a call (25× slower); and the audio thread must set flush-to-zero / denormals-are-zero — subnormal states made the kernel 130–220× slower.
Changing parameters while playing
Some controls are cheap to apply per sample; others change thousands of coefficients.
| Class | Examples | How |
|---|---|---|
| smoothed, per sample | output gain, mic blend, noise levels, sympathetic amount, pedal and damper positions | parameter smoothing on the audio thread |
| cheap per key, at the next strike | hammer hardness, strike position, velocity curve | read at note-on |
| recompute | tuning (A4, stretch, unison detune), inharmonicity scale, decay scale, model switch | compute a new coefficient set on a background thread, hand it to the audio thread through a lock-free single-slot exchange; the audio thread swaps pointers between blocks and never frees — the old set goes back to the background thread for deallocation |
Recomputing the full set (88 keys × ≤ 3 strings × 2 polarisations × up to a few hundred partials) is milliseconds of work, fast enough for interactive tuning without blocking the audio thread.
Built (T-016, T-016): the recompute path exists in crates/dsp for Sustain (free decay ×0.25 … ×4) and A4 (415–466 Hz): a worker thread per engine polls the requests every 5 ms and builds a CoeffSet; two wait-free rtrb rings carry new sets to the audio thread and old ones back; the swap happens once at the start of a block, the mode states stay (no crossfade), and a change lands ~10 ms after it is requested. Layout changes (model switch, quality levels) are not built yet: the rule for them is D6 on T-016’s page.
Pedals (T-010) take the smoothed row: no recompute. Each chunk of at most 512 samples a key runs on its free or damped coefficients, or on a blend written for that chunk (one multiply-add per mode), with from the key, the sustain travel and the sostenuto. The soft pedal reads a per-key strike-level table in the CoeffSet at the strike.
Soundboard convolution without latency
The radiation responses (page 06, two virtual mics) are a few hundred ms long. Plain FFT convolution adds one block of latency. Non-uniformly partitioned convolution (a short direct-form head, growing FFT partitions after it; Gardner 1995) gives zero added latency at modest CPU; it has to be written or adopted. Fallback: uniform partitions with the latency reported to the host through CLAP’s latency extension.
Velocity and tuning
The measured piano shapes velocity at each strike before interpolating its excitation layers. It defaults to the recording’s tuning and can compute stretched octaves from the fitted B curve, with historical temperaments available on either base. Tuning edits use the coefficient worker and apply to ringing notes at a block boundary. T-018
The physical model design uses the following mapping and default tuning.
- Velocity mapping: MIDI velocity (or the high-resolution CLAP note velocity) → hammer speed in m/s by a curve with user-adjustable range and shape. For validation on MAESTRO the curve is calibrated against the Disklavier’s velocity-to-loudness behaviour (page 12).
- Tuning: for the physical model the default is a stretched equal temperament computed from the model’s own values (a measured model defaults to its recorded tuning, T-018 D3) (octaves matched on the 2nd partial of the lower note, page 04), so octaves don’t beat. Options: A4 reference, stretch amount, historical temperaments, Scala
.scl/.kbmand MTS-ESP for microtuning (T-049: one ratio per key, so inharmonicity and unison beats stay as measured; an MTS-ESP master is polled by the coefficient worker every 5 ms). A tuning change is a recompute (table above).
Threads
The engine is single-threaded: T-011 measured Ultra’s dense pedalled passage at 6–8 % of one desktop core. On the Raspberry Pi 3 it does not fit one core (Ultra’s peak 1.4 cores, T-011 §4), so keys are processed in parallel there (T-024): in the plugin through CLAP’s thread-pool extension (the host runs our jobs on its audio worker threads), in the standalone app (no CLAP host) on its own real-time worker threads meeting at a barrier after every block, as modal-bench’s render_threads does. Key states are independent within a block except for the bridge sum, which is reduced afterwards.
Structure in crates/dsp
Built by T-008 for format v1: model.rs, coeffs.rs, key.rs (held, active; no strings or hammer yet), resonator.rs, engine.rs (PianoEngine, a Processor), and ftz.rs (DenormalGuard) beside piano/. The others come with format v2 and T-017/T-018.
piano/
model.rs the engine's layout (SoA per key), built from instruments-model-format's PianoModelV3
coeffs.rs CoeffSet: per-sample-rate coefficients; built off the audio thread
key.rs KeyState: strings (SoA partials), hammer, damper, activity
resonator.rs complex one-pole banks (SIMD), precision tests
hammer.rs precomputed pulses (stage 1) → coupled nonlinear hammer (stage 2)
bridge.rs sum of string forces; phantom partials (stage 2)
soundboard.rs non-uniform partitioned convolution (stage 1) → modal soundboard (stage 3)
noises.rs key, hammer, damper, pedal excitations
tuning.rs stretch from B, temperaments
engine.rs events at sample offsets, pedals, activity tracking, block processingReal-time rules from Plugin formats apply: everything preallocated at activate, nothing allocated, freed or locked in process.
Stages
- Stage 1 — “it sounds like a piano”: (first reached as the measured modal reference of T-007: each partial struck by an impulse whose size depends on velocity, its components heard by two mics through fixed complex gains; hammer pulses and the convolution soundboard replace these gains later) 88 key states with separate strings filled from fitted mode pairs; precomputed velocity-dependent hammer pulses; dampers; zero-latency convolution soundboard; stereo virtual mics; stretched tuning.
- Stage 2 — “it plays like a piano”: coupled nonlinear hammer; sympathetic resonance and pedals through the key states; noises; phantom partials in the bass. Pedals built by T-010 (continuous sustain with half-pedalling, sostenuto, a measured soft pedal); the rest is T-056–T-061 (Piano).
- Stage 3 — refinements: modal soundboard with feedback into the strings; una corda through the string count (T-058); frequency-dependent half-pedalling; duplex; multithreading if needed.