the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Design revisions from review; bounded score; golden generators split per area
Jameson Hodge6fcf57e10488
diff --git a/crates/chimera/Cargo.toml b/crates/chimera/Cargo.tomlindex a597219..9e1088b 100644--- a/crates/chimera/Cargo.toml+++ b/crates/chimera/Cargo.toml@@ -6,6 +6,6 @@ edition.workspace = truelicense.workspace = true[dependencies]-libm = "0.2"+libm = "=0.2.16"serde = { version = "1", features = ["derive"] }serde_json = "1"diff --git a/crates/chimera/src/control/score.rs b/crates/chimera/src/control/score.rsindex 6402e5b..d803f4a 100644--- a/crates/chimera/src/control/score.rs+++ b/crates/chimera/src/control/score.rs@@ -290,6 +290,8 @@ pub struct GestureScore {gestures: Vec<Gesture>,/// end time of the latest gesture (s)pub end: f64,+ /// gestures refused because the score was full+ pub dropped: u64,}impl Default for GestureScore {@@ -299,14 +301,18 @@ impl Default for GestureScore {}impl GestureScore {- /// Capacity reserved up front: the score never reallocates below this many gestures.- pub const RESERVE: usize = 8192;+ /// Fixed capacity: the score never reallocates. Gestures added past it are dropped (and counted).+ pub const CAPACITY: usize = 16384;pub fn new() -> Self {- GestureScore { gestures: Vec::with_capacity(Self::RESERVE), end: 0.0 }+ GestureScore { gestures: Vec::with_capacity(Self::CAPACITY), end: 0.0, dropped: 0 }}pub fn add(&mut self, g: Gesture) {+ if self.gestures.len() >= Self::CAPACITY {+ self.dropped += 1;+ return;+ }self.gestures.push(g);self.end = js_max(self.end, g.end());}diff --git a/crates/chimera/src/math.rs b/crates/chimera/src/math.rsindex 99071f3..c03a439 100644--- a/crates/chimera/src/math.rs+++ b/crates/chimera/src/math.rs@@ -84,24 +84,32 @@ pub fn sqrt(x: f64) -> f64 {x.sqrt()}-/// `Math.min(a, b)`: NaN if either is NaN.+/// `Math.min(a, b)`: NaN if either is NaN; −0 is below +0.#[inline(always)]pub fn js_min(a: f64, b: f64) -> f64 {if a.is_nan() || b.is_nan() {f64::NAN} else if a < b {a+ } else if b < a {+ b+ } else if a.is_sign_negative() {+ a} else {b}}-/// `Math.max(a, b)`: NaN if either is NaN.+/// `Math.max(a, b)`: NaN if either is NaN; +0 is above −0.#[inline(always)]pub fn js_max(a: f64, b: f64) -> f64 {if a.is_nan() || b.is_nan() {f64::NAN} else if a > b {a+ } else if b > a {+ b+ } else if a.is_sign_positive() {+ a} else {b}@@ -264,6 +272,15 @@ mod tests {assert!(v.iter().chain(&w).all(|x| (0.0..1.0).contains(x)));}#[test]+ fn js_min_max_follow_javascript() {+ assert!(js_min(f64::NAN, 1.0).is_nan() && js_min(1.0, f64::NAN).is_nan());+ assert!(js_max(f64::NAN, 1.0).is_nan() && js_max(1.0, f64::NAN).is_nan());+ assert!(js_min(0.0, -0.0).is_sign_negative() && js_min(-0.0, 0.0).is_sign_negative());+ assert!(js_max(0.0, -0.0).is_sign_positive() && js_max(-0.0, 0.0).is_sign_positive());+ assert_eq!(js_min(2.0, 3.0), 2.0);+ assert_eq!(js_max(2.0, 3.0), 3.0);+ }+ #[test]fn js_round_halves_up() {assert_eq!(js_round(2.5), 3.0);assert_eq!(js_round(-2.5), -2.0);diff --git a/docs/rust-engine.md b/docs/rust-engine.mdindex e1b4884..c35786d 100644--- a/docs/rust-engine.md+++ b/docs/rust-engine.md@@ -49,85 +49,120 @@ port can be reviewed file against file. `chimera::engine::Engine` is the old pro## Real-time contract (what JDAW needs)-- `Engine`, `HumanVoice`, `CreatureVoice`: `Send`, no shared mutable state, so each can render- on its own thread.-- `render(&mut [f32])` allocates nothing once warm. Any per-block or per-control-step temporary- is a buffer that lives in the struct and keeps its capacity. The geometry `Frame`, the- noise-source list, the beatbox gesture builder and the score storage all follow this rule; the- gesture score has a fixed capacity, as the TS version effectively does with `MAX_GESTURES`.-- The planners (text → gestures) allocate and are meant for a non-real-time thread: the main- thread in the browser, an edit thread in JDAW. Live sung notes call `plan_note_on`, which is- small; making the planner allocation-free is left for the JDAW integration.-- Output does not depend on block size: the same commands give the same samples whether you- render in blocks of 1, 128 or 48 000. Commands apply at the start of the next `render` call;- a host that needs sample accuracy splits its block at the event.+- `Engine`, `HumanVoice` and `CreatureVoice` are `Send` and share no mutable state, so each can+ render on its own thread.+- **Steady-state rendering allocates nothing.** That covers `render(&mut [f32])`, control steps,+ geometry frames, noise-source lists, beat-sequencer gesture builds and telemetry snapshots,+ which all reuse buffers held in their structs.+- **Bounded state with defined overflow.** The gesture score holds at most+ `GestureScore::CAPACITY` (16 384) gestures. A gesture added past that is dropped and counted+ (the TS score had no bound). Each `schedule` command takes at most 4 000 gestures, as the TS+ worklet did. Pruning compacts in place and keeps insertion order, which matters because+ blends sum in that order.+- **Commands that allocate.** These are meant for when nothing is sounding, or for a host that+ builds things off the audio thread:+ - a body switch (it builds a new airway network);+ - a creature switch;+ - the first `Engine::new` (it also loads the phonetics tables, so nothing initialises lazily+ on the audio thread later).++ Scheduling, releases, artic/source/gate changes and beat edits don't allocate.+- **Planners allocate** (text → gestures) and belong on a non-real-time thread: the main thread+ in the browser, an edit thread in JDAW. `plan_note_on` for live sung notes is small but+ allocates too; making it allocation-free is left for the JDAW integration.+- **Block-size independence.** `Engine::render` advances in fixed 128-sample sub-blocks, and the+ per-block work (beat-sequencer ticks) happens at those sub-block boundaries, which sit at+ absolute sample positions. The same commands at the same absolute sample positions therefore+ give the same samples whatever the host's block size. The TS worklet ticked once per host+ block, so a 48 000-sample offline block would have lost beats. Commands apply at the start of+ the next `render` call; a host that needs sample accuracy splits its block at the event.+- **Events out.** Responses go into a queue that the host drains after `handle`/`render`:+ `Ready { body, creature, n_ph, n_or }` after a voice switch, and `Planned { id, t0, end }` for a+ schedule that carries an id (the UI's timelines use `t0`).+- **Telemetry.** A snapshot is fixed-size and written into caller-owned buffers. Interval+ measures (RMS levels, the glottal scope's cycle capture) reset on each read; the struct docs+ mark which fields are which. Load measurement and message cadence stay in JS.+- **The human clock stops while a creature plays**, as before.## Determinism-- All transcendental math (`sin cos tan exp ln pow tanh atan2 acos cbrt hypot log10 log2`) goes- through `chimera::math`, which wraps the pure-Rust `libm` crate. `sqrt`, `abs`, `floor` and the- basic arithmetic are IEEE-exact everywhere. Rust never contracts to FMA on its own. The result- is that native x86-64, native aarch64 (macOS) and wasm32 produce **bit-identical** output. That- settles JDAW's open question on cross-machine determinism, at least for CHIMERA. There is a- test that renders a fixed scenario and checks a hash committed alongside it.-- `Math.min`/`Math.max` propagate NaN; `f64::min`/`f64::max` don't. The port uses explicit- comparisons wherever the TS relies on that, or where an argument could be NaN.-- Hosts must not enable FTZ/DAZ: flushed denormals change the samples. The engine already- flushes silent state itself, as the TS version does.+- **Repeatability (promised).** A given build renders the same samples every time, for any+ block size.+- **Cross-target identity (tested where possible).** All transcendental math goes through+ `chimera::math`, which wraps the pure-Rust `libm` crate at a pinned version. `sqrt` and the+ basic operations are IEEE-exact, and Rust never contracts to FMA on its own. A test renders+ fixed scenarios natively and through the wasm build and requires identical samples on+ x86-64 Linux. aarch64/macOS is untested here, so identity there is a goal, not a claim.+- **JS semantics.** `Math.min`/`Math.max` become `js_min`/`js_max`, which propagate NaN from+ either argument and order −0 below +0. Ternaries are ported as written. `Math.round` becomes+ `js_round`, which rounds halves up. The PRNG uses explicit wrapping `u32` arithmetic.+- **Precision.** State and gesture values are `f64` throughout; only output and telemetry are+ `f32`, as the TS `Float32Array`s were.+- **No FTZ/DAZ.** Hosts must not enable flush-to-zero or denormals-are-zero, because those+ change the samples. The engine already flushes silent state itself.## Port fidelity-The port is literal. It keeps the same equations, the same operation order, the same constants-and the same PRNGs (mulberry32 with the same seeds). It does not retune anything. The checks:--1. **Golden comparison against the TS engine, before the TS engine is deleted.** A TS script- (`tools/golden.ts`) renders scenarios and dumps fixtures: per-module numeric outputs- (geometry frames, area functions, transfer functions, plans as JSON, G2P on a word list,- syllabification) and audio (speech, a sung phrase, a beatbox bar, each creature's calls, live- articulator sweeps, a body switch). Rust tests compare against them.- - Plans, geometry and G2P must match exactly, or to within 1e-9 relative where floats are- involved.- - Audio is compared sample by sample. The expectation is ≲1e-6 relative to peak for the first- ~0.25 s; libm and V8 differ in the last ulp of `pow`/`exp`, and the voice's nonlinear- feedback can grow that. Over the whole render the check is a looser envelope/spectral one- (RMS envelope within 0.1 dB, log-spectrum distance) so that real porting errors still fail.- - Fixtures are short and committed (<2 MB total), so the Rust tests keep guarding behaviour- after the TS engine is gone.-2. **The existing bun tests**, which check resonances against analytic values, FDTD against the- chain matrix, stability, formants, closures and singing behaviour, are ported to `cargo test`- with the same thresholds.-3. **The app's e2e smoke test** (`tools/e2e.ts`) runs against the wasm build and must stay- green.-4. **Benchmarks** (`cargo bench`-style, plain `std::time`, so no criterion dependency): native- and wasm real-time factors next to the TS numbers measured before the port.+The port is literal. It keeps the same equations, the same operation order, the same constants,+the same PRNG seeds, and the same container order where order decides random-number+consumption or sums (noise sources, gestures). It retunes nothing. The checks:++1. **Golden comparison against the TS engine, before the TS engine is deleted.** Each+ `tools/golden/<area>.ts` runs the TS engine on fixed scenarios and writes fixtures, and the+ Rust tests compare against them.+ - Numeric outputs (geometry, area functions, plans, G2P, syllables) must agree to 1e-9+ relative, with an absolute floor near zero. Plans and G2P must agree exactly in structure.+ - Audio is compared on scenarios with events throughout (artic changes, releases, cancels,+ calls, body switches), not just at the start. Renders must agree sample for sample (≲1e-6+ of peak) until a discrete decision flips on a last-ulp difference between V8's libm and+ Rust's. After that, every 10 ms window's RMS must agree to 0.05 dB, and onset/release+ timing, silence, pitch and closures are covered by the ported behavioural tests. Any+ divergence before an event is investigated, not tolerated.+ - With the TS engine gone, `CHIMERA_BLESS=1 cargo test` rewrites the fixtures from the Rust+ engine after an intended change to the sound.+2. **The existing bun tests** (resonances against analytic values, FDTD against the chain+ matrix, stability, formants, closures, singing behaviour) are ported to `cargo test` with+ the same thresholds.+3. **The app's e2e smoke test** (`tools/e2e.ts`) runs against the wasm build and stays green.+4. **Benchmarks** measure native and wasm real-time factors against the TS numbers taken+ before the port.## The browser boundary-- **One wasm module.** The main thread compiles it once (`WebAssembly.compileStreaming`) and- passes the `WebAssembly.Module` to the worklet in `processorOptions`. Each side instantiates it- synchronously and gets its own instance and memory. The import object is empty: no WASI and- no JS glue.-- **Audio thread (worklet).** The exports are C ABI with numbers and pointers only, for example- `engine_new(fs)`, `engine_render(n) -> *f32`, `engine_set_artic(ptr, mask)` and- `engine_schedule(ptr, count, lead, replace)`.- - Gestures cross as fixed-size `#[repr(C)]` records: a header of t0, t1, ramps, strength,- speed, releaseHold and tag; 22 target slots with NaN for absent; and a 24-byte UTF-8 label.- A ~60-line TS codec (`src/engine/wire.ts`) writes them into wasm memory.- - Telemetry is a set of pointer/length getters read into the same `TelemetryMessage` shape- the UI uses today, so the UI barely changes.- - The worklet scope has no `TextEncoder`/`TextDecoder`, so labels use a tiny UTF-8 helper.- - Typed-array views are re-created after every call that might grow memory. Memory starts- pre-sized so that the audio path never grows it.-- **Main thread.** Rich, non-real-time calls take JSON in and give JSON out through- `serde_json`: `plan_phrases`, `plan_song`, `plan_note_on`, `g2p_*`, `lyrics_to_syllables`,- `model_frame` (the geometry for drawing), `model_transfer` (H(f) and formants), and the- creature, beatbox and vowel catalogues. The TS facade parses that JSON into the types the UI- already imports (`Gesture`, `Plan`, `HumanFrame`, `CreatureDef` minus the drawing data, which- stays in TS). CMUdict is still fetched and gunzipped in the browser; its text goes into the- wasm instance once.-- **Panics.** The crate is built with `panic = "abort"`, so a panic in the worklet traps. The- processor catches the trap, posts an error, outputs silence and rebuilds the instance with the- performer's state.+- **One wasm module.** The main thread compiles it once and passes the `WebAssembly.Module` to+ the worklet in `processorOptions` (structured clone). Each side instantiates it+ synchronously. The import object is empty: no WASI and no JS glue. A build check asserts the+ artifact has no imports.+- **Startup ordering.** The wasm module must be ready before any UI module that calls into it+ runs, because `ui/singing.ts` builds syllables when it loads. `main.tsx` awaits the module,+ then imports the app. A failure shows a retryable error screen.+- **Audio thread (worklet).** The exports are C ABI with numbers and pointers only, over one+ engine handle.+ - Engine-owned buffers have a stable address for the engine's lifetime: an output buffer of+ up to 4 096 frames, a command scratch area, and the telemetry block. JS re-creates its+ typed-array views whenever `memory.buffer` has changed, and copies telemetry before the+ next call.+ - Gestures cross as fixed 256-byte little-endian records, layout version 1, specified in+ `crates/chimera-wasm/src/lib.rs` and mirrored by `src/engine/wire.ts`:+ - eight `f64`s: t0, t1, rampIn, rampOut, strength, speed, releaseHold, tag;+ - 22 `f64` targets in `ControlKey` order;+ - a u8 label length and 24 bytes of UTF-8;+ - padding.++ NaN marks an absent optional or target. Labels are cut at a character boundary.+ - The worklet scope has no `TextEncoder`/`TextDecoder`, so a tiny UTF-8 helper handles+ labels and ids.+- **Main thread.** Rich, non-real-time calls are JSON in and out through `serde_json`:+ - planning, G2P and syllables;+ - the anatomy model: frame, transfer function and formants, the `P`/`unP` template maps,+ scale, tube node positions, and branch → drawing position;+ - the creature, beatbox and vowel catalogues.++ The TS facade gives the UI the types it uses today. Creature drawing data stays in TS.+- **Faults.** The crate is built with `panic = "abort"`, so a panic in the worklet traps. The+ processor then outputs silence for good and posts one error. The main thread may build a new+ node, which restarts playback state: score, clocks and beat. There's no attempt at seamless+ recovery.## Build@@ -158,6 +193,24 @@ speculative (JDAW principle: generality must earn its place).a TS tool (`tools/spectrogram.ts in.wav out.png`, reusing `tools/lib`).- `calibrate-vowels`, `calibrate-consonants` and `gen-syrinx-table` become `chimera-cli` bins,because they regenerate committed data.-- The one-off exploration and diagnostic scripts are deleted: `proto-vowel`, `explore-syrinx`,- `measure-closures`, `measure-consonants`, `speech-diagnostics` and `draw-anatomy`. Their- findings are already in the code and the commit history.+- `speech-diagnostics` (nasal leakage, formant undershoot, bandwidths, pitch) becomes+ `chimera diagnose`, because it's a measurement tool for future tuning.+- The one-off explorations are deleted: `proto-vowel`, `explore-syrinx`, `measure-closures`,+ `measure-consonants` and `draw-anatomy`. Their findings are already in the code and the+ commit history.++## Review++A design review (Codex, 2026-11-05) changed several points: block-size independence of the+beat sequencer, the bounded score and the list of allocating commands, latching faults instead+of rebuilding on the audio thread, determinism claimed only as tested, the event and telemetry+contract, the ABI layout, facade gaps and startup ordering.++It also suggested keeping G2P, planning and songs in TS for now. That suggestion was declined:+- the beat sequencer runs in the engine and needs most of the planner core (inventory, oral+ gestures, vowel targets);+- JDAW's headless core (principle 4) has to sing lyrics on notes (principle 15);+- phonetics split across two languages would drift.++The worklet's per-block replay budget stays out of Rust, because commands apply at the next+render call and so it isn't needed.diff --git a/tools/golden.ts b/tools/golden.tsdeleted file mode 100644index 77e6cab..0000000--- a/tools/golden.ts+++ /dev/null@@ -1,153 +0,0 @@-/**- * Golden fixtures for the Rust port: runs the TypeScript engine on fixed scenarios and writes- * what it computed to crates/chimera/tests/golden/, where `cargo test` compares the Rust engine- * against it. Run once, before the TypeScript engine is retired: bun tools/golden.ts [section…]- */-import { writeFileSync, mkdirSync } from "node:fs";-import { HumanVocalTract, NEUTRAL, BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanArtic, type HumanBody } from "../src/engine/anatomy/human.ts";-import { ARTIC_KEYS, ARTIC_SPECS } from "../src/engine/control/articulators.ts";-import { Rng } from "../src/engine/util/math.ts";-import TARGETS from "../src/engine/phonetics/vowelTargets.generated.json";--const OUT = "crates/chimera/tests/golden";-mkdirSync(OUT, { recursive: true });-const BODIES: Record<string, HumanBody> = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD };-const sections = new Set(process.argv.slice(2));-const want = (s: string) => sections.size === 0 || sections.has(s);-const write = (name: string, data: unknown) => {- const text = JSON.stringify(data);- writeFileSync(`${OUT}/${name}.json`, text);- console.log(`${name}.json ${(text.length / 1024).toFixed(0)} KB`);-};-/** a finite float as JSON keeps all 17 significant digits; NaN/±Infinity become strings */-const num = (x: number) => (Number.isFinite(x) ? x : String(x));--function articCases(): { body: string; artic: HumanArtic }[] {- const cases: { body: string; artic: HumanArtic }[] = [];- const T = TARGETS as unknown as Record<string, Record<string, { artic: Partial<HumanArtic> }>>;- for (const body of Object.keys(BODIES)) {- cases.push({ body, artic: { ...NEUTRAL } });- for (const v of Object.values(T[body])) cases.push({ body, artic: { ...NEUTRAL, ...v.artic } });- }- const rng = new Rng(2026);- for (let i = 0; i < 45; i++) {- const a = { ...NEUTRAL };- for (const k of ARTIC_KEYS) {- const s = ARTIC_SPECS[k];- // half the cases keep the rest of the posture neutral, so contacts and closures occur- if (i % 2 === 0 || rng.next() < 0.5) a[k] = s.min + (s.max - s.min) * rng.next();- }- cases.push({ body: ["male", "female", "child"][i % 3], artic: a });- }- return cases;-}--if (want("geometry")) {- const tracts: Record<string, HumanVocalTract> = {};- const out = articCases().map(({ body, artic }, i) => {- // full drawing outlines for a few cases; area functions and contacts for all- const pts = (ps: { x: number; y: number }[]) => (i % 12 === 0 ? ps.flatMap((p) => [p.x, p.y]) : undefined);- const t = (tracts[body] ??= new HumanVocalTract(BODIES[body]));- const f = t.compute(artic);- const nPh = 18, nOr = 18;- const ph = new Float64Array(nPh), or = new Float64Array(nOr), phMin = new Float64Array(nPh), orMin = new Float64Array(nOr);- const { phLen, orLen } = t.resample(artic, f, nPh, nOr, ph, or, phMin, orMin);- return {- body,- artic,- grid: f.grid.map((g) => [g.region, g.d, g.area, g.s]),- outer: pts(f.outer),- inner: pts(f.inner),- tongue: pts(f.tongue),- velum: pts(f.velum),- upperLip: pts(f.upperLip),- lowerLip: pts(f.lowerLip),- scalars: [f.length, f.pharynxLength, f.teethS, f.lipS, f.velumPort, f.lipArea, f.tongueRadius, f.tip.x, f.tip.y, f.splitIndex, t.contactTip, t.contactBody, t.contactTipN.x, t.contactTipN.y, t.contactBodyN.x, t.contactBodyN.y].map(num),- resample: { phLen, orLen, ph: [...ph], or: [...or], phMin: [...phMin], orMin: [...orMin] },- };- });- write("geometry", out);-}--// ------------------------------------------------------------------ audio: the human voice-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";-import { planUtterance } from "../src/engine/phonetics/planner.ts";-import { tokenizeIpa } from "../src/engine/phonetics/ipa.ts";-import type { Gesture } from "../src/engine/control/score.ts";--/** One timed operation on a voice, applied before rendering sample `at`. */-type VoiceOp =- | { at: number; op: "gate"; level: number }- | { at: number; op: "artic"; values: Partial<HumanArtic>; tipFree?: boolean }- | { at: number; op: "source"; values: Record<string, number | boolean> }- | { at: number; op: "schedule"; gestures: Gesture[]; offset: number }- | { at: number; op: "release"; tag: number }- | { at: number; op: "cancel" };-interface VoiceScenario {- name: string;- body: string;- fsOut: number;- oversample: number;- samples: number;- ops: VoiceOp[];-}--function runVoice(s: VoiceScenario): Float32Array {- const v = new HumanVoice({ fsOut: s.fsOut, body: BODIES[s.body], oversample: s.oversample });- const out = new Float32Array(s.samples);- const ops = [...s.ops].sort((a, b) => a.at - b.at);- let i = 0, oi = 0;- while (i < s.samples) {- while (oi < ops.length && ops[oi].at <= i) {- const o = ops[oi++];- if (o.op === "gate") v.setGate(o.level);- else if (o.op === "artic") v.setArticulation(o.values, o.tipFree);- else if (o.op === "source") v.setSource(o.values);- else if (o.op === "schedule") v.schedule(o.gestures.map((g) => ({ ...g, targets: { ...g.targets }, t0: g.t0 + v.clock + o.offset, t1: g.t1 + v.clock + o.offset })));- else if (o.op === "release") v.release(o.tag);- else v.cancelScore();- }- const next = Math.min(s.samples, i + 128, oi < ops.length ? Math.max(i + 1, ops[oi].at) : Infinity);- v.render(out, i, next - i);- i = next;- }- return out;-}--function plan(ipa: string, body: string, f0: number) {- return planUtterance(tokenizeIpa(ipa), { body, t0: 0, f0 }).gestures;-}--if (want("voice")) {- const FS = 48000;- const sec = (x: number) => Math.round(x * FS);- const scenarios: VoiceScenario[] = [- { name: "sustain-male", body: "male", fsOut: FS, oversample: 2, samples: sec(0.6), ops: [{ at: 0, op: "gate", level: 1 }, { at: sec(0.45), op: "gate", level: 0 }] },- {- name: "artic-sweep",- body: "male",- fsOut: FS,- oversample: 2,- samples: sec(0.8),- ops: [- { at: 0, op: "source", values: { f0: 140, breathiness: 0.4, roughness: 0.6, vibratoDepth: 40, fry: 0.2 } },- { at: 0, op: "gate", level: 1 },- { at: sec(0.15), op: "artic", values: { tbX: 4.2, tbY: 8.4, jaw: 0.3, lipWidth: 1 } },- { at: sec(0.35), op: "artic", values: { tbX: 1.6, tbY: 6.0, jaw: 1.6, lipAp: 0.4, lipProt: 0.9 }, tipFree: true },- { at: sec(0.5), op: "artic", values: { ttX: 7.0, ttY: 9.0, velum: 0.8 }, tipFree: false },- { at: sec(0.65), op: "source", values: { voiced: false, pressure: 12 } },- ],- },- { name: "speech-male", body: "male", fsOut: FS, oversample: 2, samples: sec(1.6), ops: [{ at: 0, op: "schedule", offset: 0.03, gestures: plan("ˈhɛloʊ ˈwɝld ʃi sɛlz ˈɑpɑ", "male", 110) }] },- { name: "speech-female-96k", body: "female", fsOut: 96000, oversample: 1, samples: 96000, ops: [{ at: 0, op: "schedule", offset: 0.03, gestures: plan("ˈθɪŋk ə ˈbæd ˈkæt", "female", 205) }] },- { name: "speech-child", body: "child", fsOut: FS, oversample: 2, samples: sec(1.0), ops: [{ at: 0, op: "schedule", offset: 0.03, gestures: plan("ˈmʌni ˈtʃɪp ˈʒu ˈvæn", "child", 260) }] },- ];- // a held note released early (tags), and a cancel mid-phrase- const held = plan("ˈlɑ", "male", 196).map((g) => (g.t1 >= 0.15 ? { ...g, t1: 1e9, tag: 7 } : g));- scenarios.push({ name: "release-cancel", body: "male", fsOut: FS, oversample: 2, samples: sec(1.2), ops: [{ at: 0, op: "schedule", offset: 0.01, gestures: held }, { at: sec(0.4), op: "release", tag: 7 }, { at: sec(0.6), op: "schedule", offset: 0.02, gestures: plan("ˈbɑbɑbɑbɑ", "male", 110) }, { at: sec(0.9), op: "cancel" }] });- for (const s of scenarios) {- const out = runVoice(s);- writeFileSync(`${OUT}/voice-${s.name}.f32`, Buffer.from(out.buffer));- }- write("voice", scenarios);-}diff --git a/tools/golden/geometry.ts b/tools/golden/geometry.tsnew file mode 100644index 0000000..c1d6c03--- /dev/null+++ b/tools/golden/geometry.ts@@ -0,0 +1,54 @@+/** Anatomy fixtures: grids, area functions, contacts and outlines for many postures. */+import { HumanVocalTract, NEUTRAL, type HumanArtic } from "../../src/engine/anatomy/human.ts";+import { ARTIC_KEYS, ARTIC_SPECS } from "../../src/engine/control/articulators.ts";+import { Rng } from "../../src/engine/util/math.ts";+import TARGETS from "../../src/engine/phonetics/vowelTargets.generated.json";+import { BODIES, write, num } from "./lib.ts";++function articCases(): { body: string; artic: HumanArtic }[] {+ const cases: { body: string; artic: HumanArtic }[] = [];+ const T = TARGETS as unknown as Record<string, Record<string, { artic: Partial<HumanArtic> }>>;+ for (const body of Object.keys(BODIES)) {+ cases.push({ body, artic: { ...NEUTRAL } });+ for (const v of Object.values(T[body])) cases.push({ body, artic: { ...NEUTRAL, ...v.artic } });+ }+ const rng = new Rng(2026);+ for (let i = 0; i < 45; i++) {+ const a = { ...NEUTRAL };+ for (const k of ARTIC_KEYS) {+ const s = ARTIC_SPECS[k];+ // half the cases keep the rest of the posture neutral, so contacts and closures occur+ if (i % 2 === 0 || rng.next() < 0.5) a[k] = s.min + (s.max - s.min) * rng.next();+ }+ cases.push({ body: ["male", "female", "child"][i % 3], artic: a });+ }+ return cases;+}++{+ const tracts: Record<string, HumanVocalTract> = {};+ const out = articCases().map(({ body, artic }, i) => {+ // full drawing outlines for a few cases; area functions and contacts for all+ const pts = (ps: { x: number; y: number }[]) => (i % 12 === 0 ? ps.flatMap((p) => [p.x, p.y]) : undefined);+ const t = (tracts[body] ??= new HumanVocalTract(BODIES[body]));+ const f = t.compute(artic);+ const nPh = 18, nOr = 18;+ const ph = new Float64Array(nPh), or = new Float64Array(nOr), phMin = new Float64Array(nPh), orMin = new Float64Array(nOr);+ const { phLen, orLen } = t.resample(artic, f, nPh, nOr, ph, or, phMin, orMin);+ return {+ body,+ artic,+ grid: f.grid.map((g) => [g.region, g.d, g.area, g.s]),+ outer: pts(f.outer),+ inner: pts(f.inner),+ tongue: pts(f.tongue),+ velum: pts(f.velum),+ upperLip: pts(f.upperLip),+ lowerLip: pts(f.lowerLip),+ scalars: [f.length, f.pharynxLength, f.teethS, f.lipS, f.velumPort, f.lipArea, f.tongueRadius, f.tip.x, f.tip.y, f.splitIndex, t.contactTip, t.contactBody, t.contactTipN.x, t.contactTipN.y, t.contactBodyN.x, t.contactBodyN.y].map(num),+ resample: { phLen, orLen, ph: [...ph], or: [...or], phMin: [...phMin], orMin: [...orMin] },+ };+ });+ write("geometry", out);+}+diff --git a/tools/golden/lib.ts b/tools/golden/lib.tsnew file mode 100644index 0000000..11521b8--- /dev/null+++ b/tools/golden/lib.ts@@ -0,0 +1,28 @@+/**+ * Golden fixtures for the Rust port: each file in tools/golden/ runs the TypeScript engine on+ * fixed scenarios and writes what it computed to crates/chimera/tests/golden/, where `cargo test`+ * compares the Rust engine against it. Run before the TypeScript engine is retired:+ * bun tools/golden/<area>.ts+ */+import { writeFileSync, mkdirSync } from "node:fs";+import { BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanBody } from "../../src/engine/anatomy/human.ts";++export const OUT = new URL("../../crates/chimera/tests/golden/", import.meta.url).pathname;+mkdirSync(OUT, { recursive: true });+export const BODIES: Record<string, HumanBody> = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD };++/** Write `<name>.json` (finite floats keep all 17 significant digits). */+export function write(name: string, data: unknown): void {+ const text = JSON.stringify(data);+ writeFileSync(`${OUT}/${name}.json`, text);+ console.log(`${name}.json ${(text.length / 1024).toFixed(0)} KB`);+}++/** Write `<name>.f32` (little-endian float32 samples). */+export function writeF32(name: string, data: Float32Array): void {+ writeFileSync(`${OUT}/${name}.f32`, Buffer.from(data.buffer, data.byteOffset, data.byteLength));+ console.log(`${name}.f32 ${(data.byteLength / 1024).toFixed(0)} KB`);+}++/** NaN and ±Infinity as strings (JSON has no literal for them). */+export const num = (x: number) => (Number.isFinite(x) ? x : String(x));diff --git a/tools/golden/voice.ts b/tools/golden/voice.tsnew file mode 100644index 0000000..545c0b1--- /dev/null+++ b/tools/golden/voice.ts@@ -0,0 +1,85 @@+/** Human-voice audio fixtures: timed operations on a voice, and the samples it rendered. */+import { HumanVoice } from "../../src/engine/voice/humanVoice.ts";+import { planUtterance } from "../../src/engine/phonetics/planner.ts";+import { tokenizeIpa } from "../../src/engine/phonetics/ipa.ts";+import type { Gesture } from "../../src/engine/control/score.ts";+import type { HumanArtic } from "../../src/engine/anatomy/human.ts";+import { BODIES, write, writeF32 } from "./lib.ts";+++/** One timed operation on a voice, applied before rendering sample `at`. */+type VoiceOp =+ | { at: number; op: "gate"; level: number }+ | { at: number; op: "artic"; values: Partial<HumanArtic>; tipFree?: boolean }+ | { at: number; op: "source"; values: Record<string, number | boolean> }+ | { at: number; op: "schedule"; gestures: Gesture[]; offset: number }+ | { at: number; op: "release"; tag: number }+ | { at: number; op: "cancel" };+interface VoiceScenario {+ name: string;+ body: string;+ fsOut: number;+ oversample: number;+ samples: number;+ ops: VoiceOp[];+}++function runVoice(s: VoiceScenario): Float32Array {+ const v = new HumanVoice({ fsOut: s.fsOut, body: BODIES[s.body], oversample: s.oversample });+ const out = new Float32Array(s.samples);+ const ops = [...s.ops].sort((a, b) => a.at - b.at);+ let i = 0, oi = 0;+ while (i < s.samples) {+ while (oi < ops.length && ops[oi].at <= i) {+ const o = ops[oi++];+ if (o.op === "gate") v.setGate(o.level);+ else if (o.op === "artic") v.setArticulation(o.values, o.tipFree);+ else if (o.op === "source") v.setSource(o.values);+ else if (o.op === "schedule") v.schedule(o.gestures.map((g) => ({ ...g, targets: { ...g.targets }, t0: g.t0 + v.clock + o.offset, t1: g.t1 + v.clock + o.offset })));+ else if (o.op === "release") v.release(o.tag);+ else v.cancelScore();+ }+ const next = Math.min(s.samples, i + 128, oi < ops.length ? Math.max(i + 1, ops[oi].at) : Infinity);+ v.render(out, i, next - i);+ i = next;+ }+ return out;+}++function plan(ipa: string, body: string, f0: number) {+ return planUtterance(tokenizeIpa(ipa), { body, t0: 0, f0 }).gestures;+}++{+ const FS = 48000;+ const sec = (x: number) => Math.round(x * FS);+ const scenarios: VoiceScenario[] = [+ { name: "sustain-male", body: "male", fsOut: FS, oversample: 2, samples: sec(0.6), ops: [{ at: 0, op: "gate", level: 1 }, { at: sec(0.45), op: "gate", level: 0 }] },+ {+ name: "artic-sweep",+ body: "male",+ fsOut: FS,+ oversample: 2,+ samples: sec(0.8),+ ops: [+ { at: 0, op: "source", values: { f0: 140, breathiness: 0.4, roughness: 0.6, vibratoDepth: 40, fry: 0.2 } },+ { at: 0, op: "gate", level: 1 },+ { at: sec(0.15), op: "artic", values: { tbX: 4.2, tbY: 8.4, jaw: 0.3, lipWidth: 1 } },+ { at: sec(0.35), op: "artic", values: { tbX: 1.6, tbY: 6.0, jaw: 1.6, lipAp: 0.4, lipProt: 0.9 }, tipFree: true },+ { at: sec(0.5), op: "artic", values: { ttX: 7.0, ttY: 9.0, velum: 0.8 }, tipFree: false },+ { at: sec(0.65), op: "source", values: { voiced: false, pressure: 12 } },+ ],+ },+ { name: "speech-male", body: "male", fsOut: FS, oversample: 2, samples: sec(1.6), ops: [{ at: 0, op: "schedule", offset: 0.03, gestures: plan("ˈhɛloʊ ˈwɝld ʃi sɛlz ˈɑpɑ", "male", 110) }] },+ { name: "speech-female-96k", body: "female", fsOut: 96000, oversample: 1, samples: 96000, ops: [{ at: 0, op: "schedule", offset: 0.03, gestures: plan("ˈθɪŋk ə ˈbæd ˈkæt", "female", 205) }] },+ { name: "speech-child", body: "child", fsOut: FS, oversample: 2, samples: sec(1.0), ops: [{ at: 0, op: "schedule", offset: 0.03, gestures: plan("ˈmʌni ˈtʃɪp ˈʒu ˈvæn", "child", 260) }] },+ ];+ // a held note released early (tags), and a cancel mid-phrase+ const held = plan("ˈlɑ", "male", 196).map((g) => (g.t1 >= 0.15 ? { ...g, t1: 1e9, tag: 7 } : g));+ scenarios.push({ name: "release-cancel", body: "male", fsOut: FS, oversample: 2, samples: sec(1.2), ops: [{ at: 0, op: "schedule", offset: 0.01, gestures: held }, { at: sec(0.4), op: "release", tag: 7 }, { at: sec(0.6), op: "schedule", offset: 0.02, gestures: plan("ˈbɑbɑbɑbɑ", "male", 110) }, { at: sec(0.9), op: "cancel" }] });+ for (const s of scenarios) {+ const out = runVoice(s);+ writeF32(`voice-${s.name}`, out);+ }+ write("voice", scenarios);+}