Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Docs: README and AGENTS.md (dotplan); DESIGN.md split into them and docs/architecture.md

Jameson Hodge3dea6ebc47eb
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..82f905c
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,139 @@
+# CHIMERA
+
+A physical-modeling voice synthesizer: a Rust engine (wasm in an AudioWorklet, native for tests
+and the CLI) under a React UI. The README covers the rest.
+
+## Working here
+
+- Do what was asked, the simplest way that meets it. Experiments, new tooling and paid runs nobody asked for are
+ proposals: say what they cost and what decision their result would change, and wait. If the work grows well past
+ what you first expected, stop and tell the user: what you expected, where it is now, and a smaller way to finish.
+- When you're repeating something the project has done before, reversing an earlier decision, or changing code
+ whose purpose isn't clear, look at its history (`git log -- <path>`, `git log -S<symbol>`, `git blame`) and
+ open the commits that explain it.
+- The checks below are the minimum for what you touched. Run them again after any merge, rebase or conflict
+ resolution.
+- Commit small: one change per commit, each passing its checks. The subject says what changed, and the trap if
+ there was one, in words a search would find. Unless the diff says it, the body gives the why, what you ruled
+ out, what you ran (with numbers) and what you didn't test.
+- Leave each fixed bug's reproduction behind as a test or a script.
+- A step that's hard to reverse (schema, auth, money, external API) or several sessions long: design it in
+ `docs/<topic>/` first. Judge each step on its own, not by the riskiest part of the project. Measure with the
+ checks below or existing tools before writing new ones. Have a fresh session review the work (the design first,
+ when that could save rework), from a different model family when one at least as capable is available, and ask
+ it what to cut or do more simply, not only what's missing.
+- Code and the running system outrank this file and every doc. When they disagree, fix the file in the same
+ commit. When the project's code breaks unnoticed, add a rule here, with a check if one can be written; tooling
+ built for one task doesn't get rules. Delete rules whose code is gone.
+
+## Map
+
+- `crates/chimera/src/`: the engine. No I/O. `engine.rs` is the host-facing `Engine`.
+ - `airway/`: FDTD tube network, frequency-domain oracle, decimator.
+ - `sources/`: glottis, syrinx, flow valves (trills). `anatomy/`: head geometry → area functions.
+ - `control/`: articulators, gesture score, beat player. `voice/`: the human voice and its airway.
+ - `creatures/`: songbird, seal, alligator, elephant.
+ - `phonetics/`: IPA, G2P, planner, singing, beatbox, and the calibrated `*.generated.json` tables.
+ - `math.rs`: deterministic math (libm, `js_*` helpers). `analysis/`: FFT, LPC, pitch.
+- `crates/chimera/tests/`: engine tests; `golden/` holds fixtures from the retired TS engine.
+- `crates/chimera/examples/bench.rs`: real-time load per voice.
+- `crates/chimera-wasm/`: the browser's C ABI (`lib.rs`: gesture records; `api.rs`: JSON calls).
+- `crates/chimera-cli/`: `chimera render | compare csd | diagnose | calibrate`.
+- `src/main.tsx`: loads the wasm, then imports the app.
+- `src/wasm/`: the UI's typed facade over the engine; `wire.ts` mirrors the gesture records.
+- `src/worklet/`: the AudioWorklet processor and its message protocol.
+- `src/audio/AudioEngine.ts`: the WebAudio graph (analysers, close-mic chain).
+- `src/ui/`: React app. `components/` per screen and mode; `render/` canvas renderers and the
+ vector kit (`vector.ts`); `usePhosphor.ts`; `store.ts`; `singing.ts` is the live Sing controller.
+- `src/show/`, `src/ui/components/DuetPage.tsx`: `?show=<id>` duet replay from `--tele` files.
+- `public/data/cmudict.txt.gz` (from `tools/build-dict.ts`), `public/fonts/` (Hershey, Archivo).
+- `tests/`: bun tests against the wasm build.
+- `tools/`: `e2e.ts`, `layout-lint.ts`, `spectrogram.ts`, `bench-wasm.ts`, `asr/` (Whisper speech
+ judge), `fetch-csd.sh`, and the table generators.
+- `docs/architecture.md`: the acoustic model. `docs/rust-engine.md`: real-time and determinism
+ contract, browser boundary. `docs/ui-redesign.md` + `docs/mockups/`: the look.
+ `docs/csd-comparison.md`: the singer judge. `docs/hill-climb/`: voice-tuning rules and log.
+- `out/`: renders, screenshots, scores (gitignored).
+
+## Rules
+
+### Engine
+
+- **Transcendental math goes through `chimera::math`, never `f64::sin` and friends.** Native and
+ wasm must render bit-identical samples; std math differs by target. Check:
+ `bun test tests/wasm-engine.test.ts` (after `bun run wasm`).
+- **Rendering allocates nothing once warm** (render, control steps, telemetry, beat edits). Body
+ and creature switches and the planners allocate, so they stay off the audio thread. Check:
+ `cargo test -p chimera --test beat_alloc --test creature_realtime`.
+- **Output doesn't depend on the host's block size.** Per-block work happens at the fixed
+ 128-sample sub-block boundaries, not per host call. Check: `cargo test -p chimera --test engine`.
+- **The `*.generated.json` tables are regenerated, never hand-edited** (`chimera calibrate
+ vowels|consonants`, `tools/gen-syrinx-table.ts`, `tools/gen-ipa-nfc.ts`). Vowel calibration
+ isn't bit-reproducible (it moves 7 postures by ±0.002), so only rerun it when the formants are
+ meant to move. Check: manual: the diff of the table matches the intent.
+
+### Golden fixtures
+
+- **Any change to the sound or the plans fails the golden tests, by design.** Re-bless with
+ `CHIMERA_BLESS=1 cargo test --workspace --no-fail-fast`, run twice (`engine.rs` reads a
+ fixture that `golden_planning` blesses). Only human-voice audio and the planners' plans
+ re-bless; the other fixtures record the retired TS engine, so update the expectation or swap
+ in a behavioural test (`crates/chimera/tests/golden/README.md`). Changing the airway's linear
+ acoustics on purpose breaks `golden_analysis`'s "human |H|" checks. Check:
+ `cargo test --workspace`.
+
+### Browser boundary
+
+- **`src/wasm/chimera.wasm` is a gitignored build product.** After a Rust change, `bun test tests`
+ alone tests the old engine: run `bun run wasm` first, or `bun run test`. Don't share a cargo
+ `target/` between checkouts; the copied artifact silently goes stale. Check: `bun run test`.
+- **Gesture records are defined twice**: `crates/chimera-wasm/src/lib.rs` and `src/wasm/wire.ts`
+ (size and `LAYOUT_VERSION`). Change both together and bump the version. Check:
+ `bun test tests/wasm-engine.test.ts`.
+- **The wasm module has no imports** (no wasm-bindgen, no WASI). Check: `bun test tests/wasm-engine.test.ts`.
+- **Creature telemetry layout** crosses the worklet. Check: `bun test tests/creature-abi.test.ts`.
+- **The wasm loads before any UI module runs.** `main.tsx` awaits `initChimera()` and then imports
+ the app, because Sing builds syllables at import. A module that calls the engine at import
+ must not be reachable from `main.tsx`'s static imports. Check: `bun run build && bun run preview`, then `bun tools/e2e.ts`.
+- **A panic traps the worklet** (`panic = "abort"`), which latches to silence. The JSON calls in
+ `api.rs` return `{"error": …}` for bad input rather than panicking. Check: none.
+
+### UI
+
+- **DOM content flows in `.screen-body` and is never absolutely positioned.** Control rows are
+ `auto`; canvas rows are `minmax(min-content, Nfr)` (an fr share on control rows inflates every
+ row in a short window). Add new screens and alternate states to the lint. Check:
+ `bun run lint:layout` (about 6 min; blind to canvas text over line art).
+- **The vector look:** blue is the body, amber is sound, green/red/pink/white are a screen's four
+ control slots; Hershey capitals; build with `vector.ts`, `usePhosphor`, `Screen`/`Chip`/`Encoder`.
+ DOM text keeps its natural case (capitals come from CSS) so accessible names and e2e selectors
+ stay put. Check: manual: compare with `docs/mockups/`.
+- **Frame rate on a real GPU can't be measured here** (headless Chromium uses SwiftShader). Check:
+ manual: ask the owner.
+
+### Content and data
+
+- **Nothing copyrighted goes in git.** `public/shows/` (duet covers) is gitignored; song sources
+ live outside the repo. CSD (CC BY-NC-SA) is for tuning only: never ship its audio or anything
+ derived from it. Check: manual: `git status` before committing.
+- **Voice tuning follows `docs/hill-climb/README.md`**, and never edits the judges
+ (`crates/chimera-cli/src/compare.rs`, `compare/score.rs`, `tools/asr/`, the held-out songs and
+ sentences) or shapes the output with EQ. Check: manual: the diff touches none of them.
+- **`plan_song` puts the vowel on the beat and its consonants before it.** Check:
+ `cargo test -p chimera --test golden_planning`.
+
+### Environment
+
+- **Renders, screenshots and scratch output go under `out/`.** `/tmp` here is a small tmpfs;
+ large envs and models go in `~/.cache/<name>`. The AudioWorklet needs HTTPS off localhost:
+ share previews with `tailscale serve`. Check: none.
+
+## Checks
+
+| When you touch | Run |
+|---|---|
+| anything | `bun run test` (wasm build, `cargo test --workspace`, `bun test tests`) and `bun run typecheck` |
+| `crates/chimera/` (sound) | the above, re-blessing goldens per the rule; `cargo run --release -q -p chimera --example bench` against the previous commit |
+| `crates/chimera-wasm/`, `src/wasm/`, `src/worklet/`, `src/main.tsx` | `bun run test`; `bun run build && bun run preview`, then `bun tools/e2e.ts` |
+| `src/ui/`, `src/show/`, CSS | `bun run typecheck`, `bun run lint:layout` |
+| `docs/mockups/gen/` | none (broken since cd247a6 retired the TS engine they import; the HTML pages still work) |
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 0000000..43c994c
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1 @@
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..9af5037
--- /dev/null
+++ b/README.md
@@ -0,0 +1,57 @@
+# CHIMERA
+
+A physical-modeling voice synthesizer in the browser. Every sound comes from a simulated
+airway (lungs, vocal folds or syrinx, a branched vocal tract, lips, nose), not from samples.
+The engine is Rust, compiled to WebAssembly for an AudioWorklet; the same code runs natively
+for tests and the `chimera` CLI.
+
+## What it does
+
+- **Play**: drag the tongue, lips and jaw in a live cutaway of the head; vowel pad, encoders,
+ computer keyboard and Web MIDI.
+- **Speak**: English text (CMUdict with a letter-to-sound fallback) or IPA, turned into
+ gestures and prosody, with the gestural score and a consonant chart on screen.
+- **Sing**: piano roll with lyrics per note; consonants land before the beat.
+- **Beatbox**: pads and a step sequencer, every drum an articulatory gesture.
+- **Bestiary**: songbird (two-voice syrinx), seal, alligator and elephant.
+- **Duet** (`?show=<id>`): two 3D heads replay a pre-rendered song.
+
+Male, female and child bodies blend continuously. Everything on screen animates from live
+engine state: pressure in the airway, airflow, the vocal folds, spectra and formants.
+
+## Run it
+
+Needs Rust with the `wasm32-unknown-unknown` target, and Bun.
+
+```sh
+bun install
+bun run dev # builds the wasm, then Vite on 127.0.0.1:5317
+bun run test # wasm build, cargo test --workspace, bun test tests
+```
+
+The AudioWorklet needs a secure context, so open it on localhost or over HTTPS (for example
+`tailscale serve`). Vercel builds it with `vercel.json`.
+
+Offline renders and measurement:
+
+```sh
+cargo run --release -p chimera-cli -- render speech|text|song|notes|beatbox|creature|vowels …
+cargo run --release -p chimera-cli -- diagnose # nasal leakage, formants, bandwidths, pitch
+cargo run --release -p chimera-cli -- compare csd # against a real singer (docs/csd-comparison.md)
+bun tools/spectrogram.ts in.wav out.png
+```
+
+## Docs
+
+- [docs/architecture.md](docs/architecture.md): the acoustic model (FDTD airway, sources,
+ anatomy, gestures).
+- [docs/rust-engine.md](docs/rust-engine.md): the engine's real-time and determinism contract,
+ and the browser boundary.
+- [docs/ui-redesign.md](docs/ui-redesign.md) and [docs/mockups/](docs/mockups/): the vector
+ display look.
+- [docs/csd-comparison.md](docs/csd-comparison.md): scoring the voice against the Children's
+ Song Dataset.
+- [docs/hill-climb/](docs/hill-climb/): the rules and log for tuning the voice one measured
+ step at a time.
+
+Agents: see [AGENTS.md](AGENTS.md).
diff --git a/DESIGN.md b/docs/architecture.md
similarity index 59%
rename from DESIGN.md
rename to docs/architecture.md
index d3cec96..565f5ba 100644
--- a/DESIGN.md
+++ b/docs/architecture.md
@@ -1,44 +1,20 @@
-# CHIMERA — a physical-modeling voice synthesizer for many creatures
-
-## Brief (from the user)
-
-"Create the ultimate vocal synthesizer. Web app for now. Be extremely ambitious.
-Sophisticated throat, lips, tongue modeling. Different animals: human, bird,
-reptile, etc. Tonal and percussive (beatboxing). Beautiful visuals/diagrams,
-dynamic animations based on params." Long build is expected.
-
-## Product shape
-
-A browser instrument where every sound comes from a simulated airway, not samples.
-
-* **Creatures**: human (bass/tenor/alto/soprano/child), songbird (two-voice syrinx),
- parrot (talking bird), owl, crow, cat (meow, purr), dog/wolf (bark, howl), lion (roar),
- elephant (trunk trumpet, rumble), cow, frog (vocal sac), crocodile (bellow, hiss),
- snake (hiss), gecko (chirp), dragon (fantasy). Morph between anatomies.
-* **Modes**:
- * *Play* — drag the tongue/lips/jaw in a live anatomy view; XY vowel pad; on-screen and
- computer keyboard; Web MIDI; phoneme pads (tap /t/ over a held vowel).
- * *Speak* — English text (CMUdict + letter-to-sound fallback) or raw IPA → phonemes →
- prosody → gestural score → speech. Timeline shows the gestural score.
- * *Sing* — piano roll with lyrics per note; onset consonants placed before the beat.
- * *Beatbox* — pads + 16-step sequencer; every drum is an articulatory gesture
- (bilabial ejective kick, "pf" snare, alveolar hat, inward K-snare, lip roll, click roll,
- throat bass). "One mouth" (physically honest, one tract) or "crew" (one tract per track).
- * *IPA chart* — click any symbol on the full IPA chart (incl. ejectives, implosives,
- clicks, trills) to hear/see it.
- * *Creature lab* — anatomy parameters, morphing, call presets.
-* **Visuals (first-class)**: everything animates from live engine state at 60 fps.
- * Midsagittal cutaway of the current creature: tongue, jaw, lips, velum, larynx,
- epiglottis; acoustic pressure rendered as a colour field inside the airway;
- airflow particles whose speed follows simulated volume velocity; turbulence
- shown at constrictions where the Reynolds number exceeds threshold.
- * Laryngoscope "stroboscope" (top view of vocal folds / syrinx labia) replayed
- slowed down from the real simulated glottal area waveform.
- * Area-function tube diagram (cylinders with pressure), glottal flow scope,
- transfer function with formant markers, F1–F2 vowel chart with the live point,
- scrolling spectrogram, gestural-score timeline with playhead.
-
-## Architecture
+# Architecture: the acoustic model
+
+How CHIMERA makes sound. This was the original design (moved here from `DESIGN.md`); the
+engine's real-time contract and the browser boundary are in [rust-engine.md](rust-engine.md),
+and the look in [ui-redesign.md](ui-redesign.md).
+
+The owner's brief: "Create the ultimate vocal synthesizer. Web app for now. Be extremely
+ambitious. Sophisticated throat, lips, tongue modeling. Different animals: human, bird, reptile,
+etc. Tonal and percussive (beatboxing). Beautiful visuals/diagrams, dynamic animations based on
+params."
+
+**Not built (yet):** the design's wider bestiary (only songbird, seal, alligator and elephant
+exist), the two-mass vocal folds, an IPA chart mode, the app-side EQ/reverb/limiter chain and
+in-app WAV export (the CLI renders WAVs; the app has a close-mic chain in WebAudio). Treat the
+code as the truth where this file disagrees.
+
+## Overview
```
main thread (React UI, canvas renderers)
@@ -59,7 +35,7 @@ main thread renderers
Control rate: every 64–128 output samples, with per-sample linear interpolation of areas.
-### 1. Airway acoustics — branched staggered-grid FDTD transmission line
+## 1. Airway acoustics — branched staggered-grid FDTD transmission line
Chosen over Kelly-Lochbaum because it handles, in one framework: variable section
lengths (larynx height, lip protrusion, creature size), DC aerodynamics (pressure
@@ -91,7 +67,7 @@ branching (nasal tract, sinuses, piriform fossae, two bronchi, vocal sacs, OEC).
* Cross-check: a frequency-domain chain-matrix model with the same loss terms computes
H(f) for analysis, UI formant display, and as a test oracle for the FDTD.
-### 2. Sources
+## 2. Sources
* **Parametric glottis (default, exact pitch)**: glottal *area* pulse (opening/closing
phases, open quotient, skew, max area, rest/abduction area, posterior chink) drives the
@@ -117,7 +93,7 @@ branching (nasal tract, sinuses, piriform fossae, two bronchi, vocal sacs, OEC).
larynx raising/lowering (ejectives/implosives via dV/dt); velaric closure + tongue
dorsum lowering (clicks). All physical through the FDTD — no special-cased samples.
-### 3. Anatomy & articulation (human first, others as parametric variants)
+## 3. Anatomy & articulation (human first, others as parametric variants)
* 2D midsagittal geometry (cm, head frame): fixed outer wall (posterior pharynx, velum,
hard palate, alveolar ridge, upper incisors, upper lip) and moving inner wall
@@ -144,7 +120,7 @@ branching (nasal tract, sinuses, piriform fossae, two bronchi, vocal sacs, OEC).
vocal sac = Helmholtz side branch). Birds: separate topology (syrinx/trachea/OEC/beak,
tongue for parrots).
-### 4. Control: gestures (Articulatory Phonology–style)
+## 4. Control: gestures (Articulatory Phonology–style)
* Phoneme = set of gestures, each controlling a subset of articulators with targets,
stiffness, blending strength and timing relative to the segment.
@@ -159,53 +135,13 @@ branching (nasal tract, sinuses, piriform fossae, two bronchi, vocal sacs, OEC).
syllabification; Klatt-style durations; intonation (declination, H* on stressed
syllables, final fall / question rise). Singing: notes+lyrics → syllable alignment.
-### 5. FX / output
+## 5. FX / output
DC blocker → mic model (distance/proximity) → EQ → compressor → saturation → reverb →
limiter. WAV export via the same engine in a Worker (unlimited voices, faster than RT).
-## Tech
-
-Engine: Rust (`crates/chimera`), deterministic (libm for all transcendental math), no
-allocation while rendering, block-size-independent output; `crates/chimera-wasm` exposes it to
-the browser as a C-ABI wasm module with no imports (the worklet and the main thread each
-instantiate it; see docs/rust-engine.md for the boundary). UI: TypeScript, Vite, React 19
-(controls) + hand-written canvas/SVG renderers (visuals), Zustand state; `src/wasm/` is the
-UI's typed facade over the engine. Bun for the UI's tooling and tests.
-
-## Validation
-
-* `cargo test --workspace` (engine): uniform-tube resonances vs analytic; FDTD impulse response vs chain-matrix
- H(f); long random-gesture stability (no NaN/blow-up); f0 accuracy; vowel formants vs
- targets; fricative spectral centroids (s > ʃ > f); stop bursts present; ingressive /
- ejective / click pressure signatures; bird pitch accuracy.
- Golden fixtures from the retired TypeScript engine (crates/chimera/tests/golden) check the
- port; native and wasm builds render bit-identical samples (tests/wasm-engine.test.ts).
-* `bun test tests`: the UI's live paths (Sing keys, worklet ordering, MIDI) on the wasm engine.
-* Offline renders (`cargo run --release -p chimera-cli -- render speech|text|song|beatbox|creature|vowels …`)
- → WAV; `tools/spectrogram.ts` draws the PNG to inspect. `chimera diagnose` measures speech
- (nasal leakage, formant undershoot, bandwidths, pitch); `chimera calibrate` regenerates the
- vowel/consonant tables.
-* Headless Chromium (Playwright) smoke tests: app loads, worklet runs, no console errors,
- screenshots of each mode.
-* Hosted over HTTPS via `tailscale serve` (AudioWorklet needs a secure context).
-
-## Phases
-
-0. Scaffold, analysis tools (WAV, FFT, LPC, spectrogram PNG), test harness.
-1. Airway FDTD + parametric glottis + chain-matrix oracle.
-2. Human articulatory geometry, area function, calibration; nasal; fricatives/stops.
-3. Gestures, phoneme inventory (IPA), G2P, prosody → speech.
-4. Worklet + core UI (anatomy view with drag, controls, keyboard, vowel pad, speak).
-5. Extra sources (syrinx, valves/trills, ventricular, two-mass, purr) + creatures + visuals.
-6. Beatbox (airstream mechanisms, sounds, sequencer, mic FX).
-7. Singing (piano roll, lyrics, multi-voice, export).
-8. Polish: visuals, presets, performance, mobile, onboarding.
-
## Known risks
-* Fricative/burst realism depends on noise-source calibration (gain, placement, spectrum).
-* Geometry→area calibration quality decides vowel quality.
-* Self-oscillating valves (two-mass, trills) can be finicky → parametric fallbacks.
-* CPU in the AudioWorklet (JS) with several voices; quality settings + offline render.
-* Scope: large; each phase must leave a working, polished app.
+* Fricative and burst realism depends on noise-source calibration (gain, placement, spectrum).
+* Geometry → area calibration decides vowel quality.
+* Self-oscillating valves (trills) can be finicky; keep parametric fallbacks.