pianny
A physical-model grand piano in plain C: every sound is simulated from its strings, hammers, soundboard and pedals, with no samples.
A physical-model grand piano in plain C: every sound is simulated from its strings, hammers, soundboard and pedals, with no samples.
C11 + libc/libm only (the live app additionally uses the macOS CoreAudio / CoreMIDI C APIs). No samples anywhere: every sound is the output of a simulated grand piano built from its construction — steel wire, felt hammers, bridge, soundboard, dampers and pedals.
make # bin/render bin/analyze bin/piano_live
make test # 21 physics / pedal / 3D-air / fidelity tests
bin/render -o c4.wav note 60 80 4 10 # note C4, velocity 80, key held 4 s, 10 s total
bin/render -o out.wav scores/chords_pedal.txt
bin/piano_live # real-time instrument: CoreMIDI keyboard in, CoreAudio out
bin/piano_live --demo # a pedalled progression through the speakers
bin/piano_kbd # windowed keyboard: play on the home row (GLFW + WebGPU, needs brew install glfw)
tools/fetch_refs.sh # download the reference recordings used by the fidelity tools
| Part | Model |
|---|---|
| Strings | Exact eigenmodes of the clamped, stiff, tensioned string (EI w'''' − T w'' = μ w_tt, solved per string); each string is "tuned" by adjusting its tension to the target pitch. Inharmonicity comes from wire diameter, length and tension (bass strings: core stiffness). Frequency-dependent loss. 1 / 2 / 3 strings per note with small unison mistunings and height offsets; two polarisations (the horizontal one gives the slowly-decaying after sound). |
| Hammer | Felt F = K·dᵖ solved implicitly together with all strings of the unison (Newton on 1–3 contact forces) against exactly discretised modes, so contact is unconditionally stable. Hammer mass, felt K and p vary across the keyboard; hammer speed from MIDI velocity through fitted pp/mf/ff anchors. Strike point ≈ 1/8.3 of the string. |
| Bridge + soundboard | Strings push the bridge with F_b = −T ∂u/∂x; the bridge moves (modal soundboard clamped at the rim, ≈ 650 modes, position-dependent bridge shapes) and acts back on the strings via the moving-end term. Prompt sound / after sound, unison beating and sympathetic resonance emerge with no extra code. (An earlier "foundation stiffness" that squeezed the lowest board modes into 110–140 Hz made the board boom at 130–250 Hz and cancel itself around 500 Hz; the clamped board has neither.) |
| Frame end | The agraffe / capo end is held by the iron frame, not rigidly. (1) Knock: the share 1 − a of the hammer blow that this end takes goes through frame and rim into the board (knock_g, high-passed at knock_fc, ramping in from MIDI 84 to 96), and the board rings with its own modes: the treble's "tock" between the partials. (2) Loss: the end's conductance frame_G0·(f/1 kHz)² drains each mode at 2 f₁ Zs G_f. That is proportional to the fundamental, so it is the treble whose partials die within a few tenths of a second, as in the recordings (without it they rang 2–10× too long, a pure, sine-like tone). Treble pscore (C6–G7, pp/mf/ff) 0.815 → 0.480; standard set mf 0.344 → 0.301, pp+ff 0.386 → 0.326. |
| Radiation | Two virtual microphones at physical positions over the soundboard (bass side / treble side) → pitch-dependent stereo image; a calibrated radiation-efficiency curve. |
| Nonlinearity | Kirchhoff–Carrier tension modulation (pitch glide after loud strikes, as an energy-conserving phase rotation) and longitudinal string modes driven by products of transverse modes, pushing the bridge through the down-bearing angle → phantom partials in the bass. |
| Dampers | Felt pads of finite width that resist both the string's displacement and its slope (they drag along it), with a resistance per register (big bass blocks to small treble wedges), just beyond the hammer's strike line (damper_gap, so partials with a node under the felt were hardly excited in the first place), a few mm apart on the strings of a unison, with a contact ramp; none on the top ~18 notes. The felt grips high partials less (damper_fhi), so a released note fades over a few tenths of a second as in the recordings instead of stopping dead. Optional (off): the felt's weight deflects each string slightly and lifting it releases that shape (damper_force, damper_lift). |
| Pedals | Sustain (continuous, so half-pedalling lifts the dampers progressively), sostenuto (latches only the keys held when it is pressed), una corda (fewer strings struck, softer felt region), and silent key holds. The pedal's own sound (down and up) is a short, soft, unpitched thud whose level and band are fitted to recordings (mech_pnoise_*); the action's knocks are felt contacts (mech_felt_*), not instantaneous clicks. |
Source: src/piano.c (engine), src/piano.h (API and every physical parameter), src/voicing.def
(calibrated radiation / level / hammer tables).
air_enable=2, or 1 stepped)The fast radiation model (a Rayleigh integral per soundboard mode) is what the live app uses. For offline rendering the board can instead
radiate into a 3D finite-difference model of the air around and inside the instrument (src/air.c): a staggered
pressure/velocity grid (leapfrog, second order) with perfectly matched absorbing layers, a voxel model of the instrument and room, and the
microphones as points in the grid.
Fast path: precomputed responses (air_enable=2). The air is linear and the board drives it one way, so the grid only has to be
solved once. By reciprocity, a unit source at each microphone with the board held rigid gives, in one run per microphone, the pressure
difference across every board column — the microphone's response to that column moving — and the pressure at every noise source.
Projected onto the plate modes these are a few hundred impulse responses (cached in cache/, keyed by the geometry), which are then
convolved with the mode velocities (uniformly partitioned FFT convolution, src/conv.c). Checked against the stepped grid:
0.7 % (−43 dB) difference below 700 Hz, 1 % overall. First use of a configuration: ~25 s (22 kHz grid) or ~5 min (44 kHz grid, 1.36 cm
cells, crossover 3.15 kHz); after that rendering runs at about 2× real time on the fine grid instead of ~40× slower than real time.
bin/render -p air_enable=2 -p air_rate=44100 -o c4.wav note 60 80 3 6 # fine grid, precomputed (recommended)
bin/render -p air_enable=2 -p room_enable=1 ... # ... in a 12 x 9 x 5 m room (see below)
bin/render -p air_enable=1 -o c4.wav note 60 80 3 6 # stepped 22 kHz grid, 2.7 cm cells, valid to ~1.6 kHz (about 1 s of compute per second of sound)
bin/render -p air_enable=1 -p air_rate=11025 ... # draft: 5.4 cm cells, 16x cheaper, valid to ~0.8 kHz
bin/render -p air_enable=1 -p air_rate=44100 -p os=1 ... # reference: 1.4 cm cells, valid to ~3 kHz, ~16x the cost of the default
bin/render -p air_enable=1 -p micl_x=0.7 -p micl_y=-0.4 -p micl_z=0.3 ... # move a microphone (board coordinates, m)
bin/airtest mono | baffle | bench [threads] # solver validation and timing
air_fx, default air_rate / 14, about 8 cells per wavelength) a Linkwitz–Riley split hands over to
the Rayleigh model (direct sound, lid image, underside), which is a good geometric description above it.bin/airtest, part of make test): a point source in free space reproduces p = rho Q'(t - r/c) / (4 pi r) to 0.1 dB in
level and 1-2 % in waveform; the absorbing layers reflect -84 dB; a plate in a baffle matches the Rayleigh integral within 0.1 dB / 0.004 rad
at 500 Hz. The 11 kHz and 22 kHz grids agree within 1 dB on the low-frequency radiation, so the grid is converged in its band.air_threads, air_rate
and air_npml trade speed for accuracy; air_floor_beta < 0 removes the floor (open on all sides).arad_db*, alvl_db*, fitted by tools/recalibrate_air.sh).
They were refitted for the rim-clamped board on the 44 kHz grid (tools/pvoice.py 3 --nok --prefix a -p air_enable=2 -p air_rate=44100;
more iterations lower the partial-level error but raise pdist). tools/pscore.py pdist, 3D air vs fast radiation: mf 0.358 vs 0.344,
pp+ff 0.403 vs 0.386 (before the refit: 0.452 / 0.473). Both paths have 1.5–5 kHz ~15 % too loud in the sustain against the Iowa recordings (a 2-3 dB trim there was tried and reverted: it moved pdist only 0.317 -> 0.315 and the user wanted the model brighter, not darker). ff C7 scores ~1.35 on
either path.room_enable=1)The recordings the model is calibrated to are anechoic, and so is the default output. room_enable=1 places the instrument in a
rectangular room (src/room.c): image sources (every wall reflection with the octave-band absorption room_alpha0..6,
air absorption along each path) up to 0.3 s, then a diffuse tail of band-limited noise decaying with the Eyring reverberation time of each
band, its level matched to the image sum. The response starts at the first reflection, so it is convolved with no added latency. Room
size room_lx/ly/lz, the piano's position room_px/py, room_gain. The default room has T60 ≈ 1.4 s at 500 Hz–1 kHz.
I cannot hear audio, so the project ships measurement tools (also C) and calibrates against recordings of a real Steinway (University of Iowa Musical Instrument Samples, free for any use). Highlights, on notes never used in fitting (details, figures and limitations in docs/FIDELITY.md):
tools/pscore.py);tools/release_fit.py, tools/pedal_fit.py).out/ab/*_recording.wav / *_synth.wav (made by tools/make_ab.py) are loudness-matched mono pairs for listening.
What the synth does not have: the exact soundboard of the reference piano (and a room, apart from the optional floor).
| Command | |
|---|---|
bin/render [-r rate] [-mono] [-p name=value] note M VEL HOLD [TOTAL] or … score.txt |
offline renderer; score lines: t on N V, t off N, t ped sustain|sost|una v, t hold N, t release N, t end |
bin/render -params, -describe MIDI, -trace file |
list parameters, print a note's construction, dump the hammer force |
bin/analyze spec / spec2 / partials / compare / extras / tone / env / slices / survey / bands / ploud / texture / trim |
spectrograms, partial tracking, comparison, phantom partials, line levels, octave bands in time slices, perceptual (specific-loudness) distance … |
tools/fidelity.py, tools/calib.py |
per-note comparison tables, measurement, voicing fit |
tools/recalibrate.sh, tools/decay_opt.py, tools/hammer_all.sh + hammer_apply.py |
re-fit radiation/level, loss, felt |
tools/hammer_stats.py, dyn_diff.py, strike_fit.py |
dynamics and strike-point analysis |
tools/pscore.py |
perceptual scoreboard: loudness-domain distance per note, next to the distance of another real piano playing the same note |
tools/pvoice.py |
joint, audibility-weighted voicing fit (radiation curve, note level and felt stiffness per register, Gauss-Newton) |
tools/fetch_noise_refs.sh, release_fit.py, pedal_fit.py |
release / pedal / resonance recordings of two more pianos; damper and pedal-noise fits |
bin/analyze wave file t0 t1 out.png [hp], analyze click |
waveform picture (and high-passed) at sample resolution; crest / high-frequency share of a note's first 25 ms |
tools/listen_panel.py |
listening panel: noise level, felt contact time and pedal level variants for calibration by ear |
tools/noise_cmp.py press|release |
key noise measured between the partial lines, relative to the note, recordings of three pianos vs synth (-p mech_solo=1 renders the action noise alone) |
bin/piano_kbdA window with the 88 keys, played from the computer keyboard, the mouse or any MIDI keyboard (all at once), through the speakers in real
time. Plain C: GLFW for the window and input, WebGPU (wgpu-native, the same build the air solver uses) for drawing, CoreAudio / CoreMIDI
through live/audio.c, which piano_live shares.
| Key | Does |
|---|---|
a s d f g h j k l ; ' |
white keys C D E F G A B C D E F (from the C of the current octave; the orange strip marks the range) |
w e t y u o p |
black keys |
space |
sustain pedal, held like the real one |
1 … 9, 0 |
velocity 16 … 112, 127 (press once; 6 = 76, the default) |
z / x |
octave down / up |
| mouse | click or drag across the keys (glissando) |
esc |
quit |
piano_kbd [-b frames] [-g master_db] [-r rate] [-p name=value]...; --demo plays a short pedalled arpeggio as a sound check, --shot file.png renders the UI to a PNG without a window or audio. Keys go to the audio thread from the input callbacks themselves (not at the
next frame). The window redraws only when something visible changes, and its meters tick at 4 Hz while the piano is silent: the UI thread
uses ~0.1 % CPU at rest and ~4 % while playing (Intel i5-8257U); the rest is the physics. The CPU meter shows the mean callback load,
its white tick the slowest recent callback (red past 85 % of the buffer): if it reaches the end, the audio drops out; -b 1024 doubles
the headroom (and the latency, to ~21 ms). A released note stops being simulated once its strings are below retire_e (1e-10 J: the tail is then under -90 dBFS), so the CPU
is back to idle a second or two after the last damped note instead of tens of seconds.
Spectrum. A strip above the keys shows the output's spectrum live: 8192-point FFT of the last 171 ms, 160 log-spaced bands from 20 Hz to 20 kHz, -100 to -10 dBFS, bars that rise instantly and fall at 60 dB/s, and peak marks that hold 0.8 s and then fall ever faster. It updates 30 times a second while anything sounds (the FFT is ~0.5 ms, ~1.5 % of a core) and stops when the last peak has fallen, so the idle cost stays at the 4 Hz meter tick. It shows the recorded pianos too, which makes the A/B comparison visible.
Recorded pianos for comparison. tools/fetch_soundfonts.py downloads four open sampled pianos from github.com/sfzinstruments (note samples only, 4 velocity layers, cut to 14 s, ~470 MB of FLAC -> 1.4 GB of WAV in refs/sf/): Salamander Grand Piano V3 (Yamaha C5, CC-BY 3.0, Alexander Holm), Maestro Concert Grand (Yamaha CF-3, Mats Helgesson), Splendid Grand Piano (Steinway, AKAI, public domain) and Headroom Piano (Yamaha C3, CC-BY 4.0, Bengt Nilsson). --plan shows what it would fetch. piano_kbd lists the ones present beside PIANNY; click one or press tab / shift-tab to switch while playing (the current sound fades out over one buffer). A plain sample player (live/sampler.c: cubic resampling between the sampled pitches, damper fade on key up, sustain pedal, no pedal or release noises) plays them, level-matched to the model's C4 at velocity 80, and only the selected one is kept in memory (180–630 MB, loaded in 1–3 s). The sound panel shapes the model only.
Sound panel. A plan of the piano (top view, keyboard at the bottom, 1 m grid) in which you drag the microphone pair, and sliders:
| Control | What changes | Applied |
|---|---|---|
| plan view | where the microphone pair stands; the pair turns to face the board. No level compensation: further away is quieter (1 / distance), as in a real room | ~0.15 s (0.7 s with the room on), crossfaded over 40 ms while notes ring |
| MIC HEIGHT, MIC SPACING | height above the board, distance between the two microphones | same |
| LID | lid angle (left end: no lid) | same |
| ROOM SIZE | the room scaled 50–200 % about a 12 × 9 × 5 m hall (image sources + diffuse tail; left end: anechoic); its level is what the physics gives, its length follows the reverberation time (≤ 8 s, ~4 % CPU) | same (a large room takes ~2.5 s to compute) |
| WALLS | mean absorption coefficient of the surfaces, 0.05 (hard, reverberant) – 0.6 (heavily damped); the calibrated band shape is kept. Default 0.3: a furnished room, T60 0.5–0.7 s | same |
| BOARD SIZE | soundboard and bridges scaled 80–120 % (the voicing tables were fitted at 100 %) | rebuilds the piano, ~0.7 s, when the slider is let go; sounding notes are cut |
| STRING LOSS | the strings' own frequency-dependent internal and air loss (loss_a1, loss_a2) × 20–150 %: less = upper partials ring longer |
rebuilds, as above |
| FRAME GIVE | how much the strings' frame end (agraffes / capo bar) yields, × 0–300 % of the calibrated value: the same give takes energy from the treble partials (frame_G0) and passes the hammer's blow on to the frame as the treble knock (knock_g); 0 = a rigid frame, no knock, long treble sustain |
rebuilds, as above |
| FELT STIFFNESS | hammer_k_scale: harder felt is a little brighter and louder (small effect on the top end) |
from each note's next strike |
| FELT BRIGHTNESS | -hammer_p_shift: the felt's force law F = K x^p with a lower exponent stays hard through the blow, a sharper force pulse: the main brightness control. Weighted by register as a voicer would: none on the lowest bass hammers, full from E2 to C6, 30 % at the top |
from each note's next strike |
The listening position only changes the board's radiation coefficients (the Rayleigh integral to each microphone, piano_set_view), computed on a worker thread; nothing uses the 3D air model, so nothing waits for its cache. That cache (air_enable=2, minutes to build) holds the 3D grid's responses for one geometry and one microphone position: moving a microphone, the lid or the case there means a new precompute, which is why the live app does not use it. The app starts in the 12 × 9 × 5 m room with walls 0.3 (-p room_enable=0 for the anechoic calibration). Why the model is darker than sampled pianos: it is calibrated to the Iowa Steinway recordings, which are ~13 dB darker at 4 kHz than Salamander / Maestro / Splendid / Headroom; at its calibrated voicing it has 4 kHz octave -44 dB and 8 kHz -96 dB re the total where those have about -28 and -50. FELT BRIGHTNESS +0.6 (with STRING HF DAMPING ~50 % for the sustain) brings it into their range; the live app still stops at ~9 kHz (os=0.5). Measured on a pedalled chord passage: mics high over the strings are much brighter (+18 dB at 4 kHz), felt 0.5 is −4 dB at 4 kHz, the room takes −4 dB off 1 kHz relative to the low mids.
Physics runs at 22.05 kHz for the live app (os=0.5; everything simulated is below 9 kHz) and at the output rate offline.
Chords of 5–7 notes with the sustain pedal (all 88 strings available for sympathetic resonance): ≈ 19 % of one core back-to-back,
≈ 50 % of the audio callback budget in real use (macOS lowers clocks under bursty load); piano_live -b 1024 gives more headroom.
A cap on simultaneous "full" notes (max_full) and idle strings that only wake when a partial of something ringing coincides with
one of their own keep the worst case bounded.
src/ piano.c piano.h voicing.def engine, public API/parameters, calibrated tables
analysis.c fft.c audioio.c pngw.c measurement library
tools/ render.c analyze.c + calibration scripts
live/ piano_live.c terminal instrument (MIDI in, CoreAudio out)
piano_kbd.c kbd.wgsl windowed keyboard (GLFW + WebGPU)
audio.c audio.h shared real-time output, event queue, MIDI input
tests/ test_piano.py 14 tests (stability, B, double decay, dynamics, glide, pedals, sympathetic resonance, fidelity)
scores/ example scores (make_scores.py regenerates them)
docs/ FIDELITY.md and images
refs/ recordings (fetched on demand) out/ generated audio, images, logs