Skip to content

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

Rust

Retire the TypeScript engine

Jameson Hodgecd247a6c775c
diff --git a/DESIGN.md b/DESIGN.md
index 9bc33c9..2cdf004 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -44,7 +44,8 @@ A browser instrument where every sound comes from a simulated airway, not sample
main thread (React UI, canvas renderers)
│ commands (note/score/param/drag), timestamped in audio time
▼
-AudioWorklet ── Engine (pure TS, no DOM; also runs in Bun for tests/offline export)
+AudioWorklet ── Engine (Rust crate `chimera`, compiled to wasm; the same code runs natively
+ for tests, the `chimera` CLI and, later, JDAW — see docs/rust-engine.md)
├─ Voice[] (pool)
│ ├─ Controller: gesture scheduler → articulator dynamics (control rate)
│ ├─ Anatomy: articulator state → geometry → area functions (control rate)
@@ -162,17 +163,23 @@ limiter. WAV export via the same engine in a Worker (unlimited voices, faster th
## Tech
-TypeScript, Vite, React 19 (controls) + hand-written canvas/SVG renderers (visuals),
-Zustand state. Bun for tooling/tests. Engine uses preallocated Float64Arrays, no
-allocation in the audio loop. WASM port only if profiling demands it.
+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
-* `bun test`: uniform-tube resonances vs analytic; FDTD impulse response vs chain-matrix
+* `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.
-* Offline renders → WAV + spectrogram PNG (rendered in TS) inspected visually.
+ 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 (`chimera render …`) → WAV; `tools/spectrogram.ts` draws the PNG to inspect.
* 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).
diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rs
index 8a62875..082f678 100644
--- a/crates/chimera-wasm/src/api.rs
+++ b/crates/chimera-wasm/src/api.rs
@@ -163,6 +163,7 @@ fn catalog() -> Res {
"beatSounds": &beatbox::BEAT_SOUNDS[..],
"beatPresets": &beatbox::BEAT_PRESETS[..],
"vowelTargets": vowels,
+ "consonantSymbols": chimera::phonetics::inventory::consonant_symbols(),
"demoSongs": songs::DEMO_SONGS,
"vowels": vowel_data::VOWELS,
"creatures": &chimera::creatures::CREATURES[..],
diff --git a/crates/chimera/tests/golden/README.md b/crates/chimera/tests/golden/README.md
new file mode 100644
index 0000000..1724b52
--- /dev/null
+++ b/crates/chimera/tests/golden/README.md
@@ -0,0 +1,22 @@
+# Golden fixtures
+
+These are what the TypeScript engine computed before it was retired. The generators lived in
+`tools/golden/*.ts`; recover them with `git show fdf5441:tools/golden/<area>.ts`. They ran the
+TypeScript engine that is still in that commit's `src/engine/`. The `golden_*` tests (and
+`engine.rs`) check that the Rust engine reproduces the fixtures. This is how the port was
+verified: numbers to 1e-9 relative, and audio sample for sample.
+
+| Fixture | What | Test |
+|---|---|---|
+| `geometry.json` | grids, area functions, contacts and outlines for 114 postures | `golden_geometry.rs` |
+| `voice.json`, `voice-*.f32` | human-voice scenarios (timed operations) and their samples | `golden_voice.rs` |
+| `planning.json`, `beatbox-bar.f32` | plans, durations, sung notes, beatbox builds, sequencer, one bar | `golden_planning.rs`, `engine.rs` |
+| `phonetics-*.json` | IPA tokenizer, G2P, phrases, syllables, songs and vowel data | `golden_phonetics_text.rs` |
+| `creatures.json`, `creatures.f32`, `creature-units.json` | every creature's calls and controls, valves | `golden_creatures.rs` |
+| `analysis.json` | transfer functions, FFT, LPC, YIN, Nelder–Mead | `golden_analysis.rs` |
+
+When a test fails after an **intended** change to the sound or the plans:
+- **The human-voice audio** regenerates from the Rust engine: `CHIMERA_BLESS=1 cargo test -p chimera --test golden_voice`.
+- **Other fixtures** record the TypeScript engine's behaviour. Either update the expectation the
+ change affects, or remove the case and add a behavioural test (`tests/*.rs`) for what the
+ change is meant to do.
diff --git a/docs/rust-engine.md b/docs/rust-engine.md
index c35786d..470b111 100644
--- a/docs/rust-engine.md
+++ b/docs/rust-engine.md
@@ -118,8 +118,8 @@ consumption or sums (noise sources, gestures). It retunes nothing. The checks:
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.
+ - With the TS engine gone, the fixtures record what it did (`crates/chimera/tests/golden/README.md`).
+ The human-voice audio can be re-blessed from the Rust engine (`CHIMERA_BLESS=1`).
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.
diff --git a/src/engine/airway/decimator.ts b/src/engine/airway/decimator.ts
deleted file mode 100644
index a0b6228..0000000
--- a/src/engine/airway/decimator.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-/**
- * FIR decimator: Kaiser-windowed sinc low-pass, integer factor M.
- * push() one input sample at a time; when ready, `value` holds the next output sample.
- */
-function besselI0(x: number): number {
- let sum = 1, term = 1;
- for (let k = 1; k < 30; k++) {
- term *= (x / (2 * k)) * (x / (2 * k));
- sum += term;
- if (term < 1e-12 * sum) break;
- }
- return sum;
-}
-
-export function designLowpass(taps: number, cutoff: number, beta = 8): Float64Array {
- // cutoff as a fraction of the input sample rate (0..0.5)
- const h = new Float64Array(taps);
- const mid = (taps - 1) / 2;
- const i0b = besselI0(beta);
- let sum = 0;
- for (let i = 0; i < taps; i++) {
- const x = i - mid;
- const sinc = x === 0 ? 2 * cutoff : Math.sin(2 * Math.PI * cutoff * x) / (Math.PI * x);
- const r = (2 * i) / (taps - 1) - 1;
- const w = besselI0(beta * Math.sqrt(Math.max(0, 1 - r * r))) / i0b;
- h[i] = sinc * w;
- sum += h[i];
- }
- for (let i = 0; i < taps; i++) h[i] /= sum;
- return h;
-}
-
-export class Decimator {
- readonly factor: number;
- private readonly h: Float64Array;
- private readonly buf: Float64Array;
- private pos = 0;
- private count = 0;
- value = 0;
-
- constructor(factor: number, tapsPerPhase = 24) {
- this.factor = factor;
- const taps = factor === 1 ? 1 : factor * tapsPerPhase + 1;
- this.h = factor === 1 ? Float64Array.of(1) : designLowpass(taps, 0.46 / factor, 8.5);
- this.buf = new Float64Array(taps * 2);
- }
-
- /** Push one input sample; returns true when an output sample is ready in `value`. */
- push(x: number): boolean {
- const n = this.h.length;
- this.buf[this.pos] = x;
- this.buf[this.pos + n] = x;
- this.pos = this.pos + 1 === n ? 0 : this.pos + 1;
- if (++this.count < this.factor) return false;
- this.count = 0;
- let acc = 0;
- const h = this.h;
- const b = this.buf;
- const start = this.pos; // oldest sample
- for (let i = 0; i < n; i++) acc += h[n - 1 - i] * b[start + i];
- this.value = acc;
- return true;
- }
-}
diff --git a/src/engine/airway/frequency.ts b/src/engine/airway/frequency.ts
deleted file mode 100644
index e13594c..0000000
--- a/src/engine/airway/frequency.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-/**
- * Frequency-domain analysis of the (linearised) airway network: the same lumped elements
- * as the FDTD, solved per frequency by tree elimination (O(N) per frequency).
- * Used as a test oracle, for vowel calibration, and for the live transfer-function display.
- */
-import { RHO, C_SOUND } from "../physics.ts";
-import type { LinearElements } from "./network.ts";
-
-export interface TransferResult {
- freqs: Float64Array;
- /** |U_rad / U_in| */
- mag: Float64Array;
- /** radiated pressure ∝ |jω·U_rad/U_in| (dB, arbitrary reference) */
- pressureDb: Float64Array;
-}
-
-/**
- * Transfer function from a volume-velocity source injected at `inject` to total radiated
- * volume velocity. Branches in `cut` are removed (e.g. the glottis: an ideal flow source has
- * infinite internal impedance, which decouples the subglottal system).
- */
-export function transferFunction(el: LinearElements, inject: number, freqs: ArrayLike<number>, cut: number[] = []): TransferResult {
- const N = el.nNodes;
- // adjacency of open branches
- const adjStart = new Int32Array(N + 1);
- const cutSet = new Set(cut);
- for (let j = 0; j < el.nBranches; j++) {
- if (!el.open[j] || cutSet.has(j)) continue;
- adjStart[el.a[j] + 1]++;
- adjStart[el.b[j] + 1]++;
- }
- for (let k = 0; k < N; k++) adjStart[k + 1] += adjStart[k];
- const adj = new Int32Array(adjStart[N]);
- const fill = adjStart.slice(0, N);
- for (let j = 0; j < el.nBranches; j++) {
- if (!el.open[j] || cutSet.has(j)) continue;
- adj[fill[el.a[j]]++] = j;
- adj[fill[el.b[j]]++] = j;
- }
- // BFS tree from the injection node
- const order: number[] = [];
- const parent = new Int32Array(N).fill(-2);
- const parentBranch = new Int32Array(N).fill(-1);
- parent[inject] = -1;
- order.push(inject);
- for (let q = 0; q < order.length; q++) {
- const m = order[q];
- for (let e = adjStart[m]; e < adjStart[m + 1]; e++) {
- const j = adj[e];
- const k = el.a[j] === m ? el.b[j] : el.a[j];
- if (parent[k] !== -2) continue; // visited (a loop would be ignored here)
- parent[k] = m;
- parentBranch[k] = j;
- order.push(k);
- }
- }
- const radOf = new Int32Array(N).fill(-1);
- for (let r = 0; r < el.radNodes.length; r++) radOf[el.radNodes[r]] = r;
-
- const nf = freqs.length;
- const mag = new Float64Array(nf);
- const pdb = new Float64Array(nf);
- const yr = new Float64Array(N); // total admittance of subtree (incl. node shunt)
- const yi = new Float64Array(N);
- const er = new Float64Array(N); // equivalent admittance seen from parent (incl. series branch)
- const ei = new Float64Array(N);
- const pr = new Float64Array(N);
- const pi = new Float64Array(N);
- const radYr = new Float64Array(N);
- const radYi = new Float64Array(N);
- const wYr = new Float64Array(N);
- const wYi = new Float64Array(N);
-
- for (let f = 0; f < nf; f++) {
- const w = 2 * Math.PI * Math.max(freqs[f], 1e-3);
- // shunt admittances
- for (const k of order) {
- let gr = 0;
- let gi = w * el.C[k];
- wYr[k] = wYi[k] = 0;
- if (el.wallArea[k] > 0) {
- // Y = S / (r + j(ωm − k/ω))
- const zr = el.wallR[k];
- const zi = w * el.wallM[k] - el.wallK[k] / w;
- const d = zr * zr + zi * zi;
- wYr[k] = (el.wallArea[k] * zr) / d;
- wYi[k] = (-el.wallArea[k] * zi) / d;
- gr += wYr[k];
- gi += wYi[k];
- }
- radYr[k] = radYi[k] = 0;
- const r = radOf[k];
- if (r >= 0) {
- const a = el.radArea[r];
- const Lr = (8 * RHO) / (3 * Math.PI * Math.sqrt(Math.PI * a));
- const Rr = (128 * RHO * C_SOUND) / (9 * Math.PI * Math.PI * a);
- radYr[k] = 1 / Rr;
- radYi[k] = -1 / (w * Lr);
- gr += radYr[k];
- gi += radYi[k];
- }
- if (el.fixed[k]) gr += 1e30;
- yr[k] = gr;
- yi[k] = gi;
- }
- // eliminate leaves → root
- for (let q = order.length - 1; q >= 1; q--) {
- const k = order[q];
- const j = parentBranch[k];
- // Y_eq = Y / (1 + Z·Y), Z = R + jωL
- const zr = el.R[j];
- const zi = w * el.L[j];
- const dr = 1 + zr * yr[k] - zi * yi[k];
- const di = zr * yi[k] + zi * yr[k];
- const dd = dr * dr + di * di;
- er[k] = (yr[k] * dr + yi[k] * di) / dd;
- ei[k] = (yi[k] * dr - yr[k] * di) / dd;
- const m = parent[k];
- yr[m] += er[k];
- yi[m] += ei[k];
- }
- // root pressure for unit injected flow
- {
- const dd = yr[inject] * yr[inject] + yi[inject] * yi[inject];
- pr[inject] = yr[inject] / dd;
- pi[inject] = -yi[inject] / dd;
- }
- // back-substitute root → leaves: I = p_m·Y_eq(k); p_k = p_m − Z·I
- let ur = 0;
- let ui = 0;
- for (let q = 0; q < order.length; q++) {
- const k = order[q];
- if (q > 0) {
- const m = parent[k];
- const j = parentBranch[k];
- const Ir = pr[m] * er[k] - pi[m] * ei[k];
- const Ii = pr[m] * ei[k] + pi[m] * er[k];
- const zr = el.R[j];
- const zi = w * el.L[j];
- pr[k] = pr[m] - (zr * Ir - zi * Ii);
- pi[k] = pi[m] - (zr * Ii + zi * Ir);
- }
- if (radOf[k] >= 0) {
- ur += pr[k] * radYr[k] - pi[k] * radYi[k];
- ui += pr[k] * radYi[k] + pi[k] * radYr[k];
- }
- if (el.wallRad[k] > 0 && el.wallArea[k] > 0) {
- ur += el.wallRad[k] * (pr[k] * wYr[k] - pi[k] * wYi[k]);
- ui += el.wallRad[k] * (pr[k] * wYi[k] + pi[k] * wYr[k]);
- }
- }
- mag[f] = Math.hypot(ur, ui);
- pdb[f] = 20 * Math.log10(mag[f] * w + 1e-30);
- }
- return { freqs: Float64Array.from(freqs), mag, pressureDb: pdb };
-}
-
-export interface Peak {
- freq: number;
- /** -3 dB bandwidth (Hz), NaN if not measurable */
- bw: number;
- db: number;
-}
-
-/** Local maxima of |H| (dB) with parabolic refinement and −3 dB bandwidths. */
-export function findPeaks(freqs: ArrayLike<number>, mag: ArrayLike<number>, minFreq = 80): Peak[] {
- const n = mag.length;
- const db = new Float64Array(n);
- for (let i = 0; i < n; i++) db[i] = 20 * Math.log10(mag[i] + 1e-30);
- const out: Peak[] = [];
- for (let i = 1; i < n - 1; i++) {
- if (freqs[i] < minFreq) continue;
- if (db[i] > db[i - 1] && db[i] >= db[i + 1]) {
- const a = db[i - 1], b = db[i], c = db[i + 1];
- const den = a - 2 * b + c;
- const off = Math.abs(den) > 1e-12 ? (0.5 * (a - c)) / den : 0;
- const df = freqs[i + 1] - freqs[i];
- const f = freqs[i] + off * df;
- const peakDb = b - 0.25 * (a - c) * off;
- // -3 dB points
- let lo = i, hi = i;
- while (lo > 0 && db[lo] > peakDb - 3) lo--;
- while (hi < n - 1 && db[hi] > peakDb - 3) hi++;
- let bw = NaN;
- if (db[lo] <= peakDb - 3 && db[hi] <= peakDb - 3) {
- const fl = freqs[lo] + ((peakDb - 3 - db[lo]) / (db[lo + 1] - db[lo])) * (freqs[lo + 1] - freqs[lo]);
- const fh = freqs[hi - 1] + ((db[hi - 1] - (peakDb - 3)) / (db[hi - 1] - db[hi])) * (freqs[hi] - freqs[hi - 1]);
- bw = fh - fl;
- }
- out.push({ freq: f, bw, db: peakDb });
- }
- }
- return out;
-}
-
-export function linspace(a: number, b: number, n: number): Float64Array {
- const out = new Float64Array(n);
- for (let i = 0; i < n; i++) out[i] = a + ((b - a) * i) / (n - 1);
- return out;
-}
diff --git a/src/engine/airway/network.ts b/src/engine/airway/network.ts
deleted file mode 100644
index 5046d4e..0000000
--- a/src/engine/airway/network.ts
+++ /dev/null
@@ -1,937 +0,0 @@
-/**
- * Branched airway acoustics: staggered-grid FDTD transmission-line network.
- *
- * Nodes carry pressure p (dyn/cm²) and a volume V = A·Δ; branches carry volume velocity
- * U (cm³/s) between two nodes. Leapfrog in time: branches update U(n+½) from p(n), then
- * nodes update p(n+1) from U(n+½).
- *
- * Branch momentum: the state is Φ = L·U (∝ particle velocity), so as a branch closes
- * (L → ∞) its volume flow goes to zero without remembering stale momentum. Update solves
- * (L/T)·U' + R·U' + k·|U'|·U' = Δp + Φ/T (exact quadratic, k = kinetic loss)
- * with Borda–Carnot expansion loss k = ρ/2·(1/A_up − 1/A_down)² chosen by flow direction.
- *
- * Node continuity (moving walls included):
- * (V/ρc²)·dp/dt = ΣU_in − ΣU_out − U_wall − dV/dt
- * Yielding walls: per-node mass–spring–damper per unit area, times wall area (perimeter·Δ).
- * Radiation: Flanagan parallel R–L load at open ends; output is d/dt of radiated flow.
- */
-import { RHO, RHO_C2, C_SOUND, MU, NU, RE_CRIT, type WallParams } from "../physics.ts";
-import { Rng } from "../util/math.ts";
-
-export interface TubeSpec {
- name: string;
- /** number of sections (pressure nodes) */
- n: number;
- /** total length (cm); may change at control rate */
- length: number;
- /** initial area(s) cm² */
- area: number | ArrayLike<number>;
- /** yielding wall parameters, or null for rigid */
- wall?: WallParams | null;
- /** cross-section perimeter relative to a circle of equal area (≥1) */
- perimeterFactor?: number;
- /** multiplier on viscous resistance */
- viscousFactor?: number;
- /** fraction of wall volume velocity radiated as sound (skin radiation) */
- wallRadiation?: number;
-}
-
-export class Tube {
- constructor(
- readonly index: number,
- readonly name: string,
- readonly n: number,
- readonly first: number,
- public length: number,
- ) {}
- node(i: number): number {
- return this.first + i;
- }
- get firstNode(): number {
- return this.first;
- }
- get lastNode(): number {
- return this.first + this.n - 1;
- }
- /** index of the internal branch between node i and i+1 (set at build time) */
- branchBase = -1;
- branch(i: number): number {
- return this.branchBase + i;
- }
-}
-
-const KIND_SERIES = 0; // inertance from adjacent half-sections
-const KIND_PORT = 1; // own duct (area, length) in series with adjacent half-sections
-
-export interface PortSpec {
- /** duct area (cm²) */
- area: number;
- /** duct length (cm) */
- length: number;
- /** kinetic loss coefficient for flow entering the duct (contraction) */
- kEntrance?: number;
- /** kinetic loss coefficient for flow leaving the duct (jet expansion) */
- kExit?: number;
- /** slit-viscous width factor: if >0, viscous R = 12μ·len·w²/A³ (glottis-like slit of length w) */
- slitWidth?: number;
- /** include the adjacent half-section inertances (default true) */
- includeHalfSections?: boolean;
- /** additional constant series resistance (CGS acoustic ohms) */
- extraResistance?: number;
-}
-
-export interface LinearElements {
- nNodes: number;
- nBranches: number;
- a: Int32Array;
- b: Int32Array;
- L: Float64Array;
- R: Float64Array;
- open: Uint8Array;
- C: Float64Array;
- wallArea: Float64Array;
- wallM: Float64Array;
- wallR: Float64Array;
- wallK: Float64Array;
- wallRad: Float64Array;
- fixed: Uint8Array;
- radNodes: Int32Array;
- radArea: Float64Array;
-}
-
-interface NoiseSource {
- src: number; // branch whose Reynolds number drives the source
- fwd: number; // branch to inject into when flow is positive (a→b)
- bwd: number; // branch to inject into when flow is negative
- gain: number;
- reFactor: number; // Re = |U|·reFactor
- // band-shaping filter state
- hp: number;
- lp1: number;
- lp2: number;
- lpCoef: number;
- hpCoef: number;
- level: number; // last amplitude (telemetry)
-}
-
-export class AirwayNetwork {
- readonly fs: number;
- readonly T: number;
- private readonly invT: number;
-
- readonly tubes: Tube[] = [];
- private tubeSpecs: TubeSpec[] = [];
- private finalized = false;
-
- // --- nodes ---
- nNodes = 0;
- p!: Float64Array;
- /** current node area (cm²) */
- area!: Float64Array;
- private areaTarget!: Float64Array;
- private areaStep!: Float64Array;
- /** current minimum (sub-section) area per node: drives kinetic losses and Reynolds numbers */
- amin!: Float64Array;
- private aminTarget!: Float64Array;
- private aminStep!: Float64Array;
- /** nodes with ≥3 connections get a compliance floor for leapfrog stability */
- private isJunction!: Uint8Array;
- private invLsum!: Float64Array;
- /** per-sample reciprocal minimum area (jet losses) */
- private invAmin!: Float64Array;
- /** neighbour lists (CSR) for redistributing squeezed volume of nearly closed nodes */
- private nbrStart!: Int32Array;
- private nbrList!: Int32Array;
- private spill!: Float64Array;
- /** band-limited moving-wall volume source (2-pole low-pass state per node) */
- private volSrc1!: Float64Array;
- private volSrc2!: Float64Array;
- private volLpCoef = 0;
- /** cut-off of the moving-wall volume source (Hz): articulator-driven flow is sub-audio */
- volumeSourceHz = 60;
- /** below this node area (cm²) displaced volume is pushed into the neighbours */
- squeezeArea = 0.12;
- /** model switches (diagnostics / ablation) */
- enableVolumeSource = true;
- enableJunctionFloor = true;
- energySafe = true;
- /** diagnostics: use the larger kinetic coefficient for both flow directions */
- symmetricKinetic = false;
- /** current section length (cm) */
- dx!: Float64Array;
- private dxTarget!: Float64Array;
- private dxStep!: Float64Array;
- private vol!: Float64Array;
- private invA!: Float64Array;
- private flowSum!: Float64Array;
- /** external volume-velocity injection per node for the next step (cleared after use) */
- extFlow!: Float64Array;
- private fixed!: Uint8Array;
- private wallM!: Float64Array;
- private wallR!: Float64Array;
- private wallK!: Float64Array;
- private wallPerim!: Float64Array; // perimeter factor·2√π (multiply by √A·Δ for wall area)
- private wallRad!: Float64Array;
- private hasWall!: Uint8Array;
- wallY!: Float64Array;
- private wallV!: Float64Array;
- /** per-node wall volume velocity (telemetry) */
- wallU!: Float64Array;
- private nodeTube!: Int32Array;
- private viscF!: Float64Array;
- private radOf!: Int32Array;
-
- // --- branches ---
- nBranches = 0;
- private bA: number[] = [];
- private bB: number[] = [];
- private bKind: number[] = [];
- private portSpecs: (PortSpec | null)[] = [];
- private ba!: Int32Array;
- private bb!: Int32Array;
- private bk!: Uint8Array;
- U!: Float64Array;
- private mom!: Float64Array;
- private Lprev!: Float64Array;
- /** extra series pressure sources (noise, driven sources), cleared each sample */
- psrc!: Float64Array;
- /** port branch area (cm²), current */
- portArea!: Float64Array;
- private portAreaTarget!: Float64Array;
- private portAreaStep!: Float64Array;
- private portLen!: Float64Array;
- private portKin!: Float64Array;
- private portKex!: Float64Array;
- private portSlit!: Float64Array;
- private portHalf!: Uint8Array;
- private portExtraR!: Float64Array;
- /** branch "effective" area used for telemetry and Reynolds numbers */
- branchArea!: Float64Array;
-
- // --- radiation ---
- private radNodes: number[] = [];
- private radNodeArr!: Int32Array;
- private radUL!: Float64Array;
- private radLprev!: Float64Array;
- /** radiated volume velocity of each radiator (telemetry) */
- radU!: Float64Array;
- private radPrevTotal = 0;
-
- // --- sources/boundaries ---
- private noise: NoiseSource[] = [];
- private readonly rng = new Rng(12345);
- /** closure threshold (cm²): below this a branch passes no flow */
- closedArea = 2e-4;
- /** node area floor for volume/compliance (cm²) */
- minNodeArea = 0.02;
- /** global viscous loss scale */
- viscousScale = 1;
- /** reference angular frequency for frequency-independent viscous loss */
- viscousOmega = 2 * Math.PI * 700;
- /** scale on turbulence noise gain */
- noiseScale = 1;
- /** last output sample (radiated pressure derivative) */
- out = 0;
-
- constructor(fs: number) {
- this.fs = fs;
- this.T = 1 / fs;
- this.invT = fs;
- }
-
- addTube(spec: TubeSpec): Tube {
- if (this.finalized) throw new Error("network finalized");
- const t = new Tube(this.tubes.length, spec.name, spec.n, this.nNodes, spec.length);
- this.tubes.push(t);
- this.tubeSpecs.push(spec);
- this.nNodes += spec.n;
- // internal branches
- t.branchBase = this.bA.length;
- for (let i = 0; i < spec.n - 1; i++) this.pushBranch(t.node(i), t.node(i + 1), KIND_SERIES, null);
- return t;
- }
-
- /** Connect two nodes with series half-section inertance (e.g. tube end to tube end). */
- connect(a: number, b: number): number {
- return this.pushBranch(a, b, KIND_SERIES, null);
- }
-
- /** Connect two nodes through a duct with its own (time-varying) area: glottis, velum port, valves, necks. */
- addPort(a: number, b: number, spec: PortSpec): number {
- return this.pushBranch(a, b, KIND_PORT, spec);
- }
-
- /** Add a lumped cavity node (Helmholtz resonator volume) — returns node index. */
- addCavity(name: string, volume: number, wall: WallParams | null = null): number {
- // cavity = 1-node tube with area·length = volume (use a cube-ish proportion)
- const len = Math.cbrt(volume);
- const t = this.addTube({ name, n: 1, length: len, area: volume / len, wall, perimeterFactor: 1.2 });
- return t.firstNode;
- }
-
- /** Prescribed-pressure boundary node (lungs, air sacs). Returns node index. */
- addPressureNode(name: string): number {
- const t = this.addTube({ name, n: 1, length: 1, area: 100, wall: null });
- this.pendingFixed.push(t.firstNode);
- return t.firstNode;
- }
- private pendingFixed: number[] = [];
-
- /** Attach a radiation load at an open end node. Returns radiator index. */
- addRadiation(node: number): number {
- this.radNodes.push(node);
- return this.radNodes.length - 1;
- }
-
- private pushBranch(a: number, b: number, kind: number, spec: PortSpec | null): number {
- this.bA.push(a);
- this.bB.push(b);
- this.bKind.push(kind);
- this.portSpecs.push(spec);
- return this.bA.length - 1;
- }
-
- finalize(): void {
- if (this.finalized) return;
- this.finalized = true;
- const N = this.nNodes;
- const B = (this.nBranches = this.bA.length);
- this.p = new Float64Array(N);
- this.area = new Float64Array(N);
- this.areaTarget = new Float64Array(N);
- this.areaStep = new Float64Array(N);
- this.amin = new Float64Array(N);
- this.aminTarget = new Float64Array(N);
- this.aminStep = new Float64Array(N);
- this.isJunction = new Uint8Array(N);
- this.invLsum = new Float64Array(N);
- this.invAmin = new Float64Array(N);
- this.dx = new Float64Array(N);
- this.dxTarget = new Float64Array(N);
- this.dxStep = new Float64Array(N);
- this.vol = new Float64Array(N);
- this.invA = new Float64Array(N);
- this.flowSum = new Float64Array(N);
- this.extFlow = new Float64Array(N);
- this.fixed = new Uint8Array(N);
- this.wallM = new Float64Array(N);
- this.wallR = new Float64Array(N);
- this.wallK = new Float64Array(N);
- this.wallPerim = new Float64Array(N);
- this.wallRad = new Float64Array(N);
- this.hasWall = new Uint8Array(N);
- this.wallY = new Float64Array(N);
- this.wallV = new Float64Array(N);
- this.wallU = new Float64Array(N);
- this.nodeTube = new Int32Array(N);
- this.viscF = new Float64Array(N);
- this.radOf = new Int32Array(N).fill(-1);
- for (const t of this.tubes) {
- const spec = this.tubeSpecs[t.index];
- const dx = spec.length / spec.n;
- for (let i = 0; i < t.n; i++) {
- const k = t.node(i);
- const a = typeof spec.area === "number" ? spec.area : spec.area[i];
- this.area[k] = this.areaTarget[k] = a;
- this.amin[k] = this.aminTarget[k] = a;
- this.dx[k] = this.dxTarget[k] = dx;
- this.nodeTube[k] = t.index;
- this.viscF[k] = spec.viscousFactor ?? 1;
- const w = spec.wall;
- if (w) {
- this.hasWall[k] = 1;
- this.wallM[k] = w.mass;
- this.wallR[k] = w.resistance;
- this.wallK[k] = w.stiffness;
- }
- this.wallPerim[k] = (spec.perimeterFactor ?? 1) * 2 * Math.sqrt(Math.PI);
- this.wallRad[k] = spec.wallRadiation ?? 0;
- }
- }
- for (const k of this.pendingFixed) this.fixed[k] = 1;
- this.ba = Int32Array.from(this.bA);
- this.bb = Int32Array.from(this.bB);
- this.bk = Uint8Array.from(this.bKind);
- this.U = new Float64Array(B);
- this.mom = new Float64Array(B);
- this.Lprev = new Float64Array(B);
- const degree = new Int32Array(N);
- for (let j = 0; j < B; j++) {
- degree[this.ba[j]]++;
- degree[this.bb[j]]++;
- }
- for (let k = 0; k < N; k++) this.isJunction[k] = degree[k] >= 3 ? 1 : 0;
- this.nbrStart = new Int32Array(N + 1);
- for (let k = 0; k < N; k++) this.nbrStart[k + 1] = this.nbrStart[k] + degree[k];
- this.nbrList = new Int32Array(this.nbrStart[N]);
- const fillN = this.nbrStart.slice(0, N);
- for (let j = 0; j < B; j++) {
- this.nbrList[fillN[this.ba[j]]++] = this.bb[j];
- this.nbrList[fillN[this.bb[j]]++] = this.ba[j];
- }
- this.spill = new Float64Array(N);
- this.volSrc1 = new Float64Array(N);
- this.volSrc2 = new Float64Array(N);
- this.volLpCoef = 1 - Math.exp((-2 * Math.PI * this.volumeSourceHz) / this.fs);
- this.psrc = new Float64Array(B);
- this.portArea = new Float64Array(B);
- this.portAreaTarget = new Float64Array(B);
- this.portAreaStep = new Float64Array(B);
- this.portLen = new Float64Array(B);
- this.portKin = new Float64Array(B);
- this.portKex = new Float64Array(B);
- this.portSlit = new Float64Array(B);
- this.portHalf = new Uint8Array(B);
- this.portExtraR = new Float64Array(B);
- this.branchArea = new Float64Array(B);
- for (let j = 0; j < B; j++) {
- const s = this.portSpecs[j];
- if (s) {
- this.portArea[j] = this.portAreaTarget[j] = s.area;
- this.portLen[j] = s.length;
- this.portKin[j] = s.kEntrance ?? 0.4;
- this.portKex[j] = s.kExit ?? 1.0;
- this.portSlit[j] = s.slitWidth ?? 0;
- this.portHalf[j] = s.includeHalfSections === false ? 0 : 1;
- this.portExtraR[j] = s.extraResistance ?? 0;
- }
- }
- this.radNodeArr = Int32Array.from(this.radNodes);
- this.radUL = new Float64Array(this.radNodes.length);
- this.radLprev = new Float64Array(this.radNodes.length);
- this.radU = new Float64Array(this.radNodes.length);
- for (let r = 0; r < this.radNodes.length; r++) this.radOf[this.radNodes[r]] = r;
- for (let k = 0; k < N; k++) {
- const a = Math.max(this.area[k], this.minNodeArea);
- this.vol[k] = a * this.dx[k];
- this.invA[k] = 1 / Math.max(this.area[k], 1e-6);
- }
- this.checkCfl();
- }
-
- /** Largest stable time step check (warn only). */
- checkCfl(): number {
- let minDx = Infinity;
- for (let k = 0; k < this.nNodes; k++) if (!this.fixed[k]) minDx = Math.min(minDx, this.dxTarget[k]);
- const cfl = (C_SOUND * this.T) / minDx;
- return cfl;
- }
-
- // ---------------------------------------------------------------- control-rate API
-
- /** Set target areas (and optionally total length) of a tube, reached at the end of the next block. */
- setTubeTargets(t: Tube, areas: ArrayLike<number>, length?: number, minAreas?: ArrayLike<number>): void {
- for (let i = 0; i < t.n; i++) {
- const a = Math.max(0, areas[i]);
- this.areaTarget[t.node(i)] = a;
- this.aminTarget[t.node(i)] = minAreas ? Math.max(0, Math.min(a, minAreas[i])) : a;
- }
- if (length !== undefined) {
- t.length = length;
- const d = length / t.n;
- for (let i = 0; i < t.n; i++) this.dxTarget[t.node(i)] = d;
- }
- }
-
- setNodeAreaTarget(node: number, area: number): void {
- this.areaTarget[node] = Math.max(0, area);
- this.aminTarget[node] = this.areaTarget[node];
- }
-
- setPortTarget(branch: number, area: number): void {
- this.portAreaTarget[branch] = Math.max(0, area);
- }
-
- /** Immediately set a port area (per-sample sources such as the glottis call this every sample). */
- setPortArea(branch: number, area: number): void {
- this.portArea[branch] = area < 0 ? 0 : area;
- this.portAreaTarget[branch] = this.portArea[branch];
- this.portAreaStep[branch] = 0;
- }
-
- setFixedPressure(node: number, p: number): void {
- this.p[node] = p;
- }
-
- /** Jump the geometry to the current targets immediately (initialisation; no dV/dt transient). */
- snapToTargets(): void {
- for (let k = 0; k < this.nNodes; k++) {
- this.area[k] = this.areaTarget[k];
- this.amin[k] = this.aminTarget[k];
- this.dx[k] = this.dxTarget[k];
- this.vol[k] = Math.max(this.area[k], this.minNodeArea) * this.dx[k];
- this.invA[k] = 1 / Math.max(this.area[k], 1e-6);
- this.areaStep[k] = this.aminStep[k] = this.dxStep[k] = 0;
- }
- for (let j = 0; j < this.nBranches; j++) {
- if (this.bk[j] === KIND_PORT) {
- this.portArea[j] = this.portAreaTarget[j];
- this.portAreaStep[j] = 0;
- }
- }
- }
-
- /** Prepare per-sample linear ramps toward the targets over `samples` internal samples. */
- beginBlock(samples: number): void {
- const inv = 1 / Math.max(1, samples);
- let maxP = 0;
- for (let k = 0; k < this.nNodes; k++) {
- this.areaStep[k] = (this.areaTarget[k] - this.area[k]) * inv;
- this.aminStep[k] = (this.aminTarget[k] - this.amin[k]) * inv;
- this.dxStep[k] = (this.dxTarget[k] - this.dx[k]) * inv;
- if (!this.fixed[k]) {
- const ap = Math.abs(this.p[k]);
- if (ap > maxP) maxP = ap;
- }
- }
- // flush decayed state to zero (avoids denormal slowdowns in silent tails)
- if (maxP < 1e-9) {
- let maxU = 0;
- for (let j = 0; j < this.nBranches; j++) maxU = Math.max(maxU, Math.abs(this.U[j]));
- if (maxU < 1e-9) this.flushState();
- }
- for (let j = 0; j < this.nBranches; j++) {
- if (this.bk[j] === KIND_PORT) this.portAreaStep[j] = (this.portAreaTarget[j] - this.portArea[j]) * inv;
- }
- }
-
- /** Replace the set of turbulence noise sources (called at control rate). */
- setNoiseSources(list: { src: number; fwd: number; bwd: number; gain: number; lowpassHz?: number; highpassHz?: number }[]): void {
- // reuse filter states for sources whose (src, fwd) pair persists, to avoid clicks
- const old = this.noise;
- const next: NoiseSource[] = [];
- for (const s of list) {
- const prev = old.find((o) => o.src === s.src && o.fwd === s.fwd);
- const lpHz = s.lowpassHz ?? 7000;
- const hpHz = s.highpassHz ?? 400;
- next.push({
- src: s.src,
- fwd: s.fwd,
- bwd: s.bwd,
- gain: s.gain,
- reFactor: 0,
- hp: prev?.hp ?? 0,
- lp1: prev?.lp1 ?? 0,
- lp2: prev?.lp2 ?? 0,
- lpCoef: 1 - Math.exp((-2 * Math.PI * lpHz) / this.fs),
- hpCoef: Math.exp((-2 * Math.PI * hpHz) / this.fs),
- level: 0,
- });
- }
- this.noise = next;
- }
-
- private flushState(): void {
- for (let k = 0; k < this.nNodes; k++) {
- if (!this.fixed[k]) this.p[k] = 0;
- this.wallV[k] = 0;
- if (Math.abs(this.wallY[k]) < 1e-12) this.wallY[k] = 0;
- }
- this.U.fill(0);
- this.mom.fill(0);
- this.radUL.fill(0);
- }
-
- get noiseSources(): readonly { src: number; level: number }[] {
- return this.noise;
- }
-
- // ---------------------------------------------------------------- per-sample step
-
- /** Advance one internal sample. Returns radiated pressure (arbitrary units ∝ dU_rad/dt). */
- step(): number {
- const N = this.nNodes;
- const B = this.nBranches;
- const T = this.T;
- const invT = this.invT;
- const p = this.p;
- const area = this.area;
- const amin = this.amin;
- const dx = this.dx;
- const invA = this.invA;
- const vol = this.vol;
- const flowSum = this.flowSum;
- const minA = this.minNodeArea;
- const isJ = this.isJunction;
- const invLsum = this.invLsum;
-
- // 1) geometry ramps and the moving-wall volume source. The raw −dV/dt of each node is first
- // split between the node and its open neighbours (a nearly closed cell cannot hold the air
- // its walls displace), THEN each node's total injection is low-passed: dV/dt is piecewise
- // constant across control blocks and the split switches as cells close, and the output is a
- // derivative of flow, so unfiltered steps would radiate as clicks. Linear filtering after
- // the split keeps mass conserved.
- const sq = this.squeezeArea;
- const inj = this.spill; // reused as the per-node raw injection accumulator
- const volOn = this.enableVolumeSource;
- if (volOn) inj.fill(0);
- let anySpill = false;
- for (let k = 0; k < N; k++) {
- let a = area[k] + this.areaStep[k];
- if (a < 0) a = 0;
- area[k] = a;
- let am = amin[k] + this.aminStep[k];
- if (am < 0) am = 0;
- const amk = am > a ? a : am;
- amin[k] = amk;
- const d = (dx[k] += this.dxStep[k]);
- invA[k] = 1 / (a > 1e-6 ? a : 1e-6);
- this.invAmin[k] = 1 / (amk > 1e-6 ? amk : 1e-6);
- const v = (a > minA ? a : minA) * d;
- if (volOn) {
- const raw = -(v - vol[k]) * invT;
- const ae = amin[k] < a ? amin[k] : a; // a node sealed at its minimum cannot hold air either
- if (raw !== 0 && ae < sq) {
- const t = ae / sq;
- const keep = t * t * (3 - 2 * t);
- inj[k] += raw * keep;
- const sp = raw * (1 - keep);
- const s0 = this.nbrStart[k], s1 = this.nbrStart[k + 1];
- let nOpen = 0;
- for (let e = s0; e < s1; e++) {
- const m = this.nbrList[e];
- if (Math.min(area[m], amin[m]) >= sq || this.aminTarget[m] >= sq) nOpen++;
- }
- if (nOpen > 0) {
- const share = sp / nOpen;
- for (let e = s0; e < s1; e++) {
- const m = this.nbrList[e];
- if (Math.min(area[m], amin[m]) >= sq || this.aminTarget[m] >= sq) inj[m] += share;
- }
- } // else: fully sealed pocket, the squeezed air leaves laterally (absorbed)
- anySpill = true;
- } else inj[k] += raw;
- }
- vol[k] = v;
- invLsum[k] = 0;
- flowSum[k] = this.extFlow[k];
- this.extFlow[k] = 0;
- }
- void anySpill;
- if (volOn) {
- const c = this.volLpCoef;
- for (let k = 0; k < N; k++) {
- const s1 = (this.volSrc1[k] += c * (inj[k] - this.volSrc1[k]));
- flowSum[k] += this.volSrc2[k] += c * (s1 - this.volSrc2[k]);
- }
- }
-
- // 2) turbulence noise → series pressure sources
- const psrc = this.psrc;
- psrc.fill(0);
- if (this.noise.length) this.computeNoise();
-
- // 3) branches
- const ba = this.ba;
- const bb = this.bb;
- const bk = this.bk;
- const U = this.U;
- const mom = this.mom;
- const Lprev = this.Lprev;
- const visc = Math.sqrt((RHO * MU * this.viscousOmega) / 2) * this.viscousScale;
- const closed = this.closedArea;
- const halfRho = 0.5 * RHO;
- for (let j = 0; j < B; j++) {
- const a = ba[j];
- const b = bb[j];
- let L: number;
- let R: number;
- let kf: number;
- let kb: number;
- let aEff: number;
- if (bk[j] === KIND_SERIES) {
- const Aa = area[a];
- const Ab = area[b];
- const ma = amin[a];
- const mb = amin[b];
- aEff = ma < mb ? ma : mb;
- if ((Aa < Ab ? Aa : Ab) < closed || aEff < closed) {
- U[j] = 0;
- mom[j] = 0;
- this.branchArea[j] = aEff;
- continue;
- }
- const ia = invA[a];
- const ib = invA[b];
- L = halfRho * (dx[a] * ia + dx[b] * ib);
- // viscous: R = S·l/A² · sqrt(ρμω/2) with S = perimeter of each half-section
- R = 0.5 * visc * (this.wallPerim[a] * dx[a] * Math.sqrt(Aa) * ia * ia * this.viscF[a] + this.wallPerim[b] * dx[b] * Math.sqrt(Ab) * ib * ib * this.viscF[b]);
- // Borda–Carnot: the jet leaving the narrowest point of the upstream node expands into
- // the downstream node (sub-section minima make short constrictions lossy as they should be)
- const ima = this.invAmin[a], imb = this.invAmin[b];
- const ef = ima - ib; // a→b
- const eb = imb - ia; // b→a
- kf = ef > 0 ? halfRho * ef * ef : 0;
- kb = eb > 0 ? halfRho * eb * eb : 0;
- // small contraction (vena contracta) loss entering a narrower node
- const cf = imb - ia;
- const cb = ima - ib;
- if (cf > 0) kf += 0.1 * halfRho * cf * cf;
- if (cb > 0) kb += 0.1 * halfRho * cb * cb;
- } else {
- let Ap = (this.portArea[j] += this.portAreaStep[j]);
- if (Ap < 0) Ap = this.portArea[j] = 0;
- aEff = Ap;
- if (Ap < closed) {
- U[j] = 0;
- mom[j] = 0;
- this.branchArea[j] = Ap;
- continue;
- }
- const ip = 1 / Ap;
- const len = this.portLen[j];
- L = RHO * len * ip;
- if (this.portHalf[j]) L += halfRho * (dx[a] * invA[a] + dx[b] * invA[b]);
- const w = this.portSlit[j];
- if (w > 0) R = (12 * MU * len * w * w) * ip * ip * ip;
- else R = visc * 2 * Math.sqrt(Math.PI) * len * Math.sqrt(Ap) * ip * ip;
- R += this.portExtraR[j];
- // kinetic: entrance (contraction) + exit (jet expansion into the downstream node)
- const exF = ip - invA[b]; // flow a→b exits into b
- const exB = ip - invA[a]; // flow b→a exits into a
- const kin = this.portKin[j] * halfRho * ip * ip;
- kf = kin + this.portKex[j] * halfRho * (exF > 0 ? exF * exF : 0);
- kb = kin + this.portKex[j] * halfRho * (exB > 0 ? exB * exB : 0);
- }
- this.branchArea[j] = aEff;
- // energy-safe momentum transfer when the inertance changes: closing (L↑) conserves
- // momentum (flow drops), opening (L↓) conserves flow — never injects kinetic energy
- if (this.symmetricKinetic) {
- const km = kf > kb ? kf : kb;
- kf = km;
- kb = km;
- }
- const Lp = Lprev[j];
- const m0 = this.energySafe && L < Lp ? L * U[j] : mom[j];
- const c = p[a] - p[b] + psrc[j] + m0 * invT;
- const bq = L * invT + R;
- let u: number;
- if (c >= 0) {
- u = kf > 0 ? (2 * c) / (bq + Math.sqrt(bq * bq + 4 * kf * c)) : c / bq;
- } else {
- u = kb > 0 ? (2 * c) / (bq + Math.sqrt(bq * bq - 4 * kb * c)) : c / bq;
- }
- U[j] = u;
- mom[j] = L * u;
- Lprev[j] = L;
- flowSum[a] -= u;
- flowSum[b] += u;
- if (isJ[a] | isJ[b]) {
- const il = 1 / L;
- invLsum[a] += il;
- invLsum[b] += il;
- }
- }
-
- // 4) walls (velocity at half step from p(n), displacement integrates)
- const wallU = this.wallU;
- const hasWall = this.hasWall, wallM = this.wallM, wallR = this.wallR, wallK = this.wallK;
- const wallV = this.wallV, wallY = this.wallY, wallRad = this.wallRad;
- let wallRadSum = 0;
- for (let k = 0; k < N; k++) {
- if (!hasWall[k]) continue;
- const m = wallM[k];
- const r = wallR[k];
- const v = ((m * invT - 0.5 * r) * wallV[k] + p[k] - wallK[k] * wallY[k]) / (m * invT + 0.5 * r);
- wallV[k] = v;
- wallY[k] += T * v;
- const a = area[k] > minA ? area[k] : minA;
- const uw = this.wallPerim[k] * Math.sqrt(a) * dx[k] * v;
- wallU[k] = uw;
- flowSum[k] -= uw;
- wallRadSum += uw * wallRad[k];
- }
-
- // 5) nodes (radiation loads handled semi-implicitly)
- const radUL = this.radUL;
- const T2 = T * T;
- let radTotal = wallRadSum;
- const cl = this.closedArea;
- for (let k = 0; k < N; k++) {
- if (this.fixed[k]) continue;
- // sealed if the cell itself, or its narrowest point, is closed (then all its series
- // branches are closed too, and compressing its remaining volume would trap pressure)
- if (area[k] < cl || amin[k] < cl) {
- const rr = this.radOf[k];
- if (rr >= 0) {
- // sealed aperture: its outer face is the atmosphere, so it relaxes to 0 (tracking the
- // pressurised cavity behind would discharge as a radiated spike on reopening)
- p[k] *= 0.98;
- } else {
- // sealed interior cell (tissue contact): no air of its own; follow open neighbours
- let sum = 0, cnt = 0;
- for (let e = this.nbrStart[k]; e < this.nbrStart[k + 1]; e++) {
- const m = this.nbrList[e];
- if (area[m] >= cl && amin[m] >= cl) {
- sum += p[m];
- cnt++;
- }
- }
- if (cnt > 0) p[k] += 0.02 * (sum / cnt - p[k]);
- }
- if (rr >= 0) {
- // sealed aperture: let the radiated flow die away smoothly (no derivative step)
- radUL[rr] *= 0.995;
- this.radU[rr] = radUL[rr];
- radTotal += radUL[rr];
- }
- continue;
- }
- let C = vol[k] / RHO_C2;
- // junction stability: local breathing mode ω² ≈ ΣL⁻¹/C must satisfy T²ω² ≤ 2.4
- if (isJ[k] && this.enableJunctionFloor) {
- const cMin = (T2 * invLsum[k]) / 2.4;
- if (C < cMin) C = cMin;
- }
- const r = this.radOf[k];
- if (r < 0) {
- p[k] += (T / C) * flowSum[k];
- } else {
- const a = area[k] > 1e-4 ? area[k] : 1e-4;
- const Lr = (8 * RHO) / (3 * Math.PI * Math.sqrt(Math.PI * a));
- const Rr = (128 * RHO * C_SOUND) / (9 * Math.PI * Math.PI * a);
- const pOld = p[k];
- // energy-safe: when the radiation inertance grows (aperture closing) conserve momentum
- const Lp = this.radLprev[r];
- let ulPrev = radUL[r];
- if (Lp > 0 && Lr > Lp) ulPrev *= Lp / Lr;
- this.radLprev[r] = Lr;
- // Crank–Nicolson coupling of the node and its parallel R–L load (A-stable, energy-
- // conserving for the reactive part): Lr ∝ A^-½ against C ∝ A makes the explicit form
- // unstable at small apertures. U_L lives at integer steps; the node sees its mean.
- const h = T / (2 * Lr);
- const g = 0.5 / Rr;
- const pNew = (pOld * (C * invT - 0.5 * h - g) + flowSum[k] - ulPrev) / (C * invT + 0.5 * h + g);
- p[k] = pNew;
- const ul = ulPrev + h * (pOld + pNew);
- radUL[r] = ul;
- const ur = 0.5 * (ulPrev + ul) + g * (pNew + pOld);
- this.radU[r] = ur;
- radTotal += ur;
- }
- }
- const out = (radTotal - this.radPrevTotal) * invT;
- this.radPrevTotal = radTotal;
- this.out = out;
- return out;
- }
-
- private computeNoise(): void {
- const U = this.U;
- const psrc = this.psrc;
- const rng = this.rng;
- // white noise power per Hz scales with fs: normalise to a 96 kHz reference
- const scale = this.noiseScale * Math.sqrt(96000 / this.fs);
- const sat = 12000 * 12000 - RE_CRIT * RE_CRIT;
- for (let i = 0; i < this.noise.length; i++) {
- const s = this.noise[i];
- const a = this.branchArea[s.src];
- const u = U[s.src];
- let amp = 0;
- if (a > this.closedArea) {
- // Re = v·d_h/ν with d_h = 2√(A/π) → Re = |U|·2/(ν·√(πA))
- const re = (Math.abs(u) * 2) / (NU * Math.sqrt(Math.PI * a));
- if (re > RE_CRIT) {
- const x = re * re - RE_CRIT * RE_CRIT;
- amp = (s.gain * scale * x) / (1 + x / sat); // bounded growth at very high Re
- }
- }
- // white → high-pass (1st order) → 2nd-order low-pass
- const w = rng.bipolar() * 1.732;
- s.hp += (1 - s.hpCoef) * (w - s.hp); // s.hp holds a low-passed copy
- const hpOut = w - s.hp;
- s.lp1 += s.lpCoef * (hpOut - s.lp1);
- s.lp2 += s.lpCoef * (s.lp1 - s.lp2);
- s.level = amp;
- if (amp === 0) continue;
- const v = amp * s.lp2;
- if (u >= 0) psrc[s.fwd] += v;
- else psrc[s.bwd] -= v;
- }
- }
-
- /** Total radiated volume velocity of radiator r. */
- radiatedFlow(r: number): number {
- return this.radU[r];
- }
-
- /**
- * Linearised element values at the *target* geometry (what the next block ramps to), for
- * frequency-domain analysis. Same formulas as step(); kinetic losses are omitted (they
- * vanish for small signals about zero mean flow).
- */
- linearElements(): LinearElements {
- const N = this.nNodes;
- const B = this.nBranches;
- const visc = Math.sqrt((RHO * MU * this.viscousOmega) / 2) * this.viscousScale;
- const A = this.areaTarget;
- const dx = this.dxTarget;
- const L = new Float64Array(B);
- const R = new Float64Array(B);
- const open = new Uint8Array(B);
- for (let j = 0; j < B; j++) {
- const a = this.ba[j];
- const b = this.bb[j];
- const ia = 1 / Math.max(A[a], 1e-6);
- const ib = 1 / Math.max(A[b], 1e-6);
- if (this.bk[j] === KIND_SERIES) {
- if (Math.min(A[a], A[b]) < this.closedArea) continue;
- open[j] = 1;
- L[j] = 0.5 * RHO * (dx[a] * ia + dx[b] * ib);
- R[j] = 0.5 * visc * (this.wallPerim[a] * dx[a] * Math.sqrt(A[a]) * ia * ia * this.viscF[a] + this.wallPerim[b] * dx[b] * Math.sqrt(A[b]) * ib * ib * this.viscF[b]);
- } else {
- const Ap = this.portAreaTarget[j];
- if (Ap < this.closedArea) continue;
- open[j] = 1;
- const ip = 1 / Ap;
- const len = this.portLen[j];
- L[j] = RHO * len * ip + (this.portHalf[j] ? 0.5 * RHO * (dx[a] * ia + dx[b] * ib) : 0);
- const w = this.portSlit[j];
- R[j] = (w > 0 ? 12 * MU * len * w * w * ip * ip * ip : visc * 2 * Math.sqrt(Math.PI) * len * Math.sqrt(Ap) * ip * ip) + this.portExtraR[j];
- }
- }
- const C = new Float64Array(N);
- const wallArea = new Float64Array(N);
- for (let k = 0; k < N; k++) {
- const a = Math.max(A[k], this.minNodeArea);
- C[k] = (a * dx[k]) / RHO_C2;
- wallArea[k] = this.hasWall[k] ? this.wallPerim[k] * Math.sqrt(a) * dx[k] : 0;
- }
- return {
- nNodes: N,
- nBranches: B,
- a: this.ba,
- b: this.bb,
- L,
- R,
- open,
- C,
- wallArea,
- wallM: this.wallM,
- wallR: this.wallR,
- wallK: this.wallK,
- wallRad: this.wallRad,
- fixed: this.fixed,
- radNodes: this.radNodeArr,
- radArea: Float64Array.from(this.radNodeArr, (k) => Math.max(A[k], 1e-4)),
- };
- }
-
- /** Tube index of a node. */
- tubeOfNode(node: number): number {
- return this.nodeTube[node];
- }
-
- /** Reset all acoustic state. */
- reset(): void {
- this.p.fill(0);
- this.U.fill(0);
- this.mom.fill(0);
- this.Lprev.fill(0);
- this.wallY.fill(0);
- this.wallV.fill(0);
- this.radUL.fill(0);
- this.radLprev.fill(0);
- this.radPrevTotal = 0;
- }
-}
diff --git a/src/engine/analysis/lpc.ts b/src/engine/analysis/lpc.ts
deleted file mode 100644
index 051f64f..0000000
--- a/src/engine/analysis/lpc.ts
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * Linear prediction and formant estimation (autocorrelation method + Levinson–Durbin,
- * roots via Durand–Kerner). Pure TS; used by tests, offline tools and the UI.
- */
-
-export function autocorr(x: ArrayLike<number>, order: number): Float64Array {
- const r = new Float64Array(order + 1);
- const n = x.length;
- for (let k = 0; k <= order; k++) {
- let s = 0;
- for (let i = k; i < n; i++) s += x[i] * x[i - k];
- r[k] = s;
- }
- return r;
-}
-
-/** Returns LPC polynomial a[0..p] with a[0] = 1 (A(z) = 1 + a1 z^-1 + ...), and prediction error. */
-export function levinson(r: Float64Array, p: number): { a: Float64Array; err: number } {
- const a = new Float64Array(p + 1);
- a[0] = 1;
- let err = r[0] * (1 + 1e-9) + 1e-30;
- const tmp = new Float64Array(p + 1);
- for (let i = 1; i <= p; i++) {
- let acc = r[i];
- for (let j = 1; j < i; j++) acc += a[j] * r[i - j];
- const k = -acc / err;
- tmp.set(a);
- for (let j = 1; j < i; j++) a[j] = tmp[j] + k * tmp[i - j];
- a[i] = k;
- err *= 1 - k * k;
- if (err <= 0) break;
- }
- return { a, err };
-}
-
-/** Complex roots of polynomial with real coefficients c[0] z^n + c[1] z^(n-1) + ... + c[n]. */
-export function polyRoots(c: ArrayLike<number>, iters = 400): { re: Float64Array; im: Float64Array } {
- const n = c.length - 1;
- const lead = c[0];
- const coef = new Float64Array(n + 1);
- for (let i = 0; i <= n; i++) coef[i] = c[i] / lead;
- const re = new Float64Array(n);
- const im = new Float64Array(n);
- for (let i = 0; i < n; i++) {
- const ang = (2 * Math.PI * i) / n + 0.4;
- re[i] = 0.9 * Math.cos(ang);
- im[i] = 0.9 * Math.sin(ang);
- }
- for (let it = 0; it < iters; it++) {
- let maxDelta = 0;
- for (let i = 0; i < n; i++) {
- // evaluate p(z_i) by Horner
- let pr = 1, pi = 0;
- for (let k = 1; k <= n; k++) {
- const nr = pr * re[i] - pi * im[i] + coef[k];
- const ni = pr * im[i] + pi * re[i];
- pr = nr;
- pi = ni;
- }
- // denominator prod (z_i - z_j)
- let dr = 1, di = 0;
- for (let j = 0; j < n; j++) {
- if (j === i) continue;
- const xr = re[i] - re[j];
- const xi = im[i] - im[j];
- const nr = dr * xr - di * xi;
- const ni = dr * xi + di * xr;
- dr = nr;
- di = ni;
- }
- const den = dr * dr + di * di + 1e-300;
- const qr = (pr * dr + pi * di) / den;
- const qi = (pi * dr - pr * di) / den;
- re[i] -= qr;
- im[i] -= qi;
- maxDelta = Math.max(maxDelta, Math.abs(qr) + Math.abs(qi));
- }
- if (maxDelta < 1e-12) break;
- }
- return { re, im };
-}
-
-export interface Formant {
- freq: number;
- bw: number;
-}
-
-/**
- * Estimate formants of a voiced frame. Pre-emphasis, Hamming window, LPC order p.
- * Returns formants sorted by frequency with bandwidth filter.
- */
-export function estimateFormants(
- frame: ArrayLike<number>,
- sampleRate: number,
- opts: { order?: number; preEmph?: number; maxBw?: number; minFreq?: number } = {},
-): Formant[] {
- const order = opts.order ?? Math.round(2 + sampleRate / 1000);
- const pre = opts.preEmph ?? 0.97;
- const n = frame.length;
- const x = new Float64Array(n);
- for (let i = 0; i < n; i++) {
- const v = frame[i] - (i > 0 ? pre * frame[i - 1] : 0);
- x[i] = v * (0.54 - 0.46 * Math.cos((2 * Math.PI * i) / (n - 1)));
- }
- const r = autocorr(x, order);
- // lag window (mild) for numerical robustness
- for (let k = 1; k <= order; k++) r[k] *= Math.exp(-0.5 * Math.pow((2 * Math.PI * 40 * k) / sampleRate, 2));
- const { a } = levinson(r, order);
- const { re, im } = polyRoots(a);
- const out: Formant[] = [];
- for (let i = 0; i < re.length; i++) {
- if (im[i] <= 0) continue;
- const mag = Math.hypot(re[i], im[i]);
- const freq = (Math.atan2(im[i], re[i]) * sampleRate) / (2 * Math.PI);
- const bw = (-Math.log(mag) * sampleRate) / Math.PI;
- if (freq < (opts.minFreq ?? 90) || bw > (opts.maxBw ?? 600)) continue;
- out.push({ freq, bw });
- }
- out.sort((p, q) => p.freq - q.freq);
- return out;
-}
-
-/** LPC spectral envelope in dB at given frequencies. */
-export function lpcEnvelopeDb(a: Float64Array, err: number, sampleRate: number, freqs: ArrayLike<number>): Float64Array {
- const out = new Float64Array(freqs.length);
- for (let f = 0; f < freqs.length; f++) {
- const w = (2 * Math.PI * freqs[f]) / sampleRate;
- let re = 0, im = 0;
- for (let k = 0; k < a.length; k++) {
- re += a[k] * Math.cos(w * k);
- im -= a[k] * Math.sin(w * k);
- }
- out[f] = 10 * Math.log10(err / (re * re + im * im + 1e-30));
- }
- return out;
-}
diff --git a/src/engine/analysis/pitch.ts b/src/engine/analysis/pitch.ts
deleted file mode 100644
index 9977974..0000000
--- a/src/engine/analysis/pitch.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-/**
- * YIN fundamental-frequency estimator (de Cheveigné & Kawahara 2002) for one frame.
- * Returns 0 if unvoiced (aperiodicity above threshold).
- */
-export function yinPitch(
- frame: ArrayLike<number>,
- sampleRate: number,
- opts: { minF0?: number; maxF0?: number; threshold?: number } = {},
-): { f0: number; aperiodicity: number } {
- const minF0 = opts.minF0 ?? 50;
- const maxF0 = opts.maxF0 ?? 2000;
- const thr = opts.threshold ?? 0.15;
- const maxLag = Math.min(Math.floor(sampleRate / minF0), Math.floor(frame.length / 2));
- const minLag = Math.max(2, Math.floor(sampleRate / maxF0));
- const w = frame.length - maxLag;
- if (w <= 0) return { f0: 0, aperiodicity: 1 };
- const d = new Float64Array(maxLag + 1);
- for (let tau = 1; tau <= maxLag; tau++) {
- let s = 0;
- for (let i = 0; i < w; i++) {
- const diff = frame[i] - frame[i + tau];
- s += diff * diff;
- }
- d[tau] = s;
- }
- // cumulative mean normalized difference
- const cmnd = new Float64Array(maxLag + 1);
- cmnd[0] = 1;
- let run = 0;
- for (let tau = 1; tau <= maxLag; tau++) {
- run += d[tau];
- cmnd[tau] = run > 0 ? (d[tau] * tau) / run : 1;
- }
- let best = -1;
- for (let tau = minLag; tau <= maxLag; tau++) {
- if (cmnd[tau] < thr) {
- while (tau + 1 <= maxLag && cmnd[tau + 1] < cmnd[tau]) tau++;
- best = tau;
- break;
- }
- }
- if (best < 0) {
- // global minimum as fallback, reported with its aperiodicity
- let mi = minLag;
- for (let tau = minLag; tau <= maxLag; tau++) if (cmnd[tau] < cmnd[mi]) mi = tau;
- return { f0: 0, aperiodicity: cmnd[mi] };
- }
- // parabolic interpolation
- let tauF = best;
- if (best > 1 && best < maxLag) {
- const a = cmnd[best - 1], b = cmnd[best], c = cmnd[best + 1];
- const den = a - 2 * b + c;
- if (Math.abs(den) > 1e-12) tauF = best + (0.5 * (a - c)) / den;
- }
- return { f0: sampleRate / tauF, aperiodicity: cmnd[best] };
-}
diff --git a/src/engine/anatomy/geom.ts b/src/engine/anatomy/geom.ts
deleted file mode 100644
index 632485d..0000000
--- a/src/engine/anatomy/geom.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-/** 2D geometry helpers for articulatory models (plain numbers / flat arrays, no allocation in hot paths where avoidable). */
-
-export interface Vec {
- x: number;
- y: number;
-}
-
-export const v = (x: number, y: number): Vec => ({ x, y });
-export const add = (a: Vec, b: Vec): Vec => ({ x: a.x + b.x, y: a.y + b.y });
-export const sub = (a: Vec, b: Vec): Vec => ({ x: a.x - b.x, y: a.y - b.y });
-export const scale = (a: Vec, s: number): Vec => ({ x: a.x * s, y: a.y * s });
-export const len = (a: Vec): number => Math.hypot(a.x, a.y);
-export const dist = (a: Vec, b: Vec): number => Math.hypot(a.x - b.x, a.y - b.y);
-export const norm = (a: Vec): Vec => {
- const l = Math.hypot(a.x, a.y) || 1;
- return { x: a.x / l, y: a.y / l };
-};
-export const lerpV = (a: Vec, b: Vec, t: number): Vec => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });
-export const polar = (c: Vec, r: number, ang: number): Vec => ({ x: c.x + r * Math.cos(ang), y: c.y + r * Math.sin(ang) });
-export const rotateAbout = (p: Vec, c: Vec, ang: number): Vec => {
- const s = Math.sin(ang), co = Math.cos(ang);
- const dx = p.x - c.x, dy = p.y - c.y;
- return { x: c.x + dx * co - dy * s, y: c.y + dx * s + dy * co };
-};
-
-/** Polyline stored as flat arrays for fast intersection. */
-export class Polyline {
- xs: number[] = [];
- ys: number[] = [];
- push(p: Vec): this {
- this.xs.push(p.x);
- this.ys.push(p.y);
- return this;
- }
- pushXY(x: number, y: number): this {
- this.xs.push(x);
- this.ys.push(y);
- return this;
- }
- append(pts: Vec[], skipFirst = false): this {
- for (let i = skipFirst ? 1 : 0; i < pts.length; i++) this.push(pts[i]);
- return this;
- }
- get length(): number {
- return this.xs.length;
- }
- point(i: number): Vec {
- return { x: this.xs[i], y: this.ys[i] };
- }
- toArray(): Vec[] {
- return this.xs.map((x, i) => ({ x, y: this.ys[i] }));
- }
- clear(): void {
- this.xs.length = 0;
- this.ys.length = 0;
- }
-}
-
-/**
- * All intersections of the ray o + t·d (t in [tMin, tMax]) with a polyline.
- * Writes parameters t into `out` and returns their count.
- */
-export function rayPolyline(ox: number, oy: number, dx: number, dy: number, pl: Polyline, tMin: number, tMax: number, out: number[]): number {
- let n = 0;
- const xs = pl.xs, ys = pl.ys;
- for (let i = 0; i < xs.length - 1; i++) {
- const t = crossingT(ox, oy, dx, dy, xs[i], ys[i], xs[i + 1], ys[i + 1]);
- if (t >= tMin && t <= tMax && n < out.length) out[n++] = t;
- }
- return n;
-}
-
-/**
- * Where segment A→B crosses the line through o along d (as t along d), or NaN. A segment
- * crosses only if its ends lie on different sides of the line, a point on the line counting as
- * the positive side: a polyline passing through a vertex then crosses once, and one that only
- * touches the line at a vertex crosses twice at the same t or not at all (a half-open rule on
- * the segment parameter kept one crossing of such a touch, an unmatched entry or exit).
- */
-function crossingT(ox: number, oy: number, dx: number, dy: number, ax: number, ay: number, bx: number, by: number): number {
- const sa = dx * (ay - oy) - dy * (ax - ox) >= 0;
- const sb = dx * (by - oy) - dy * (bx - ox) >= 0;
- if (sa === sb) return NaN;
- const ex = bx - ax, ey = by - ay;
- const den = dx * ey - dy * ex;
- if (Math.abs(den) < 1e-15) return NaN;
- return ((ax - ox) * ey - (ay - oy) * ex) / den;
-}
-
-/**
- * Like rayPolyline, also telling for each crossing whether the ray leaves the tissue (the
- * polyline's right-hand side, along its direction) for the air: `exit[i]` is 1 then, else 0.
- */
-export function rayCrossings(ox: number, oy: number, dx: number, dy: number, pl: Polyline, tMin: number, tMax: number, outT: number[], exit: Uint8Array): number {
- let n = 0;
- const xs = pl.xs, ys = pl.ys;
- for (let i = 0; i < xs.length - 1; i++) {
- const t = crossingT(ox, oy, dx, dy, xs[i], ys[i], xs[i + 1], ys[i + 1]);
- if (t >= tMin && t <= tMax && n < outT.length) {
- outT[n] = t;
- // leaving the tissue (on the polyline's right) for the air: the ray turns left across it
- exit[n] = dx * (ys[i + 1] - ys[i]) - dy * (xs[i + 1] - xs[i]) < 0 ? 1 : 0;
- n++;
- }
- }
- return n;
-}
-
-/** Sample a cubic Bézier into `count` points (including both ends). */
-export function bezier3(p0: Vec, p1: Vec, p2: Vec, p3: Vec, count: number): Vec[] {
- const pts: Vec[] = [];
- for (let i = 0; i < count; i++) {
- const t = i / (count - 1);
- const u = 1 - t;
- const a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t;
- pts.push({ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y });
- }
- return pts;
-}
-
-/** Sample a quadratic Bézier. */
-export function bezier2(p0: Vec, p1: Vec, p2: Vec, count: number): Vec[] {
- const pts: Vec[] = [];
- for (let i = 0; i < count; i++) {
- const t = i / (count - 1);
- const u = 1 - t;
- pts.push({ x: u * u * p0.x + 2 * u * t * p1.x + t * t * p2.x, y: u * u * p0.y + 2 * u * t * p1.y + t * t * p2.y });
- }
- return pts;
-}
-
-/** Arc from angle a0 to a1 (radians, either direction), `count` points. */
-export function arc(c: Vec, r: number, a0: number, a1: number, count: number): Vec[] {
- const pts: Vec[] = [];
- for (let i = 0; i < count; i++) pts.push(polar(c, r, a0 + ((a1 - a0) * i) / (count - 1)));
- return pts;
-}
-
-/** Catmull–Rom spline through points (centripetal-ish uniform), `per` samples per segment. */
-export function catmullRom(pts: Vec[], per: number): Vec[] {
- if (pts.length < 3) return pts.slice();
- const out: Vec[] = [];
- for (let i = 0; i < pts.length - 1; i++) {
- const p0 = pts[Math.max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[Math.min(pts.length - 1, i + 2)];
- for (let k = 0; k < per; k++) {
- const t = k / per;
- const t2 = t * t, t3 = t2 * t;
- out.push({
- x: 0.5 * (2 * p1.x + (-p0.x + p2.x) * t + (2 * p0.x - 5 * p1.x + 4 * p2.x - p3.x) * t2 + (-p0.x + 3 * p1.x - 3 * p2.x + p3.x) * t3),
- y: 0.5 * (2 * p1.y + (-p0.y + p2.y) * t + (2 * p0.y - 5 * p1.y + 4 * p2.y - p3.y) * t2 + (-p0.y + 3 * p1.y - 3 * p2.y + p3.y) * t3),
- });
- }
- }
- out.push(pts[pts.length - 1]);
- return out;
-}
-
-/** Upper tangent point from external point p to circle (c, r): returns angle on the circle. */
-export function tangentAngle(c: Vec, r: number, p: Vec, upper: boolean): number | null {
- const d = dist(c, p);
- if (d <= r * 1.0001) return null;
- const base = Math.atan2(p.y - c.y, p.x - c.x);
- const off = Math.acos(r / d);
- return upper ? base + off : base - off;
-}
diff --git a/src/engine/anatomy/human.ts b/src/engine/anatomy/human.ts
deleted file mode 100644
index c4255d5..0000000
--- a/src/engine/anatomy/human.ts
+++ /dev/null
@@ -1,795 +0,0 @@
-/**
- * Human midsagittal articulatory model.
- *
- * Head frame (cm): x forward, y up, glottis at (0,0) for a neutral larynx (adult male template,
- * scaled for other bodies). Fixed outer wall: posterior pharyngeal wall, velum (moves), hard
- * palate, alveolar ridge, upper incisors, upper lip. Moving inner wall: epiglottis, tongue root,
- * tongue body (circle), blade, tip, sublingual floor, lower incisors, lower lip — the lower parts
- * are carried by the jaw (rotation about the condyle).
- *
- * Area function: a semipolar grid (horizontal lines in the pharynx, radial lines in the
- * oral cavity, vertical lines at the teeth/lips) is intersected with both walls; the
- * midsagittal distance d gives area A = α·d^β per region (lips: elliptical slit d·w·π/4).
- * The epilarynx is a short parametric tube above the glottis.
- */
-import { type Vec, v, add, sub, scale, lerpV, polar, rotateAbout, Polyline, rayPolyline, rayCrossings, bezier3, bezier2, arc, catmullRom, tangentAngle, dist, norm } from "./geom.ts";
-import { clamp, lerp, smoothstep } from "../util/math.ts";
-
-export interface HumanArtic {
- /** jaw opening at the incisors (cm) */
- jaw: number;
- /** tongue body centre (cm, head frame) */
- tbX: number;
- tbY: number;
- /** tongue tip (cm, head frame) */
- ttX: number;
- ttY: number;
- /** retroflex curl 0..1 */
- ttCurl: number;
- /** tongue root advance (+) / retraction (−), cm */
- root: number;
- /** lip aperture (cm); negative = compressed */
- lipAp: number;
- /** lip protrusion (cm) */
- lipProt: number;
- /** lip spreading 0 (rounded) .. 1 (spread) */
- lipWidth: number;
- /** lower lip to upper teeth 0..1 */
- labiodental: number;
- /** velopharyngeal port area (cm²) */
- velum: number;
- /** larynx height offset (cm, + raised) */
- larynx: number;
- /** epilaryngeal narrowing 0..1 (twang) */
- epilarynx: number;
- /** ventricular-fold narrowing 0..1 */
- ventricular: number;
- /** lateral channel opening 0..1 (for /l/) */
- lateral: number;
- /** tongue dorsum depression between closures 0..1 (clicks) */
- dorsum: number;
-}
-
-export interface HumanBody {
- name: string;
- /** overall size scale (1 = adult male) */
- scale: number;
- /** extra pharynx length scale (female/child have proportionally shorter pharynx) */
- pharynx: number;
- /** tongue body radius (cm, before scale) */
- tongueRadius: number;
- /** max lip width (cm, before scale) */
- lipWidth: number;
-}
-
-export const BODY_MALE: HumanBody = { name: "Adult male", scale: 1, pharynx: 1, tongueRadius: 2.25, lipWidth: 4.6 };
-export const BODY_FEMALE: HumanBody = { name: "Adult female", scale: 0.9, pharynx: 0.88, tongueRadius: 2.2, lipWidth: 4.4 };
-export const BODY_CHILD: HumanBody = { name: "Child", scale: 0.74, pharynx: 0.8, tongueRadius: 2.15, lipWidth: 4.0 };
-
-/** Neutral (schwa-like) articulation for the male template, unscaled coordinates. */
-export const NEUTRAL: HumanArtic = {
- jaw: 0.6,
- tbX: 2.9,
- tbY: 6.85,
- ttX: 6.45,
- ttY: 7.3,
- ttCurl: 0,
- root: 0,
- lipAp: 0.7,
- lipProt: 0.2,
- lipWidth: 0.5,
- labiodental: 0,
- velum: -0.15,
- larynx: 0,
- epilarynx: 0,
- ventricular: 0,
- lateral: 0,
- dorsum: 0,
-};
-
-/**
- * Resting tongue-tip position (template coordinates) for a given jaw and tongue body:
- * behind the lower incisors, carried by the jaw and dragged by the tongue body.
- */
-export function restTip(jaw: number, tbX: number, tbY: number): { x: number; y: number } {
- const cx = -2.5, cy = 10.5;
- const px = 6.45, py = 7.35;
- const ang = -jaw / 9.84;
- const dx = px - cx, dy = py - cy;
- const x = cx + dx * Math.cos(ang) - dy * Math.sin(ang);
- const y = cy + dx * Math.sin(ang) + dy * Math.cos(ang);
- return { x: x + 0.3 * (tbX - NEUTRAL.tbX), y: y + 0.35 * (tbY - NEUTRAL.tbY) };
-}
-
-export interface GridSample {
- inner: Vec;
- outer: Vec;
- mid: Vec;
- /** midsagittal distance (cm), 0 when closed */
- d: number;
- /** area (cm²) */
- area: number;
- /** distance from the glottis along the centreline (cm) */
- s: number;
- region: 0 | 1 | 2 | 3; // 0 epilarynx, 1 pharynx, 2 oral (radial), 3 front (teeth/lips)
- /** the gap the ray measured, before the contact models (cm) */
- ray: number;
-}
-
-export interface HumanFrame {
- /** outer wall (posterior pharynx → velum → palate → incisors → upper lip) */
- outer: Vec[];
- /** inner wall (epiglottis → tongue → floor → lower incisors → lower lip) */
- inner: Vec[];
- /** tongue outline for drawing (closed) */
- tongue: Vec[];
- velum: Vec[];
- upperLip: Vec[];
- lowerLip: Vec[];
- upperTeeth: Vec[];
- lowerTeeth: Vec[];
- jawBone: Vec[];
- epiglottis: Vec[];
- nasalCavity: Vec[];
- /** glottis position */
- glottis: Vec;
- grid: GridSample[];
- /** total length glottis → lips (cm) */
- length: number;
- /** length glottis → velopharyngeal junction (cm) */
- pharynxLength: number;
- /** s position of the upper incisor edge (cm from glottis) */
- teethS: number;
- /** s of the lip opening (end) */
- lipS: number;
- velumPort: number;
- lipArea: number;
- tongueCenter: Vec;
- tongueRadius: number;
- tip: Vec;
- /** grid index where the oral tube begins */
- splitIndex: number;
-}
-
-const DEG = Math.PI / 180;
-/** points on the tongue body's arc */
-const ARC_POINTS = 32;
-
-export class HumanVocalTract {
- readonly body: HumanBody;
- private readonly k: number; // scale
- // fixed landmarks (scaled)
- private readonly pharWall: Vec[];
- private readonly palate: Vec[];
- private readonly pns: Vec;
- private readonly condyle: Vec;
- private readonly polarC: Vec;
- private readonly polarC2: Vec;
- private readonly tmpT: number[] = new Array(64);
- private readonly crossT: number[] = new Array(64);
- private readonly crossExit = new Uint8Array(64);
- /** signed closest approach (cm) of tongue tip / dorsum to the oral roof in the last frame */
- contactTip = 1;
- contactBody = 1;
- /** unit normals at the contacts, pointing from the roof into the airway (body coords) */
- contactTipN = { x: 0, y: -1 };
- contactBodyN = { x: 0, y: -1 };
- /** area-law coefficients per region [α, β] */
- areaLaw = {
- pharynx: [2.0, 1.4] as [number, number],
- oral: [2.6, 1.4] as [number, number],
- front: [2.0, 1.4] as [number, number],
- };
-
- constructor(body: HumanBody = BODY_MALE) {
- this.body = body;
- this.k = body.scale;
- const P = (x: number, y: number) => this.P(x, y);
- // posterior pharyngeal wall, bottom → top (curving forward into nasopharynx roof)
- this.pharWall = catmullRom([P(-1.0, -1.5), P(-1.1, 1.5), P(-1.2, 3.6), P(-1.3, 5.6), P(-1.38, 7.5), P(-1.33, 8.9), P(-1.05, 10.1), P(-0.45, 10.9), P(0.4, 11.3)], 4);
- this.pns = P(1.0, 9.75);
- this.palate = catmullRom([P(1.0, 9.6), P(1.8, 9.92), P(2.7, 10.18), P(3.6, 10.3), P(4.4, 10.25), P(5.1, 10.05), P(5.7, 9.72), P(6.15, 9.36), P(6.5, 9.05), P(6.78, 8.7), P(6.98, 8.3), P(7.12, 7.95)], 3);
- this.condyle = P(-2.5, 10.5);
- this.polarC = P(2.6, 6.95);
- this.polarC2 = P(5.0, 6.85);
- }
-
- /**
- * Template point → body coordinates. The oral region (x > 0.5) is compressed by 0.86 so the
- * template's landmarks give a ≈17.5 cm neutral tract; the pharynx (y < 7) is shortened by the
- * body's pharynx factor; everything is scaled by the body size.
- */
- P(x: number, y: number): Vec {
- const k = this.k;
- const ph = this.body.pharynx;
- const xx = x > 0.5 ? 0.5 + (x - 0.5) * 0.86 : x;
- const yy = y < 7 ? 7 - (7 - y) * ph : y;
- return { x: xx * k, y: yy * k };
- }
-
- /** Inverse of P(): body coordinates → template coordinates (for direct manipulation). */
- unP(x: number, y: number): Vec {
- const k = this.k;
- const ph = this.body.pharynx;
- let xx = x / k;
- let yy = y / k;
- if (xx > 0.5) xx = 0.5 + (xx - 0.5) / 0.86;
- if (yy < 7) yy = 7 - (7 - yy) / ph;
- return { x: xx, y: yy };
- }
-
- get scale(): number {
- return this.k;
- }
-
- compute(a: HumanArtic): HumanFrame {
- const k = this.k;
- const P = (x: number, y: number) => this.P(x, y);
- const lar = a.larynx * k;
- const glottis = add(P(0, 0), v(0, lar));
-
- // ---- jaw (rotation about the condyle)
- const jawRef = P(6.95, 7.75);
- const jawR = dist(this.condyle, jawRef);
- const phi = -clamp(a.jaw, -0.2, 3.0) * k / jawR;
- const J = (x: number, y: number) => rotateAbout(P(x, y), this.condyle, phi);
-
- // ---- velum flap from PNS; angle from port area
- const vOpen = clamp(a.velum / 1.2, 0, 1);
- const vAng = (194 + 46 * vOpen) * DEG;
- const vLen = 2.8 * k;
- const vel: Vec[] = [];
- const velOral: Vec[] = [];
- const velNasal: Vec[] = [];
- for (let i = 0; i <= 10; i++) {
- const s = i / 10;
- const sag = Math.sin(s * Math.PI) * k * (0.3 * vOpen - 0.12);
- const c = add(polar(this.pns, vLen * s, vAng), { x: 0, y: -sag });
- const nrm = { x: -Math.sin(vAng), y: Math.cos(vAng) }; // oral-side normal (forward-down)
- const th = (0.48 - 0.2 * s) * k;
- velOral.push(add(c, scale(nrm, th)));
- velNasal.push(sub(c, scale(nrm, th)));
- vel.push(c);
- }
- // the velum's oral surface runs into the hard palate's: its root sat below the palate's edge,
- // folding the roof back on itself there, and rays crossed the fold as the velum turned
- const pal0 = this.palate[0];
- for (let i = 0; i < velOral.length; i++) {
- const u = i / 10 / 0.35;
- if (u < 1) velOral[i] = lerpV(velOral[i], pal0, (1 - u) * (1 - u));
- }
- const uvula = vel[vel.length - 1];
-
- // ---- outer contour: pharyngeal wall up to just below the uvula, then velum oral surface
- // (tip→PNS), palate, incisors, upper lip
- const outer = new Polyline();
- // The port window's lid runs from the posterior wall up to the uvula's tip. It must slope
- // up: a lid leaving the wall above the tip left rays just under the tip to hit the wall far
- // behind, so the back of the oral tract jumped as the velum moved.
- const uvY = velOral[velOral.length - 1].y - 0.3 * k;
- for (let i = 0; i < this.pharWall.length; i++) {
- const p = this.pharWall[i];
- if (p.y < uvY) {
- outer.push(p);
- continue;
- }
- // end exactly at that height: whole wall points popping in and out made the port
- // window, and every ray through it, jump as the velum moved
- if (i > 0) {
- const a = this.pharWall[i - 1];
- outer.push(lerpV(a, p, clamp((uvY - a.y) / Math.max(1e-9, p.y - a.y), 0, 1)));
- }
- break;
- }
- // bridge to the uvula tip (velopharyngeal port window)
- const roofStart = outer.length;
- for (let i = velOral.length - 1; i >= 0; i--) outer.push(velOral[i]);
- outer.append(this.palate, true);
- const roofEnd = outer.length - 1;
- // upper lip
- const prot = clamp(a.lipProt, -0.2, 1.6) * k;
- const spreadW = clamp(a.lipWidth, 0, 1);
- const yMid = (7.85 - 0.3 * a.jaw) * k;
- const lab = clamp(a.labiodental, 0, 1);
- const ap = a.lipAp * k;
- const lipFrontX = P(8.15 + 0.12 * (1 - spreadW), 0).x + prot * 0.95;
- let ulEdge = v(lipFrontX - 0.15 * k, yMid + ap * 0.35 + lab * 0.35 * k);
- let llEdge = v(lipFrontX - 0.25 * k, yMid - ap * 0.65);
- if (lab > 0) {
- // lower lip tucks under the upper incisor edge for /f v/
- const incisor = this.palate[this.palate.length - 1];
- const target = v(incisor.x + 0.05 * k, incisor.y - Math.max(a.lipAp * k, -0.1));
- llEdge = lerpV(llEdge, target, lab);
- ulEdge = lerpV(ulEdge, v(incisor.x + 0.55 * k, incisor.y + 0.45 * k), lab * 0.7);
- }
- const ulBase = P(7.32, 8.35);
- const upperLipIn = bezier3(ulBase, add(ulBase, v(0.3 * k + prot * 0.4, 0.05 * k)), add(ulEdge, v(-0.35 * k, 0.12 * k)), ulEdge, 7);
- outer.append(upperLipIn);
-
- // ---- tongue
- const r = this.body.tongueRadius * k;
- const B = this.P(a.tbX, a.tbY);
- const B0 = P(NEUTRAL.tbX, NEUTRAL.tbY);
- const vallecula = add(P(0.75, 3.3), v(0.45 * (B.x - B0.x) + a.root * k, 0.3 * (B.y - B0.y) + 0.55 * lar));
- const epiBase = add(P(0.3, 2.4), v(0, lar));
- const epiTip = add(P(0.0, 4.5), v(0.35 * (vallecula.x - 0.75 * k), lar * 0.8 + 0.15 * (B.y - B0.y)));
- const thB = 200 * DEG;
- const pB = polar(B, r, thB);
- const tanB = v(Math.sin(thB), -Math.cos(thB));
- const hR = dist(vallecula, pB) / 3;
- const root = bezier3(vallecula, add(vallecula, v(0.08 * k, hR)), sub(pB, scale(tanB, hR)), pB, 9);
- let T = this.P(a.ttX, a.ttY);
- // keep tip outside the body circle
- const dT = dist(T, B);
- if (dT < r * 1.05) T = add(B, scale(norm(sub(T, B)), r * 1.05));
- let thF = tangentAngle(B, r, T, true);
- if (thF === null) thF = Math.atan2(T.y - B.y, T.x - B.x);
- // arc runs from thB (200°) decreasing to thF
- while (thF > thB) thF -= 2 * Math.PI;
- while (thF < thB - 2 * Math.PI) thF += 2 * Math.PI;
- // a fixed number of points: a count that changed with the angle re-spaced every vertex at once
- const arcPts = arc(B, r, thB, thF, ARC_POINTS);
- const pF = arcPts[arcPts.length - 1];
- const tanF = v(Math.sin(thF), -Math.cos(thF)); // direction of decreasing angle
- // blade: quadratic from the tangent point to the tip; curl lifts the tip and turns it back
- const bl = dist(pF, T);
- const curl = clamp(a.ttCurl, 0, 1);
- const ctrl = add(add(pF, scale(tanF, bl * 0.5)), v(0, (0.18 + 0.5 * curl) * k));
- // dorsum depression (clicks): hollow the tongue between the back (velar) contact at the top
- // of the body and the tip, leaving both contacts in place, so a sealed pocket expands
- const blade = bezier2(pF, ctrl, T, 7);
- if (a.dorsum > 0) {
- const x0 = B.x, x1 = T.x;
- const dip = (p: Vec): Vec => {
- const u = (p.x - x0) / Math.max(1e-6, x1 - x0);
- if (u <= 0 || u >= 1) return p;
- const w = Math.sin(Math.PI * Math.pow(u, 0.8));
- return add(p, v(0, -a.dorsum * 0.9 * k * w * w));
- };
- for (let i = 0; i < arcPts.length; i++) arcPts[i] = dip(arcPts[i]);
- for (let i = 1; i < blade.length - 1; i++) blade[i] = dip(blade[i]);
- }
- // underside back to the frenulum / floor of mouth (jaw-carried)
- const fren = J(5.7, 6.15);
- const under = bezier2(T, add(T, v(-0.3 * k - curl * 0.4 * k, -0.6 * k)), fren, 6);
- const floor = [fren, J(6.2, 6.25), J(6.45, 6.55)];
- // lower incisors (jaw)
- const liTip = J(6.95, 7.75);
- const lowerTeethPts = [J(6.45, 6.55), J(6.72, 7.15), liTip, J(7.12, 7.45)];
- // lower lip: from labial base of lower incisor to the edge
- const llBase = J(7.12, 7.45);
- const lowerLipIn = bezier3(llBase, add(llBase, v(0.25 * k + prot * 0.3, -0.05 * k)), add(llEdge, v(-0.3 * k, -0.12 * k)), llEdge, 7);
-
- // acoustic inner wall: epiglottis (laryngeal surface) then the tongue root *above* the
- // epiglottis tip — the vallecula pocket is omitted so the wall is single-valued along the
- // pharyngeal rays (a pocket makes ray crossings flip discontinuously)
- const inner = new Polyline();
- inner.push(epiBase).push(epiTip);
- // The wall leaves the epiglottis tip upward, for where the tongue's back (root, then the
- // dorsum arc) first rises above it: with the tongue low and the larynx high the whole root
- // can sit below the tip, and a wall coming back down from it made the tip a peak that a
- // horizontal ray measured past (to the root) or not (to the epiglottis) — a jump.
- const yRoot = epiTip.y + 0.05 * k;
- const back = [...root, ...arcPts.slice(1)];
- let start = back.findIndex((q) => q.y > yRoot);
- if (start < 0) start = back.length - 1;
- else if (start > 0) {
- // start exactly at that height, not at the next sample point (which jumped along the root)
- const a = back[start - 1], b = back[start];
- inner.push(lerpV(a, b, clamp((yRoot - a.y) / Math.max(1e-9, b.y - a.y), 0, 1)));
- }
- if (start < root.length) {
- for (let i = start; i < root.length; i++) inner.push(root[i]);
- inner.append(arcPts, true);
- } else inner.append(arcPts.slice(start - root.length + 1), true);
- inner.append(blade, true);
- inner.append(under, true);
- inner.append(floor, true);
- inner.append(lowerTeethPts, true);
- inner.append(lowerLipIn);
-
- // ---- grid
- const grid: GridSample[] = [];
- const tmp = this.tmpT;
- const yEpiTop = glottis.y + 2.4 * k * this.body.pharynx;
- const yPharTop = this.polarC.y;
- const nPh = 12;
- // A fan ray's inner surface. The ray starts in the tongue: the gap begins where it leaves it
- // (or, if the tongue has moved off the origin, at the surface behind it: a fixed fallback
- // gap jumped as the surface crossed the origin). The gap is the air along the ray up to the
- // roof: tissue the ray passes through on the way (a curled tip with air beneath it) is taken
- // out by its thickness, so a layer that vanishes as the ray grazes it changes nothing ("the
- // last crossing before the roof" jumped deep into the mouth whenever a ray slipped past the
- // tip, as on the way into a rhotic).
- const crossT = this.crossT, crossExit = this.crossExit;
- const fanInner = (o: Vec, dir: Vec, tOut: number): number => {
- const n = rayCrossings(o.x, o.y, dir.x, dir.y, inner, 0, tOut + 1.5 * k, crossT, crossExit);
- // sort the crossings along the ray (there are only a few)
- for (let i = 1; i < n; i++) {
- const t = crossT[i], e = crossExit[i];
- let j = i - 1;
- while (j >= 0 && crossT[j] > t) {
- crossT[j + 1] = crossT[j];
- crossExit[j + 1] = crossExit[j];
- j--;
- }
- crossT[j + 1] = t;
- crossExit[j + 1] = e;
- }
- let tIn: number, i = 0;
- if (n > 0 && crossExit[0] === 1) {
- tIn = crossT[0];
- i = 1;
- } else {
- const back = 2.5 * k;
- const nBack = rayPolyline(o.x, o.y, -dir.x, -dir.y, inner, 0, back, tmp);
- let tb = back;
- for (let q = 0; q < nBack; q++) tb = Math.min(tb, tmp[q]);
- tIn = -tb;
- }
- let tissue = 0;
- for (; i < n && crossT[i] < tOut; i++) {
- if (crossExit[i] === 1) continue; // a surface without its entry: nothing to take out
- const b = i + 1 < n ? crossT[i + 1] : tOut + 1.5 * k;
- tissue += Math.min(b, tOut) - crossT[i];
- i++; // skip the layer's exit
- }
- return tIn + tissue;
- };
- // `fan`: a ray of the oral fan, whose origin the tongue can move off (the others start below
- // or in front of all tissue they measure)
- const measure = (o: Vec, dir: Vec, maxLen: number, fan = false): { inner: Vec; outer: Vec; d: number } | null => {
- // walk from o along dir: last inner crossing before the first outer crossing
- const nOut = rayPolyline(o.x, o.y, dir.x, dir.y, outer, 0, maxLen, tmp);
- if (nOut === 0) return null;
- let tOut = Infinity;
- for (let i = 0; i < nOut; i++) tOut = Math.min(tOut, tmp[i]);
- let tIn: number;
- if (fan) tIn = fanInner(o, dir, tOut);
- else {
- const nIn = rayPolyline(o.x, o.y, dir.x, dir.y, inner, 0, tOut + 1.5 * k, tmp);
- tIn = -Infinity;
- for (let i = 0; i < nIn; i++) if (tmp[i] > tIn && tmp[i] < tOut + 1.5 * k) tIn = tmp[i];
- if (tIn === -Infinity) tIn = Math.max(0, tOut - 3.5 * k);
- }
- // if the tongue crosses the wall, the outermost inner crossing lies beyond tOut → closed
- const d = Math.max(0, tOut - tIn);
- const pIn = add(o, scale(dir, Math.min(tIn, tOut)));
- const pOut = add(o, scale(dir, tOut));
- return { inner: pIn, outer: pOut, d };
- };
- // pharyngeal horizontals (origin in front, looking back)
- for (let i = 0; i < nPh; i++) {
- const y = lerp(yEpiTop + 0.12 * k, yPharTop, i / nPh);
- const m = measure(v(4.6 * k, y), v(-1, 0), 9 * k);
- if (m) grid.push({ ...m, mid: lerpV(m.inner, m.outer, 0.5), area: 0, s: 0, ray: m.d, region: 1 });
- }
- // oral family: rays from a centre that glides from C1 (mid-oral) to C2 (behind the incisors)
- // while the angle sweeps back → up → forward; consecutive rays never cross inside the airway.
- const nRad = 30;
- let splitIndex = -1;
- for (let i = 0; i <= nRad; i++) {
- const t = i / nRad;
- const ang = lerp(180, 36, t) * DEG;
- const w = t < 0.45 ? 0 : (t - 0.45) / 0.55;
- const c = lerpV(this.polarC, this.polarC2, w * w * (3 - 2 * w));
- const dir = v(Math.cos(ang), Math.sin(ang));
- const m = measure(c, dir, 8 * k, true);
- if (!m) continue;
- if (splitIndex < 0 && ang <= 150 * DEG) splitIndex = grid.length;
- // rays behind the velum still measure the (laterally wide) oropharynx
- grid.push({ ...m, mid: lerpV(m.inner, m.outer, 0.5), area: 0, s: 0, ray: m.d, region: splitIndex < 0 ? 1 : 2 });
- }
- // front verticals (upper incisor edge → lip opening), looking up
- const incisorTip = this.palate[this.palate.length - 1];
- const xStart = incisorTip.x + 0.03 * k;
- const xEnd = Math.max(xStart + 0.3 * k, Math.min(ulEdge.x, llEdge.x) - 0.04 * k);
- const nFr = 6;
- const lipW = (1.1 + (this.body.lipWidth - 1.1) * spreadW) * k;
- const teethIdx = grid.length;
- for (let i = 0; i < nFr; i++) {
- const x = lerp(xStart, xEnd, i / (nFr - 1));
- const m = measure(v(x, 4.0 * k), v(0, 1), 8 * k);
- if (!m) continue;
- grid.push({ ...m, mid: lerpV(m.inner, m.outer, 0.5), area: 0, s: 0, ray: m.d, region: 3 });
- }
-
- // ---- soft-tissue contact model: near the oral roof, the gap at each roof point is its
- // distance to the tongue surface itself (dorsum arc, blade, tip and underside), negative
- // where the tongue is pressed into the roof. The raw ray crossings of the tissue polygon can
- // leave sealed pockets beside a contact, and a jet released into such a pocket water-hammers;
- // the surface distance has none, gives seals whose length grows with contact pressure, and
- // handles two contacts at once (a single contact point hopped between them, jumping areas).
- const roof = { xs: outer.xs.slice(roofStart, roofEnd + 1), ys: outer.ys.slice(roofStart, roofEnd + 1) };
- const cum = new Float64Array(roof.xs.length);
- for (let i = 1; i < roof.xs.length; i++) cum[i] = cum[i - 1] + Math.hypot(roof.xs[i] - roof.xs[i - 1], roof.ys[i] - roof.ys[i - 1]);
- const tipPts = [...blade.slice(2), ...under.slice(1, 3)];
- const tipC = closestApproach(roof, cum, tipPts);
- const bodyC = closestApproach(roof, cum, arcPts);
- this.contactTip = tipC.d;
- this.contactBody = bodyC.d;
- this.contactTipN = tipC.n;
- this.contactBodyN = bodyC.n;
- // No outer gate: each ray's own weight fades the contact in. A gate on the sampled
- // tongue-to-roof distance could open with the per-ray correction already part-way on.
- {
- // the whole tongue outline, closed: distance to its surface, signed by whether the roof
- // point is inside it (so the sign only changes where the distance is zero)
- const outl: Vec[] = [...root, ...arcPts.slice(1), ...blade.slice(1), ...under.slice(1), ...floor.slice(1), root[0]];
- const tongueOutline = { xs: outl.map((q) => q.x), ys: outl.map((q) => q.y) };
- const tongueGap = (x: number, y: number) => signedGap(tongueOutline, x, y);
- // Each roof ray takes the narrowest gap along its own stretch of roof: ±1 mm, so the rays
- // near a contact seal together and open together (a sharp burst), widening to ±2 mm while
- // the tongue is pressed in, because the tip's contact on the alveolar ridge is narrower
- // than the ~4 mm between rays there and could otherwise fall between two and never seal.
- const press = 1 - smoothstep(-0.06 * k, 0, Math.min(tipC.d, bodyC.d));
- const half = 0.1 * k * (1 + press);
- const roofLen = cum[cum.length - 1];
- for (const g of grid) {
- if (g.region === 0) continue;
- // only rays ending on the oral roof, fading out (not switching off) as they leave it
- const pr = projectOn(roof, cum, g.outer.x, g.outer.y);
- const onRoof = 1 - smoothstep(0.15 * k, 0.25 * k, pr.dist);
- if (onRoof <= 0) continue;
- let dc = tongueGap(g.outer.x, g.outer.y);
- // the gap changes no faster than the distance moved along the roof
- if (dc - half <= 0.6 * k)
- for (const f of [-1, -0.5, 0.5, 1]) {
- const q = pointAlong(roof, cum, clamp(pr.s + f * half, 0, roofLen));
- dc = Math.min(dc, tongueGap(q.x, q.y));
- }
- // the surface distance takes over as the tongue comes within ~6 mm of this roof point,
- // fully from 1.5 mm; it also caps the ray's gap from 4.5 mm in
- const w = (1 - smoothstep(0.15 * k, 0.6 * k, dc)) * onRoof;
- const cap = (1 - smoothstep(0.45 * k, 0.6 * k, dc)) * onRoof;
- if (w <= 0 && cap <= 0) continue;
- const dp = Math.max(0, dc);
- const dm = g.d + (Math.min(g.d, dp) - g.d) * cap;
- g.d = dm + (dp - dm) * w;
- }
- }
-
- // lip contact: between the lips the gap follows aperture + Δx²/2R back from the lip edge, so
- // compressed lips (aperture < 0) seal over a length that grows with compression
- {
- const edgeX = Math.min(ulEdge.x, llEdge.x);
- const Rl = 0.6 * k;
- const apEff = lab > 0.5 ? Infinity : ap; // labiodental uses its own geometry
- for (const g of grid) {
- if (g.region !== 3 || g.mid.x < this.palate[this.palate.length - 1].x) continue;
- const dxl = Math.max(0, edgeX - g.mid.x);
- g.d = Math.min(g.d, Math.max(0, apEff + (dxl * dxl) / (2 * Rl)));
- }
- }
-
- // ---- areas
- const [aP, bP] = this.areaLaw.pharynx;
- const [aO, bO] = this.areaLaw.oral;
- const [aF, bF] = this.areaLaw.front;
- const teethX = this.palate[this.palate.length - 1].x;
- for (const g of grid) {
- if (g.region === 1) g.area = aP * Math.pow(g.d, bP);
- else if (g.region === 2) g.area = aO * Math.pow(g.d, bO);
- else {
- // behind the incisors: dental arch; in front: elliptical lip slit of width lipW
- const u = clamp((g.mid.x - teethX) / (0.45 * k), 0, 1);
- const dental = aF * Math.pow(g.d, bF);
- const lip = (Math.PI / 4) * g.d * lipW;
- g.area = lerp(dental, lip, u);
- }
- }
- // suppress isolated spikes (rays grazing the port window / tooth corners): clamp each open
- // sample to 1.35× the larger of its neighbours
- for (let i = 1; i < grid.length - 1; i++) {
- const lim = 1.35 * Math.max(grid[i - 1].area, grid[i + 1].area);
- if (grid[i].area > lim) grid[i].area = lim;
- }
- // lateral channel (for /l/): keeps a side passage open around a midline tip closure
- if (a.lateral > 0) {
- for (const g of grid) {
- if (g.region >= 2 && dist(g.mid, T) < 1.4 * k) g.area = Math.max(g.area, a.lateral * 0.35 * k * k);
- }
- }
-
- // ---- centreline s
- const epiLen = 2.4 * k * this.body.pharynx;
- let s = epiLen;
- for (let i = 0; i < grid.length; i++) {
- if (i > 0) s += dist(grid[i].mid, grid[i - 1].mid);
- grid[i].s = s;
- }
- // teeth position along s (first front line sits at the upper incisor edge)
- const teethS = teethIdx < grid.length ? grid[teethIdx].s : grid[grid.length - 1].s;
- const lipS = grid[grid.length - 1].s;
- const pharynxLength = splitIndex > 0 ? grid[splitIndex].s : grid[nPh].s;
-
- // ---- drawing parts
- const tongue = [...root, ...arcPts.slice(1), ...blade.slice(1), ...under.slice(1), ...floor.slice(1)];
- const upperLipOut = bezier3(ulEdge, add(ulEdge, v(0.25 * k, 0.35 * k)), P(8.3 + 0.0, 9.6), P(7.9, 10.4), 6);
- const lowerLipOut = bezier3(llEdge, add(llEdge, v(0.3 * k, -0.4 * k)), J(8.1, 6.3), J(7.6, 5.6), 6);
- const jawBone = [J(7.25, 6.75), J(7.4, 5.4), J(6.4, 4.6), J(3.5, 4.4), J(1.2, 5.2), J(-0.6, 7.4), J(-1.9, 9.6)];
- const nasal = catmullRom([this.pns, P(2.5, 10.8), P(5.0, 11.2), P(7.3, 10.6), P(8.0, 10.1)], 4);
- return {
- outer: outer.toArray(),
- inner: inner.toArray(),
- tongue,
- velum: [...velNasal, ...velOral.slice().reverse()],
- upperLip: [...upperLipIn, ...upperLipOut.slice(1)],
- lowerLip: [...lowerLipIn, ...lowerLipOut.slice(1)],
- upperTeeth: [P(6.15, 9.36), P(6.78, 8.7), P(7.12, 7.95), P(7.38, 8.7), P(7.4, 9.3)],
- lowerTeeth: lowerTeethPts,
- jawBone,
- epiglottis: [epiBase, epiTip, vallecula],
- nasalCavity: nasal,
- glottis,
- grid,
- length: lipS,
- pharynxLength,
- teethS,
- lipS,
- velumPort: Math.max(0, a.velum) * k * k,
- lipArea: grid[grid.length - 1].area,
- tongueCenter: B,
- tongueRadius: r,
- tip: T,
- splitIndex,
- };
- }
-
- /** Epilarynx area profile at s ∈ [0, epiLen]. */
- epilarynxArea(a: HumanArtic, s: number, epiLen: number): number {
- const u = s / epiLen;
- const vent = 0.95 * (1 - 0.75 * clamp(a.ventricular, 0, 1));
- const top = lerp(1.9, 0.35, clamp(a.epilarynx, 0, 1));
- // laryngeal ventricle, ventricular folds, then the tube to its top
- const f = (x: number) => (x < 0.3 ? 1.3 : x < 0.5 ? vent : lerp(1.2, top, (x - 0.5) / 0.5));
- // the steps between them are short ramps: a section boundary sliding across a step made
- // that section's area jump
- const r = 0.03;
- let A = f(u);
- for (const u0 of [0.3, 0.5]) if (Math.abs(u - u0) < r) A = lerp(f(u0 - r), f(u0 + r), (u - (u0 - r)) / (2 * r));
- return A * this.k * this.k;
- }
-
- /**
- * Resample the tract into two uniform tubes (pharynx: glottis→velum, oral: velum→lips).
- * Uses the harmonic mean of area over each section (preserves constriction inertance and
- * exact closures).
- */
- resample(a: HumanArtic, f: HumanFrame, nPh: number, nOr: number, outPh: Float64Array, outOr: Float64Array, minPh?: Float64Array, minOr?: Float64Array): { phLen: number; orLen: number } {
- const epiLen = 2.4 * this.k * this.body.pharynx;
- const g = f.grid;
- // the epilarynx's last few millimetres flare into the pharynx (no step at its top)
- const flare = 0.1 * epiLen;
- const areaAt = (s: number): number => {
- if (s <= epiLen - flare) return this.epilarynxArea(a, s, epiLen);
- if (s <= epiLen) return lerp(this.epilarynxArea(a, s, epiLen), g[0].area, (s - (epiLen - flare)) / flare);
- if (s <= g[0].s) return g[0].area;
- // binary search
- let lo = 0, hi = g.length - 1;
- if (s >= g[hi].s) return g[hi].area;
- while (hi - lo > 1) {
- const m = (lo + hi) >> 1;
- if (g[m].s <= s) lo = m;
- else hi = m;
- }
- const t = (s - g[lo].s) / Math.max(1e-9, g[hi].s - g[lo].s);
- return lerp(g[lo].area, g[hi].area, t);
- };
- const fill = (s0: number, s1: number, n: number, out: Float64Array, mins?: Float64Array) => {
- const d = (s1 - s0) / n;
- const sub = 8;
- let gi = 0;
- for (let i = 0; i < n; i++) {
- let inv = 0;
- let closed = false;
- let mn = Infinity;
- for (let j = 0; j < sub; j++) {
- const A = areaAt(s0 + d * (i + (j + 0.5) / sub));
- if (A < mn) mn = A;
- if (A <= 1e-5) {
- closed = true;
- break;
- }
- inv += 1 / A;
- }
- // actual grid samples inside the section (a point closure must seal the section)
- const a0 = s0 + d * i, a1 = s0 + d * (i + 1) + (i === n - 1 ? 1e-6 : 0);
- while (gi < g.length && g[gi].s < a0) gi++;
- for (let q = gi; q < g.length && g[q].s <= a1; q++) {
- if (g[q].area < mn) mn = g[q].area;
- if (g[q].area <= 1e-5) closed = true;
- }
- out[i] = closed ? 0 : sub / inv;
- if (mins) mins[i] = closed ? 0 : Math.min(mn, out[i]);
- }
- };
- const sp = f.pharynxLength;
- fill(0, sp, nPh, outPh, minPh);
- fill(sp, f.lipS, nOr, outOr, minOr);
- return { phLen: sp, orLen: f.lipS - sp };
- }
-}
-
-/** Project a point onto a polyline: arc position, distance, and the side (cross<0 = airway side). */
-function projectOn(pl: { xs: number[]; ys: number[] }, cum: Float64Array, px: number, py: number): { s: number; dist: number; signed: number; x: number; y: number; seg: number } {
- let best = Infinity, bs = 0, bx = 0, by = 0, sign = 1, bseg = 0;
- for (let i = 0; i < pl.xs.length - 1; i++) {
- const ax = pl.xs[i], ay = pl.ys[i];
- const ex = pl.xs[i + 1] - ax, ey = pl.ys[i + 1] - ay;
- const L2 = ex * ex + ey * ey;
- if (L2 < 1e-12) continue;
- let t = ((px - ax) * ex + (py - ay) * ey) / L2;
- t = t < 0 ? 0 : t > 1 ? 1 : t;
- const qx = ax + ex * t, qy = ay + ey * t;
- const d = Math.hypot(px - qx, py - qy);
- if (d < best) {
- best = d;
- bs = cum[i] + t * Math.sqrt(L2);
- bx = qx;
- by = qy;
- const cross = ex * (py - ay) - ey * (px - ax);
- sign = cross < 0 ? 1 : -1;
- bseg = i;
- }
- }
- return { s: bs, dist: best, signed: sign * best, x: bx, y: by, seg: bseg };
-}
-
-/** The point at arc length s along a polyline. */
-function pointAlong(pl: { xs: number[]; ys: number[] }, cum: Float64Array, s: number): Vec {
- let i = 0;
- while (i < cum.length - 2 && cum[i + 1] < s) i++;
- const L = cum[i + 1] - cum[i];
- const u = L > 1e-9 ? clamp((s - cum[i]) / L, 0, 1) : 0;
- return { x: pl.xs[i] + (pl.xs[i + 1] - pl.xs[i]) * u, y: pl.ys[i] + (pl.ys[i + 1] - pl.ys[i]) * u };
-}
-
-/**
- * Distance from a point to a closed polygon's boundary (its last point repeats its first),
- * negative inside (even-odd rule), in one pass over the edges.
- */
-function signedGap(pl: { xs: number[]; ys: number[] }, px: number, py: number): number {
- let best = Infinity, inside = false;
- const xs = pl.xs, ys = pl.ys;
- for (let i = 0; i < xs.length - 1; i++) {
- const ax = xs[i], ay = ys[i], bx = xs[i + 1], by = ys[i + 1];
- const ex = bx - ax, ey = by - ay;
- const L2 = ex * ex + ey * ey;
- let t = L2 > 1e-12 ? ((px - ax) * ex + (py - ay) * ey) / L2 : 0;
- t = t < 0 ? 0 : t > 1 ? 1 : t;
- const dx = px - ax - ex * t, dy = py - ay - ey * t;
- const d2 = dx * dx + dy * dy;
- if (d2 < best) best = d2;
- if (ay > py !== by > py && px < ax + ((py - ay) * ex) / ey) inside = !inside;
- }
- const d = Math.sqrt(best);
- return inside ? -d : d;
-}
-
-/** Closest approach of a set of tissue points to the roof: signed gap δ (negative = pressed in) and the roof normal there. */
-function closestApproach(pl: { xs: number[]; ys: number[] }, cum: Float64Array, pts: Vec[]): { d: number; n: { x: number; y: number } } {
- let d = Infinity, seg = 0;
- for (const p of pts) {
- const pr = projectOn(pl, cum, p.x, p.y);
- if (pr.signed < d) {
- d = pr.signed;
- seg = pr.seg;
- }
- }
- // inward normal of the roof segment (airway side is to the right of travel: (ey, −ex))
- const ex = pl.xs[seg + 1] - pl.xs[seg], ey = pl.ys[seg + 1] - pl.ys[seg];
- const L = Math.hypot(ex, ey) || 1;
- return { d, n: { x: ey / L, y: -ex / L } };
-}
-
-/** Clamp drawn tissue points that penetrate a wall onto its surface (drawing only). */
-export function clampToWall(points: Vec[], wall: Vec[]): Vec[] {
- const pl = { xs: wall.map((p) => p.x), ys: wall.map((p) => p.y) };
- const cum = new Float64Array(wall.length);
- for (let i = 1; i < wall.length; i++) cum[i] = cum[i - 1] + Math.hypot(wall[i].x - wall[i - 1].x, wall[i].y - wall[i - 1].y);
- return points.map((p) => {
- const pr = projectOn(pl, cum, p.x, p.y);
- return pr.signed < 0 && pr.dist < 1.5 ? { x: pr.x, y: pr.y } : p;
- });
-}
diff --git a/src/engine/control/articulators.ts b/src/engine/control/articulators.ts
deleted file mode 100644
index 7e80666..0000000
--- a/src/engine/control/articulators.ts
+++ /dev/null
@@ -1,133 +0,0 @@
-/**
- * Articulator dynamics: each articulator is a critically damped second-order system tracking
- * its target (Task-Dynamics style), with physiological natural frequencies. Runs at control
- * rate. Velocities are bounded implicitly by the dynamics, so UI drags and gestures produce
- * physiologically plausible motion (and therefore plausible dV/dt in the airway).
- */
-import type { HumanArtic } from "../anatomy/human.ts";
-import { NEUTRAL, restTip } from "../anatomy/human.ts";
-
-export type ArticKey = keyof HumanArtic;
-
-export const ARTIC_KEYS: ArticKey[] = ["jaw", "tbX", "tbY", "ttX", "ttY", "ttCurl", "root", "lipAp", "lipProt", "lipWidth", "labiodental", "velum", "larynx", "epilarynx", "ventricular", "lateral", "dorsum"];
-
-export interface ArticSpec {
- min: number;
- max: number;
- /** natural frequency (Hz) of the critically damped tracking dynamics */
- hz: number;
-}
-
-/** keys blended as base + min(1, w/2)·(value − base) instead of a weighted mean */
-const BOUNDED = new Set<ArticKey>(["velum"]);
-
-export const ARTIC_SPECS: Record<ArticKey, ArticSpec> = {
- // vowel articulators fast enough to reach their targets in Klatt-length vowels (VocalTractLab's
- // fitted time constants are mostly 5–40 ms; second-order ω = 2π·hz here)
- jaw: { min: -0.1, max: 2.6, hz: 10 },
- tbX: { min: 1.0, max: 4.8, hz: 12 },
- tbY: { min: 4.8, max: 9.2, hz: 12 },
- ttX: { min: 3.5, max: 8.0, hz: 13 },
- ttY: { min: 5.0, max: 10.8, hz: 13 },
- ttCurl: { min: 0, max: 1, hz: 9 },
- root: { min: -1, max: 1, hz: 9 },
- lipAp: { min: -0.4, max: 2.4, hz: 11 },
- lipProt: { min: -0.2, max: 1.5, hz: 11 },
- lipWidth: { min: 0, max: 1, hz: 11 },
- labiodental: { min: 0, max: 1, hz: 10 },
- // the velum moves fast (it must seal within a few tens of ms after a nasal) and rests a
- // little past closed, so a closure seals in finite time instead of creeping to zero
- velum: { min: -0.25, max: 1.4, hz: 12 },
- larynx: { min: -1.6, max: 1.6, hz: 8 },
- epilarynx: { min: 0, max: 1, hz: 6 },
- ventricular: { min: 0, max: 1, hz: 6 },
- lateral: { min: 0, max: 1, hz: 10 },
- dorsum: { min: 0, max: 1, hz: 9 },
-};
-
-export class ArticulatorBank {
- readonly x: HumanArtic = { ...NEUTRAL };
- readonly v: Record<ArticKey, number>;
- readonly target: HumanArtic = { ...NEUTRAL };
- /** when true the tongue tip rests behind the lower incisors (follows jaw & tongue body) */
- tipFree = true;
- /** per-articulator speed multiplier (gestures can request faster/slower motion) */
- readonly speed: Record<ArticKey, number>;
- private readonly omega: Record<ArticKey, number>;
-
- constructor() {
- this.v = Object.fromEntries(ARTIC_KEYS.map((k) => [k, 0])) as Record<ArticKey, number>;
- this.speed = Object.fromEntries(ARTIC_KEYS.map((k) => [k, 1])) as Record<ArticKey, number>;
- this.omega = Object.fromEntries(ARTIC_KEYS.map((k) => [k, 2 * Math.PI * ARTIC_SPECS[k].hz])) as Record<ArticKey, number>;
- const tip = restTip(NEUTRAL.jaw, NEUTRAL.tbX, NEUTRAL.tbY);
- this.x.ttX = this.target.ttX = tip.x;
- this.x.ttY = this.target.ttY = tip.y;
- }
-
- setTarget(values: Partial<HumanArtic>): void {
- for (const k of Object.keys(values) as ArticKey[]) {
- const val = values[k];
- if (val === undefined || !Number.isFinite(val)) continue;
- const s = ARTIC_SPECS[k];
- if (!s) continue;
- this.target[k] = Math.min(s.max, Math.max(s.min, val));
- }
- }
-
- /** Jump immediately (no dynamics), e.g. on voice creation. */
- snap(values: Partial<HumanArtic>): void {
- this.setTarget(values);
- for (const k of ARTIC_KEYS) {
- this.x[k] = this.target[k];
- this.v[k] = 0;
- }
- }
-
- /** effective targets used in the last step (base blended with gestures), for telemetry */
- readonly effective: HumanArtic = { ...NEUTRAL };
-
- /**
- * Advance the dynamics. `blend(k)` may return a gesture blend for key k: weighted mean value,
- * total weight and a speed multiplier. The performer's base target joins with weight `baseWeight`.
- */
- step(dt: number, blend?: (k: ArticKey) => { value: number; weight: number; speed: number } | null, baseWeight = 1): void {
- let restX = 0, restY = 0;
- if (this.tipFree) {
- const tip = restTip(this.x.jaw, this.x.tbX, this.x.tbY);
- restX = tip.x;
- restY = tip.y;
- this.target.ttX = tip.x;
- this.target.ttY = tip.y;
- }
- for (const k of ARTIC_KEYS) {
- let tgt = this.target[k];
- let sp = this.speed[k];
- if (blend) {
- const b = blend(k);
- if (b && b.weight > 0) {
- if (BOUNDED.has(k)) {
- // keys only consonant gestures touch (the velum): follow the gesture's own ramps
- // (with the weighted mean, a strength-4 gesture at 5 % activation already took 80 %
- // of the step, so nasality spread far into neighbouring vowels)
- tgt += Math.min(1, b.weight / 2) * (b.value - tgt);
- } else {
- const bw = baseWeight;
- tgt = (tgt * bw + b.value * b.weight) / (bw + b.weight);
- }
- sp *= b.speed;
- }
- }
- const s = ARTIC_SPECS[k];
- if (tgt < s.min) tgt = s.min;
- else if (tgt > s.max) tgt = s.max;
- this.effective[k] = tgt;
- const w = this.omega[k] * sp;
- // semi-implicit Euler on x'' = w²(T − x) − 2w x' (stable for w·dt < 1)
- const acc = w * w * (tgt - this.x[k]) - 2 * w * this.v[k];
- this.v[k] += acc * dt;
- this.x[k] += this.v[k] * dt;
- }
- void restX;
- void restY;
- }
-}
diff --git a/src/engine/control/beatPlayer.ts b/src/engine/control/beatPlayer.ts
deleted file mode 100644
index 0954cad..0000000
--- a/src/engine/control/beatPlayer.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-/**
- * Step sequencer for the beatboxer. Runs on the voice clock (in the AudioWorklet, or offline),
- * so hits are sample-accurate whatever the main thread is doing. Each step's gestures are built
- * when its hit comes within `horizon` of the clock: early enough for the slowest sound's set-up,
- * late enough that edits to the pattern are heard within a step or two.
- */
-import { beatSound, BASS_NOTE, type BeatStep } from "../phonetics/beatbox.ts";
-import type { Gesture } from "./score.ts";
-
-const midiToHz = (m: number) => 440 * Math.pow(2, (m - 69) / 12);
-
-/** scheduled steps remembered for the playhead (well over a horizon's worth) */
-const MARKS = 32;
-
-export class BeatPlayer {
- steps: (BeatStep | null)[] = [];
- bpm = 96;
- /** 0..0.6: off-beat sixteenths are delayed by swing × half a step */
- swing = 0;
- readonly stepsPerBeat = 4;
- playing = false;
- body = "male";
- /** schedule a step when its hit is this close (s); covers every sound's set-up time */
- readonly horizon = 0.2;
- private anchorTime = 0;
- private anchorStep = 0;
- private next = 0;
- /** step number and hit time of recently scheduled steps (−1 = empty slot) */
- private readonly markN = new Int32Array(MARKS).fill(-1);
- private readonly markT = new Float64Array(MARKS);
- private markPos = 0;
-
- get stepDur(): number {
- return 60 / this.bpm / this.stepsPerBeat;
- }
-
- private stepTime(n: number): number {
- const base = this.anchorTime + (n - this.anchorStep) * this.stepDur;
- return n % 2 === 1 ? base + this.swing * 0.5 * this.stepDur : base;
- }
-
- start(clock: number): void {
- this.playing = true;
- this.anchorTime = clock + this.horizon;
- this.anchorStep = 0;
- this.next = 0;
- this.markN.fill(-1);
- }
-
- stop(): void {
- this.playing = false;
- }
-
- /** Change tempo without a jump: the next unscheduled step keeps its time. */
- setTempo(bpm: number, swing: number): void {
- const b = Math.min(200, Math.max(40, bpm));
- if (this.playing && b !== this.bpm) {
- this.anchorTime += (this.next - this.anchorStep) * this.stepDur;
- this.anchorStep = this.next;
- }
- this.bpm = b;
- this.swing = Math.min(0.6, Math.max(0, swing));
- }
-
- /** The voice clock restarted (new voice after a body change): keep the beat's phase. */
- rebase(delta: number): void {
- this.anchorTime += delta;
- for (let i = 0; i < MARKS; i++) this.markT[i] += delta;
- }
-
- /**
- * The score holding the scheduled hits was replaced (new voice): schedule again every step
- * not yet heard at `clock`, at the times they were given.
- */
- rewind(clock: number): void {
- let first = -1, firstT = 0;
- for (let i = 0; i < MARKS; i++) {
- const n = this.markN[i];
- if (n >= 0 && this.markT[i] >= clock && (first < 0 || n < first)) {
- first = n;
- firstT = this.markT[i];
- }
- }
- if (first < 0) return;
- this.anchorStep = first;
- this.anchorTime = firstT - (first % 2 === 1 ? this.swing * 0.5 * this.stepDur : 0);
- this.next = first;
- for (let i = 0; i < MARKS; i++) if (this.markN[i] >= first) this.markN[i] = -1;
- }
-
- /** Step under the playhead at `clock`: the last scheduled step whose hit has come (−1: none). */
- stepAt(clock: number): number {
- if (!this.playing || this.steps.length === 0) return -1;
- let best = -1, bestT = -Infinity;
- for (let i = 0; i < MARKS; i++) {
- const t = this.markT[i];
- if (this.markN[i] >= 0 && t <= clock && t > bestT) {
- best = this.markN[i];
- bestT = t;
- }
- }
- return best < 0 ? -1 : best % this.steps.length;
- }
-
- /** Schedule every step whose hit falls within the horizon. */
- tick(clock: number, schedule: (gs: Gesture[]) => void): void {
- if (!this.playing || this.steps.length === 0) return;
- for (let guard = 0; guard < 64; guard++) {
- const hit = this.stepTime(this.next);
- if (hit > clock + this.horizon) break;
- const L = this.steps.length;
- this.markN[this.markPos] = this.next;
- this.markT[this.markPos] = hit;
- this.markPos = (this.markPos + 1) % MARKS;
- const cell = this.steps[this.next % L];
- if (cell && hit >= clock) {
- // sustained sounds (hum, open hat) last until the next sound
- let rests = 0;
- while (rests < L - 1 && !this.steps[(this.next + 1 + rests) % L]) rests++;
- schedule(this.gestures(cell, hit, (1 + rests) * this.stepDur));
- }
- this.next++;
- }
- }
-
- /** Gestures for one sound whose acoustic hit lands at `hit` on the voice clock. */
- gestures(cell: BeatStep, hit: number, len = this.stepDur): Gesture[] {
- const s = beatSound(cell.id);
- if (!s) return [];
- const gs = s.build(this.body, { f0: midiToHz(cell.note ?? BASS_NOTE), len, accent: cell.accent ?? 1 });
- const off = hit - s.latency;
- for (const g of gs) {
- g.t0 += off;
- g.t1 += off;
- }
- return gs;
- }
-
- /** Set-up time a sound needs before its hit (s): when a pad press can sound at the earliest. */
- static leadIn(id: string, body = "male"): number {
- const s = beatSound(id);
- if (!s) return 0;
- let lead = 0;
- for (const g of s.build(body, { f0: 100, len: 0.15, accent: 1 })) lead = Math.max(lead, -(g.t0 - g.rampIn));
- return lead + s.latency;
- }
-}
diff --git a/src/engine/control/score.ts b/src/engine/control/score.ts
deleted file mode 100644
index 5b23fe7..0000000
--- a/src/engine/control/score.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-/**
- * Gestural score (Articulatory-Phonology style). A gesture drives a subset of control keys
- * toward targets over an activation interval with smooth ramps and a blending strength.
- * At each control step, every key's target is the strength-weighted mean of the active
- * gestures' targets, blended with the performer's base value (weight 1 when nothing is active).
- * Consonant gestures use high strength on their articulators; vowel gestures are long and
- * overlapping, so the tongue body keeps moving vowel-to-vowel through consonants (coarticulation).
- */
-import type { ArticKey } from "./articulators.ts";
-
-/** Non-articulator control channels a gesture may drive. */
-export type SourceKey =
- /** extra glottal abduction (cm², body-scaled at use) */
- | "abduction"
- /** forced glottal closure 0..1 (glottal stop, ejectives) */
- | "closure"
- /** breath pressure multiplier (0 = no breath, 1 = performer's pressure, <0 = ingressive) */
- | "breath"
- /** pitch in Hz (absolute) */
- | "f0"
- /** vibrato depth (cents): singers let it bloom a few hundred ms into a held note */
- | "vibrato";
-
-export type ControlKey = ArticKey | SourceKey;
-
-export interface Gesture {
- t0: number;
- t1: number;
- rampIn: number;
- rampOut: number;
- strength: number;
- targets: Partial<Record<ControlKey, number>>;
- /** articulator speed multiplier while active and during `releaseHold` seconds after t1 */
- speed?: number;
- releaseHold?: number;
- /** label for visualisation (phoneme / gesture name) */
- label?: string;
- /** open-ended gestures (a sung note held until its key is released) end via release(tag) */
- tag?: number;
-}
-
-export interface Blended {
- value: number;
- /** total active weight (0 = no gesture controls this key) */
- weight: number;
- speed: number;
-}
-
-/** Smooth activation 0..1..0 with cosine ramps. */
-export function activation(g: Gesture, t: number): number {
- if (t <= g.t0 - g.rampIn || t >= g.t1 + g.rampOut) return 0;
- if (t < g.t0) {
- const u = (t - (g.t0 - g.rampIn)) / Math.max(1e-6, g.rampIn);
- return 0.5 - 0.5 * Math.cos(Math.PI * u);
- }
- if (t > g.t1) {
- const u = (t - g.t1) / Math.max(1e-6, g.rampOut);
- return 0.5 + 0.5 * Math.cos(Math.PI * u);
- }
- return 1;
-}
-
-export class GestureScore {
- private gestures: Gesture[] = [];
- /** end time of the latest gesture (s) */
- end = 0;
-
- add(g: Gesture): void {
- this.gestures.push(g);
- this.end = Math.max(this.end, g.t1 + g.rampOut + (g.releaseHold ?? 0));
- }
-
- addAll(gs: Gesture[]): void {
- for (const g of gs) this.add(g);
- }
-
- clear(): void {
- this.gestures.length = 0;
- this.end = 0;
- }
-
- /**
- * End every gesture with this tag at time t. One not yet begun is dropped; one still ramping
- * in turns round and ramps out from its present activation (no later rise); one at full
- * strength starts its ramp-out now. Those already ending are left alone.
- */
- release(tag: number, t: number): void {
- this.gestures = this.gestures.filter((g) => g.tag !== tag || t > g.t0 - g.rampIn);
- for (const g of this.gestures) {
- if (g.tag !== tag || g.t1 <= t) continue;
- if (t < g.t0) {
- // the point on the ramp-out curve whose value is the present activation
- const a = activation(g, t);
- const u = Math.acos(Math.min(1, Math.max(-1, 2 * a - 1))) / Math.PI;
- g.t1 = t - u * Math.max(1e-6, g.rampOut);
- g.t0 = g.t1;
- } else g.t1 = t;
- }
- let end = 0;
- for (const g of this.gestures) end = Math.max(end, g.t1 + g.rampOut + (g.releaseHold ?? 0));
- this.end = end;
- }
-
- /** Drop gestures that have fully finished before time t. */
- prune(t: number): void {
- if (this.gestures.length === 0) return;
- this.gestures = this.gestures.filter((g) => g.t1 + g.rampOut + (g.releaseHold ?? 0) > t);
- }
-
- get size(): number {
- return this.gestures.length;
- }
-
- /** Active gestures at time t (for visualisation). */
- activeAt(t: number): Gesture[] {
- return this.gestures.filter((g) => activation(g, t) > 0);
- }
-
- /** Blend for one key at time t. */
- blend(key: ControlKey, t: number, out: Blended): Blended {
- let wsum = 0, vsum = 0, speed = 1;
- for (let i = 0; i < this.gestures.length; i++) {
- const g = this.gestures[i];
- const target = g.targets[key];
- if (target === undefined) continue;
- const act = activation(g, t);
- if (g.speed && g.speed > speed && t >= g.t0 - g.rampIn && t <= g.t1 + g.rampOut + (g.releaseHold ?? 0)) speed = g.speed;
- if (act <= 0) continue;
- const w = act * g.strength;
- wsum += w;
- vsum += w * target;
- }
- out.value = wsum > 0 ? vsum / wsum : 0;
- out.weight = wsum;
- out.speed = speed;
- return out;
- }
-}
diff --git a/src/engine/creatures/alligator.ts b/src/engine/creatures/alligator.ts
deleted file mode 100644
index 1c2d5ac..0000000
--- a/src/engine/creatures/alligator.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-/**
- * American alligator: bellows are noisy and chaotic with most power far below 100 Hz; the body
- * vibrates the water into a "dance" before the audible roar. Chaotic laryngeal source, long tract,
- * closed mouth (sound leaves through nostrils and skin).
- */
-import type { CreatureDef, CreatureSim } from "./types.ts";
-import { mammalAirway, stepGlottis, mammalNoise } from "./mammal.ts";
-import { fillAreas, CMH2O } from "./build.ts";
-
-function create(fs: number): CreatureSim {
- const a = mammalAirway(fs, { trachea: [30, 6], pharynx: [18, 7], oral: [24, 6], nasal: [26, 1.8], wallRadiation: 1.0, coarse: 1.3 });
- const g = a.glottisSrc;
- g.threshold = 1.5 * CMH2O;
- return {
- net: a.net,
- tubes: { trachea: a.trachea, pharynx: a.pharynx, oral: a.oral, nasal: a.nasal! },
- gain: 2.8e-7,
- control(p, gate) {
- a.net.setFixedPressure(a.lungs, p.pressure * CMH2O * gate);
- g.params.f0 = p.pitch;
- g.params.amplitude = 0.9 * (1 - p.hiss);
- g.params.abduction = 0.02 + 0.8 * p.hiss;
- g.params.openQuotient = 0.5;
- g.params.closureSharpness = 0.8;
- g.params.effort = 1;
- g.params.chaos = p.chaos;
- g.params.jitter = 0.01 + 0.05 * p.chaos;
- g.params.shimmer = 0.05 + 0.25 * p.chaos;
- g.params.drift = 8;
- a.net.setTubeTargets(a.pharynx, fillAreas(a.pharynx, () => 7, a.pharArea));
- const m = p.mouth;
- a.net.setTubeTargets(a.oral, fillAreas(a.oral, (u) => (u > 0.85 ? 0.05 + 12 * m : 6), a.oralArea));
- a.net.setPortTarget(a.velum, 0.4 + 1.6 * p.nostrils);
- mammalNoise(a, { glottis: 6e-6, oral: 4e-6 });
- },
- sample() {
- stepGlottis(a);
- return a.net.step();
- },
- sourceState: () => ({ glottis: Math.min(1, g.area / 1) }),
- };
-}
-
-export const ALLIGATOR: CreatureDef = {
- id: "alligator",
- name: "American alligator",
- latin: "Alligator mississippiensis",
- group: "reptile",
- blurb: "A chaotic, very low laryngeal roar through a long, closed-mouthed tract; the whole body radiates.",
- role: "Distorted sub drones, noise bass, impacts",
- oversample: 2,
- params: [
- { key: "pitch", label: "Pitch", min: 12, max: 120, default: 28, unit: "Hz", log: true, smooth: 0.05, role: "pitch" },
- { key: "chaos", label: "Bifurcation (period doubling → chaos)", min: 0, max: 1, default: 0.75, smooth: 0.05 },
- { key: "pressure", label: "Breath pressure", min: 3, max: 40, default: 18, unit: "cmH₂O", smooth: 0.03 },
- { key: "mouth", label: "Mouth opening", min: 0, max: 1, default: 0.02, smooth: 0.05 },
- { key: "nostrils", label: "Nasal passage", min: 0, max: 1, default: 0.8, smooth: 0.05 },
- { key: "hiss", label: "Hiss (open glottis)", min: 0, max: 1, default: 0, smooth: 0.04 },
- ],
- calls: [
- { id: "bellow", name: "Bellow", hint: "Two seconds of chaotic roar, rising into full chaos", pitchRef: 28, keys: [{ t: 0, v: { gate: 0, chaos: 0.55, pitch: 30, hiss: 0, mouth: 0.02 } }, { t: 0.15, v: { gate: 1 } }, { t: 1.6, v: { gate: 1, chaos: 0.95, pitch: 24 } }, { t: 2.0, v: { gate: 0 } }] },
- { id: "growl", name: "Growl", hint: "Short, rough warning", pitchRef: 45, keys: [{ t: 0, v: { gate: 1, chaos: 0.7, pitch: 45, mouth: 0.15 } }, { t: 0.5, v: { pitch: 38 } }, { t: 0.6, v: { gate: 0 } }] },
- { id: "hiss", name: "Hiss", hint: "Open mouth, open glottis: pure turbulence", keys: [{ t: 0, v: { gate: 0, hiss: 1, mouth: 0.9 } }, { t: 0.1, v: { gate: 1 } }, { t: 1.2, v: { gate: 1 } }, { t: 1.3, v: { gate: 0, hiss: 0, mouth: 0.02 } }] },
- { id: "dance", name: "Water dance", hint: "Steady subsonic throb that shakes the water", pitchRef: 18, keys: [{ t: 0, v: { gate: 1, chaos: 0, pitch: 18, mouth: 0 } }, { t: 1.6, v: { gate: 1 } }, { t: 1.7, v: { gate: 0, chaos: 0.75 } }] },
- ],
- visual: {
- view: { x0: -120, x1: 120, y0: -40, y1: 40 },
- silhouette: [[-118, 2], [-90, -4], [-60, -8], [-30, -14], [0, -16], [30, -14], [50, -10], [70, -8], [95, -5], [114, -3], [118, 0], [115, 3], [98, 5], [75, 7], [52, 9], [40, 12], [20, 14], [-10, 14], [-40, 11], [-70, 7], [-100, 4]],
- parts: [{ shade: 0.15, pts: [[54, 9], [56, 11], [58, 9], [56, 8]] }],
- tubes: [
- { tube: "trachea", path: [[0, -6], [18, -5], [36, -4]], label: "Trachea" },
- { tube: "pharynx", path: [[36, -4], [46, -2], [54, 0]], label: "Pharynx" },
- { tube: "oral", path: [[54, 0], [80, -1], [112, -1]], label: "Mouth" },
- { tube: "nasal", path: [[54, 2], [80, 4], [113, 2]], label: "Nostrils" },
- ],
- tubeScale: 1.05,
- sources: [{ key: "glottis", at: [36, -4], label: "Larynx" }],
- },
- create,
-};
diff --git a/src/engine/creatures/build.ts b/src/engine/creatures/build.ts
deleted file mode 100644
index c4bb999..0000000
--- a/src/engine/creatures/build.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-/** Shared helpers for building creature airways. */
-import { AirwayNetwork, type Tube } from "../airway/network.ts";
-import { C_SOUND, RHO, type WallParams } from "../physics.ts";
-
-/** Smallest stable section length at this internal rate (CFL 0.93). */
-export const dxMin = (fs: number) => C_SOUND / fs / 0.93;
-
-/** Number of sections for a tube: as fine as stability allows, but at least `min`, at most `max`. */
-export function sections(fs: number, length: number, min = 3, max = 120, coarse = 1): number {
- return Math.max(min, Math.min(max, Math.floor(length / (dxMin(fs) * coarse))));
-}
-
-export function tube(net: AirwayNetwork, name: string, fs: number, length: number, area: number | ((u: number) => number), opts: { wall?: WallParams | null; coarse?: number; min?: number; max?: number; perimeterFactor?: number; viscousFactor?: number; wallRadiation?: number } = {}): Tube {
- const n = sections(fs, length, opts.min ?? 3, opts.max ?? 120, opts.coarse ?? 1);
- const areas = typeof area === "number" ? area : Array.from({ length: n }, (_, i) => area((i + 0.5) / n));
- return net.addTube({ name, n, length, area: areas, wall: opts.wall ?? null, perimeterFactor: opts.perimeterFactor, viscousFactor: opts.viscousFactor, wallRadiation: opts.wallRadiation });
-}
-
-/** Lungs/air-sac pressure node feeding a tube through a mildly resistive connection. */
-export function lungs(net: AirwayNetwork, into: number, area: number): number {
- const node = net.addPressureNode("lungs");
- net.addPort(node, into, { area, length: 1, kEntrance: 0, kExit: 0, extraResistance: (0.5 * RHO * C_SOUND) / area });
- return node;
-}
-
-/** Fill a tube's areas from a function of position u ∈ (0,1). */
-export function fillAreas(t: Tube, f: (u: number) => number, out: Float64Array): Float64Array {
- for (let i = 0; i < t.n; i++) out[i] = Math.max(0, f((i + 0.5) / t.n));
- return out;
-}
-
-export const CMH2O = 980.665;
diff --git a/src/engine/creatures/elephant.ts b/src/engine/creatures/elephant.ts
deleted file mode 100644
index 5b81b92..0000000
--- a/src/engine/creatures/elephant.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-/**
- * African elephant: infrasonic rumbles from self-oscillating vocal folds, routed through the trunk
- * or the mouth; trumpets from a valve at the trunk entrance that locks onto the trunk's resonances
- * like a brass player's lips on a bugle; squeaks from tensed lips.
- */
-import type { CreatureDef, CreatureSim } from "./types.ts";
-import { mammalAirway, stepGlottis, mammalNoise } from "./mammal.ts";
-import { fillAreas, tube, CMH2O } from "./build.ts";
-import { LipReed } from "../sources/valves.ts";
-import { WALL_NASAL } from "../physics.ts";
-import type { Tube } from "../airway/network.ts";
-
-function create(fs: number): CreatureSim {
- let trunk: Tube | null = null;
- let valve = -1;
- const a = mammalAirway(fs, { trachea: [45, 14], pharynx: [32, 14], oral: [28, 10], nasal: [14, 6], wallRadiation: 0.6, coarse: 1.2, nasalRadiates: false }, (net, parts) => {
- // the "nasal" tube is the trunk base; a lip-like valve leads into the long trunk
- trunk = tube(net, "trunk", fs, 185, (u) => 4.2 - 3.0 * u, { wall: WALL_NASAL, coarse: 2.3, max: 110, perimeterFactor: 1.4 });
- valve = net.addPort(parts.nasal!.lastNode, (trunk as Tube).firstNode, { area: 0, length: 0.6, kEntrance: 0.3, kExit: 1 });
- net.addRadiation((trunk as Tube).lastNode);
- });
- const trunkTube = trunk as unknown as Tube;
- const lips = new LipReed(fs);
- const g = a.glottisSrc;
- g.threshold = 1.5 * CMH2O;
- let mode = 0;
- return {
- net: a.net,
- tubes: { trachea: a.trachea, pharynx: a.pharynx, oral: a.oral, trunk: trunkTube },
- gain: 1.8e-6,
- control(p, gate) {
- mode = p.mode;
- a.net.setFixedPressure(a.lungs, p.pressure * CMH2O * gate);
- // rumble: folds vibrate; trumpet: folds open, valve buzzes
- g.params.f0 = p.pitch;
- g.params.amplitude = 1.6 * (1 - mode);
- g.params.abduction = 0.05 + 3.0 * mode; // trumpet: larynx wide open, silent
- g.params.openQuotient = 0.6;
- g.params.closureSharpness = 0.6;
- g.params.effort = 0.9;
- g.params.chaos = p.chaos * 0.6;
- lips.f = p.lipPitch;
- lips.zeta = 0.08;
- lips.h0 = 0.003; // a slight rest gap: buzzing lips start from just apart
- lips.width = 2.4;
- lips.surfacePerMass = 40;
- const toTrunk = p.trunk;
- a.net.setPortTarget(a.velum, 0.1 + 6 * toTrunk);
- a.net.setTubeTargets(a.pharynx, fillAreas(a.pharynx, () => 14, a.pharArea));
- a.net.setTubeTargets(a.oral, fillAreas(a.oral, (u) => (u > 0.85 ? 0.05 + 10 * (1 - toTrunk) : 10), a.oralArea));
- mammalNoise(a, { glottis: 4e-7 * (1 - mode) });
- },
- sample() {
- stepGlottis(a);
- if (mode > 0.02) {
- const p = a.net.p;
- const dp = p[a.nasal!.lastNode] - p[trunkTube.firstNode];
- const open = lips.next(dp * mode);
- a.net.setPortArea(valve, Math.max(open, 4.5 * (1 - mode)));
- } else a.net.setPortArea(valve, 4.5);
- return a.net.step();
- },
- sourceState: () => ({ glottis: Math.min(1, g.area / 1.6), lips: Math.min(1, lips.opening / 1.2) }),
- };
-}
-
-export const ELEPHANT: CreatureDef = {
- id: "elephant",
- name: "African elephant",
- latin: "Loxodonta africana",
- group: "mammal",
- blurb: "Infrasonic rumbles from huge vocal folds, routed through a two-metre trunk or the mouth; trumpets from a buzzing valve at the trunk entrance.",
- role: "Sub-bass rumbles, distorted brass leads",
- oversample: 1,
- params: [
- { key: "mode", label: "Rumble ↔ trumpet", min: 0, max: 1, default: 0, smooth: 0.03 },
- { key: "pitch", label: "Rumble pitch", min: 8, max: 45, default: 14, unit: "Hz", log: true, smooth: 0.05, role: "pitch" },
- { key: "lipPitch", label: "Trumpet valve pitch", min: 150, max: 900, default: 470, unit: "Hz", log: true, smooth: 0.02 },
- { key: "pressure", label: "Breath pressure", min: 3, max: 45, default: 16, unit: "cmH₂O", smooth: 0.02 },
- { key: "trunk", label: "Mouth ↔ trunk", min: 0, max: 1, default: 1, smooth: 0.04 },
- { key: "chaos", label: "Chaos", min: 0, max: 1, default: 0.2, smooth: 0.05 },
- ],
- calls: [
- { id: "rumble", name: "Rumble", hint: "Three seconds of infrasonic rumble through the trunk", pitchRef: 14, keys: [{ t: 0, v: { mode: 0, gate: 0, pitch: 15, trunk: 1 } }, { t: 0.3, v: { gate: 1 } }, { t: 2.7, v: { gate: 1, pitch: 12 } }, { t: 3.1, v: { gate: 0 } }] },
- { id: "trumpet", name: "Trumpet", hint: "A brassy blast that bends up and breaks into chaos", pitchRef: 470, keys: [{ t: 0, v: { mode: 1, gate: 0, lipPitch: 380, pressure: 26, chaos: 0.1 } }, { t: 0.05, v: { gate: 1 } }, { t: 0.5, v: { lipPitch: 520 }, curve: "exp" }, { t: 1.1, v: { lipPitch: 470, chaos: 0.6, pressure: 34 }, curve: "exp" }, { t: 1.25, v: { gate: 0, mode: 0, pressure: 16 } }] },
- { id: "squeak", name: "Squeak", hint: "Tensed, high valve buzz", pitchRef: 850, keys: [{ t: 0, v: { mode: 1, gate: 0, lipPitch: 820, pressure: 20 } }, { t: 0.04, v: { gate: 1 } }, { t: 0.45, v: { lipPitch: 880 } }, { t: 0.5, v: { gate: 0, mode: 0, pressure: 16 } }] },
- ],
- visual: {
- view: { x0: -170, x1: 170, y0: -170, y1: 130 },
- silhouette: [[-160, 20], [-150, 70], [-110, 105], [-40, 118], [30, 115], [70, 100], [95, 112], [120, 108], [140, 85], [148, 55], [146, 25], [140, 5], [132, -20], [128, -60], [122, -110], [118, -150], [108, -152], [112, -100], [110, -50], [104, -20], [96, -5], [80, 0], [70, -10], [66, -90], [40, -95], [44, -30], [-90, -30], [-95, -95], [-125, -95], [-122, -10], [-150, -5]],
- parts: [{ shade: 0.15, pts: [[118, 62], [122, 66], [126, 62], [122, 58]] }, { shade: 0.62, pts: [[70, 100], [40, 60], [55, 25], [85, 40], [95, 80]] }],
- tubes: [
- { tube: "trachea", path: [[40, 20], [70, 30], [95, 38]], label: "Trachea" },
- { tube: "pharynx", path: [[95, 38], [112, 50], [124, 58]], label: "Pharynx" },
- { tube: "oral", path: [[124, 58], [130, 42], [134, 30]], label: "Mouth" },
- { tube: "trunk", path: [[136, 70], [142, 40], [136, 0], [128, -50], [120, -100], [113, -148]], label: "Trunk" },
- ],
- tubeScale: 3,
- sources: [{ key: "glottis", at: [95, 38], label: "Vocal folds" }, { key: "lips", at: [136, 70], label: "Trunk valve" }],
- },
- create,
-};
diff --git a/src/engine/creatures/index.ts b/src/engine/creatures/index.ts
deleted file mode 100644
index 93ceb6c..0000000
--- a/src/engine/creatures/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-/** Creature registry. */
-import type { CreatureDef } from "./types.ts";
-import { SONGBIRD } from "./songbird.ts";
-import { SEAL } from "./seal.ts";
-import { ALLIGATOR } from "./alligator.ts";
-import { ELEPHANT } from "./elephant.ts";
-
-export const CREATURES: CreatureDef[] = [SONGBIRD, SEAL, ALLIGATOR, ELEPHANT];
-export const creatureById = (id: string) => CREATURES.find((c) => c.id === id);
diff --git a/src/engine/creatures/mammal.ts b/src/engine/creatures/mammal.ts
deleted file mode 100644
index 9d93126..0000000
--- a/src/engine/creatures/mammal.ts
+++ /dev/null
@@ -1,81 +0,0 @@
-/** Parametrised mammalian/reptilian airway: lungs → trachea → glottis → pharynx ─┬─ oral → mouth
- * └─ velum → nasal → nostrils */
-import { AirwayNetwork, type Tube } from "../airway/network.ts";
-import { WALL_SOFT, WALL_TRACHEA, WALL_NASAL, type WallParams } from "../physics.ts";
-import { ParametricGlottis } from "../sources/glottis.ts";
-import { tube, lungs } from "./build.ts";
-
-export interface MammalSpec {
- trachea: [length: number, area: number];
- pharynx: [length: number, area: number];
- oral: [length: number, area: number];
- nasal?: [length: number, area: number];
- wall?: WallParams;
- /** fraction of wall motion that radiates (body/skin radiation) */
- wallRadiation?: number;
- /** coarse sections for very long tubes (×dxMin) */
- coarse?: number;
- /** the nasal tube ends in nostrils (default) or continues into something else (trunk) */
- nasalRadiates?: boolean;
-}
-
-export interface MammalAirway {
- net: AirwayNetwork;
- trachea: Tube;
- pharynx: Tube;
- oral: Tube;
- nasal: Tube | null;
- lungs: number;
- glottis: number;
- velum: number;
- glottisSrc: ParametricGlottis;
- pharArea: Float64Array;
- oralArea: Float64Array;
-}
-
-export function mammalAirway(fs: number, s: MammalSpec, extra?: (net: AirwayNetwork, a: Omit<MammalAirway, "glottisSrc" | "pharArea" | "oralArea" | "lungs" | "glottis" | "velum"> & { lungs?: number }) => void): MammalAirway {
- const net = new AirwayNetwork(fs);
- const wall = s.wall ?? WALL_SOFT;
- const coarse = s.coarse ?? 1;
- const trachea = tube(net, "trachea", fs, s.trachea[0], s.trachea[1], { wall: WALL_TRACHEA, coarse: Math.max(coarse, 1.6), max: 60 });
- const pharynx = tube(net, "pharynx", fs, s.pharynx[0], s.pharynx[1], { wall, coarse, wallRadiation: s.wallRadiation ?? 0.25, perimeterFactor: 1.3 });
- const oral = tube(net, "oral", fs, s.oral[0], s.oral[1], { wall, coarse, wallRadiation: s.wallRadiation ?? 0.25, perimeterFactor: 1.5 });
- const nasal = s.nasal ? tube(net, "nasal", fs, s.nasal[0], s.nasal[1], { wall: WALL_NASAL, coarse, perimeterFactor: 2.6, viscousFactor: 2 }) : null;
- const lungNode = lungs(net, trachea.firstNode, s.trachea[1]);
- const glottis = net.addPort(trachea.lastNode, pharynx.firstNode, { area: 0, length: 0.4, kEntrance: 0.37, kExit: 1, slitWidth: Math.sqrt(s.trachea[1]) * 0.9 });
- net.connect(pharynx.lastNode, oral.firstNode);
- const velum = nasal ? net.addPort(pharynx.lastNode, nasal.firstNode, { area: 0, length: 1, kEntrance: 0.3, kExit: 0.8 }) : -1;
- net.addRadiation(oral.lastNode);
- if (nasal && s.nasalRadiates !== false) net.addRadiation(nasal.lastNode);
- extra?.(net, { net, trachea, pharynx, oral, nasal });
- net.finalize();
- return { net, trachea, pharynx, oral, nasal, lungs: lungNode, glottis, velum, glottisSrc: new ParametricGlottis(fs), pharArea: new Float64Array(pharynx.n), oralArea: new Float64Array(oral.n) };
-}
-
-/**
- * Register turbulence sources: aspiration at the glottis (hiss, breathiness) and the narrowest
- * point of the oral tube (mouth/teeth hiss). Call at control rate.
- */
-export function mammalNoise(a: MammalAirway, gains: { glottis: number; oral?: number }): void {
- const list: { src: number; fwd: number; bwd: number; gain: number; lowpassHz?: number; highpassHz?: number }[] = [
- { src: a.glottis, fwd: a.pharynx.branch(Math.min(1, a.pharynx.n - 2)), bwd: a.trachea.branch(a.trachea.n - 2), gain: gains.glottis, lowpassHz: 4000, highpassHz: 250 },
- ];
- if (gains.oral) {
- let mi = 0, mv = Infinity;
- for (let i = 0; i < a.oral.n - 1; i++) {
- const v = a.oralArea[i];
- if (v > 0 && v < mv) {
- mv = v;
- mi = i;
- }
- }
- if (mv < 2) list.push({ src: a.oral.branch(mi), fwd: a.oral.branch(Math.min(a.oral.n - 2, mi + 1)), bwd: a.oral.branch(Math.max(0, mi - 1)), gain: gains.oral, lowpassHz: 5000, highpassHz: 600 });
- }
- a.net.setNoiseSources(list);
-}
-
-/** Drive the glottal port from its source for one sample. */
-export function stepGlottis(a: MammalAirway): void {
- const p = a.net.p;
- a.net.setPortArea(a.glottis, a.glottisSrc.next(p[a.trachea.lastNode] - p[a.pharynx.firstNode]));
-}
diff --git a/src/engine/creatures/seal.ts b/src/engine/creatures/seal.ts
deleted file mode 100644
index 84b1043..0000000
--- a/src/engine/creatures/seal.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-/**
- * Weddell seal: male trills sweep down over seconds from several kHz to below 100 Hz while their
- * pulse rate also slows — researchers compared them to ARP synthesizers. Modelled as a laryngeal
- * source with an extreme pitch range, a pulse (amplitude) oscillator, and a short tract.
- */
-import type { CreatureDef, CreatureSim } from "./types.ts";
-import { mammalAirway, stepGlottis, mammalNoise } from "./mammal.ts";
-import { fillAreas, CMH2O } from "./build.ts";
-
-function create(fs: number): CreatureSim {
- const a = mammalAirway(fs, { trachea: [24, 4], pharynx: [11, 3.2], oral: [12, 3.6], nasal: [12, 1.5], wallRadiation: 0.6 });
- const g = a.glottisSrc;
- g.params.jitter = 0.002;
- g.params.shimmer = 0.01;
- g.params.drift = 2;
- let pulsePhase = 0;
- let pulseGate = 1;
- return {
- net: a.net,
- tubes: { trachea: a.trachea, pharynx: a.pharynx, oral: a.oral },
- gain: 6.4e-8,
- control(p, gate, dt) {
- pulsePhase += p.pulseRate * dt;
- pulsePhase -= Math.floor(pulsePhase);
- const ph = pulsePhase < p.duty ? Math.sin((Math.PI * pulsePhase) / p.duty) : 0;
- pulseGate = 1 - p.pulse + p.pulse * ph;
- a.net.setFixedPressure(a.lungs, p.pressure * CMH2O * gate * pulseGate);
- g.params.f0 = p.pitch;
- g.params.amplitude = 0.22;
- g.params.openQuotient = 0.55 - 0.25 * p.bright;
- g.params.closureSharpness = 0.4 + 0.6 * p.bright;
- g.params.effort = 0.5 + 0.5 * p.bright;
- g.params.chink = 0.01;
- g.params.chaos = p.rough;
- const mouth = p.mouth;
- a.net.setTubeTargets(a.pharynx, fillAreas(a.pharynx, () => 3.0, a.pharArea));
- a.net.setTubeTargets(a.oral, fillAreas(a.oral, (u) => (u > 0.8 ? 0.3 + 4 * mouth : 3.6), a.oralArea));
- mammalNoise(a, { glottis: 2e-6 });
- },
- sample() {
- stepGlottis(a);
- return a.net.step();
- },
- sourceState: () => ({ glottis: Math.min(1, g.area / 0.3) }),
- };
-}
-
-export const SEAL: CreatureDef = {
- id: "seal",
- name: "Weddell seal",
- latin: "Leptonychotes weddellii",
- group: "marine",
- blurb: "Laryngeal calls with an extreme range: trills glide down for seconds while their pulses slow.",
- role: "Downlifters, laser zaps, acid-style sweeping leads",
- oversample: 2,
- gateTimes: { attack: 0.006, release: 0.03 },
- params: [
- { key: "pitch", label: "Pitch", min: 40, max: 6000, default: 900, unit: "Hz", log: true, smooth: 0.01, role: "pitch" },
- { key: "pulseRate", label: "Pulse rate", min: 2, max: 60, default: 18, unit: "Hz", log: true, smooth: 0.02 },
- { key: "pulse", label: "Pulsing depth", min: 0, max: 1, default: 0.6, smooth: 0.02 },
- { key: "duty", label: "Pulse duty", min: 0.15, max: 1, default: 0.55, smooth: 0.02 },
- { key: "bright", label: "Brightness", min: 0, max: 1, default: 0.6, smooth: 0.02 },
- { key: "rough", label: "Roughness", min: 0, max: 0.8, default: 0.05, smooth: 0.05 },
- { key: "pressure", label: "Breath pressure", min: 2, max: 25, default: 10, unit: "cmH₂O", smooth: 0.01 },
- { key: "mouth", label: "Mouth opening", min: 0, max: 1, default: 0.35, smooth: 0.03 },
- ],
- calls: [
- { id: "trill", name: "Descending trill", hint: "Several seconds falling from bright to subsonic, pulses slowing", pitchRef: 3600, keys: [{ t: 0, v: { gate: 1, pitch: 3600, pulseRate: 42, pulse: 0.9, duty: 0.5 } }, { t: 3.6, v: { gate: 1, pitch: 95, pulseRate: 6 }, curve: "exp" }, { t: 3.9, v: { gate: 0 } }] },
- { id: "zap", name: "Laser chirp", hint: "A 150 ms downward zap", pitchRef: 6000, keys: [{ t: 0, v: { gate: 1, pitch: 6000, pulse: 0 } }, { t: 0.15, v: { pitch: 1100 }, curve: "exp" }, { t: 0.17, v: { gate: 0 } }] },
- { id: "whistle", name: "U whistle", hint: "Dips and returns", pitchRef: 1700, keys: [{ t: 0, v: { gate: 1, pitch: 1700, pulse: 0.1 } }, { t: 0.45, v: { pitch: 620 }, curve: "exp" }, { t: 0.95, v: { pitch: 1500 }, curve: "exp" }, { t: 1.0, v: { gate: 0 } }] },
- { id: "chug", name: "Chug", hint: "Low, pulsed grunt", pitchRef: 90, keys: [{ t: 0, v: { gate: 1, pitch: 90, pulseRate: 11, pulse: 1, duty: 0.35, rough: 0.3 } }, { t: 0.9, v: { gate: 1 } }, { t: 0.95, v: { gate: 0, rough: 0.05 } }] },
- ],
- visual: {
- view: { x0: -60, x1: 60, y0: -30, y1: 30 },
- silhouette: [[-58, -2], [-50, -8], [-30, -14], [-5, -16], [20, -14], [38, -10], [48, -6], [55, -3], [58, 1], [56, 5], [50, 8], [42, 10], [30, 11], [10, 13], [-15, 13], [-35, 10], [-50, 6], [-56, 3], [-62, 8], [-64, 4], [-60, 0], [-64, -4], [-62, -8]],
- parts: [{ shade: 0.15, pts: [[47, 4], [48.5, 5], [50, 4], [48.5, 3]] }],
- tubes: [
- { tube: "trachea", path: [[8, -4], [20, -3], [30, -2]], label: "Trachea" },
- { tube: "pharynx", path: [[30, -2], [38, 0], [44, 1.5]], label: "Pharynx" },
- { tube: "oral", path: [[44, 1.5], [50, 0.5], [57, -0.5]], label: "Mouth" },
- ],
- tubeScale: 1.3,
- sources: [{ key: "glottis", at: [30, -2], label: "Larynx" }],
- },
- create,
-};
diff --git a/src/engine/creatures/songbird.ts b/src/engine/creatures/songbird.ts
deleted file mode 100644
index 7579bf2..0000000
--- a/src/engine/creatures/songbird.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * Two-voice songbird (thrush-sized). Each side of the syrinx has its own labial oscillator and
- * pitch; both bronchi merge into the trachea → larynx → oropharyngeal–oesophageal cavity (OEC,
- * a Helmholtz resonator whose volume can track f0 for pure tones) → beak (gape controls radiation).
- */
-import { AirwayNetwork } from "../airway/network.ts";
-import { WALL_TRACHEA } from "../physics.ts";
-import { SyrinxLabia } from "../sources/syrinx.ts";
-import type { CreatureDef, CreatureSim, CallKey } from "./types.ts";
-import { tube, fillAreas } from "./build.ts";
-
-const OEC_NECK = 0.03; // cm² (larynx)
-const OEC_LEN = 0.35; // cm, with end corrections
-
-function create(fs: number): CreatureSim {
- const net = new AirwayNetwork(fs);
- const bronL = tube(net, "bronchusL", fs, 0.8, 0.02);
- const bronR = tube(net, "bronchusR", fs, 0.8, 0.02);
- const trachea = tube(net, "trachea", fs, 3.6, 0.045, { wall: WALL_TRACHEA });
- const sac = net.addPressureNode("air sac");
- net.addPort(sac, bronL.firstNode, { area: 0.05, length: 0.4 });
- net.addPort(sac, bronR.firstNode, { area: 0.05, length: 0.4 });
- const vL = net.addPort(bronL.lastNode, trachea.firstNode, { area: 0, length: 0.08, kEntrance: 0.5, kExit: 1 });
- const vR = net.addPort(bronR.lastNode, trachea.firstNode, { area: 0, length: 0.08, kEntrance: 0.5, kExit: 1 });
- const oec = net.addCavity("oec", 0.4);
- net.addPort(trachea.lastNode, oec, { area: OEC_NECK, length: 0.25, kEntrance: 0.3, kExit: 0.8 });
- const beak = tube(net, "beak", fs, 1.3, 0.08);
- net.connect(oec, beak.firstNode);
- net.addRadiation(beak.lastNode);
- net.finalize();
- const oecLen = Math.cbrt(0.4);
- const labL = new SyrinxLabia(fs, 0);
- const labR = new SyrinxLabia(fs, 1);
- const beakAreas = new Float64Array(beak.n);
- const AMAX = 0.03;
- return {
- net,
- tubes: { trachea, beak, bronchusL: bronL, bronchusR: bronR },
- gain: 4.8e-7,
- control(p, gate) {
- net.setFixedPressure(sac, p.pressure * 1000 * gate * 10); // kPa → dyn/cm² (×10 000)
- labL.f0 = p.pitch;
- labR.f0 = p.pitch * Math.pow(2, p.interval / 12);
- labL.drive = labR.drive = p.drive;
- labL.tension = labR.tension = p.tension;
- // voices: 0 = left only, 0.5 = both, 1 = right only
- labL.gate = p.voices <= 0.5 ? 1 : Math.max(0, 2 - 2 * p.voices);
- labR.gate = p.voices >= 0.5 ? 1 : Math.max(0, 2 * p.voices);
- // OEC tracks the (lower) fundamental for pure tones, or stays at its own size
- const fT = Math.min(labL.f0, labR.f0);
- const vTrack = OEC_NECK / (OEC_LEN * Math.pow(fT / 5570, 2));
- const vol = Math.min(2.5, Math.max(0.04, p.purity * vTrack + (1 - p.purity) * p.oec));
- net.setNodeAreaTarget(oec, vol / oecLen);
- const gape = p.gape;
- net.setTubeTargets(beak, fillAreas(beak, (u) => 0.012 + gape * (0.05 + 0.22 * u), beakAreas));
- },
- sample() {
- net.setPortArea(vL, AMAX * labL.next());
- net.setPortArea(vR, AMAX * labR.next());
- return net.step();
- },
- sourceState: () => ({ left: labL.opening, right: labR.opening }),
- };
-}
-
-// --- calls --------------------------------------------------------------------------------------
-function trill(f0: number, rate: number, n: number, sweep: number): CallKey[] {
- const keys: CallKey[] = [];
- const per = 1 / rate;
- for (let i = 0; i < n; i++) {
- const t = i * per;
- keys.push({ t, v: { gate: 0, pitch: f0 * (1 - sweep / 2) } , curve: "step" });
- keys.push({ t: t + per * 0.08, v: { gate: 1 } });
- keys.push({ t: t + per * 0.62, v: { gate: 1, pitch: f0 * (1 + sweep / 2) }, curve: "exp" });
- keys.push({ t: t + per * 0.75, v: { gate: 0 } });
- }
- return keys;
-}
-
-export const SONGBIRD: CreatureDef = {
- id: "songbird",
- name: "Songbird",
- latin: "Hylocichla mustelina & kin",
- group: "bird",
- blurb: "Two independent labial pairs in the syrinx, one per bronchus, each with its own pitch; a throat cavity tracks the note.",
- role: "Shimmering two-note leads, arpeggio trills, glitchy chirps",
- oversample: 4,
- gateTimes: { attack: 0.004, release: 0.012 },
- params: [
- { key: "pitch", label: "Pitch, left voice", min: 400, max: 9000, default: 2600, unit: "Hz", log: true, smooth: 0.008, role: "pitch" },
- { key: "interval", label: "Right voice interval", min: -12, max: 12, default: 7, unit: "st", smooth: 0.02, digits: 1 },
- { key: "voices", label: "Left ↔ both ↔ right", min: 0, max: 1, default: 0.5, smooth: 0.02 },
- { key: "drive", label: "Drive (pure → raspy)", min: 0, max: 1, default: 0.35, smooth: 0.02 },
- { key: "tension", label: "Labial tension", min: 0, max: 1, default: 0.4, smooth: 0.02 },
- { key: "pressure", label: "Air-sac pressure", min: 0.1, max: 2, default: 0.9, unit: "kPa", smooth: 0.01, digits: 2 },
- { key: "purity", label: "Throat tracks note", min: 0, max: 1, default: 0.8, smooth: 0.02 },
- { key: "oec", label: "Throat cavity size", min: 0.05, max: 2, default: 0.4, unit: "cm³", log: true, smooth: 0.03, digits: 2 },
- { key: "gape", label: "Beak gape", min: 0, max: 1, default: 0.55, smooth: 0.02 },
- ],
- calls: [
- {
- id: "flute",
- name: "Flute phrase",
- hint: "Wood-thrush style: three notes, then a two-voice shimmer",
- pitchRef: 2600,
- keys: [
- { t: 0, v: { gate: 0, pitch: 2000, voices: 0.15, drive: 0.25, interval: 7 } },
- { t: 0.02, v: { gate: 1 } },
- { t: 0.2, v: { gate: 1, pitch: 2100 }, curve: "exp" },
- { t: 0.23, v: { gate: 0 } },
- { t: 0.3, v: { gate: 1, pitch: 2600 }, curve: "step" },
- { t: 0.5, v: { pitch: 2500 }, curve: "exp" },
- { t: 0.53, v: { gate: 0 } },
- { t: 0.6, v: { gate: 1, pitch: 3300, voices: 0.5, interval: 4 }, curve: "step" },
- { t: 1.1, v: { pitch: 3500, interval: 5 }, curve: "exp" },
- { t: 1.2, v: { gate: 0 } },
- ],
- },
- { id: "trill", name: "Canary trill", hint: "16 notes a second, each a quick upsweep", pitchRef: 3000, keys: [{ t: 0, v: { voices: 0.15, drive: 0.3 } }, ...trill(3000, 16, 18, 0.35)] },
- {
- id: "chirps",
- name: "Chirp cascade",
- hint: "Falling chirps, faster and faster",
- pitchRef: 4500,
- keys: [{ t: 0, v: { voices: 0.15, drive: 0.4 } }, ...Array.from({ length: 9 }, (_, i): CallKey[] => {
- const t = i * (0.14 - i * 0.008);
- return [
- { t, v: { gate: 0, pitch: 7000 - i * 300 }, curve: "step" },
- { t: t + 0.01, v: { gate: 1 } },
- { t: t + 0.06, v: { gate: 1, pitch: 2400 - i * 80 }, curve: "exp" },
- { t: t + 0.07, v: { gate: 0 } },
- ];
- }).flat()],
- },
- {
- id: "buzz",
- name: "Finch buzz",
- hint: "Zebra-finch style: raspy, pulsed by mini-breaths",
- pitchRef: 1200,
- keys: [
- { t: 0, v: { voices: 0.5, drive: 0.95, tension: 0.15, interval: 0.5, pitch: 1200, purity: 0.1, gate: 0 } },
- ...Array.from({ length: 8 }, (_, i): CallKey[] => [
- { t: 0.02 + i * 0.07, v: { gate: 1 } },
- { t: 0.06 + i * 0.07, v: { gate: 0.35 } },
- ]).flat(),
- { t: 0.6, v: { gate: 0 } },
- ],
- },
- ],
- visual: {
- view: { x0: -4, x1: 14, y0: -6, y1: 8 },
- silhouette: [[-3.2, -1.2], [-1.6, -3.4], [1.6, -4.6], [5.2, -4.4], [7.8, -2.6], [9.0, -0.4], [9.6, 1.8], [10.4, 2.4], [12.8, 2.6], [10.6, 3.0], [9.8, 3.6], [9.2, 4.6], [7.6, 5.2], [6.0, 4.6], [4.2, 2.8], [2.0, 2.0], [-0.2, 1.6], [-3.6, 1.4], [-3.4, 0.2]],
- parts: [{ shade: 0.2, pts: [[8.6, 4.0], [8.95, 4.3], [9.2, 4.0], [8.95, 3.7]] }],
- tubes: [
- { tube: "bronchusL", path: [[3.4, -1.9], [4.4, -1.4]], label: "Left bronchus", inView: false },
- { tube: "bronchusR", path: [[3.4, -0.9], [4.4, -1.2]], label: "Right bronchus", inView: false },
- { tube: "trachea", path: [[4.4, -1.3], [5.6, -0.4], [6.8, 0.8], [7.8, 1.9], [8.6, 2.5]], label: "Trachea" },
- { tube: "beak", path: [[9.4, 2.75], [10.6, 2.75], [12.4, 2.7]], label: "Beak" },
- ],
- tubeScale: 1.6,
- sources: [{ key: "left", at: [4.2, -1.6], label: "Left voice" }, { key: "right", at: [4.2, -1.0], label: "Right voice" }],
- },
- create,
-};
diff --git a/src/engine/creatures/types.ts b/src/engine/creatures/types.ts
deleted file mode 100644
index f5119cc..0000000
--- a/src/engine/creatures/types.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/** Creature definitions: physics (airway + sources), playable parameters, calls, and drawing. */
-import type { AirwayNetwork, Tube } from "../airway/network.ts";
-
-export type CreatureGroup = "human" | "bird" | "mammal" | "marine" | "reptile" | "amphibian" | "insect" | "crustacean" | "fantasy";
-
-export interface ParamDef {
- key: string;
- label: string;
- min: number;
- max: number;
- default: number;
- unit?: string;
- log?: boolean;
- /** smoothing time constant (s) */
- smooth?: number;
- /** "pitch" params follow the keyboard */
- role?: "pitch";
- /** decimals for display */
- digits?: number;
-}
-
-export interface CallKey {
- t: number;
- v: Record<string, number>;
- /** interpolation from the previous key: linear (default), exponential (for frequencies), or step */
- curve?: "lin" | "exp" | "step";
-}
-
-export interface CallDef {
- id: string;
- name: string;
- hint: string;
- keys: CallKey[];
- /** pitch params in the call are scaled by playedPitch / pitchRef when triggered from the keys */
- pitchRef?: number;
-}
-
-export interface CreatureVisual {
- /** body outline in drawing units (≈ cm; y up) */
- silhouette: [number, number][];
- /** extra shapes drawn in tissue tones (shade 0 black … 1 white) */
- parts?: { shade: number; pts: [number, number][]; stroke?: boolean }[];
- /** airway centrelines per tube name (tube nodes are distributed along the path); inView: false
- * keeps the label out of the cross-section (it still names the tube's lane) */
- tubes: { tube: string; path: [number, number][]; label?: string; inView?: boolean }[];
- /** how much wider than life to draw the airway (narrow tubes stay legible) */
- tubeScale?: number;
- /** drawing extents */
- view: { x0: number; x1: number; y0: number; y1: number };
- /** sound sources to draw, keyed into CreatureSim.sourceState() */
- sources?: { key: string; at: [number, number]; label: string }[];
-}
-
-export interface CreatureSim {
- readonly net: AirwayNetwork | null;
- /** tubes exposed to telemetry/visuals, by name */
- readonly tubes: Record<string, Tube>;
- /** control-rate update with smoothed parameters; gate 0..1 is the breath */
- control(p: Record<string, number>, gate: number, dt: number): void;
- /** one internal sample → radiated output (arbitrary units) */
- sample(): number;
- /** fixed output normalisation */
- readonly gain: number;
- /** a few named source values for the source glyph (0..1) */
- sourceState?(): Record<string, number>;
- /** discrete events from calls (e.g. clicks, snaps) */
- trigger?(name: string, amount: number): void;
-}
-
-export interface CreatureDef {
- id: string;
- name: string;
- latin: string;
- group: CreatureGroup;
- /** how it makes sound, one sentence */
- blurb: string;
- /** musical role in a track */
- role: string;
- /** internal oversampling factor relative to the output rate */
- oversample: number;
- /** breath gate attack/release time constants (s) */
- gateTimes?: { attack: number; release: number };
- params: ParamDef[];
- calls: CallDef[];
- visual: CreatureVisual;
- create(fs: number): CreatureSim;
-}
diff --git a/src/engine/creatures/voice.ts b/src/engine/creatures/voice.ts
deleted file mode 100644
index 4b762fe..0000000
--- a/src/engine/creatures/voice.ts
+++ /dev/null
@@ -1,260 +0,0 @@
-/**
- * Generic runtime for non-human creatures: parameter smoothing, breath gate, call playback
- * (keyframed automation), control-rate scheduling, oversampled simulation, decimation, DC block,
- * limiter and fixed-size telemetry. Runs in the AudioWorklet and in Bun.
- */
-import type { CreatureDef, CreatureSim, CallDef } from "./types.ts";
-import { Decimator } from "../airway/decimator.ts";
-
-export interface CreatureTelemetry {
- kind: "creature";
- id: string;
- params: Record<string, number>;
- gate: number;
- outRms: number;
- clock: number;
- /** per tube: areas (cm²) and acoustic pressure RMS (dyn/cm², static pressure removed) per node */
- tubes: Record<string, { areas: Float32Array; rms: Float32Array }>;
- source: Record<string, number>;
- call: string | null;
-}
-
-interface ActiveCall {
- def: CallDef;
- t0: number;
- pitch: number;
- amp: number;
- fired: Set<number>;
- /** params the call automates (restored to the performer's values when it ends) */
- owns: Set<string>;
- /** every key the call mentions, including "gate" and "!events" */
- names: string[];
-}
-
-export class CreatureVoice {
- readonly def: CreatureDef;
- readonly fsOut: number;
- readonly fs: number;
- readonly M: number;
- readonly sim: CreatureSim;
- /** performer settings, targets (performer or call automation) and smoothed values */
- readonly performer: Record<string, number> = {};
- readonly target: Record<string, number> = {};
- readonly value: Record<string, number> = {};
- gate = 0;
- private gateTarget = 0;
- private callGate = 0;
- clock = 0;
- private call: ActiveCall | null = null;
- private readonly dec: Decimator;
- private readonly ctrlEvery: number;
- private ctrlCounter = 0;
- private dcX = 0;
- private dcY = 0;
- private readonly dcCoef: number;
- private outAcc = 0;
- private outCount = 0;
- private readonly rmsAcc: Record<string, Float64Array> = {};
- private readonly meanAcc: Record<string, Float64Array> = {};
- private rmsCount = 0;
- private sub = 0;
- /** master trim (performer) */
- level = 1;
-
- constructor(def: CreatureDef, fsOut: number, initial?: Record<string, number>) {
- this.def = def;
- this.fsOut = fsOut;
- this.M = Math.max(1, Math.round(def.oversample * (fsOut > 60000 ? 0.5 : 1)));
- this.fs = fsOut * this.M;
- this.sim = def.create(this.fs);
- this.dec = new Decimator(this.M);
- this.ctrlEvery = 64 * this.M;
- this.dcCoef = Math.exp((-2 * Math.PI * 12) / fsOut);
- for (const p of def.params) {
- const x = initial?.[p.key];
- this.performer[p.key] = this.target[p.key] = this.value[p.key] = x !== undefined && Number.isFinite(x) ? Math.min(p.max, Math.max(p.min, x)) : p.default;
- }
- for (const [name, t] of Object.entries(this.sim.tubes)) {
- this.rmsAcc[name] = new Float64Array(t.n);
- this.meanAcc[name] = new Float64Array(t.n);
- }
- this.sim.control(this.value, 0, this.ctrlEvery / this.fs);
- this.sim.net?.snapToTargets();
- }
-
- setParams(v: Record<string, number>): void {
- for (const [k, x] of Object.entries(v)) {
- const d = this.def.params.find((p) => p.key === k);
- if (!d || !Number.isFinite(x)) continue;
- const v = Math.min(d.max, Math.max(d.min, x));
- this.performer[k] = v;
- if (!this.call?.owns.has(k)) this.target[k] = v;
- }
- }
-
- setGate(level: number): void {
- this.gateTarget = Math.max(0, Math.min(1.5, level));
- }
-
- /** Play a call; pitch scales the call's pitch params relative to its reference. */
- playCall(id: string, pitch?: number, amp = 1): void {
- const def = this.def.calls.find((c) => c.id === id);
- if (!def) return;
- const ref = def.pitchRef ?? 0;
- this.endCall();
- const owns = new Set<string>();
- const names = new Set<string>();
- for (const k of def.keys)
- for (const n of Object.keys(k.v)) {
- names.add(n);
- if (n !== "gate" && !n.startsWith("!")) owns.add(n);
- }
- this.call = { def, t0: this.clock, pitch: pitch && ref ? pitch / ref : 1, amp, fired: new Set(), owns, names: [...names] };
- }
-
- stopCall(): void {
- this.endCall();
- }
-
- /** End the active call and hand its parameters back to the performer. */
- private endCall(): void {
- if (this.call) for (const n of this.call.owns) this.target[n] = this.performer[n];
- this.call = null;
- this.callGate = 0;
- }
-
- get activeCall(): string | null {
- return this.call?.def.id ?? null;
- }
-
- /** Evaluate the active call's automation at the current clock (writes into targets). */
- private evalCall(): void {
- const c = this.call;
- if (!c) return;
- const t = this.clock - c.t0;
- const keys = c.def.keys;
- const last = keys[keys.length - 1];
- if (t > last.t + 0.05) {
- this.endCall();
- return;
- }
- for (const n of c.names) {
- // find surrounding keys that define n
- let prev: { t: number; x: number } | null = null, next: { t: number; x: number; curve?: string } | null = null;
- for (const k of keys) {
- if (!(n in k.v)) continue;
- if (k.t <= t) prev = { t: k.t, x: k.v[n] };
- else {
- next = { t: k.t, x: k.v[n], curve: k.curve };
- break;
- }
- }
- if (!prev) continue;
- let x = prev.x;
- if (next && next.curve !== "step") {
- const u = (t - prev.t) / Math.max(1e-6, next.t - prev.t);
- if (next.curve === "exp" && prev.x > 0 && next.x > 0) x = prev.x * Math.pow(next.x / prev.x, u);
- else x = prev.x + (next.x - prev.x) * u;
- }
- if (n === "gate") {
- this.callGate = x * c.amp;
- continue;
- }
- if (n.startsWith("!")) {
- // events: "!click" etc. fire once when crossing the key time with value = amount
- continue;
- }
- const d = this.def.params.find((p) => p.key === n);
- if (!d) continue;
- if (d.role === "pitch") x *= c.pitch;
- this.target[n] = Math.min(d.max, Math.max(d.min, x));
- }
- // one-shot events
- keys.forEach((k, i) => {
- if (k.t > t || c.fired.has(i)) return;
- for (const [n, amount] of Object.entries(k.v)) if (n.startsWith("!")) this.sim.trigger?.(n.slice(1), amount * c.amp);
- c.fired.add(i);
- });
- }
-
- private control(): void {
- const dt = this.ctrlEvery / this.fs;
- this.evalCall();
- for (const p of this.def.params) {
- const tau = p.smooth ?? 0.03;
- const a = 1 - Math.exp(-dt / Math.max(0.001, tau));
- const cur = this.value[p.key], tgt = this.target[p.key];
- this.value[p.key] = p.log && cur > 0 && tgt > 0 ? cur * Math.pow(tgt / cur, a) : cur + (tgt - cur) * a;
- }
- const goal = Math.max(this.gateTarget, this.callGate);
- const gt = this.def.gateTimes ?? { attack: 0.012, release: 0.06 };
- const tau = goal > this.gate ? gt.attack : gt.release;
- this.gate += (goal - this.gate) * (1 - Math.exp(-dt / tau));
- this.sim.control(this.value, this.gate, dt);
- this.sim.net?.beginBlock(this.ctrlEvery);
- this.ctrlCounter = this.ctrlEvery;
- this.clock += dt;
- }
-
- render(out: Float32Array, offset: number, n: number): void {
- const M = this.M;
- const gain = this.sim.gain * this.level;
- const tubes = Object.entries(this.sim.tubes);
- for (let i = 0; i < n; i++) {
- for (let m = 0; m < M; m++) {
- if (this.ctrlCounter <= 0) this.control();
- this.ctrlCounter--;
- const y = this.sim.sample();
- if ((++this.sub & 7) === 0 && this.sim.net) {
- const p = this.sim.net.p;
- for (const [name, t] of tubes) {
- const acc = this.rmsAcc[name], mean = this.meanAcc[name];
- for (let k = 0; k < t.n; k++) {
- const v = p[t.first + k];
- acc[k] += v * v;
- mean[k] += v;
- }
- }
- this.rmsCount++;
- }
- if (this.dec.push(y)) {
- let v = this.dec.value * gain;
- const hp = v - this.dcX + this.dcCoef * this.dcY;
- this.dcX = v;
- this.dcY = hp;
- v = hp;
- const av = Math.abs(v);
- if (av > 0.7) v = Math.sign(v) * (0.7 + 0.3 * Math.tanh((av - 0.7) / 0.3));
- if (!Number.isFinite(v)) v = 0;
- out[offset + i] = v;
- this.outAcc += v * v;
- this.outCount++;
- }
- }
- }
- }
-
- telemetry(): CreatureTelemetry {
- const tubes: CreatureTelemetry["tubes"] = {};
- const c = Math.max(1, this.rmsCount);
- for (const [name, t] of Object.entries(this.sim.tubes)) {
- const areas = new Float32Array(t.n);
- const rms = new Float32Array(t.n);
- const net = this.sim.net!;
- const acc = this.rmsAcc[name], mean = this.meanAcc[name];
- for (let k = 0; k < t.n; k++) {
- areas[k] = net.area[t.first + k];
- const m = mean[k] / c;
- rms[k] = Math.sqrt(Math.max(0, acc[k] / c - m * m));
- }
- acc.fill(0);
- mean.fill(0);
- tubes[name] = { areas, rms };
- }
- this.rmsCount = 0;
- const outRms = Math.sqrt(this.outAcc / Math.max(1, this.outCount));
- this.outAcc = 0;
- this.outCount = 0;
- return { kind: "creature", id: this.def.id, params: { ...this.value }, gate: this.gate, outRms, clock: this.clock, tubes, source: this.sim.sourceState?.() ?? {}, call: this.activeCall };
- }
-}
diff --git a/src/engine/phonetics/beatbox.ts b/src/engine/phonetics/beatbox.ts
deleted file mode 100644
index aea50fd..0000000
--- a/src/engine/phonetics/beatbox.ts
+++ /dev/null
@@ -1,293 +0,0 @@
-/**
- * A physically modelled beatboxer. Each drum sound is a short gestural score on the human vocal
- * tract, made with the airstream mechanisms beatboxers actually use:
- * - pulmonic: breath from the lungs (snares, hats, crash)
- * - glottalic (ejective): the glottis sealed, the larynx rises like a piston and compresses the
- * air behind an oral closure (kick, rimshot): punchy, dry, no breath noise
- * - velaric (click): the tongue seals a pocket against the palate and hollows it; the release
- * pops inward (tongue click, lip pop)
- * - ingressive: breath drawn in through a constriction (inward K snare)
- * - voiced: a hummed bass through the nose
- * One throat makes one sound at a time, so patterns are monophonic like a real beatboxer's.
- * Symbols follow Standard Beatbox Notation where it has one.
- */
-import type { Gesture } from "../control/score.ts";
-import type { HumanArtic } from "../anatomy/human.ts";
-import { phoneme } from "./inventory.ts";
-import { oralGestures, vowelArtic } from "./planner.ts";
-
-/** A beatboxer's ready posture: jaw nearly closed, lips just apart, tongue relaxed. */
-export function beatReady(body: string): Partial<HumanArtic> {
- // with the jaw nearly closed the tongue rests a little higher than in a spoken schwa; the
- // velar hits need it there: from lower, the release peels open and loses its punch
- const schwa = vowelArtic("ə", body) ?? {};
- return { ...schwa, tbY: (schwa.tbY ?? 6.85) + 0.1, jaw: 0.4, lipAp: 0.25, lipProt: 0.1 };
-}
-
-export type BeatRole = "kick" | "snare" | "hat" | "perc" | "bass";
-export type Airstream = "pulmonic" | "ejective" | "click" | "ingressive" | "voiced";
-
-export interface BeatBuild {
- /** hum pitch (Hz) */
- f0: number;
- /** how long the sound may last (s): its step length, for sustained sounds */
- len: number;
- /** loudness 0.5..1.5 */
- accent: number;
-}
-
-export interface BeatSound {
- /** pattern symbol */
- id: string;
- name: string;
- role: BeatRole;
- airstream: Airstream;
- hint: string;
- /**
- * Gestures with the acoustic hit at t = 0. `latency` (s) is the measured delay from the
- * planned hit to the acoustic onset; the sequencer schedules that much earlier.
- */
- build(body: string, o: BeatBuild): Gesture[];
- latency: number;
-}
-
-const oral = (body: string, ipa: string, a: number, b: number, speed: number, label: string, extra: Record<string, number> = {}): Gesture[] => {
- const d = phoneme(ipa, body);
- if (!d) return [];
- return oralGestures(d, { ...d.targets, ...extra }, a, b, speed, label);
-};
-
-const g = (t0: number, t1: number, rampIn: number, rampOut: number, strength: number, targets: Gesture["targets"], label: string, speed?: number): Gesture => ({ t0, t1, rampIn, rampOut, strength, targets, label, speed });
-
-/** Beatboxers snap their releases: faster than speech, and the heavy dorsum is no exception. */
-const snap = (gs: Gesture[], speed = 3.5, rampOut = 0.01): Gesture[] => {
- for (const x of gs) if (x.strength >= 40) {
- x.speed = speed;
- x.rampOut = rampOut;
- }
- return gs;
-};
-
-/**
- * A release fricative that starts only after the burst: with the planner's 30 ms ramp it would
- * grip the articulators while the closure is still held and pry it open early.
- */
-const after = (gs: Gesture[], rampIn = 0.008): Gesture[] => {
- for (const x of gs) x.rampIn = Math.min(x.rampIn, rampIn);
- return gs;
-};
-
-/** Glottalic piston: glottis sealed through the closure, larynx raised just before release. */
-const ejective = (a: number, accent: number, label: string): Gesture[] => [
- g(a - 0.012, 0.03, 0.012, 0.03, 8, { closure: 1 }, label),
- g(-0.05, 0.004, 0.03, 0.08, 40, { larynx: Math.min(1.6, 1.25 + 0.3 * accent) }, label, 3),
-];
-
-/**
- * Lung pressure (× the performer's breath pressure) over [a, b], with the glottis held open
- * until the breath has gone (otherwise the folds start to vibrate on the leftover pressure).
- */
-const blow = (a: number, b: number, level: number, abduction: number, label: string, tail = 0.03): Gesture[] => [
- g(a, b + tail + 0.02, 0.02, 0.03, 6, { abduction }, label),
- g(a - 0.01, b, 0.02, tail, 1, { breath: level }, label),
-];
-
-export const BEAT_SOUNDS: BeatSound[] = [
- {
- id: "B",
- name: "Kick",
- role: "kick",
- airstream: "ejective",
- hint: "Lips burst on air the rising larynx compresses",
- latency: 0.01,
- build: (body, o) => [...snap(oral(body, "p", -0.075, 0, 2, "B", { jaw: 0.3 })), ...ejective(-0.075, o.accent, "B")],
- },
- {
- id: "t",
- name: "Hi-hat",
- role: "hat",
- airstream: "pulmonic",
- hint: "Tongue-tip release into a short hiss",
- latency: -0.005,
- build: (body, o) => [...snap(oral(body, "t", -0.05, 0, 2, "t", { jaw: 0.3 })), ...after(oral(body, "s", 0.012, 0.03, 1.6, "t")), ...blow(-0.03, 0.026, 1.25 * o.accent, 0.36, "t", 0.02)],
- },
- {
- id: "tss",
- name: "Open hat",
- role: "hat",
- airstream: "pulmonic",
- hint: "The hi-hat left ringing as a long hiss",
- latency: -0.005,
- build: (body, o) => {
- const end = Math.max(0.09, Math.min(0.26, o.len * 1.6));
- return [...snap(oral(body, "t", -0.05, 0, 2, "tss", { jaw: 0.3 })), ...after(oral(body, "s", 0.012, end, 1.4, "tss")), ...blow(-0.03, end, 1.2 * o.accent, 0.4, "tss", 0.09)];
- },
- },
- {
- id: "Pf",
- name: "Snare",
- role: "snare",
- airstream: "pulmonic",
- hint: "Lips burst, then the lower lip hisses against the teeth",
- latency: 0.018,
- build: (body, o) => [...snap(oral(body, "p", -0.06, 0, 2, "Pf")), ...after(oral(body, "f", 0.018, 0.08, 1.6, "Pf")), ...blow(-0.045, 0.075, 1.7 * o.accent, 0.45, "Pf", 0.04)],
- },
- {
- id: "K",
- name: "Rimshot",
- role: "snare",
- airstream: "ejective",
- hint: "Back of the tongue bursts on larynx-compressed air",
- latency: -0.0165,
- build: (body, o) => [...snap(oral(body, "k", -0.08, 0, 2, "K", { jaw: 0.35 }), 4, 0.008), ...ejective(-0.08, o.accent, "K")],
- },
- {
- id: "^K",
- name: "Inward snare",
- role: "snare",
- airstream: "ingressive",
- hint: "A sharp breath in past the back of the tongue",
- latency: -0.014,
- build: (body, o) => [
- ...snap(oral(body, "k", -0.06, 0, 2, "^K", { jaw: 0.35 }), 4, 0.008),
- ...after(oral(body, "x", 0.012, 0.085, 1.4, "^K", { tbY: 7.35 })),
- g(-0.05, 0.085, 0.02, 0.04, 6, { abduction: 0.5 }, "^K"),
- // draw the breath in behind the closure so the release rushes inward
- g(-0.035, 0.085, 0.015, 0.05, 2, { breath: -1.7 * o.accent }, "^K"),
- ],
- },
- {
- id: "!",
- name: "Tongue click",
- role: "perc",
- airstream: "click",
- hint: "Tongue seals a pocket, hollows it and pops",
- latency: -0.007,
- build: (body) => [
- // the tip seals without the alveolar's fronted tongue body (that would close the pocket)
- ...snap(oral(body, "t", -0.12, 0, 2, "!")).filter((x) => x.targets.tbX === undefined),
- // the back seal sits low, leaving a pocket for the dorsum to hollow
- ...oral(body, "k", -0.12, 0.035, 2, "!", { tbY: 7.85, jaw: 0.4 }),
- g(-0.03, 0.006, 0.04, 0.03, 40, { dorsum: 1 }, "!", 2),
- ],
- },
- {
- id: "P!",
- name: "Lip pop",
- role: "perc",
- airstream: "click",
- hint: "Sealed lips, the jaw drops, the lips pop open",
- latency: -0.001,
- build: (body) => [
- // a light seal (pressing the lips squeezes the pocket before the suction starts)
- ...snap(oral(body, "p", -0.12, 0, 2, "P!", { lipAp: -0.08 }), 5, 0.006),
- ...oral(body, "k", -0.12, 0.03, 2, "P!"),
- // lips stay sealed while the jaw and tongue hollow the mouth: about −30 cmH₂O of suction
- g(-0.07, 0.004, 0.04, 0.05, 40, { jaw: 1.6, dorsum: 1 }, "P!", 2),
- ],
- },
- {
- id: "kch",
- name: "Crash",
- role: "hat",
- airstream: "pulmonic",
- hint: "Back-of-tongue release into a long rounded hiss",
- latency: -0.013,
- build: (body, o) => {
- const end = Math.max(0.14, Math.min(0.34, o.len * 2));
- // the "ch": the back of the tongue lingers by the velum after the burst ([x]) while the
- // blade rises into the long rounded [ʃ]
- return [...snap(oral(body, "k", -0.06, 0, 2, "kch"), 4, 0.008), ...after(oral(body, "x", 0.002, 0.045, 2, "kch")), ...after(oral(body, "ʃ", 0.025, end, 1.4, "kch")), ...blow(-0.035, end, 1.75 * o.accent, 0.45, "kch", 0.14)];
- },
- },
- {
- id: "m",
- name: "Hum",
- role: "bass",
- airstream: "voiced",
- hint: "Hummed bass note through the nose",
- latency: 0.0056,
- build: (body, o) => {
- const end = Math.max(0.06, o.len * 0.92);
- return [
- // lips shut before the voice starts, so the note begins as a hum rather than a vowel;
- // the folds stay apart (breathing) while the velum drops into the sealed mouth, so the
- // squeezed air goes to the lungs instead of popping out through the nose
- ...oral(body, "m", -0.03, end, 1.6, "m"),
- g(-0.02, end, 0.03, 0.03, 4, { velum: 0.9 }, "m"),
- g(-0.08, -0.03, 0.02, 0.02, 5, { abduction: 0.3 }, "m"),
- g(-0.01, end, 0.02, 0.04, 1, { breath: 0.95 * o.accent }, "m"),
- g(-0.02, end, 0.015, 0.02, 8, { f0: o.f0 }, "m"),
- ];
- },
- },
-];
-
-const BY_ID = new Map(BEAT_SOUNDS.map((s) => [s.id, s]));
-export const beatSound = (id: string): BeatSound | undefined => BY_ID.get(id);
-
-/** One step of a pattern: a sound (null = rest), optional MIDI note for pitched sounds. */
-export interface BeatStep {
- id: string;
- note?: number;
- accent?: number;
-}
-
-/** Default hum note (MIDI E2) */
-export const BASS_NOTE = 40;
-
-/**
- * Parse a beat written as text: tokens separated by spaces or "|" (bar lines, ignored);
- * "." or "-" is a rest; a hum may carry a MIDI note ("m:43"); a trailing ">" accents.
- */
-export function parseBeat(text: string): (BeatStep | null)[] {
- const out: (BeatStep | null)[] = [];
- for (const raw of text.split(/[\s|]+/)) {
- if (!raw) continue;
- if (raw === "." || raw === "-") {
- out.push(null);
- continue;
- }
- let tok = raw;
- let accent: number | undefined;
- if (tok.endsWith(">")) {
- accent = 1.3;
- tok = tok.slice(0, -1);
- }
- let note: number | undefined;
- const m = /^(.+?):(\d+)$/.exec(tok);
- if (m) {
- tok = m[1];
- note = Number(m[2]);
- }
- const s = BY_ID.get(tok) ?? BEAT_SOUNDS.find((x) => x.id.toLowerCase() === tok.toLowerCase());
- if (s) out.push({ id: s.id, ...(note !== undefined ? { note } : {}), ...(accent ? { accent } : {}) });
- else out.push(null);
- }
- return out;
-}
-
-/** Inverse of parseBeat: four steps per group, groups separated by spaces. */
-export function formatBeat(steps: (BeatStep | null)[]): string {
- const toks = steps.map((s) => (s ? `${s.id}${s.note !== undefined ? `:${s.note}` : ""}${s.accent && s.accent > 1 ? ">" : ""}` : "."));
- const groups: string[] = [];
- for (let i = 0; i < toks.length; i += 4) groups.push(toks.slice(i, i + 4).join(" "));
- return groups.join(" | ");
-}
-
-export interface BeatPreset {
- name: string;
- bpm: number;
- swing: number;
- text: string;
-}
-
-export const BEAT_PRESETS: BeatPreset[] = [
- { name: "Boots and cats", bpm: 96, swing: 0, text: "B . t . | Pf . t . | B . t . | Pf . t ." },
- { name: "Four on the floor", bpm: 122, swing: 0, text: "B . t . | B . tss . | B . t . | B . tss ." },
- { name: "Breakbeat", bpm: 94, swing: 0.18, text: "B . t . | Pf . t B | . B t . | Pf . t t" },
- { name: "Rimshot shuffle", bpm: 88, swing: 0.4, text: "B . t K | . t B . | t . K t | . B K t" },
- { name: "Inward snare", bpm: 100, swing: 0, text: "B . t . | ^K . t . | B B t . | ^K . t ." },
- { name: "Clicks and pops", bpm: 90, swing: 0.25, text: "B . ! . | P! . ! . | B ! . ! | P! . ! !" },
- { name: "Hum bass", bpm: 92, swing: 0.1, text: "B m . m:43 | Pf . m:45 . | B m:40 . m | Pf . t kch" },
-];
diff --git a/src/engine/phonetics/consonantTargets.generated.json b/src/engine/phonetics/consonantTargets.generated.json
deleted file mode 100644
index f5e7bbf..0000000
--- a/src/engine/phonetics/consonantTargets.generated.json
+++ /dev/null
@@ -1,188 +0,0 @@
-{
- "male": {
- "ɸ": {
- "lipAp": 0.032
- },
- "β": {
- "lipAp": 0.04
- },
- "f": {
- "lipAp": 0.016
- },
- "v": {
- "lipAp": 0.031
- },
- "θ": {
- "ttY": 8.228
- },
- "ð": {
- "ttY": 8.19
- },
- "s": {
- "ttY": 9.111
- },
- "z": {
- "ttY": 9.097
- },
- "ʃ": {
- "ttY": 9.513
- },
- "ʒ": {
- "ttY": 9.496
- },
- "ʂ": {
- "ttY": 9.73
- },
- "ʐ": {
- "ttY": 9.718
- },
- "ç": {
- "tbY": 7.93
- },
- "ʝ": {
- "tbY": 7.918
- },
- "x": {
- "tbY": 7.364
- },
- "ɣ": {
- "tbY": 7.351
- },
- "χ": {
- "tbY": 7.06
- },
- "ʁ": {
- "tbY": 7.048
- },
- "ħ": {
- "tbX": 1.248
- },
- "ʕ": {
- "tbX": 1.285
- }
- },
- "female": {
- "ɸ": {
- "lipAp": 0.033
- },
- "β": {
- "lipAp": 0.042
- },
- "f": {
- "lipAp": 0.013
- },
- "v": {
- "lipAp": 0.028
- },
- "θ": {
- "ttY": 8.244
- },
- "ð": {
- "ttY": 8.209
- },
- "s": {
- "ttY": 9.117
- },
- "z": {
- "ttY": 9.104
- },
- "ʃ": {
- "ttY": 9.522
- },
- "ʒ": {
- "ttY": 9.506
- },
- "ʂ": {
- "ttY": 9.738
- },
- "ʐ": {
- "ttY": 9.727
- },
- "ç": {
- "tbY": 7.985
- },
- "ʝ": {
- "tbY": 7.973
- },
- "x": {
- "tbY": 7.428
- },
- "ɣ": {
- "tbY": 7.416
- },
- "χ": {
- "tbY": 7.12
- },
- "ʁ": {
- "tbY": 7.109
- },
- "ħ": {
- "tbX": 1.186
- },
- "ʕ": {
- "tbX": 1.22
- }
- },
- "child": {
- "ɸ": {
- "lipAp": 0.045
- },
- "β": {
- "lipAp": 0.056
- },
- "f": {
- "lipAp": 0.008
- },
- "v": {
- "lipAp": 0.022
- },
- "θ": {
- "ttY": 8.272
- },
- "ð": {
- "ttY": 8.245
- },
- "s": {
- "ttY": 9.126
- },
- "z": {
- "ttY": 9.114
- },
- "ʃ": {
- "ttY": 9.538
- },
- "ʒ": {
- "ttY": 9.525
- },
- "ʂ": {
- "ttY": 9.75
- },
- "ʐ": {
- "ttY": 9.739
- },
- "ç": {
- "tbY": 8.043
- },
- "ʝ": {
- "tbY": 8.032
- },
- "x": {
- "tbY": 7.5
- },
- "ɣ": {
- "tbY": 7.488
- },
- "χ": {
- "tbY": 7.186
- },
- "ʁ": {
- "tbY": 7.176
- },
- "ħ": {
- "tbX": 1.106
- },
- "ʕ": {
- "tbX": 1.138
- }
- }
-}
\ No newline at end of file
diff --git a/src/engine/phonetics/durations.ts b/src/engine/phonetics/durations.ts
deleted file mode 100644
index 2c6e309..0000000
--- a/src/engine/phonetics/durations.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-/**
- * Segment durations by the Klatt (1979) / MITalk rules (Allen, Hunnicutt & Klatt 1987, ch. 9):
- * DUR = MIN + (INH − MIN) · PRCNT
- * with PRCNT the product of context factors: phrase-final lengthening, non-final shortening,
- * non-word-final and polysyllabic shortening, unstressed shortening (MIN halved), the vowel
- * length cue of the following consonant (bat/bad), cluster shortening, and aspiration.
- * Inherent / minimum durations (ms) per phoneme follow Klatt's table.
- */
-import type { Segment } from "./planner.ts";
-
-const T: Record<string, [number, number]> = {
- // vowels
- i: [155, 55], ɪ: [135, 40], e: [190, 70], eɪ: [190, 70], ɛ: [150, 70], æ: [230, 80], a: [230, 80], ɑ: [240, 100], ɒ: [240, 100],
- ɔ: [240, 100], o: [220, 80], oʊ: [220, 80], ʊ: [160, 60], u: [210, 70], ʌ: [140, 60], ə: [120, 60], ɚ: [180, 80], ɝ: [180, 80],
- aɪ: [250, 150], aʊ: [240, 100], ɔɪ: [280, 150], ɨ: [110, 40],
- // consonants
- p: [85, 50], t: [75, 50], k: [80, 60], b: [85, 60], d: [75, 50], g: [80, 60], ʔ: [40, 30],
- tʃ: [70, 50], dʒ: [50, 30],
- f: [100, 80], v: [60, 40], θ: [90, 60], ð: [50, 30], s: [105, 60], z: [75, 40], ʃ: [105, 80], ʒ: [70, 40], h: [80, 20],
- m: [70, 60], n: [60, 50], ŋ: [95, 45], l: [80, 40], ɫ: [80, 40], ɹ: [80, 30], w: [80, 60], j: [80, 40], ɾ: [20, 20],
-};
-
-export interface SegInfo {
- vowel: boolean;
- manner?: string;
- voiced?: boolean;
- /** fallback inherent duration (s) for phonemes outside the table */
- dur?: number;
-}
-
-/** Durations (s) for one phrase of segments (explicit `dur` values are kept). */
-export function klattDurations(segs: Segment[], info: (s: Segment) => SegInfo): number[] {
- const n = segs.length;
- const inf = segs.map(info);
- // words: index ranges split after wordEnd
- const word = new Array<number>(n);
- const wordStart: number[] = [];
- let w = 0;
- for (let i = 0; i < n; i++) {
- if (i === 0 || segs[i - 1].wordEnd) wordStart.push(i);
- word[i] = wordStart.length - 1;
- if (segs[i].wordEnd) w++;
- }
- void w;
- const vowelsInWord = new Map<number, number>();
- for (let i = 0; i < n; i++) if (inf[i].vowel) vowelsInWord.set(word[i], (vowelsInWord.get(word[i]) ?? 0) + 1);
- let lastVowel = -1;
- for (let i = 0; i < n; i++) if (inf[i].vowel) lastVowel = i;
-
- return segs.map((s, i) => {
- if (s.dur !== undefined) return s.dur;
- const [inh0, min0] = T[s.ipa] ?? [1000 * (inf[i].dur ?? 0.08), 600 * (inf[i].dur ?? 0.08)];
- let inh = inh0, min = min0, p = 1;
- if (inf[i].vowel) {
- const stress = s.stress ?? 0;
- const finalSyl = i === lastVowel;
- let wordFinalSyl = true;
- for (let k = i + 1; k < n && word[k] === word[i]; k++) if (inf[k].vowel) wordFinalSyl = false;
- if (finalSyl) p *= 1.4; // clause-final lengthening
- else p *= 0.6; // non-phrase-final shortening
- if (!wordFinalSyl) p *= 0.85; // non-word-final shortening
- if ((vowelsInWord.get(word[i]) ?? 1) > 1) p *= 0.8; // polysyllabic shortening
- if (stress === 0) {
- min *= 0.5; // unstressed: minimum halved, shortened
- p *= 0.7;
- }
- // the following consonant (same word): voiced fricatives lengthen, voiceless stops shorten
- const nx = i + 1 < n && word[i + 1] === word[i] && !inf[i + 1].vowel ? inf[i + 1] : null;
- if (nx) {
- let f = 1;
- if (nx.manner === "fricative") f = nx.voiced ? 1.6 : 1;
- else if (nx.manner === "stop" || nx.manner === "affricate") f = nx.voiced ? 1.2 : 0.7;
- else if (nx.manner === "nasal") f = 0.85;
- p *= finalSyl ? f : 0.7 + 0.3 * f;
- }
- // vowel next to vowel
- if (i + 1 < n && inf[i + 1].vowel) p *= 1.2;
- if (i > 0 && inf[i - 1].vowel) p *= 0.7;
- let d = min + (inh - min) * p;
- // aspiration after a voiceless stop eats into a stressed vowel's onset: give it back
- const pv = i > 0 ? inf[i - 1] : null;
- if (stress > 0 && pv && pv.manner === "stop" && !pv.voiced) d += 20;
- return d / 1000;
- }
- // consonants
- const wordInitial = i === wordStart[word[i]];
- if (i > lastVowel && (inf[i].manner === "nasal" || inf[i].manner === "lateral" || inf[i].manner === "approximant")) p *= 1.4;
- if (!wordInitial) p *= 0.85;
- const prevC = i > 0 && !inf[i - 1].vowel;
- const nextC = i + 1 < n && !inf[i + 1].vowel;
- if (prevC && nextC) p *= 0.5;
- else if (prevC || nextC) p *= 0.7;
- return (min + (inh - min) * p) / 1000;
- });
-}
diff --git a/src/engine/phonetics/english.ts b/src/engine/phonetics/english.ts
deleted file mode 100644
index 400831e..0000000
--- a/src/engine/phonetics/english.ts
+++ /dev/null
@@ -1,247 +0,0 @@
-/**
- * English text → phoneme segments: CMUdict (ARPAbet with stress) when loaded, letter-to-sound
- * rules otherwise; American flapping and dark /l/; numbers spelled out; punctuation → phrase
- * breaks and intonation.
- */
-import type { Segment } from "./planner.ts";
-
-const ARPA: Record<string, string> = {
- AA: "ɑ", AE: "æ", AH: "ʌ", AO: "ɔ", AW: "aʊ", AY: "aɪ", EH: "ɛ", ER: "ɝ", EY: "eɪ", IH: "ɪ", IY: "i", OW: "oʊ", OY: "ɔɪ", UH: "ʊ", UW: "u",
- B: "b", CH: "tʃ", D: "d", DH: "ð", F: "f", G: "g", HH: "h", JH: "dʒ", K: "k", L: "l", M: "m", N: "n", NG: "ŋ", P: "p", R: "ɹ", S: "s", SH: "ʃ", T: "t", TH: "θ", V: "v", W: "w", Y: "j", Z: "z", ZH: "ʒ",
-};
-const VOWELS = new Set(["ɑ", "æ", "ʌ", "ə", "ɔ", "aʊ", "aɪ", "ɛ", "ɝ", "ɚ", "eɪ", "ɪ", "i", "oʊ", "ɔɪ", "ʊ", "u"]);
-/**
- * The dictionary keeps one pronunciation per word; for these homographs it kept the rarer one
- * (the verb "wind", past-tense "read"). Telling them apart needs grammar; the common reading wins.
- */
-const HOMOGRAPHS = new Map<string, string>([
- ["wind", "W IH1 N D"],
- ["read", "R IY1 D"],
- ["live", "L IH1 V"],
- ["lead", "L IY1 D"],
- ["close", "K L OW1 Z"],
- ["wound", "W UW1 N D"],
-]);
-
-/** monosyllabic function words are unstressed in running speech (and reduce) */
-const FUNCTION_WORDS = new Set("a an the of to in on at by for from with as and or but nor so if is am are was were be been do does did has have had will would can could should shall may might must it its i you he she we they me him her us them my your his our their this that than then there not no".split(" "));
-const REDUCE: Record<string, string> = { ʌ: "ə", æ: "ə", ɑ: "ə", ɛ: "ə", ɔ: "ə", u: "ə", ʊ: "ə" };
-
-export interface Phrase {
- segments: Segment[];
- intonation: "statement" | "question";
- /** pause after the phrase (s) */
- pause: number;
- words: string[];
-}
-
-export class EnglishG2P {
- private dict: Map<string, string> | null = null;
- private loading: Promise<void> | null = null;
-
- get loaded(): boolean {
- return !!this.dict;
- }
-
- /** Load the gzipped dictionary ("word\tPHONES" lines). Browser: fetch + DecompressionStream. */
- load(url = "/data/cmudict.txt.gz"): Promise<void> {
- if (this.dict) return Promise.resolve();
- if (this.loading) return this.loading;
- this.loading = (async () => {
- try {
- const res = await fetch(url);
- if (!res.ok) throw new Error(`dictionary ${res.status}`);
- const bytes = new Uint8Array(await res.arrayBuffer());
- // servers differ: some send Content-Encoding: gzip (already inflated by the browser)
- let text: string;
- if (bytes[0] === 0x1f && bytes[1] === 0x8b) {
- const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
- text = await new Response(stream).text();
- } else text = new TextDecoder().decode(bytes);
- this.setDictionaryText(text);
- } catch (e) {
- this.loading = null; // allow a retry
- throw e;
- }
- })();
- return this.loading;
- }
-
- setDictionaryText(text: string): void {
- const m = new Map<string, string>();
- for (const line of text.split("\n")) {
- const tab = line.indexOf("\t");
- if (tab > 0) m.set(line.slice(0, tab), line.slice(tab + 1));
- }
- this.dict = m;
- }
-
- /** Text → phrases of segments. */
- toPhrases(text: string): Phrase[] {
- const phrases: Phrase[] = [];
- const normalized = expandNumbers(text.replace(/[’']/g, "'"));
- // split on phrase punctuation, keeping the delimiter
- const parts = normalized.split(/([.!?;:,]+)/);
- let words: string[] = [];
- const flush = (delim: string) => {
- if (!words.length) return;
- const segs: Segment[] = [];
- for (const w of words) {
- const ws = this.word(w);
- if (!ws.length) continue;
- ws[ws.length - 1].wordEnd = true;
- segs.push(...ws);
- }
- applyAllophones(segs);
- const q = delim.includes("?");
- const pause = /[.!?]/.test(delim) ? 0.35 : delim ? 0.18 : 0.3;
- if (segs.length) phrases.push({ segments: segs, intonation: q ? "question" : "statement", pause, words });
- words = [];
- };
- for (const part of parts) {
- if (/^[.!?;:,]+$/.test(part)) flush(part);
- else words.push(...part.toLowerCase().split(/[^a-z'\-]+/).filter(Boolean));
- }
- flush("");
- return phrases;
- }
-
- /** One word → segments with lexical stress. `reduce`: weak forms of function words (speech). */
- word(w: string, reduce = true): Segment[] {
- const clean = w.toLowerCase().replace(/^'+|'+$/g, "");
- const entry = HOMOGRAPHS.get(clean) ?? this.dict?.get(clean);
- if (entry) {
- const segs = arpabetToSegments(entry);
- if (reduce && FUNCTION_WORDS.has(clean)) {
- const nv = segs.filter((s) => VOWELS.has(s.ipa)).length;
- for (const s of segs) {
- s.stress = 0;
- // short function words reduce toward schwa ("of" → əv, "and" → ənd), except /i ɪ eɪ aɪ oʊ/
- if (nv === 1 && REDUCE[s.ipa] && !["you", "do", "to", "who", "not", "no"].includes(clean)) s.ipa = REDUCE[s.ipa];
- }
- }
- return segs;
- }
- // hyphenated compounds
- if (clean.includes("-")) return clean.split("-").flatMap((p) => this.word(p, reduce));
- return letterToSound(clean);
- }
-}
-
-export function arpabetToSegments(phones: string): Segment[] {
- const out: Segment[] = [];
- for (const ph of phones.trim().split(/\s+/)) {
- const m = ph.match(/^([A-Z]+)([012])?$/);
- if (!m) continue;
- const base = m[1];
- const stress = m[2] === "1" ? 1 : m[2] === "2" ? 2 : 0;
- let ipa = ARPA[base];
- if (!ipa) continue;
- if (base === "AH" && stress === 0) ipa = "ə";
- if (base === "ER" && stress === 0) ipa = "ɚ";
- out.push({ ipa, stress: VOWELS.has(ipa) ? stress : 0 });
- }
- return out;
-}
-
-/** American English allophones: flapping and velarised coda /l/ (in place). */
-function applyAllophones(segs: Segment[]): void {
- for (let i = 1; i < segs.length - 1; i++) {
- const s = segs[i];
- const prev = segs[i - 1], next = segs[i + 1];
- const pv = VOWELS.has(prev.ipa) || prev.ipa === "ɹ";
- const nv = VOWELS.has(next.ipa);
- // /t d/ between a vowel and an unstressed vowel → tap ("water", "ladder", "got it"), but not
- // at the start of a word ("were disputing" keeps its /d/)
- if ((s.ipa === "t" || s.ipa === "d") && pv && nv && !next.stress && !prev.wordEnd) s.ipa = "ɾ";
- }
- for (let i = 0; i < segs.length; i++) {
- const s = segs[i];
- if (s.ipa !== "l") continue;
- const next = segs[i + 1];
- // coda /l/ (before a consonant, pause, or word end) is velarised
- if (!next || !VOWELS.has(next.ipa) || s.wordEnd) s.ipa = "ɫ";
- }
-}
-
-// ---------------------------------------------------------------- numbers
-const ONES = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"];
-const TENS = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"];
-function numberWords(n: number): string {
- if (n < 20) return ONES[n];
- if (n < 100) return TENS[Math.floor(n / 10)] + (n % 10 ? " " + ONES[n % 10] : "");
- if (n < 1000) return ONES[Math.floor(n / 100)] + " hundred" + (n % 100 ? " " + numberWords(n % 100) : "");
- if (n < 1e6) return numberWords(Math.floor(n / 1000)) + " thousand" + (n % 1000 ? " " + numberWords(n % 1000) : "");
- return n.toString().split("").map((d) => ONES[+d]).join(" ");
-}
-function expandNumbers(t: string): string {
- return t.replace(/\d+/g, (d) => " " + numberWords(parseInt(d, 10)) + " ");
-}
-
-// ---------------------------------------------------------------- letter-to-sound fallback
-/**
- * Compact rule set for words missing from the dictionary. Rules are tried longest-first at each
- * position; context classes: '#' word boundary, 'V' vowel letter, 'C' consonant letter.
- */
-type Rule = [pre: string, grapheme: string, post: string, phones: string];
-const RULES: Rule[] = [
- ["", "tion", "", "ʃ ə n"], ["", "sion", "", "ʒ ə n"], ["", "ture", "", "tʃ ɚ"], ["", "ough", "#", "oʊ"], ["", "augh", "", "ɔ"],
- ["", "igh", "", "aɪ"], ["", "eigh", "", "eɪ"], ["", "tch", "", "tʃ"], ["", "dge", "", "dʒ"], ["", "sch", "", "s k"],
- ["", "ch", "", "tʃ"], ["", "sh", "", "ʃ"], ["", "th", "", "θ"], ["", "ph", "", "f"], ["", "wh", "", "w"], ["", "ck", "", "k"],
- ["", "ng", "#", "ŋ"], ["", "ng", "", "ŋ g"], ["", "qu", "", "k w"], ["#", "kn", "", "n"], ["#", "wr", "", "ɹ"], ["", "gh", "", ""],
- ["", "ee", "", "i"], ["", "ea", "", "i"], ["", "oo", "", "u"], ["", "ou", "", "aʊ"], ["", "ow", "#", "oʊ"], ["", "ow", "", "aʊ"],
- ["", "oi", "", "ɔɪ"], ["", "oy", "", "ɔɪ"], ["", "ai", "", "eɪ"], ["", "ay", "", "eɪ"], ["", "au", "", "ɔ"], ["", "aw", "", "ɔ"],
- ["", "ie", "#", "aɪ"], ["", "ie", "", "i"], ["", "ei", "", "eɪ"], ["", "ey", "#", "i"], ["", "oa", "", "oʊ"], ["", "ue", "#", "u"],
- ["", "er", "#", "ɚ"], ["", "er", "C", "ɝ"], ["", "ir", "", "ɝ"], ["", "ur", "", "ɝ"], ["", "or", "", "ɔ ɹ"], ["", "ar", "", "ɑ ɹ"],
- ["", "le", "#", "ə ɫ"], ["", "ed", "#", "d"], ["", "es", "#", "z"], ["C", "s", "#", "s"], ["V", "s", "#", "z"], ["", "y", "#", "i"],
- ["#", "y", "", "j"], ["C", "y", "", "aɪ"], ["", "e", "#", ""],
- ["", "a", "CV", "eɪ"], ["", "a", "", "æ"], ["", "e", "", "ɛ"], ["", "i", "CV", "aɪ"], ["", "i", "", "ɪ"], ["", "o", "CV", "oʊ"],
- ["", "o", "", "ɑ"], ["", "u", "CV", "u"], ["", "u", "", "ʌ"], ["", "y", "", "ɪ"],
- ["", "c", "e", "s"], ["", "c", "i", "s"], ["", "c", "y", "s"], ["", "c", "", "k"], ["", "g", "e", "dʒ"], ["", "g", "i", "dʒ"], ["", "g", "", "g"],
- ["", "x", "", "k s"], ["", "j", "", "dʒ"], ["", "q", "", "k"], ["", "b", "", "b"], ["", "d", "", "d"], ["", "f", "", "f"], ["", "h", "", "h"],
- ["", "k", "", "k"], ["", "l", "", "l"], ["", "m", "", "m"], ["", "n", "", "n"], ["", "p", "", "p"], ["", "r", "", "ɹ"], ["", "s", "", "s"],
- ["", "t", "", "t"], ["", "v", "", "v"], ["", "w", "", "w"], ["", "z", "", "z"],
-];
-const isV = (ch: string | undefined) => !!ch && "aeiouy".includes(ch);
-function matchCtx(word: string, i: number, ctx: string, dir: 1 | -1): boolean {
- if (!ctx) return true;
- let pos = i;
- for (let k = 0; k < ctx.length; k++) {
- const c = dir === 1 ? ctx[k] : ctx[ctx.length - 1 - k];
- const ch = word[pos];
- if (c === "#") {
- if (ch !== undefined) return false;
- } else if (c === "V") {
- if (!isV(ch)) return false;
- } else if (c === "C") {
- if (!ch || isV(ch)) return false;
- } else if (ch !== c) return false;
- pos += dir;
- }
- return true;
-}
-export function letterToSound(word: string): Segment[] {
- const phones: string[] = [];
- let i = 0;
- while (i < word.length) {
- let done = false;
- for (const [pre, g, post, ph] of RULES) {
- if (!word.startsWith(g, i)) continue;
- if (!matchCtx(word, i - 1, pre, -1)) continue;
- if (!matchCtx(word, i + g.length, post, 1)) continue;
- if (ph) phones.push(...ph.split(" "));
- i += g.length;
- done = true;
- break;
- }
- if (!done) i++;
- }
- // stress the first vowel (crude but serviceable)
- let stressed = false;
- return phones.map((ipa) => {
- const v = VOWELS.has(ipa);
- const seg: Segment = { ipa, stress: v && !stressed ? 1 : 0 };
- if (v) stressed = true;
- return seg;
- });
-}
diff --git a/src/engine/phonetics/inventory.ts b/src/engine/phonetics/inventory.ts
deleted file mode 100644
index 7f4bb29..0000000
--- a/src/engine/phonetics/inventory.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-/**
- * Phoneme inventory (IPA) as articulatory specifications for the human model.
- * Coordinates are template-space (cm) and apply to every body (the anatomy scales them).
- * Fricative/approximant constriction heights are refined by tools/calibrate-consonants.ts
- * to hit target constriction areas; calibrated values override the defaults here.
- */
-import type { HumanArtic } from "../anatomy/human.ts";
-import type { ArticKey } from "../control/articulators.ts";
-import consonantCal from "./consonantTargets.generated.json";
-
-export type Manner = "vowel" | "stop" | "nasal" | "fricative" | "affricate" | "approximant" | "lateral" | "tap" | "trill" | "glottal";
-export type Voicing = "voiced" | "voiceless";
-
-export interface PhonemeDef {
- ipa: string;
- name: string;
- manner: Manner;
- voicing: Voicing;
- place: string;
- targets: Partial<HumanArtic>;
- /** articulators this segment controls strongly (others coarticulate with vowels) */
- dominant: ArticKey[];
- nasal?: boolean;
- /** default duration (s) */
- dur: number;
- /** target constriction area (cm², adult male) for calibration of the main coordinate */
- area?: number;
- /** which coordinate the calibration adjusts */
- calKey?: ArticKey;
- /** affricate: the fricative release */
- release?: string;
- /** glottal-only segments */
- glottal?: "open" | "stop" | "breathy";
-}
-
-const TIP: ArticKey[] = ["ttX", "ttY"];
-const BODY: ArticKey[] = ["tbX", "tbY"];
-const LIPS: ArticKey[] = ["lipAp"];
-
-function c(ipa: string, name: string, manner: Manner, voicing: Voicing, place: string, targets: Partial<HumanArtic>, dominant: ArticKey[], dur: number, extra: Partial<PhonemeDef> = {}): PhonemeDef {
- return { ipa, name, manner, voicing, place, targets, dominant, dur, ...extra };
-}
-
-// place templates
-const BILABIAL = { lipAp: -0.25 };
-const ALV_STOP = { ttX: 6.25, ttY: 9.68 };
-const DENT_STOP = { ttX: 6.85, ttY: 9.0 };
-const POSTALV_STOP = { ttX: 5.75, ttY: 10.0 };
-const RETRO_STOP = { ttX: 5.45, ttY: 10.05, ttCurl: 0.95 };
-const PAL_STOP = { tbX: 3.75, tbY: 8.45 };
-// velar closure: aimed past contact (the contact model caps penetration) so it seals wherever the
-// vowel puts the tongue body front–back, and the jaw rises part-way (open-vowel contexts leaked)
-const VEL_STOP = { tbX: 2.3, tbY: 8.35, jaw: 0.7 };
-const UVU_STOP = { tbX: 1.55, tbY: 7.6 };
-
-const BASE: PhonemeDef[] = [
- // stops
- c("p", "voiceless bilabial stop", "stop", "voiceless", "bilabial", BILABIAL, LIPS, 0.085),
- c("b", "voiced bilabial stop", "stop", "voiced", "bilabial", BILABIAL, LIPS, 0.07),
- c("t", "voiceless alveolar stop", "stop", "voiceless", "alveolar", ALV_STOP, TIP, 0.075),
- c("d", "voiced alveolar stop", "stop", "voiced", "alveolar", ALV_STOP, TIP, 0.06),
- c("ʈ", "voiceless retroflex stop", "stop", "voiceless", "retroflex", RETRO_STOP, [...TIP, "ttCurl"], 0.075),
- c("ɖ", "voiced retroflex stop", "stop", "voiced", "retroflex", RETRO_STOP, [...TIP, "ttCurl"], 0.065),
- c("c", "voiceless palatal stop", "stop", "voiceless", "palatal", PAL_STOP, BODY, 0.08),
- c("ɟ", "voiced palatal stop", "stop", "voiced", "palatal", PAL_STOP, BODY, 0.07),
- c("k", "voiceless velar stop", "stop", "voiceless", "velar", VEL_STOP, ["tbY"], 0.08),
- c("g", "voiced velar stop", "stop", "voiced", "velar", VEL_STOP, ["tbY"], 0.07),
- c("q", "voiceless uvular stop", "stop", "voiceless", "uvular", UVU_STOP, BODY, 0.085),
- c("ɢ", "voiced uvular stop", "stop", "voiced", "uvular", UVU_STOP, BODY, 0.075),
- c("ʔ", "glottal stop", "glottal", "voiceless", "glottal", {}, [], 0.06, { glottal: "stop" }),
- // nasals
- c("m", "bilabial nasal", "nasal", "voiced", "bilabial", BILABIAL, LIPS, 0.075, { nasal: true }),
- c("ɱ", "labiodental nasal", "nasal", "voiced", "labiodental", { labiodental: 1, lipAp: -0.1 }, ["labiodental", "lipAp"], 0.075, { nasal: true }),
- c("n", "alveolar nasal", "nasal", "voiced", "alveolar", ALV_STOP, TIP, 0.07, { nasal: true }),
- c("ɳ", "retroflex nasal", "nasal", "voiced", "retroflex", RETRO_STOP, [...TIP, "ttCurl"], 0.07, { nasal: true }),
- c("ɲ", "palatal nasal", "nasal", "voiced", "palatal", PAL_STOP, BODY, 0.075, { nasal: true }),
- c("ŋ", "velar nasal", "nasal", "voiced", "velar", VEL_STOP, ["tbY"], 0.08, { nasal: true }),
- c("ɴ", "uvular nasal", "nasal", "voiced", "uvular", UVU_STOP, BODY, 0.08, { nasal: true }),
- // fricatives
- c("ɸ", "voiceless bilabial fricative", "fricative", "voiceless", "bilabial", { lipAp: 0.08 }, LIPS, 0.11, { area: 0.12, calKey: "lipAp" }),
- c("β", "voiced bilabial fricative", "fricative", "voiced", "bilabial", { lipAp: 0.1 }, LIPS, 0.09, { area: 0.15, calKey: "lipAp" }),
- c("f", "voiceless labiodental fricative", "fricative", "voiceless", "labiodental", { labiodental: 1, lipAp: 0.05 }, ["labiodental", "lipAp"], 0.11, { area: 0.11, calKey: "lipAp" }),
- c("v", "voiced labiodental fricative", "fricative", "voiced", "labiodental", { labiodental: 1, lipAp: 0.06 }, ["labiodental", "lipAp"], 0.08, { area: 0.13, calKey: "lipAp" }),
- c("θ", "voiceless dental fricative", "fricative", "voiceless", "dental", { ttX: 6.85, ttY: 8.5 }, TIP, 0.11, { area: 0.15, calKey: "ttY" }),
- c("ð", "voiced dental fricative", "fricative", "voiced", "dental", { ttX: 6.85, ttY: 8.5 }, TIP, 0.07, { area: 0.17, calKey: "ttY" }),
- c("s", "voiceless alveolar fricative", "fricative", "voiceless", "alveolar", { ttX: 6.3, ttY: 9.15, jaw: 0.3 }, [...TIP, "jaw"], 0.12, { area: 0.085, calKey: "ttY" }),
- c("z", "voiced alveolar fricative", "fricative", "voiced", "alveolar", { ttX: 6.3, ttY: 9.15, jaw: 0.3 }, [...TIP, "jaw"], 0.09, { area: 0.1, calKey: "ttY" }),
- c("ʃ", "voiceless postalveolar fricative", "fricative", "voiceless", "postalveolar", { ttX: 5.7, ttY: 9.5, jaw: 0.35, lipProt: 0.75, lipWidth: 0.2 }, [...TIP, "jaw", "lipProt", "lipWidth"], 0.12, { area: 0.2, calKey: "ttY" }),
- c("ʒ", "voiced postalveolar fricative", "fricative", "voiced", "postalveolar", { ttX: 5.7, ttY: 9.5, jaw: 0.35, lipProt: 0.75, lipWidth: 0.2 }, [...TIP, "jaw", "lipProt", "lipWidth"], 0.09, { area: 0.22, calKey: "ttY" }),
- c("ʂ", "voiceless retroflex fricative", "fricative", "voiceless", "retroflex", { ttX: 5.45, ttY: 9.7, ttCurl: 0.9 }, [...TIP, "ttCurl"], 0.12, { area: 0.15, calKey: "ttY" }),
- c("ʐ", "voiced retroflex fricative", "fricative", "voiced", "retroflex", { ttX: 5.45, ttY: 9.7, ttCurl: 0.9 }, [...TIP, "ttCurl"], 0.09, { area: 0.17, calKey: "ttY" }),
- c("ç", "voiceless palatal fricative", "fricative", "voiceless", "palatal", { tbX: 3.75, tbY: 8.25 }, BODY, 0.12, { area: 0.14, calKey: "tbY" }),
- c("ʝ", "voiced palatal fricative", "fricative", "voiced", "palatal", { tbX: 3.75, tbY: 8.25 }, BODY, 0.09, { area: 0.16, calKey: "tbY" }),
- c("x", "voiceless velar fricative", "fricative", "voiceless", "velar", { tbX: 2.3, tbY: 7.7 }, ["tbY"], 0.12, { area: 0.18, calKey: "tbY" }),
- c("ɣ", "voiced velar fricative", "fricative", "voiced", "velar", { tbX: 2.3, tbY: 7.7 }, ["tbY"], 0.09, { area: 0.2, calKey: "tbY" }),
- c("χ", "voiceless uvular fricative", "fricative", "voiceless", "uvular", { tbX: 1.55, tbY: 7.6 }, BODY, 0.12, { area: 0.2, calKey: "tbY" }),
- c("ʁ", "voiced uvular fricative", "fricative", "voiced", "uvular", { tbX: 1.55, tbY: 7.6 }, BODY, 0.09, { area: 0.22, calKey: "tbY" }),
- c("ħ", "voiceless pharyngeal fricative", "fricative", "voiceless", "pharyngeal", { root: -0.95, tbX: 1.3, tbY: 6.2 }, ["root", "tbX", "tbY"], 0.12, { area: 0.25, calKey: "tbX" }),
- c("ʕ", "voiced pharyngeal fricative", "fricative", "voiced", "pharyngeal", { root: -0.95, tbX: 1.3, tbY: 6.2 }, ["root", "tbX", "tbY"], 0.09, { area: 0.3, calKey: "tbX" }),
- c("h", "voiceless glottal fricative", "glottal", "voiceless", "glottal", {}, [], 0.09, { glottal: "open" }),
- c("ɦ", "voiced glottal fricative", "glottal", "voiced", "glottal", {}, [], 0.08, { glottal: "breathy" }),
- c("ɬ", "voiceless lateral fricative", "fricative", "voiceless", "alveolar", { ...ALV_STOP, lateral: 0.35 }, [...TIP, "lateral"], 0.12),
- c("ɮ", "voiced lateral fricative", "fricative", "voiced", "alveolar", { ...ALV_STOP, lateral: 0.45 }, [...TIP, "lateral"], 0.09),
- // affricates
- c("ts", "voiceless alveolar affricate", "affricate", "voiceless", "alveolar", ALV_STOP, TIP, 0.14, { release: "s" }),
- c("dz", "voiced alveolar affricate", "affricate", "voiced", "alveolar", ALV_STOP, TIP, 0.12, { release: "z" }),
- c("tʃ", "voiceless postalveolar affricate", "affricate", "voiceless", "postalveolar", { ...POSTALV_STOP, lipProt: 0.75, lipWidth: 0.2 }, [...TIP, "lipProt", "lipWidth"], 0.15, { release: "ʃ" }),
- c("dʒ", "voiced postalveolar affricate", "affricate", "voiced", "postalveolar", { ...POSTALV_STOP, lipProt: 0.75, lipWidth: 0.2 }, [...TIP, "lipProt", "lipWidth"], 0.13, { release: "ʒ" }),
- c("pf", "voiceless labiodental affricate", "affricate", "voiceless", "labiodental", BILABIAL, LIPS, 0.14, { release: "f" }),
- // approximants, laterals, taps, trills
- c("w", "labial-velar approximant", "approximant", "voiced", "labial-velar", { lipAp: 0.28, lipProt: 1.0, lipWidth: 0.05, tbX: 2.45, tbY: 7.45 }, ["lipAp", "lipProt", "lipWidth", "tbX", "tbY"], 0.06),
- c("ʋ", "labiodental approximant", "approximant", "voiced", "labiodental", { labiodental: 0.9, lipAp: 0.25 }, ["labiodental", "lipAp"], 0.06),
- c("ɹ", "alveolar approximant", "approximant", "voiced", "postalveolar", { ttX: 5.35, ttY: 9.35, ttCurl: 0.85, lipProt: 0.5, lipWidth: 0.3, root: -0.6, tbX: 2.3, tbY: 7.1 }, ["ttX", "ttY", "ttCurl", "lipProt", "lipWidth", "root"], 0.065),
- c("ɻ", "retroflex approximant", "approximant", "voiced", "retroflex", { ttX: 5.4, ttY: 9.55, ttCurl: 1 }, [...TIP, "ttCurl"], 0.065),
- c("j", "palatal approximant", "approximant", "voiced", "palatal", { tbX: 3.8, tbY: 7.95, jaw: 0.25 }, BODY, 0.055),
- c("ɰ", "velar approximant", "approximant", "voiced", "velar", { tbX: 2.35, tbY: 7.45 }, BODY, 0.06),
- c("l", "alveolar lateral approximant", "lateral", "voiced", "alveolar", { ...ALV_STOP, lateral: 1 }, [...TIP, "lateral"], 0.065),
- c("ɫ", "velarised lateral", "lateral", "voiced", "alveolar", { ...ALV_STOP, lateral: 1, tbX: 1.9, tbY: 6.8 }, [...TIP, "lateral", "tbX", "tbY"], 0.075),
- c("ɭ", "retroflex lateral", "lateral", "voiced", "retroflex", { ...RETRO_STOP, lateral: 1 }, [...TIP, "ttCurl", "lateral"], 0.065),
- c("ʎ", "palatal lateral", "lateral", "voiced", "palatal", { ...PAL_STOP, lateral: 1 }, [...BODY, "lateral"], 0.07),
- c("ɾ", "alveolar tap", "tap", "voiced", "alveolar", ALV_STOP, TIP, 0.025),
- c("ɽ", "retroflex flap", "tap", "voiced", "retroflex", RETRO_STOP, [...TIP, "ttCurl"], 0.03),
- c("r", "alveolar trill", "trill", "voiced", "alveolar", { ttX: 6.25, ttY: 9.45 }, TIP, 0.11),
- c("ʀ", "uvular trill", "trill", "voiced", "uvular", { tbX: 1.55, tbY: 7.85 }, BODY, 0.11),
- c("ʙ", "bilabial trill", "trill", "voiced", "bilabial", { lipAp: 0.02 }, LIPS, 0.12),
-];
-void DENT_STOP;
-
-type CalTable = Record<string, Record<string, Partial<HumanArtic>>>;
-const CAL = consonantCal as unknown as CalTable;
-
-const byIpa = new Map<string, PhonemeDef>(BASE.map((p) => [p.ipa, p]));
-
-/** Phoneme definition with calibrated targets for a body (falls back to defaults). */
-export function phoneme(ipa: string, body: string = "male"): PhonemeDef | undefined {
- const p = byIpa.get(ipa);
- if (!p) return undefined;
- const cal = CAL[body]?.[ipa];
- return cal ? { ...p, targets: { ...p.targets, ...cal } } : p;
-}
-
-export const CONSONANTS: readonly PhonemeDef[] = BASE;
-export const CONSONANT_SYMBOLS = BASE.map((p) => p.ipa);
diff --git a/src/engine/phonetics/ipa.ts b/src/engine/phonetics/ipa.ts
deleted file mode 100644
index 814f3bc..0000000
--- a/src/engine/phonetics/ipa.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/** IPA string → segments (stress ˈ ˌ, length ː, tie bars, affricates, diphthongs, word gaps). */
-import type { Segment } from "./planner.ts";
-import { CONSONANT_SYMBOLS } from "./inventory.ts";
-
-const VOWEL_CHARS = "iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶɑɒɝɚ";
-const MULTI = ["tʃ", "dʒ", "ts", "dz", "pf", "aɪ", "aʊ", "ɔɪ", "eɪ", "oʊ"];
-const ALIASES: Record<string, string> = { "t͡ʃ": "tʃ", "d͡ʒ": "dʒ", "t͡s": "ts", "d͡z": "dz", ɡ: "g", ʧ: "tʃ", ʤ: "dʒ", r̥: "r", ɐ̯: "ɐ" };
-
-export function tokenizeIpa(input: string): Segment[] {
- let s = input.normalize("NFC");
- for (const [a, b] of Object.entries(ALIASES)) s = s.split(a).join(b);
- s = s.replace(/[͜͡]/g, ""); // tie bars
- const out: Segment[] = [];
- let stress = 0;
- let i = 0;
- const known = new Set([...CONSONANT_SYMBOLS, ...VOWEL_CHARS.split(""), ...MULTI]);
- while (i < s.length) {
- const ch = s[i];
- if (ch === "ˈ" || ch === "'") {
- stress = 1;
- i++;
- continue;
- }
- if (ch === "ˌ") {
- stress = 2;
- i++;
- continue;
- }
- if (ch === " " || ch === "." || ch === "|" || ch === ",") {
- if (out.length) out[out.length - 1].wordEnd = true;
- if (ch === "," || ch === "|") out.push({ ipa: "_", dur: 0.16 });
- i++;
- continue;
- }
- if (ch === "ː" || ch === ":") {
- const last = out[out.length - 1];
- if (last) last.dur = (last.dur ?? (VOWEL_CHARS.includes(last.ipa[0]) ? 0.15 : 0.09)) * 1.7;
- i++;
- continue;
- }
- let tok = "";
- for (const m of MULTI) if (s.startsWith(m, i)) tok = m;
- if (!tok) tok = ch;
- i += tok.length;
- // skip combining diacritics we do not model
- while (i < s.length && /[̀-ͯ]/.test(s[i])) i++;
- if (!known.has(tok)) continue;
- const isV = VOWEL_CHARS.includes(tok[0]) && !CONSONANT_SYMBOLS.includes(tok);
- out.push({ ipa: tok, stress: isV ? stress : 0 });
- if (isV) stress = 0;
- }
- return out.filter((x) => x.ipa !== "_" || true);
-}
diff --git a/src/engine/phonetics/planner.ts b/src/engine/phonetics/planner.ts
deleted file mode 100644
index fedea17..0000000
--- a/src/engine/phonetics/planner.ts
+++ /dev/null
@@ -1,317 +0,0 @@
-/**
- * Segment sequence → gestural score. Timing and phonation are articulatory: aspiration is a
- * glottal opening gesture peaking at the release (VOT emerges), nasality is velum lowering with
- * anticipation, coarticulation comes from overlapping vowel gestures beneath consonant gestures.
- */
-import type { Gesture } from "../control/score.ts";
-import type { HumanArtic } from "../anatomy/human.ts";
-import { phoneme, type PhonemeDef } from "./inventory.ts";
-import { klattDurations } from "./durations.ts";
-import vowelTable from "./vowelTargets.generated.json";
-
-export interface Segment {
- ipa: string;
- /** duration override (s) */
- dur?: number;
- /** 0 unstressed, 1 primary, 2 secondary */
- stress?: number;
- /** explicit pitch (Hz) for this segment (singing) */
- f0?: number;
- /** word boundary after this segment */
- wordEnd?: boolean;
-}
-
-export interface PlanOptions {
- body: string;
- /** voice-clock start time (s) */
- t0: number;
- /** speaking-rate multiplier (>1 = faster) */
- rate?: number;
- /** baseline pitch (Hz) */
- f0?: number;
- /** "statement" (final fall) or "question" (final rise) */
- intonation?: "statement" | "question" | "flat";
- /** pitch excursion for stressed syllables (fraction) */
- accent?: number;
- /** the last segment is held open-ended (a sung note): no end-of-breath release */
- openEnd?: boolean;
-}
-
-export interface PlannedSegment {
- ipa: string;
- t0: number;
- t1: number;
- /** lexical stress of vowels (0 unstressed, 1 primary, 2 secondary) */
- stress?: number;
- kind: string;
-}
-
-export interface Plan {
- gestures: Gesture[];
- segments: PlannedSegment[];
- end: number;
-}
-
-/** label of the end-of-breath-group abduction (a live note can drop it when the next one starts) */
-export const EXHALE_LABEL = "exhale";
-
-const VOWEL_KEYS = ["tbX", "tbY", "jaw", "lipAp", "lipProt", "lipWidth", "root", "larynx", "ttCurl"] as const;
-type VTable = Record<string, Record<string, { artic: Partial<HumanArtic> }>>;
-const VT = vowelTable as unknown as VTable;
-
-/**
- * Diphthongs and r-coloured vowels expand to vowel sequences. American /eɪ oʊ/ glide toward
- * [i u] (Hillenbrand et al. 1995: /e/ F2 rises ~150 Hz, /o/ F1 falls with F2 steady); with
- * [ɪ ʊ] as targets they barely moved (/e/ and /ɪ/ share F2) and sounded like the steady
- * [eː oː] of Indian English. The other offglides undershoot toward [ɪ ʊ].
- */
-const EXPAND: Record<string, string[]> = {
- aɪ: ["a", "ɪ"],
- aʊ: ["a", "ʊ"],
- ɔɪ: ["ɔ", "ɪ"],
- eɪ: ["e", "i"],
- oʊ: ["o", "u"],
- ɚ: ["ɝ"],
-};
-
-/** The two vowel targets of a diphthong ("aɪ" → ["a", "ɪ"]), or null. */
-export function diphthongParts(ipa: string): [string, string] | null {
- const p = EXPAND[ipa];
- return p && p.length === 2 ? [p[0], p[1]] : null;
-}
-
-export function isVowel(ipa: string, body = "male"): boolean {
- return !!VT[body]?.[ipa] || ipa in EXPAND;
-}
-
-export function vowelArtic(ipa: string, body: string): Partial<HumanArtic> | null {
- const v = VT[body]?.[ipa] ?? VT.male?.[ipa];
- if (!v) return null;
- const out: Partial<HumanArtic> = {};
- for (const k of VOWEL_KEYS) if (v.artic[k] !== undefined) out[k] = v.artic[k] as number;
- // a rhotic's tip is raised and curled back, not resting behind the teeth: without its
- // calibrated position the tip stayed down and /ɝ/'s F3 sat ~15–20 % high (weakly rhotic)
- if ((v.artic.ttCurl ?? 0) > 0.05) {
- if (v.artic.ttX !== undefined) out.ttX = v.artic.ttX;
- if (v.artic.ttY !== undefined) out.ttY = v.artic.ttY;
- }
- return out;
-}
-
-export function planUtterance(input: Segment[], o: PlanOptions): Plan {
- const rate = o.rate ?? 1;
- const body = o.body;
- // durations by the Klatt rules, on whole segments (diphthongs before they are split)
- const durs = klattDurations(input, (s) => {
- if (isVowel(s.ipa, body)) return { vowel: true };
- const d = phoneme(s.ipa, body);
- return { vowel: false, manner: d?.manner, voiced: d?.voicing === "voiced", dur: d?.dur };
- });
- // expand diphthongs into two vowel targets sharing the duration
- const segs: (Segment & { def?: PhonemeDef; vowel?: Partial<HumanArtic>; glideFrom?: boolean })[] = [];
- input.forEach((s, si) => {
- if (EXPAND[s.ipa]) {
- const parts = EXPAND[s.ipa];
- const base = durs[si];
- parts.forEach((p, i) => segs.push({ ...s, ipa: p, dur: parts.length > 1 ? base * (i === 0 ? 0.55 : 0.45) : base, glideFrom: i > 0, wordEnd: i === parts.length - 1 ? s.wordEnd : false }));
- } else segs.push({ ...s, dur: durs[si] });
- });
- for (const s of segs) {
- const v = vowelArtic(s.ipa, body);
- if (v) s.vowel = v;
- else s.def = phoneme(s.ipa, body);
- }
- const gestures: Gesture[] = [];
- const planned: PlannedSegment[] = [];
- let t = o.t0 + 0.06; // breath onset lead
- const times: { t0: number; t1: number }[] = [];
- for (const s of segs) {
- let d: number;
- if (s.dur !== undefined) d = s.dur;
- else if (s.vowel) d = s.stress === 1 ? 0.17 : s.stress === 2 ? 0.13 : 0.095;
- else d = s.def?.dur ?? 0.08;
- // final lengthening on the last syllable rhyme
- d /= rate;
- times.push({ t0: t, t1: t + d });
- t += d;
- }
- const end = t;
- // ---- vowel gestures: overlap neighbours so the tongue travels vowel-to-vowel
- const vIdx = segs.map((s, i) => (s.vowel ? i : -1)).filter((i) => i >= 0);
- vIdx.forEach((i, n) => {
- const prev = n > 0 ? times[vIdx[n - 1]].t1 : times[i].t0 - 0.08;
- const next = n < vIdx.length - 1 ? times[vIdx[n + 1]].t0 : times[i].t1 + 0.08;
- // vowel-to-vowel through the consonant (Öhman): the previous vowel lets go early in the gap
- // and the next one's target ramps in over most of it, so the tongue body is already near
- // the next vowel at the release and the transitions carry the consonant's place
- const rIn = Math.max(0.03, 0.75 * (times[i].t0 - prev)) + 0.01;
- const rOut = Math.max(0.03, 0.4 * (next - times[i].t1)) + 0.01;
- gestures.push({ t0: times[i].t0, t1: times[i].t1, rampIn: rIn, rampOut: rOut, strength: 1, targets: segs[i].vowel!, label: segs[i].ipa });
- });
- // utterance-initial/final consonants: lend them the nearest vowel's body posture
- // ---- consonant gestures
- segs.forEach((s, i) => {
- const { t0, t1 } = times[i];
- const dur = t1 - t0;
- planned.push({ ipa: s.ipa, t0, t1, kind: s.vowel ? "vowel" : s.def?.manner ?? "?", ...(s.vowel ? { stress: s.stress ?? 0 } : {}) });
- const def = s.def;
- if (!def) return;
- const prevVowel = i > 0 && !!segs[i - 1].vowel;
- const nextVowel = i < segs.length - 1 && !!segs[i + 1].vowel;
- const prevSeg = i > 0 ? segs[i - 1] : null;
- const addOral = (tg: Partial<HumanArtic>, a: number, b: number, speed: number, label: string) => gestures.push(...oralGestures(def, tg, a, b, speed, label));
- switch (def.manner) {
- case "stop":
- case "nasal":
- addOral(def.targets, t0, t1, 1.55, def.ipa);
- break;
- case "tap":
- addOral(def.targets, t0, t1, 2.8, def.ipa);
- break;
- case "trill": {
- // driven trill: rapid alternation of near-closure and release at ~26 Hz
- const n = Math.max(2, Math.round(dur * 26));
- for (let k = 0; k < n; k++) {
- const a = t0 + (k / n) * dur;
- addOral(def.targets, a, a + 0.35 / 26, 3.2, def.ipa);
- }
- break;
- }
- case "affricate": {
- const split = t0 + dur * 0.55;
- addOral(def.targets, t0, split, 2.0, def.ipa);
- const rel = def.release ? phoneme(def.release, body) : undefined;
- if (rel) addOral(rel.targets, split + 0.008, t1, 1.4, def.ipa);
- break;
- }
- case "fricative":
- case "approximant":
- case "lateral":
- addOral(def.targets, t0, t1, 1.3, def.ipa);
- break;
- case "glottal":
- break;
- }
- // nasality: the velum lowers in anticipation (into the preceding vowel, as in English) and
- // seals again by the end of the nasal; 0.45 cm² is ample for the murmur
- if (def.nasal) gestures.push({ t0: t0 - 0.02, t1: t1 - 0.02, rampIn: 0.05, rampOut: 0.03, strength: 4, targets: { velum: 0.45 }, label: "velum" });
- // phonation
- const k2 = 1; // abduction is body-scaled in the voice
- if (def.glottal === "open") gestures.push({ t0: t0 - 0.01, t1, rampIn: 0.03, rampOut: 0.035, strength: 5, targets: { abduction: 0.33 * k2 }, label: "h" });
- else if (def.glottal === "breathy") gestures.push({ t0, t1, rampIn: 0.03, rampOut: 0.03, strength: 5, targets: { abduction: 0.1 * k2 }, label: "ɦ" });
- else if (def.glottal === "stop") gestures.push({ t0, t1, rampIn: 0.012, rampOut: 0.015, strength: 8, targets: { closure: 1 }, label: "ʔ" });
- else if (def.voicing === "voiceless") {
- if (def.manner === "stop" || def.manner === "affricate") {
- // aspirated when syllable-initial before a vowel and not after /s/ (English-like)
- const aspirated = nextVowel && !(prevSeg && prevSeg.ipa === "s");
- const vot = aspirated ? 0.05 / rate : 0.012;
- gestures.push({ t0: t0 + 0.25 * dur, t1: t1 + vot * 0.4, rampIn: 0.035, rampOut: aspirated ? 0.045 : 0.02, strength: 6, targets: { abduction: aspirated ? 0.36 : 0.22 }, label: "aspiration" });
- } else {
- gestures.push({ t0: t0 - 0.015, t1: t1 + 0.005, rampIn: 0.03, rampOut: 0.03, strength: 6, targets: { abduction: 0.3 }, label: "voiceless" });
- }
- } else if (def.manner === "fricative") {
- gestures.push({ t0, t1, rampIn: 0.03, rampOut: 0.03, strength: 3, targets: { abduction: 0.035 }, label: "voiced frication" });
- }
- void prevVowel;
- });
- // ---- breath: on through the utterance
- gestures.push({ t0: o.t0 + 0.04, t1: end, rampIn: 0.04, rampOut: o.openEnd ? 0.07 : 0.05, strength: 1, targets: { breath: 1 }, label: "breath" });
- // ---- end of the breath group: the folds part as the breath stops, so a final obstruent is
- // released into silence instead of into an added vowel ("cat-uh"). After a vowel or sonorant
- // they part once the pressure has fallen, so the voice fades out instead of ending in an [h].
- if (!o.openEnd) {
- const last = segs[segs.length - 1];
- const sonorant = !!last?.vowel || ["nasal", "approximant", "lateral", "tap", "trill"].includes(last?.def?.manner ?? "");
- const at = end + (sonorant ? 0.045 : 0.015);
- gestures.push({ t0: at, t1: end + 0.1, rampIn: 0.03, rampOut: 0.06, strength: 6, targets: { abduction: 0.22 }, label: EXHALE_LABEL });
- }
- // ---- intonation: pitch targets on vowels
- const f0 = o.f0 ?? 110;
- const accent = o.accent ?? 0.14;
- const total = Math.max(0.2, end - o.t0);
- // the nuclear accent: the phrase's last primary-stressed vowel, a bigger excursion that falls
- // (statements) into the final low; earlier accents are smaller (a "hat" pattern)
- let nuclear = -1;
- for (const i of vIdx) if (segs[i].stress === 1 && !segs[i].glideFrom) nuclear = i;
- vIdx.forEach((i, n) => {
- const s = segs[i];
- const { t0, t1 } = times[i];
- // pitch holds through the consonants up to the next vowel (instead of sagging to the base)
- const hold = n < vIdx.length - 1 ? Math.max(t1, times[vIdx[n + 1]].t0 - 0.03) : t1;
- let target: number;
- if (s.f0) target = s.f0;
- else {
- const prog = (t0 - o.t0) / total;
- const decl = 1 - 0.1 * prog;
- const acc = s.stress === 1 ? 1 + (i === nuclear ? accent * 1.8 : accent) : s.stress === 2 ? 1 + accent * 0.5 : 1;
- target = f0 * decl * acc;
- const last = n === vIdx.length - 1;
- if (last && o.intonation === "question") target = f0 * 1.35;
- if (last && (o.intonation ?? "statement") === "statement") {
- if (i === nuclear && t1 - t0 > 0.08) {
- // accent peak early in the vowel, then the fall within it
- gestures.push({ t0, t1: t0 + 0.35 * (t1 - t0), rampIn: 0.05, rampOut: 0.05, strength: 1, targets: { f0: target }, label: "pitch" });
- gestures.push({ t0: t0 + 0.55 * (t1 - t0), t1, rampIn: 0.06, rampOut: 0.06, strength: 1, targets: { f0: f0 * 0.82 }, label: "pitch" });
- return;
- }
- target = f0 * 0.82;
- }
- }
- gestures.push({ t0, t1: s.f0 ? t1 : hold, rampIn: 0.06, rampOut: 0.06, strength: s.f0 ? 6 : 1, targets: { f0: target }, label: "pitch" });
- });
- return { gestures, segments: planned, end };
-}
-
-/**
- * Oral gestures for one consonant constriction held acoustically from `a` to `b` (closure to
- * release): a dominant gesture on the consonant's own articulators and a weak one on the rest.
- * Movement latencies are compensated so the acoustic closure and release land on a and b.
- */
-export function oralGestures(def: PhonemeDef, tg: Partial<HumanArtic>, a: number, b: number, speed: number, label: string): Gesture[] {
- const out: Gesture[] = [];
- const dom: Partial<HumanArtic> = {};
- const sec: Partial<HumanArtic> = {};
- for (const [k, v] of Object.entries(tg) as [keyof HumanArtic, number][]) (def.dominant.includes(k) ? dom : sec)[k] = v;
- // the dorsum is heavy: its releases are slower than tip and lip releases
- const bodyOnly = def.dominant.every((k) => k === "tbX" || k === "tbY" || k === "root");
- const sp = bodyOnly ? 1 + (speed - 1) * 0.35 : speed;
- // articulators need ~10–15 ms to climb out of the overshoot (contact) target, so the
- // gesture releases early and the acoustic release lands on the planned boundary:
- // measured movement latencies (closure lag / release lag) per articulator class
- const closing = def.manner === "stop" || def.manner === "nasal" || def.manner === "affricate";
- const lipsOnly = def.dominant.every((k) => k === "lipAp" || k === "labiodental");
- const lead = closing ? (bodyOnly ? 0.034 : lipsOnly ? 0.019 : 0.02) : 0;
- // a consonant must own its constriction articulators (Task-Dynamics style): at strength 40
- // the overlapping vowel contributes ~2 %, so closures seal instead of being diluted
- const early = closing ? (bodyOnly ? 0.024 : lipsOnly ? 0.022 : 0.031) : 0.008;
- if (Object.keys(dom).length) out.push({ t0: a - early, t1: Math.max(a + 0.01, b - lead), rampIn: 0.03, rampOut: bodyOnly ? 0.03 : 0.018, strength: 40, targets: dom, speed: sp, releaseHold: 0.045, label });
- // alveolars front the tongue body during the closure (the alveolar F2 locus, ~1.8 kHz)
- const alveolar = def.place === "alveolar" && tg.tbX === undefined && ["stop", "nasal", "fricative", "affricate", "tap"].includes(def.manner);
- if (alveolar) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 1.2, targets: { tbX: 3.2, tbY: 7.4 }, label });
- if (Object.keys(sec).length) {
- // a velar's front–back place follows the vowel (fronted /k/ in "key", backed in "caw"):
- // its own tbX only weakly, so the F2 locus moves with the vowel as in natural speech
- const place = bodyOnly && sec.tbX !== undefined ? { tbX: sec.tbX } : null;
- if (place) delete sec.tbX;
- if (Object.keys(sec).length) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 2.2, targets: sec, label });
- if (place) out.push({ t0: a, t1: b, rampIn: 0.05, rampOut: 0.05, strength: 0.25, targets: place, label });
- }
- return out;
-}
-
-/** Plan consecutive phrases (each with its own breath group and intonation) from t0. */
-export function planPhrases(
- phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[],
- o: Omit<PlanOptions, "intonation">,
-): Plan {
- const all: Plan = { gestures: [], segments: [], end: o.t0 };
- let t = o.t0;
- for (const p of phrases) {
- const plan = planUtterance(p.segments, { ...o, t0: t, intonation: p.intonation ?? "statement" });
- all.gestures.push(...plan.gestures);
- all.segments.push(...plan.segments);
- t = plan.end + (p.pause ?? 0.25);
- all.end = plan.end;
- }
- return all;
-}
diff --git a/src/engine/phonetics/sing.ts b/src/engine/phonetics/sing.ts
deleted file mode 100644
index 261943c..0000000
--- a/src/engine/phonetics/sing.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-/**
- * Singing: syllables on notes, through the same gestural planner as speech.
- * - A note's vowel lands on the beat. Its onset consonants are sung just before it (they take
- * their time from the previous note, as singers do), its coda just before the next onset.
- * - Diphthongs sustain their first vowel and glide to the second at the end of the note.
- * - A melisma ("-") carries the vowel onto further notes; the coda waits for the last of them.
- * - Vibrato blooms a quarter of a second into a held vowel.
- * Live playing uses open-ended notes: a key press sings the onset and starts a vowel that lasts
- * until the key is released (tagged gestures, ended with GestureScore.release), and the release
- * sings the glide and the coda.
- */
-import { planUtterance, diphthongParts, type Plan, type PlannedSegment, type Segment } from "./planner.ts";
-import { phoneme } from "./inventory.ts";
-import type { Gesture } from "../control/score.ts";
-import type { Syllable } from "./syllables.ts";
-
-export const midiToHz = (m: number): number => 440 * Math.pow(2, (m - 69) / 12);
-
-/** sung consonants are a little shorter than spoken ones */
-const cdur = (ipa: string, body: string, k = 0.8) => (phoneme(ipa, body)?.dur ?? 0.07) * k;
-const consonants = (segs: Segment[], body: string, k = 0.8): Segment[] => segs.map((c) => ({ ipa: c.ipa, dur: cdur(c.ipa, body, k) }));
-const total = (segs: Segment[]) => segs.reduce((s, c) => s + (c.dur ?? 0), 0);
-
-const vibratoGesture = (t0: number, t1: number, depth: number, tag?: number): Gesture => ({ t0: t0 + 0.22, t1, rampIn: 0.3, rampOut: 0.06, strength: 4, targets: { vibrato: depth }, label: "vibrato", tag });
-
-export interface SungNote {
- midi: number;
- /** length in beats */
- beats: number;
- syl: Syllable;
-}
-
-export interface SongOptions {
- body: string;
- bpm: number;
- /** plan time of the first note's beat (its onset consonants come before) */
- t0: number;
- /** vibrato depth (cents) on held vowels */
- vibrato: number;
-}
-
-/** Plan a whole melody: one utterance per phrase, so each phrase gets its own breath. */
-export function planSong(notes: SungNote[], o: SongOptions): Plan {
- const beat = 60 / o.bpm;
- const gestures: Gesture[] = [];
- const segments: PlannedSegment[] = [];
- const times: number[] = [];
- let t = o.t0;
- for (const n of notes) {
- times.push(t);
- t += n.beats * beat;
- }
- let end = t;
- let i = 0;
- while (i < notes.length) {
- let j = i;
- while (j < notes.length - 1 && !notes[j].syl.phraseEnd) j++;
- const segs: Segment[] = [];
- const vowelSpans: [number, number][] = [];
- const onsetOf = (k: number) => (notes[k].syl.melisma ? [] : consonants(notes[k].syl.onset, o.body));
- for (let k = i; k <= j; k++) {
- const n = notes[k];
- const hz = midiToHz(n.midi);
- const nextMelisma = k < j && notes[k + 1].syl.melisma;
- const coda = nextMelisma ? [] : consonants(lastOfChain(notes, k).coda, o.body);
- const onset = onsetOf(k);
- // vowel from this note's beat to the next note's onset (less this note's coda);
- // the phrase's last vowel leaves a short breath before the next phrase
- const noteEnd = k < j ? times[k + 1] - total(onsetOf(k + 1)) : times[j] + notes[j].beats * beat - Math.min(0.12, 0.3 * notes[j].beats * beat);
- const vdur = Math.max(0.05, noteEnd - times[k] - total(coda));
- segs.push(...onset);
- const parts = diphthongParts(n.syl.nucleus.ipa);
- if (parts && !nextMelisma) {
- segs.push({ ipa: parts[0], dur: vdur * 0.8, f0: hz, stress: 1 }, { ipa: parts[1], dur: vdur * 0.2, f0: hz, stress: 1 });
- } else segs.push({ ipa: parts ? parts[0] : n.syl.nucleus.ipa, dur: vdur, f0: hz, stress: 1 });
- segs.push(...coda);
- vowelSpans.push([times[k], times[k] + vdur]);
- }
- if (segs.length) {
- // the planner lays segments out from t0 + 0.06: start so the first vowel lands on its beat
- const plan = planUtterance(segs, { body: o.body, t0: times[i] - total(onsetOf(i)) - 0.06, f0: midiToHz(notes[i].midi), intonation: "flat" });
- gestures.push(...plan.gestures);
- segments.push(...plan.segments);
- for (const [a, b] of vowelSpans) if (b - a > 0.3) gestures.push(vibratoGesture(a, b, o.vibrato));
- end = Math.max(end, plan.end);
- }
- i = j + 1;
- }
- return { gestures, segments, end };
-}
-
-/** The syllable whose coda ends a melisma chain starting at note k. */
-function lastOfChain(notes: SungNote[], k: number): Syllable {
- let b = k;
- while (b > 0 && notes[b].syl.melisma) b--;
- return notes[b].syl;
-}
-
-/** Live: gestures relative to "now" (the planner's 60 ms lead is mostly taken back). */
-const LIVE_T0 = -0.045;
-/** a held vowel lasts at most this long (s) */
-const HOLD = 30;
-
-/**
- * Key pressed: sing the previous syllable's glide and coda if it is still sounding (legato),
- * then this syllable's onset, then its vowel held open-ended. Every gesture gets `tag`; the
- * pitch and vibrato get `tag + 1`, so a melisma can change pitch without ending the vowel.
- */
-export function planNoteOn(syl: Syllable, midi: number, o: { body: string; vibrato: number; tag: number; legatoFrom?: { syl: Syllable; midi: number } }): Gesture[] {
- const hz = midiToHz(midi);
- const segs: Segment[] = [];
- if (o.legatoFrom) segs.push(...tail(o.legatoFrom.syl, o.body, midiToHz(o.legatoFrom.midi)));
- segs.push(...consonants(syl.onset, o.body, 0.7));
- const parts = diphthongParts(syl.nucleus.ipa);
- segs.push({ ipa: parts ? parts[0] : syl.nucleus.ipa, dur: HOLD, f0: hz, stress: 1 });
- const plan = planUtterance(segs, { body: o.body, t0: LIVE_T0, f0: hz, intonation: "flat", openEnd: true });
- const vowel = plan.segments[plan.segments.length - 1];
- const out: Gesture[] = plan.gestures.map((g) => ({ ...g, tag: g.targets.f0 !== undefined ? o.tag + 1 : o.tag }));
- out.push(vibratoGesture(vowel.t0, vowel.t1, o.vibrato, o.tag + 1));
- return out;
-}
-
-/** Melisma, live: the held vowel moves to a new pitch (release tag + 1 first). */
-export function planMelisma(midi: number, o: { vibrato: number; tag: number }): Gesture[] {
- return [
- { t0: 0, t1: HOLD, rampIn: 0.05, rampOut: 0.06, strength: 6, targets: { f0: midiToHz(midi) }, label: "pitch", tag: o.tag + 1 },
- vibratoGesture(0, HOLD, o.vibrato, o.tag + 1),
- ];
-}
-
-/** Key released: the diphthong's glide and the coda (release the note's tags first). */
-export function planNoteOff(syl: Syllable, midi: number, body: string): Gesture[] {
- const hz = midiToHz(midi);
- const segs = tail(syl, body, hz);
- if (!segs.length) return [];
- return planUtterance(segs, { body, t0: LIVE_T0, f0: hz, intonation: "flat" }).gestures;
-}
-
-/** What follows a held vowel: the diphthong's glide (at the note's pitch) and the coda. */
-function tail(syl: Syllable, body: string, hz: number): Segment[] {
- const parts = diphthongParts(syl.nucleus.ipa);
- const out: Segment[] = [];
- if (parts) out.push({ ipa: parts[1], dur: 0.07, stress: 1, f0: hz });
- out.push(...consonants(syl.coda, body, 0.7));
- return out;
-}
diff --git a/src/engine/phonetics/songs.ts b/src/engine/phonetics/songs.ts
deleted file mode 100644
index 36cc1a3..0000000
--- a/src/engine/phonetics/songs.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/** Demo melodies for Sing mode: [MIDI note, beats] per syllable, in the adult female register. */
-export interface DemoSong {
- name: string;
- bpm: number;
- lyrics: string;
- notes: [number, number][];
- /** octave shift per body */
- octave: { male: number; female: number; child: number };
-}
-
-export const DEMO_SONGS: DemoSong[] = [
- {
- // an original tune for this instrument
- name: "Made of air",
- bpm: 84,
- lyrics: "Breathe in, breathe out, I am made of air. Tongue and lips and throat, singing anywhere.",
- notes: [
- [64, 1], [60, 1], [62, 1], [57, 1],
- [57, 0.5], [60, 0.5], [64, 1], [62, 0.5], [60, 1.5],
- [65, 1], [64, 0.5], [62, 0.5], [60, 0.5], [62, 1.5],
- [64, 0.5], [62, 0.5], [60, 0.5], [59, 0.5], [57, 2],
- ],
- octave: { male: -1, female: 0, child: 0 },
- },
- {
- // traditional (public domain)
- name: "Twinkle, twinkle",
- bpm: 100,
- lyrics: "Twinkle twinkle little star, how I wonder what you are.",
- notes: [
- [60, 1], [60, 1], [67, 1], [67, 1], [69, 1], [69, 1], [67, 2],
- [65, 1], [65, 1], [64, 1], [64, 1], [62, 1], [62, 1], [60, 2],
- ],
- octave: { male: -1, female: 0, child: 0 },
- },
-];
diff --git a/src/engine/phonetics/syllables.ts b/src/engine/phonetics/syllables.ts
deleted file mode 100644
index ac36cc7..0000000
--- a/src/engine/phonetics/syllables.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * Lyrics → sung syllables. Words come from the pronouncing dictionary (unreduced: sung function
- * words keep full vowels), are split into syllables by the maximal-onset principle with English
- * onset clusters, and the spelling is split to match for display ("twin-kle").
- * Typed hyphens force syllable breaks; a lone "-" (or "~") holds the previous vowel onto the
- * next note (melisma), as in vocaloid editors.
- */
-import type { Segment } from "./planner.ts";
-import { isVowel } from "./planner.ts";
-
-export interface Syllable {
- /** lyric text shown on the note */
- text: string;
- onset: Segment[];
- /** vowel (a diphthong stays one nucleus: "aɪ") */
- nucleus: Segment;
- coda: Segment[];
- /** continue the previous syllable's vowel at a new pitch */
- melisma?: boolean;
- /** last syllable of a word (codas sound here; phrase breaks follow punctuation) */
- wordEnd: boolean;
- /** a breath follows (comma, full stop, line break) */
- phraseEnd: boolean;
-}
-
-// English onsets (IPA), longest first matters only for the search below
-const ONSETS = new Set([
- "p", "b", "t", "d", "k", "g", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "h", "m", "n", "l", "ɹ", "w", "j", "tʃ", "dʒ",
- "pl", "bl", "kl", "gl", "fl", "sl", "pɹ", "bɹ", "tɹ", "dɹ", "kɹ", "gɹ", "fɹ", "θɹ", "ʃɹ",
- "sp", "st", "sk", "sm", "sn", "sw", "sf", "tw", "kw", "dw", "gw", "θw",
- "pj", "bj", "kj", "gj", "mj", "nj", "fj", "vj", "hj", "lj",
- "spl", "spɹ", "stɹ", "skɹ", "skw", "skj", "spj",
-]);
-
-/** Split one word's segments into onset / nucleus / coda syllables. */
-export function syllabifySegments(segs: Segment[]): { onset: Segment[]; nucleus: Segment; coda: Segment[] }[] {
- const vi = segs.map((s, i) => (isVowel(s.ipa) ? i : -1)).filter((i) => i >= 0);
- if (!vi.length) return [];
- const out: { onset: Segment[]; nucleus: Segment; coda: Segment[] }[] = [];
- let start = 0;
- vi.forEach((v, n) => {
- const next = vi[n + 1];
- let end = segs.length; // exclusive end of this syllable
- if (next !== undefined) {
- // consonants between this vowel and the next: the longest legal onset goes right
- const between = segs.slice(v + 1, next);
- let k = 0;
- for (let len = Math.min(3, between.length); len >= 1; len--) {
- if (ONSETS.has(between.slice(between.length - len).map((s) => s.ipa).join(""))) {
- k = len;
- break;
- }
- }
- end = next - k;
- }
- out.push({ onset: segs.slice(start, v), nucleus: segs[v], coda: segs.slice(v + 1, end) });
- start = end;
- });
- return out;
-}
-
-const V = /[aeiouy]+/g;
-
-/** Split a written word into n chunks at its vowel groups (approximate hyphenation). */
-export function splitSpelling(word: string, n: number): string[] {
- if (n <= 1) return [word];
- const groups: [number, number][] = [];
- for (const m of word.toLowerCase().matchAll(V)) groups.push([m.index!, m.index! + m[0].length]);
- // a final silent e ("like") is not a syllable, but consonant + "le" is ("twin-kle", "lit-tle")
- if (groups.length > 1 && /[^aeiouy]e$/i.test(word) && !/[^aeiouyl]le$/i.test(word) && groups[groups.length - 1][0] === word.length - 1) groups.pop();
- if (groups.length < n) {
- // fewer written vowels than sung syllables (e.g. "fire"): hold the word, then continue marks
- return [word, ...Array(n - 1).fill("~")];
- }
- while (groups.length > n) {
- const last = groups.pop()!;
- groups[groups.length - 1][1] = last[1];
- }
- const cuts: number[] = [0];
- for (let i = 0; i < groups.length - 1; i++) {
- const a = groups[i][1], b = groups[i + 1][0]; // consonant letters a..b between vowel groups
- // a digraph stays together on the right ("any-where", "fa-ther"); otherwise one consonant
- // goes right and longer runs split in the middle ("lit-tle", "won-der")
- const gap = b - a;
- const dig = gap >= 2 && /^(th|sh|ch|ph|wh|ck|gh)$/i.test(word.slice(b - 2, b));
- cuts.push(dig ? b - 2 : a + (gap <= 1 ? 0 : Math.floor(gap / 2)));
- }
- cuts.push(word.length);
- return cuts.slice(0, -1).map((c, i) => word.slice(c, cuts[i + 1]));
-}
-
-export interface WordSource {
- word(w: string, reduce?: boolean): Segment[];
-}
-
-/** Lyrics text → syllables (needs the pronouncing dictionary for real words). */
-export function lyricsToSyllables(text: string, g2p: WordSource): Syllable[] {
- const out: Syllable[] = [];
- // words, melisma marks and phrase punctuation, in order
- const tokens = text.replace(/[’']/g, "'").match(/[A-Za-z'][A-Za-z'\-]*|(?<=\s|^)[~-](?=\s|$)|[.,;:!?\n]/g) ?? [];
- for (const tok of tokens) {
- if (/^[.,;:!?\n]$/.test(tok)) {
- if (out.length) out[out.length - 1].phraseEnd = true;
- continue;
- }
- if (tok === "-" || tok === "~") {
- const prev = out[out.length - 1];
- if (prev) out.push({ text: "~", onset: [], nucleus: prev.nucleus, coda: [], melisma: true, wordEnd: prev.wordEnd, phraseEnd: false });
- continue;
- }
- // typed hyphens split syllables explicitly ("ti-ger"); otherwise the dictionary decides
- const parts = tok.split("-").filter(Boolean);
- const syls: Syllable[] = [];
- for (const part of parts) {
- const sy = syllabifySegments(g2p.word(part.toLowerCase(), false));
- const spell = parts.length > 1 ? [part, ...Array(Math.max(0, sy.length - 1)).fill("~")] : splitSpelling(part, sy.length);
- sy.forEach((s, i) => syls.push({ ...s, text: spell[i] ?? "~", wordEnd: false, phraseEnd: false }));
- }
- if (syls.length) syls[syls.length - 1].wordEnd = true;
- out.push(...syls);
- }
- return out;
-}
diff --git a/src/engine/phonetics/vowelData.ts b/src/engine/phonetics/vowelData.ts
deleted file mode 100644
index 7c2e336..0000000
--- a/src/engine/phonetics/vowelData.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * Reference vowel formants (Hz) used to calibrate articulatory vowel targets.
- * English vowels: Hillenbrand, Getty, Clark & Wheeler (1995) means (men / women / children).
- * Other cardinal-ish vowels: typical literature values (men), scaled for women/children.
- */
-export interface VowelRef {
- ipa: string;
- /** example word / description */
- example: string;
- male: [number, number, number];
- female: [number, number, number];
- child: [number, number, number];
- round: boolean;
- /** 0 close … 1 open */
- height: number;
- /** 0 front … 1 back */
- back: number;
-}
-
-const scaleRef = (m: [number, number, number], k: [number, number, number]): [number, number, number] => [m[0] * k[0], m[1] * k[1], m[2] * k[2]];
-const FEM: [number, number, number] = [1.17, 1.2, 1.15];
-const CHI: [number, number, number] = [1.3, 1.33, 1.24];
-
-function ref(ipa: string, example: string, male: [number, number, number], female: [number, number, number] | null, child: [number, number, number] | null, round: boolean, height: number, back: number): VowelRef {
- return { ipa, example, male, female: female ?? scaleRef(male, FEM), child: child ?? scaleRef(male, CHI), round, height, back };
-}
-
-export const VOWELS: VowelRef[] = [
- ref("i", "heed", [342, 2322, 3000], [437, 2761, 3372], [452, 3081, 3702], false, 0, 0),
- ref("ɪ", "hid", [427, 2034, 2684], [483, 2365, 3053], [511, 2552, 3403], false, 0.2, 0.15),
- ref("e", "hayed", [476, 2089, 2691], [536, 2530, 3047], [564, 2656, 3323], false, 0.3, 0.05),
- ref("ɛ", "head", [580, 1799, 2605], [731, 2058, 2979], [749, 2267, 3310], false, 0.55, 0.1),
- ref("æ", "had", [640, 1760, 2500], [669, 2349, 2972], [717, 2501, 3289], false, 0.8, 0.15),
- ref("a", "front open (Fr. patte)", [780, 1450, 2550], null, null, false, 1, 0.35),
- ref("ɑ", "hod", [768, 1333, 2522], [936, 1551, 2815], [1002, 1688, 2950], false, 1, 0.85),
- ref("ɒ", "Br. lot", [620, 880, 2500], null, null, true, 0.9, 1),
- ref("ɔ", "hawed", [652, 997, 2538], [781, 1136, 2824], [803, 1210, 2982], true, 0.65, 1),
- ref("o", "hoed", [497, 910, 2459], [555, 1035, 2828], [597, 1137, 2987], true, 0.35, 1),
- ref("ʊ", "hood", [469, 1122, 2434], [519, 1225, 2827], [568, 1490, 3072], true, 0.2, 0.85),
- ref("u", "who'd", [378, 997, 2343], [459, 1105, 2735], [494, 1345, 2988], true, 0, 1),
- ref("ʌ", "hud", [623, 1200, 2550], [753, 1426, 2933], [749, 1546, 3145], false, 0.6, 0.7),
- ref("ə", "sofa", [500, 1450, 2450], null, null, false, 0.5, 0.5),
- ref("ɐ", "near-open central", [640, 1350, 2500], null, null, false, 0.8, 0.5),
- ref("ɝ", "heard", [474, 1379, 1710], [523, 1588, 1929], [586, 1719, 2143], true, 0.45, 0.5),
- ref("y", "Fr. tu", [300, 1800, 2150], null, null, true, 0, 0),
- ref("ø", "Fr. peu", [390, 1550, 2250], null, null, true, 0.3, 0.1),
- ref("œ", "Fr. peur", [520, 1450, 2350], null, null, true, 0.55, 0.15),
- ref("ɨ", "close central", [330, 1600, 2400], null, null, false, 0, 0.5),
- ref("ɯ", "close back unrounded", [340, 1350, 2400], null, null, false, 0, 1),
- ref("ɤ", "close-mid back unrounded", [460, 1250, 2450], null, null, false, 0.35, 1),
-];
diff --git a/src/engine/phonetics/vowelTargets.generated.json b/src/engine/phonetics/vowelTargets.generated.json
deleted file mode 100644
index 4e032e8..0000000
--- a/src/engine/phonetics/vowelTargets.generated.json
+++ /dev/null
@@ -1,2029 +0,0 @@
-{
- "male": {
- "i": {
- "artic": {
- "tbX": 3.668,
- "tbY": 7.744,
- "jaw": 0.438,
- "lipAp": 1.065,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.548,
- "larynx": 0.818,
- "ttX": 6.531,
- "ttY": 7.268,
- "ttCurl": 0
- },
- "formants": [
- 337,
- 2236,
- 2905,
- 3911
- ],
- "target": [
- 342,
- 2322,
- 3000
- ],
- "err": [
- -1.5,
- -3.7,
- -3.2
- ]
- },
- "ɪ": {
- "artic": {
- "tbX": 3.633,
- "tbY": 7.412,
- "jaw": 0.63,
- "lipAp": 1.201,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.039,
- "larynx": 0.244,
- "ttX": 6.45,
- "ttY": 6.981,
- "ttCurl": 0
- },
- "formants": [
- 423,
- 2016,
- 2599,
- 3689
- ],
- "target": [
- 427,
- 2034,
- 2684
- ],
- "err": [
- -0.9,
- -0.9,
- -3.1
- ]
- },
- "e": {
- "artic": {
- "tbX": 3.598,
- "tbY": 7.247,
- "jaw": 0.861,
- "lipAp": 1.395,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.257,
- "larynx": 0.497,
- "ttX": 6.35,
- "ttY": 6.719,
- "ttCurl": 0
- },
- "formants": [
- 466,
- 2005,
- 2598,
- 3782
- ],
- "target": [
- 476,
- 2089,
- 2691
- ],
- "err": [
- -2,
- -4,
- -3.4
- ]
- },
- "ɛ": {
- "artic": {
- "tbX": 3.416,
- "tbY": 6.575,
- "jaw": 1.155,
- "lipAp": 1.597,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.06,
- "larynx": 0.331,
- "ttX": 6.174,
- "ttY": 6.228,
- "ttCurl": 0
- },
- "formants": [
- 572,
- 1776,
- 2547,
- 3714
- ],
- "target": [
- 580,
- 1799,
- 2605
- ],
- "err": [
- -1.4,
- -1.3,
- -2.2
- ]
- },
- "æ": {
- "artic": {
- "tbX": 3.265,
- "tbY": 6.226,
- "jaw": 1.587,
- "lipAp": 1.925,
- "lipProt": 0,
- "lipWidth": 1,
- "root": -0.106,
- "larynx": 0.353,
- "ttX": 5.938,
- "ttY": 5.736,
- "ttCurl": 0
- },
- "formants": [
- 626,
- 1714,
- 2556,
- 3770
- ],
- "target": [
- 640,
- 1760,
- 2500
- ],
- "err": [
- -2.2,
- -2.6,
- 2.2
- ]
- },
- "a": {
- "artic": {
- "tbX": 2.305,
- "tbY": 5.715,
- "jaw": 1.764,
- "lipAp": 2,
- "lipProt": 0,
- "lipWidth": 1,
- "root": -0.292,
- "larynx": 0.351,
- "ttX": 5.566,
- "ttY": 5.407,
- "ttCurl": 0
- },
- "formants": [
- 733,
- 1454,
- 2520,
- 3983
- ],
- "target": [
- 780,
- 1450,
- 2550
- ],
- "err": [
- -6,
- 0.3,
- -1.2
- ]
- },
- "ɑ": {
- "artic": {
- "tbX": 2.027,
- "tbY": 5.707,
- "jaw": 1.759,
- "lipAp": 2,
- "lipProt": 0,
- "lipWidth": 1,
- "root": -0.246,
- "larynx": 0.181,
- "ttX": 5.485,
- "ttY": 5.409,
- "ttCurl": 0
- },
- "formants": [
- 740,
- 1338,
- 2507,
- 3966
- ],
- "target": [
- 768,
- 1333,
- 2522
- ],
- "err": [
- -3.6,
- 0.3,
- -0.6
- ]
- },
- "ɒ": {
- "artic": {
- "tbX": 1.366,
- "tbY": 5.803,
- "jaw": 1.559,
- "lipAp": 0.959,
- "lipProt": 0.343,
- "lipWidth": 0.48,
- "root": -0.157,
- "larynx": -0.032,
- "ttX": 5.381,
- "ttY": 5.611,
- "ttCurl": 0
- },
- "formants": [
- 607,
- 891,
- 2471,
- 3934
- ],
- "target": [
- 620,
- 880,
- 2500
- ],
- "err": [
- -2,
- 1.3,
- -1.2
- ]
- },
- "ɔ": {
- "artic": {
- "tbX": 1.504,
- "tbY": 6.109,
- "jaw": 1.143,
- "lipAp": 0.836,
- "lipProt": 0.311,
- "lipWidth": 0.532,
- "root": -0.273,
- "larynx": 0.165,
- "ttX": 5.605,
- "ttY": 6.076,
- "ttCurl": 0.001
- },
- "formants": [
- 628,
- 1010,
- 2418,
- 3940
- ],
- "target": [
- 652,
- 997,
- 2538
- ],
- "err": [
- -3.7,
- 1.3,
- -4.7
- ]
- },
- "o": {
- "artic": {
- "tbX": 1.77,
- "tbY": 6.937,
- "jaw": 0.919,
- "lipAp": 0.233,
- "lipProt": 1.399,
- "lipWidth": 0.302,
- "root": 0.496,
- "larynx": 0.421,
- "ttX": 5.778,
- "ttY": 6.56,
- "ttCurl": 0
- },
- "formants": [
- 491,
- 924,
- 2236,
- 3714
- ],
- "target": [
- 497,
- 910,
- 2459
- ],
- "err": [
- -1.3,
- 1.5,
- -9.1
- ]
- },
- "ʊ": {
- "artic": {
- "tbX": 2.343,
- "tbY": 7.161,
- "jaw": 0.528,
- "lipAp": 0.44,
- "lipProt": 1.387,
- "lipWidth": 0.254,
- "root": 0.448,
- "larynx": 0.393,
- "ttX": 6.101,
- "ttY": 6.983,
- "ttCurl": 0
- },
- "formants": [
- 467,
- 1125,
- 2272,
- 3685
- ],
- "target": [
- 469,
- 1122,
- 2434
- ],
- "err": [
- -0.4,
- 0.3,
- -6.6
- ]
- },
- "u": {
- "artic": {
- "tbX": 2.426,
- "tbY": 7.432,
- "jaw": 0.196,
- "lipAp": 0.3,
- "lipProt": 1.4,
- "lipWidth": 0.067,
- "root": 0.446,
- "larynx": 0.284,
- "ttX": 6.243,
- "ttY": 7.376,
- "ttCurl": 0
- },
- "formants": [
- 378,
- 997,
- 2249,
- 3733
- ],
- "target": [
- 378,
- 997,
- 2343
- ],
- "err": [
- 0,
- 0,
- -4
- ]
- },
- "ʌ": {
- "artic": {
- "tbX": 1.96,
- "tbY": 6.199,
- "jaw": 0.935,
- "lipAp": 0.693,
- "lipProt": 0,
- "lipWidth": 0.651,
- "root": 0.24,
- "larynx": 0.059,
- "ttX": 5.828,
- "ttY": 6.29,
- "ttCurl": 0.001
- },
- "formants": [
- 622,
- 1212,
- 2393,
- 3816
- ],
- "target": [
- 623,
- 1200,
- 2550
- ],
- "err": [
- -0.1,
- 1,
- -6.2
- ]
- },
- "ə": {
- "artic": {
- "tbX": 2.936,
- "tbY": 6.647,
- "jaw": 0.503,
- "lipAp": 0.31,
- "lipProt": 0,
- "lipWidth": 0.54,
- "root": 0.393,
- "larynx": 0.153,
- "ttX": 6.288,
- "ttY": 6.826,
- "ttCurl": 0
- },
- "formants": [
- 502,
- 1456,
- 2356,
- 3618
- ],
- "target": [
- 500,
- 1450,
- 2450
- ],
- "err": [
- 0.5,
- 0.4,
- -3.9
- ]
- },
- "ɐ": {
- "artic": {
- "tbX": 2.391,
- "tbY": 6.042,
- "jaw": 1.348,
- "lipAp": 1.007,
- "lipProt": 0,
- "lipWidth": 0.667,
- "root": 0.161,
- "larynx": -0.004,
- "ttX": 5.783,
- "ttY": 5.875,
- "ttCurl": 0
- },
- "formants": [
- 638,
- 1372,
- 2405,
- 3754
- ],
- "target": [
- 640,
- 1350,
- 2500
- ],
- "err": [
- -0.3,
- 1.6,
- -3.8
- ]
- },
- "ɝ": {
- "artic": {
- "tbX": 2.733,
- "tbY": 7.236,
- "jaw": 0.762,
- "lipAp": 0.645,
- "lipProt": 0.596,
- "lipWidth": 0.336,
- "root": -0.9,
- "larynx": -0.886,
- "ttX": 5.73,
- "ttY": 8.802,
- "ttCurl": 1
- },
- "formants": [
- 466,
- 1362,
- 1819,
- 3075
- ],
- "target": [
- 474,
- 1379,
- 1710
- ],
- "err": [
- -1.7,
- -1.2,
- 6.4
- ]
- },
- "y": {
- "artic": {
- "tbX": 3.478,
- "tbY": 7.838,
- "jaw": 0.203,
- "lipAp": 0.3,
- "lipProt": 1.371,
- "lipWidth": 0.3,
- "root": 0.039,
- "larynx": 0.039,
- "ttX": 6.557,
- "ttY": 7.513,
- "ttCurl": 0
- },
- "formants": [
- 300,
- 1800,
- 2135,
- 3678
- ],
- "target": [
- 300,
- 1800,
- 2150
- ],
- "err": [
- -0.1,
- 0,
- -0.7
- ]
- },
- "ø": {
- "artic": {
- "tbX": 3.461,
- "tbY": 7.301,
- "jaw": 0.61,
- "lipAp": 0.323,
- "lipProt": 0.598,
- "lipWidth": 0.01,
- "root": 0.173,
- "larynx": 0.094,
- "ttX": 6.406,
- "ttY": 6.96,
- "ttCurl": 0
- },
- "formants": [
- 390,
- 1551,
- 2213,
- 3439
- ],
- "target": [
- 390,
- 1550,
- 2250
- ],
- "err": [
- 0.1,
- 0,
- -1.6
- ]
- },
- "œ": {
- "artic": {
- "tbX": 3.029,
- "tbY": 6.635,
- "jaw": 1.034,
- "lipAp": 0.685,
- "lipProt": 0.637,
- "lipWidth": 0.301,
- "root": 0.151,
- "larynx": 0.093,
- "ttX": 6.109,
- "ttY": 6.353,
- "ttCurl": 0
- },
- "formants": [
- 518,
- 1463,
- 2295,
- 3513
- ],
- "target": [
- 520,
- 1450,
- 2350
- ],
- "err": [
- -0.5,
- 0.9,
- -2.3
- ]
- },
- "ɨ": {
- "artic": {
- "tbX": 2.939,
- "tbY": 7.71,
- "jaw": 0.188,
- "lipAp": 0.191,
- "lipProt": 0.002,
- "lipWidth": 1,
- "root": 0.669,
- "larynx": 0.241,
- "ttX": 6.399,
- "ttY": 7.483,
- "ttCurl": 0.001
- },
- "formants": [
- 331,
- 1600,
- 2272,
- 3778
- ],
- "target": [
- 330,
- 1600,
- 2400
- ],
- "err": [
- 0.3,
- 0,
- -5.3
- ]
- },
- "ɯ": {
- "artic": {
- "tbX": 2.725,
- "tbY": 7.631,
- "jaw": 0.175,
- "lipAp": 0.177,
- "lipProt": 0.35,
- "lipWidth": 0.55,
- "root": 0.702,
- "larynx": 0.273,
- "ttX": 6.34,
- "ttY": 7.465,
- "ttCurl": 0
- },
- "formants": [
- 341,
- 1350,
- 2284,
- 3773
- ],
- "target": [
- 340,
- 1350,
- 2400
- ],
- "err": [
- 0.4,
- 0,
- -4.8
- ]
- },
- "ɤ": {
- "artic": {
- "tbX": 2.258,
- "tbY": 7.257,
- "jaw": 0.637,
- "lipAp": 0.465,
- "lipProt": 0.352,
- "lipWidth": 0.545,
- "root": 0.642,
- "larynx": 0.392,
- "ttX": 6.035,
- "ttY": 6.921,
- "ttCurl": 0
- },
- "formants": [
- 461,
- 1251,
- 2284,
- 3720
- ],
- "target": [
- 460,
- 1250,
- 2450
- ],
- "err": [
- 0.2,
- 0.1,
- -6.8
- ]
- }
- },
- "female": {
- "i": {
- "artic": {
- "tbX": 3.746,
- "tbY": 7.655,
- "jaw": 0.508,
- "lipAp": 1.132,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.332,
- "larynx": 1.016,
- "ttX": 6.529,
- "ttY": 7.175,
- "ttCurl": 0
- },
- "formants": [
- 428,
- 2670,
- 3235,
- 4543
- ],
- "target": [
- 437,
- 2761,
- 3372
- ],
- "err": [
- -2,
- -3.3,
- -4.1
- ]
- },
- "ɪ": {
- "artic": {
- "tbX": 3.65,
- "tbY": 7.423,
- "jaw": 0.587,
- "lipAp": 1.16,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.07,
- "larynx": 0.165,
- "ttX": 6.471,
- "ttY": 7.023,
- "ttCurl": 0
- },
- "formants": [
- 481,
- 2357,
- 2967,
- 4299
- ],
- "target": [
- 483,
- 2365,
- 3053
- ],
- "err": [
- -0.5,
- -0.3,
- -2.8
- ]
- },
- "e": {
- "artic": {
- "tbX": 3.577,
- "tbY": 7.384,
- "jaw": 0.918,
- "lipAp": 1.451,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.105,
- "larynx": 0.81,
- "ttX": 6.321,
- "ttY": 6.716,
- "ttCurl": 0
- },
- "formants": [
- 522,
- 2406,
- 2999,
- 4453
- ],
- "target": [
- 536,
- 2530,
- 3047
- ],
- "err": [
- -2.6,
- -4.9,
- -1.6
- ]
- },
- "ɛ": {
- "artic": {
- "tbX": 3.101,
- "tbY": 6.531,
- "jaw": 1.277,
- "lipAp": 1.705,
- "lipProt": 0,
- "lipWidth": 1,
- "root": -0.077,
- "larynx": 0.746,
- "ttX": 6.027,
- "ttY": 6.106,
- "ttCurl": 0
- },
- "formants": [
- 713,
- 2033,
- 2971,
- 4475
- ],
- "target": [
- 731,
- 2058,
- 2979
- ],
- "err": [
- -2.5,
- -1.2,
- -0.3
- ]
- },
- "æ": {
- "artic": {
- "tbX": 3.644,
- "tbY": 6.45,
- "jaw": 1.565,
- "lipAp": 1.916,
- "lipProt": 0,
- "lipWidth": 1,
- "root": -0.03,
- "larynx": 0.806,
- "ttX": 6.061,
- "ttY": 5.832,
- "ttCurl": 0
- },
- "formants": [
- 657,
- 2204,
- 3124,
- 4472
- ],
- "target": [
- 669,
- 2349,
- 2972
- ],
- "err": [
- -1.8,
- -6.2,
- 5.1
- ]
- },
- "a": {
- "artic": {
- "tbX": 2.222,
- "tbY": 5.785,
- "jaw": 1.778,
- "lipAp": 2,
- "lipProt": 0,
- "lipWidth": 1,
- "root": -0.311,
- "larynx": 0.626,
- "ttX": 5.535,
- "ttY": 5.42,
- "ttCurl": 0
- },
- "formants": [
- 840,
- 1735,
- 2887,
- 4545
- ],
- "target": [
- 913,
- 1740,
- 2933
- ],
- "err": [
- -8,
- -0.3,
- -1.6
- ]
- },
- "ɑ": {
- "artic": {
- "tbX": 1.858,
- "tbY": 5.835,
- "jaw": 1.853,
- "lipAp": 2,
- "lipProt": 0,
- "lipWidth": 1,
- "root": -0.534,
- "larynx": 0.506,
- "ttX": 5.389,
- "ttY": 5.375,
- "ttCurl": 0
- },
- "formants": [
- 858,
- 1553,
- 2820,
- 4543
- ],
- "target": [
- 936,
- 1551,
- 2815
- ],
- "err": [
- -8.4,
- 0.1,
- 0.2
- ]
- },
- "ɒ": {
- "artic": {
- "tbX": 1.332,
- "tbY": 5.86,
- "jaw": 1.486,
- "lipAp": 0.993,
- "lipProt": 0.318,
- "lipWidth": 0.519,
- "root": -0.18,
- "larynx": 0.005,
- "ttX": 5.403,
- "ttY": 5.694,
- "ttCurl": 0.001
- },
- "formants": [
- 704,
- 1069,
- 2757
- ],
- "target": [
- 725,
- 1056,
- 2875
- ],
- "err": [
- -2.9,
- 1.2,
- -4.1
- ]
- },
- "ɔ": {
- "artic": {
- "tbX": 1.403,
- "tbY": 6.232,
- "jaw": 1.253,
- "lipAp": 0.895,
- "lipProt": 0.285,
- "lipWidth": 0.582,
- "root": -0.57,
- "larynx": 0.24,
- "ttX": 5.528,
- "ttY": 6.022,
- "ttCurl": 0
- },
- "formants": [
- 728,
- 1162,
- 2700
- ],
- "target": [
- 781,
- 1136,
- 2824
- ],
- "err": [
- -6.7,
- 2.3,
- -4.4
- ]
- },
- "o": {
- "artic": {
- "tbX": 1.879,
- "tbY": 7.125,
- "jaw": 0.994,
- "lipAp": 0.304,
- "lipProt": 1.4,
- "lipWidth": 0.304,
- "root": 0.269,
- "larynx": 0.469,
- "ttX": 5.781,
- "ttY": 6.56,
- "ttCurl": 0
- },
- "formants": [
- 546,
- 1048,
- 2643,
- 4234
- ],
- "target": [
- 555,
- 1035,
- 2828
- ],
- "err": [
- -1.6,
- 1.2,
- -6.5
- ]
- },
- "ʊ": {
- "artic": {
- "tbX": 2.34,
- "tbY": 7.274,
- "jaw": 0.571,
- "lipAp": 0.374,
- "lipProt": 1.4,
- "lipWidth": 0.301,
- "root": 0.343,
- "larynx": 0.395,
- "ttX": 6.084,
- "ttY": 6.985,
- "ttCurl": 0
- },
- "formants": [
- 517,
- 1229,
- 2713,
- 4316
- ],
- "target": [
- 519,
- 1225,
- 2827
- ],
- "err": [
- -0.5,
- 0.3,
- -4
- ]
- },
- "u": {
- "artic": {
- "tbX": 2.256,
- "tbY": 7.388,
- "jaw": 0.263,
- "lipAp": 0.194,
- "lipProt": 1.4,
- "lipWidth": 0.301,
- "root": 0.206,
- "larynx": 0.237,
- "ttX": 6.17,
- "ttY": 7.3,
- "ttCurl": 0
- },
- "formants": [
- 457,
- 1107,
- 2657,
- 4413
- ],
- "target": [
- 459,
- 1105,
- 2735
- ],
- "err": [
- -0.4,
- 0.2,
- -2.8
- ]
- },
- "ʌ": {
- "artic": {
- "tbX": 1.891,
- "tbY": 6.293,
- "jaw": 1.053,
- "lipAp": 0.894,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.178,
- "larynx": 0.086,
- "ttX": 5.759,
- "ttY": 6.217,
- "ttCurl": 0
- },
- "formants": [
- 748,
- 1447,
- 2729
- ],
- "target": [
- 753,
- 1426,
- 2933
- ],
- "err": [
- -0.7,
- 1.5,
- -7
- ]
- },
- "ə": {
- "artic": {
- "tbX": 2.976,
- "tbY": 6.838,
- "jaw": 0.749,
- "lipAp": 0.531,
- "lipProt": 0,
- "lipWidth": 0.544,
- "root": 0.262,
- "larynx": 0.111,
- "ttX": 6.207,
- "ttY": 6.675,
- "ttCurl": 0
- },
- "formants": [
- 587,
- 1745,
- 2741,
- 4248
- ],
- "target": [
- 585,
- 1740,
- 2818
- ],
- "err": [
- 0.4,
- 0.3,
- -2.7
- ]
- },
- "ɐ": {
- "artic": {
- "tbX": 2.392,
- "tbY": 6.13,
- "jaw": 1.393,
- "lipAp": 1.124,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.139,
- "larynx": 0.032,
- "ttX": 5.763,
- "ttY": 5.866,
- "ttCurl": 0
- },
- "formants": [
- 744,
- 1646,
- 2769,
- 4459
- ],
- "target": [
- 749,
- 1620,
- 2875
- ],
- "err": [
- -0.6,
- 1.6,
- -3.7
- ]
- },
- "ɝ": {
- "artic": {
- "tbX": 2.683,
- "tbY": 7.314,
- "jaw": 0.664,
- "lipAp": 0.651,
- "lipProt": 0.587,
- "lipWidth": 0.345,
- "root": -0.9,
- "larynx": -0.815,
- "ttX": 5.752,
- "ttY": 8.916,
- "ttCurl": 1
- },
- "formants": [
- 513,
- 1568,
- 2171,
- 3435
- ],
- "target": [
- 523,
- 1588,
- 1929
- ],
- "err": [
- -1.9,
- -1.3,
- 12.5
- ]
- },
- "y": {
- "artic": {
- "tbX": 3.501,
- "tbY": 7.868,
- "jaw": 0.225,
- "lipAp": 0.303,
- "lipProt": 0.741,
- "lipWidth": 0.303,
- "root": -0.308,
- "larynx": 0.213,
- "ttX": 6.556,
- "ttY": 7.505,
- "ttCurl": 0.001
- },
- "formants": [
- 350,
- 2159,
- 2514,
- 4499
- ],
- "target": [
- 351,
- 2160,
- 2473
- ],
- "err": [
- -0.2,
- -0.1,
- 1.7
- ]
- },
- "ø": {
- "artic": {
- "tbX": 3.458,
- "tbY": 7.421,
- "jaw": 0.648,
- "lipAp": 0.508,
- "lipProt": 1.09,
- "lipWidth": 0.265,
- "root": -0.027,
- "larynx": -0.027,
- "ttX": 6.391,
- "ttY": 6.968,
- "ttCurl": 0
- },
- "formants": [
- 457,
- 1859,
- 2595,
- 3971
- ],
- "target": [
- 456,
- 1860,
- 2588
- ],
- "err": [
- 0,
- 0,
- 0.3
- ]
- },
- "œ": {
- "artic": {
- "tbX": 3.071,
- "tbY": 6.652,
- "jaw": 1.044,
- "lipAp": 0.748,
- "lipProt": 0.573,
- "lipWidth": 0.379,
- "root": -0.208,
- "larynx": 0.166,
- "ttX": 6.118,
- "ttY": 6.351,
- "ttCurl": 0
- },
- "formants": [
- 596,
- 1732,
- 2700,
- 4145
- ],
- "target": [
- 608,
- 1740,
- 2703
- ],
- "err": [
- -2.1,
- -0.5,
- -0.1
- ]
- },
- "ɨ": {
- "artic": {
- "tbX": 2.866,
- "tbY": 7.732,
- "jaw": 0.195,
- "lipAp": 0.644,
- "lipProt": 0.35,
- "lipWidth": 0.78,
- "root": 0.339,
- "larynx": 0.172,
- "ttX": 6.376,
- "ttY": 7.482,
- "ttCurl": 0
- },
- "formants": [
- 386,
- 1920,
- 2698
- ],
- "target": [
- 386,
- 1920,
- 2760
- ],
- "err": [
- 0,
- 0,
- -2.2
- ]
- },
- "ɯ": {
- "artic": {
- "tbX": 2.648,
- "tbY": 7.644,
- "jaw": 0.182,
- "lipAp": 0.263,
- "lipProt": 0,
- "lipWidth": 1,
- "root": 0.364,
- "larynx": 0.186,
- "ttX": 6.314,
- "ttY": 7.464,
- "ttCurl": 0
- },
- "formants": [
- 399,
- 1620,
- 2699,
- 4573
- ],
- "target": [
- 398,
- 1620,
- 2760
- ],
- "err": [
- 0.2,
- 0,
- -2.2
- ]
- },
- "ɤ": {
- "artic": {
- "tbX": 2.315,
- "tbY": 7.3,
- "jaw": 0.687,
- "lipAp": 0.514,
- "lipProt": 0,
- "lipWidth": 0.837,
- "root": 0.431,
- "larynx": 0.283,
- "ttX": 6.033,
- "ttY": 6.891,
- "ttCurl": 0
- },
- "formants": [
- 539,
- 1500,
- 2699,
- 4488
- ],
- "target": [
- 538,
- 1500,
- 2818
- ],
- "err": [
- 0.2,
- 0,
- -4.2
- ]
- }
- },
- "child": {
- "i": {
- "artic": {
- "tbX": 3.72,
- "tbY": 7.753,
- "jaw": 0.094,
- "lipAp": 0.381,
- "lipProt": 0,
- "lipWidth": 0.636,
- "root": 0.095,
- "larynx": -0.002,
- "ttX": 6.665,
- "ttY": 7.583,
- "ttCurl": 0.001
- },
- "formants": [
- 453,
- 3102,
- 3632
- ],
- "target": [
- 452,
- 3081,
- 3702
- ],
- "err": [
- 0.1,
- 0.7,
- -1.9
- ]
- },
- "ɪ": {
- "artic": {
- "tbX": 3.379,
- "tbY": 7.696,
- "jaw": 0.486,
- "lipAp": 0.363,
- "lipProt": 0,
- "lipWidth": 0.55,
- "root": 0.007,
- "larynx": -0.024,
- "ttX": 6.427,
- "ttY": 7.208,
- "ttCurl": 0
- },
- "formants": [
- 512,
- 2551,
- 3416
- ],
- "target": [
- 511,
- 2552,
- 3403
- ],
- "err": [
- 0.1,
- 0,
- 0.4
- ]
- },
- "e": {
- "artic": {
- "tbX": 3.484,
- "tbY": 7.553,
- "jaw": 0.678,
- "lipAp": 0.704,
- "lipProt": 0.351,
- "lipWidth": 0.55,
- "root": -0.202,
- "larynx": -0.135,
- "ttX": 6.387,
- "ttY": 6.987,
- "ttCurl": 0
- },
- "formants": [
- 564,
- 2651,
- 3386
- ],
- "target": [
- 564,
- 2656,
- 3323
- ],
- "err": [
- 0,
- -0.2,
- 1.9
- ]
- },
- "ɛ": {
- "artic": {
- "tbX": 3.124,
- "tbY": 6.839,
- "jaw": 1.113,
- "lipAp": 1.132,
- "lipProt": 0.355,
- "lipWidth": 0.548,
- "root": -0.3,
- "larynx": -0.152,
- "ttX": 6.104,
- "ttY": 6.356,
- "ttCurl": 0
- },
- "formants": [
- 745,
- 2274,
- 3402
- ],
- "target": [
- 749,
- 2267,
- 3310
- ],
- "err": [
- -0.5,
- 0.3,
- 2.8
- ]
- },
- "æ": {
- "artic": {
- "tbX": 3.534,
- "tbY": 6.687,
- "jaw": 1.455,
- "lipAp": 1.473,
- "lipProt": 0.358,
- "lipWidth": 0.547,
- "root": -0.48,
- "larynx": -0.227,
- "ttX": 6.079,
- "ttY": 6.009,
- "ttCurl": 0
- },
- "formants": [
- 719,
- 2469,
- 3475
- ],
- "target": [
- 717,
- 2501,
- 3289
- ],
- "err": [
- 0.2,
- -1.3,
- 5.7
- ]
- },
- "a": {
- "artic": {
- "tbX": 2.076,
- "tbY": 6.177,
- "jaw": 1.952,
- "lipAp": 2,
- "lipProt": 0.323,
- "lipWidth": 1,
- "root": -0.56,
- "larynx": -0.058,
- "ttX": 5.407,
- "ttY": 5.413,
- "ttCurl": 0
- },
- "formants": [
- 987,
- 1959,
- 3333
- ],
- "target": [
- 1014,
- 1929,
- 3162
- ],
- "err": [
- -2.6,
- 1.6,
- 5.4
- ]
- },
- "ɑ": {
- "artic": {
- "tbX": 1.7,
- "tbY": 6.233,
- "jaw": 2.006,
- "lipAp": 2,
- "lipProt": 0.361,
- "lipWidth": 0.761,
- "root": -0.9,
- "larynx": -0.345,
- "ttX": 5.267,
- "ttY": 5.387,
- "ttCurl": 0
- },
- "formants": [
- 985,
- 1709,
- 3214
- ],
- "target": [
- 1002,
- 1688,
- 2950
- ],
- "err": [
- -1.7,
- 1.2,
- 9
- ]
- },
- "ɒ": {
- "artic": {
- "tbX": 1.2,
- "tbY": 6.165,
- "jaw": 1.787,
- "lipAp": 0.947,
- "lipProt": 1.075,
- "lipWidth": 0.476,
- "root": -0.056,
- "larynx": -0.217,
- "ttX": 5.224,
- "ttY": 5.545,
- "ttCurl": 0
- },
- "formants": [
- 791,
- 1203,
- 3264
- ],
- "target": [
- 806,
- 1170,
- 3100
- ],
- "err": [
- -1.9,
- 2.8,
- 5.3
- ]
- },
- "ɔ": {
- "artic": {
- "tbX": 1.22,
- "tbY": 6.771,
- "jaw": 1.398,
- "lipAp": 0.761,
- "lipProt": 1.031,
- "lipWidth": 0.459,
- "root": -0.453,
- "larynx": -0.052,
- "ttX": 5.41,
- "ttY": 6.088,
- "ttCurl": 0.001
- },
- "formants": [
- 788,
- 1229,
- 3098
- ],
- "target": [
- 803,
- 1210,
- 2982
- ],
- "err": [
- -1.9,
- 1.6,
- 3.9
- ]
- },
- "o": {
- "artic": {
- "tbX": 1.862,
- "tbY": 7.266,
- "jaw": 0.787,
- "lipAp": 0.129,
- "lipProt": 1.188,
- "lipWidth": 0.301,
- "root": -0.587,
- "larynx": -0.227,
- "ttX": 5.858,
- "ttY": 6.79,
- "ttCurl": 0
- },
- "formants": [
- 596,
- 1139,
- 3066
- ],
- "target": [
- 597,
- 1137,
- 2987
- ],
- "err": [
- -0.2,
- 0.2,
- 2.6
- ]
- },
- "ʊ": {
- "artic": {
- "tbX": 2.335,
- "tbY": 7.487,
- "jaw": 0.498,
- "lipAp": 0.368,
- "lipProt": 0.6,
- "lipWidth": 0.266,
- "root": -0.495,
- "larynx": -0.248,
- "ttX": 6.109,
- "ttY": 7.124,
- "ttCurl": 0
- },
- "formants": [
- 568,
- 1490,
- 3162
- ],
- "target": [
- 568,
- 1490,
- 3072
- ],
- "err": [
- 0.1,
- 0,
- 2.9
- ]
- },
- "u": {
- "artic": {
- "tbX": 2.334,
- "tbY": 7.569,
- "jaw": 0.166,
- "lipAp": 0.3,
- "lipProt": 0.651,
- "lipWidth": 0.057,
- "root": -0.652,
- "larynx": -0.325,
- "ttX": 6.226,
- "ttY": 7.452,
- "ttCurl": 0
- },
- "formants": [
- 495,
- 1344,
- 3081
- ],
- "target": [
- 494,
- 1345,
- 2988
- ],
- "err": [
- 0.2,
- -0.1,
- 3.1
- ]
- },
- "ʌ": {
- "artic": {
- "tbX": 1.915,
- "tbY": 7.103,
- "jaw": 0.882,
- "lipAp": 0.578,
- "lipProt": 0.373,
- "lipWidth": 0.512,
- "root": -0.172,
- "larynx": -0.16,
- "ttX": 5.837,
- "ttY": 6.65,
- "ttCurl": 0
- },
- "formants": [
- 749,
- 1565,
- 3212
- ],
- "target": [
- 749,
- 1546,
- 3145
- ],
- "err": [
- -0.1,
- 1.2,
- 2.1
- ]
- },
- "ə": {
- "artic": {
- "tbX": 2.54,
- "tbY": 7.427,
- "jaw": 0.801,
- "lipAp": 0.56,
- "lipProt": 0.359,
- "lipWidth": 1,
- "root": -0.519,
- "larynx": -0.357,
- "ttX": 6.056,
- "ttY": 6.834,
- "ttCurl": 0
- },
- "formants": [
- 652,
- 1937,
- 3146
- ],
- "target": [
- 650,
- 1929,
- 3038
- ],
- "err": [
- 0.4,
- 0.4,
- 3.6
- ]
- },
- "ɐ": {
- "artic": {
- "tbX": 2.235,
- "tbY": 6.605,
- "jaw": 1.373,
- "lipAp": 0.981,
- "lipProt": 0.38,
- "lipWidth": 0.513,
- "root": -0.317,
- "larynx": -0.295,
- "ttX": 5.726,
- "ttY": 6.05,
- "ttCurl": 0
- },
- "formants": [
- 832,
- 1827,
- 3247
- ],
- "target": [
- 832,
- 1796,
- 3100
- ],
- "err": [
- 0,
- 1.8,
- 4.7
- ]
- },
- "ɝ": {
- "artic": {
- "tbX": 1.908,
- "tbY": 6.905,
- "jaw": 0.05,
- "lipAp": 0.12,
- "lipProt": 1.4,
- "lipWidth": 0.341,
- "root": -0.9,
- "larynx": -1.013,
- "ttX": 5.736,
- "ttY": 9.324,
- "ttCurl": 1
- },
- "formants": [
- 569,
- 1670,
- 2411,
- 3631
- ],
- "target": [
- 586,
- 1719,
- 2143
- ],
- "err": [
- -2.8,
- -2.9,
- 12.5
- ]
- },
- "y": {
- "artic": {
- "tbX": 3.55,
- "tbY": 7.97,
- "jaw": 0.241,
- "lipAp": 0.183,
- "lipProt": 1.024,
- "lipWidth": 0.302,
- "root": -0.9,
- "larynx": 0.122,
- "ttX": 6.565,
- "ttY": 7.524,
- "ttCurl": 0
- },
- "formants": [
- 389,
- 2394,
- 3127
- ],
- "target": [
- 390,
- 2394,
- 2666
- ],
- "err": [
- -0.2,
- 0,
- 17.3
- ]
- },
- "ø": {
- "artic": {
- "tbX": 3.451,
- "tbY": 7.637,
- "jaw": 0.697,
- "lipAp": 0.285,
- "lipProt": 1.4,
- "lipWidth": 0.302,
- "root": -0.9,
- "larynx": -0.599,
- "ttX": 6.37,
- "ttY": 7,
- "ttCurl": 0
- },
- "formants": [
- 507,
- 2058,
- 2971
- ],
- "target": [
- 507,
- 2062,
- 2790
- ],
- "err": [
- 0,
- -0.2,
- 6.5
- ]
- },
- "œ": {
- "artic": {
- "tbX": 2.999,
- "tbY": 6.988,
- "jaw": 1.197,
- "lipAp": 0.695,
- "lipProt": 1.169,
- "lipWidth": 0.319,
- "root": -0.9,
- "larynx": -0.46,
- "ttX": 6.031,
- "ttY": 6.336,
- "ttCurl": 0
- },
- "formants": [
- 671,
- 1932,
- 3082
- ],
- "target": [
- 676,
- 1929,
- 2914
- ],
- "err": [
- -0.8,
- 0.2,
- 5.8
- ]
- },
- "ɨ": {
- "artic": {
- "tbX": 3.09,
- "tbY": 7.892,
- "jaw": 0.178,
- "lipAp": 0.131,
- "lipProt": 0,
- "lipWidth": 0.804,
- "root": -0.868,
- "larynx": 0.161,
- "ttX": 6.449,
- "ttY": 7.554,
- "ttCurl": 0
- },
- "formants": [
- 430,
- 2128,
- 3161
- ],
- "target": [
- 429,
- 2128,
- 2976
- ],
- "err": [
- 0.2,
- 0,
- 6.2
- ]
- },
- "ɯ": {
- "artic": {
- "tbX": 2.712,
- "tbY": 7.766,
- "jaw": 0.155,
- "lipAp": 0.198,
- "lipProt": 0.352,
- "lipWidth": 0.608,
- "root": -0.55,
- "larynx": -0.434,
- "ttX": 6.343,
- "ttY": 7.531,
- "ttCurl": 0
- },
- "formants": [
- 446,
- 1793,
- 3097
- ],
- "target": [
- 442,
- 1796,
- 2976
- ],
- "err": [
- 1,
- -0.1,
- 4.1
- ]
- },
- "ɤ": {
- "artic": {
- "tbX": 1.934,
- "tbY": 7.366,
- "jaw": 0.721,
- "lipAp": 0.816,
- "lipProt": 0.095,
- "lipWidth": 0.582,
- "root": -0.442,
- "larynx": -0.208,
- "ttX": 5.905,
- "ttY": 6.884,
- "ttCurl": 0
- },
- "formants": [
- 598,
- 1662,
- 3114
- ],
- "target": [
- 598,
- 1663,
- 3038
- ],
- "err": [
- 0.1,
- 0,
- 2.5
- ]
- }
- }
-}
\ No newline at end of file
diff --git a/src/engine/physics.ts b/src/engine/physics.ts
deleted file mode 100644
index 5a53dcf..0000000
--- a/src/engine/physics.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-/**
- * Physical constants for airway acoustics, CGS units throughout
- * (cm, g, s; pressure in dyn/cm² = 0.1 Pa; volume velocity in cm³/s).
- */
-
-/** Air density at body temperature, saturated (g/cm³). */
-export const RHO = 1.14e-3;
-/** Speed of sound in warm humid air (cm/s). */
-export const C_SOUND = 35000;
-/** Dynamic viscosity of air (poise = g/(cm·s)). */
-export const MU = 1.86e-4;
-/** Kinematic viscosity (cm²/s). */
-export const NU = MU / RHO;
-/** ρc² — bulk modulus of air (dyn/cm²). */
-export const RHO_C2 = RHO * C_SOUND * C_SOUND;
-/** 1 cm H2O in dyn/cm². */
-export const CM_H2O = 980.665;
-
-/** Soft-tissue wall parameters per unit area (Ishizaka, French & Flanagan 1975, cheek/neck). */
-export interface WallParams {
- /** mass per unit area (g/cm²) */
- mass: number;
- /** resistance per unit area (dyn·s/cm³) */
- resistance: number;
- /** stiffness per unit area (dyn/cm³) */
- stiffness: number;
-}
-
-export const WALL_SOFT: WallParams = { mass: 1.5, resistance: 1600, stiffness: 3.0e5 };
-/** Cartilaginous trachea: stiffer and lighter. */
-export const WALL_TRACHEA: WallParams = { mass: 0.6, resistance: 1000, stiffness: 1.0e6 };
-/** Nasal mucosa: lossy. */
-export const WALL_NASAL: WallParams = { mass: 1.0, resistance: 3000, stiffness: 1.0e6 };
-
-/** Critical Reynolds number for onset of turbulence noise. */
-export const RE_CRIT = 1800;
diff --git a/src/engine/sources/glottis.ts b/src/engine/sources/glottis.ts
deleted file mode 100644
index 8fd3aba..0000000
--- a/src/engine/sources/glottis.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-/**
- * Parametric vocal-fold source: generates the glottal *area* waveform, which drives the
- * interactive glottal port of the airway network. Flow is computed by the network
- * (Bernoulli + inertance), so pulse skewing, F1 ripple and devoicing under oral closure
- * emerge from the physics.
- *
- * Voicing is gated physiologically:
- * - transglottal pressure must exceed the phonation threshold (≈2–3 cmH₂O),
- * - wide abduction (voiceless consonants, /h/) stops vibration.
- */
-import { CM_H2O } from "../physics.ts";
-import { Rng, Drift, TAU, clamp, smoothstep } from "../util/math.ts";
-
-export interface GlottisParams {
- /** fundamental frequency (Hz) */
- f0: number;
- /** peak vibratory area (cm²) at full effort */
- amplitude: number;
- /** abduction: static opening between the vocal processes (cm²) */
- abduction: number;
- /** posterior chink leakage (cm²), always open */
- chink: number;
- /** open quotient 0..1 */
- openQuotient: number;
- /** fraction of the open phase spent opening (0.5 symmetric, larger = faster closing) */
- skew: number;
- /** 0 = smooth (raised-cosine) closure, 1 = abrupt slope at closure */
- closureSharpness: number;
- /** vocal effort 0..1 (scales amplitude; pressed voice lowers OQ) */
- effort: number;
- /** cycle-to-cycle period perturbation (fraction, e.g. 0.006) */
- jitter: number;
- /** cycle-to-cycle amplitude perturbation (fraction, e.g. 0.04) */
- shimmer: number;
- /** vibrato depth (cents) and rate (Hz) */
- vibratoDepth: number;
- vibratoRate: number;
- /** slow random pitch drift (cents) */
- drift: number;
- /** vocal fry 0..1: low-frequency double-pulsing with short open phase */
- fry: number;
- /** diplophonia / period doubling 0..1 (alternating amplitude & period) */
- diplophonia: number;
- /** extra glottal closure force 0..1 (glottal stop / ejective: holds the folds shut) */
- closure: number;
- /**
- * bifurcation 0..1: a logistic map drives per-cycle period and amplitude. Rising values walk
- * through period doubling (subharmonics, ~0.3), period four (~0.55) into deterministic chaos (>0.62).
- */
- chaos: number;
-}
-
-export const DEFAULT_GLOTTIS: GlottisParams = {
- f0: 110,
- amplitude: 0.16,
- abduction: 0.0,
- chink: 0.006,
- openQuotient: 0.62,
- skew: 0.62,
- closureSharpness: 0.6,
- effort: 0.7,
- jitter: 0.004,
- shimmer: 0.03,
- vibratoDepth: 0,
- vibratoRate: 5.5,
- drift: 6,
- fry: 0,
- diplophonia: 0,
- closure: 0,
- chaos: 0,
-};
-
-export class ParametricGlottis {
- readonly fs: number;
- params: GlottisParams = { ...DEFAULT_GLOTTIS };
- private phase = 0;
- private cycleAmp = 1;
- private cyclePeriodScale = 1;
- private cycleIndex = 0;
- private chaosX = 0.37;
- private vibPhase = 0;
- private readonly rng = new Rng(777);
- private readonly drift: Drift;
- private driftValue = 0;
- private driftCounter = 0;
- private pitchFactor = 1;
- /** smoothed voicing gate 0..1 (telemetry) */
- voicing = 0;
- private voicingSm = 0;
- /** smoothed transglottal pressure (dyn/cm²) */
- private dpSm = 0;
- private readonly dpCoef: number;
- private readonly voiceCoef: number;
- /** last area (telemetry) */
- area = 0;
- /** instantaneous f0 actually used (telemetry) */
- f0Now = 110;
- /** phonation threshold pressure (dyn/cm²) */
- threshold = 2.5 * CM_H2O;
- // per-sample smoothing of control-rate parameters (steps in the glottal area at high airflow
- // radiate as clicks, because the output is the derivative of flow)
- private staticSm = 0;
- private closureSm = 0;
- private ampSm = 0;
- private readonly smCoef: number;
-
- constructor(fs: number) {
- this.fs = fs;
- this.drift = new Drift(fs / 32, 0.3, 4242);
- this.dpCoef = 1 - Math.exp(-TAU * 30 / fs);
- this.voiceCoef = 1 - Math.exp(-TAU * 25 / fs);
- this.smCoef = 1 - Math.exp(-1 / (0.004 * fs));
- }
-
- /** Reset phase etc. */
- reset(): void {
- this.phase = 0;
- this.voicingSm = 0;
- this.dpSm = 0;
- }
-
- /**
- * Advance one sample. `dp` is the instantaneous transglottal pressure (p_sub − p_supra).
- * Returns the glottal area (cm²).
- */
- next(dp: number): number {
- const P = this.params;
- this.dpSm += this.dpCoef * (dp - this.dpSm);
-
- // drift and vibrato evaluated at a decimated rate (pitch modulation is slow)
- if (--this.driftCounter <= 0) {
- this.driftCounter = 32;
- this.driftValue = this.drift.step();
- this.vibPhase += ((P.vibratoRate * 32) / this.fs) * (1 + 0.04 * this.driftValue);
- if (this.vibPhase > 1) this.vibPhase -= 1;
- const cents = P.vibratoDepth * Math.sin(TAU * this.vibPhase) + P.drift * this.driftValue;
- this.pitchFactor = Math.pow(2, cents / 1200);
- }
- let f0 = P.f0 * this.pitchFactor;
- // fry pulls the rate down toward ~45 Hz
- if (P.fry > 0) f0 = f0 * (1 - P.fry) + Math.min(f0, 48) * P.fry;
- this.f0Now = f0;
-
- // voicing gate: pressure above threshold, adduction sufficient, not forcibly closed
- const pressureGate = smoothstep(this.threshold * 0.8, this.threshold * 1.6, this.dpSm);
- const adductGate = 1 - smoothstep(0.08, 0.22, this.staticSm - P.chink);
- const target = pressureGate * adductGate * (1 - this.closureSm);
- this.voicingSm += this.voiceCoef * (target - this.voicingSm);
- this.voicing = this.voicingSm;
-
- // phase advance with per-cycle perturbations
- this.phase += (f0 / this.fs) / this.cyclePeriodScale;
- if (this.phase >= 1) {
- this.phase -= 1;
- this.cycleIndex++;
- const alt = this.cycleIndex & 1 ? 1 : -1;
- let chaosP = 0, chaosA = 0;
- if (P.chaos > 0) {
- const r = 2.9 + 1.1 * Math.min(1, P.chaos);
- this.chaosX = r * this.chaosX * (1 - this.chaosX);
- if (!(this.chaosX > 0 && this.chaosX < 1)) this.chaosX = 0.37;
- const dev = this.chaosX - 0.5;
- chaosP = 0.45 * P.chaos * dev;
- chaosA = 1.1 * P.chaos * dev;
- }
- this.cyclePeriodScale = 1 + P.jitter * this.rng.gauss() + P.diplophonia * 0.08 * alt + chaosP;
- this.cyclePeriodScale = clamp(this.cyclePeriodScale, 0.55, 1.8);
- this.cycleAmp = Math.max(0.12, 1 + P.shimmer * this.rng.gauss() - P.diplophonia * 0.35 * (alt > 0 ? 1 : 0) + chaosA);
- }
-
- // pulse shape within the cycle
- let oq = clamp(P.openQuotient - 0.18 * (P.effort - 0.5), 0.25, 0.98);
- if (P.fry > 0) oq = oq * (1 - P.fry) + 0.28 * P.fry;
- let pulse = this.shape(this.phase, oq, P.skew, P.closureSharpness);
- if (P.fry > 0.3) {
- // second, weaker pulse shortly after the first (double pulsing typical of fry)
- const ph2 = this.phase - 0.38;
- if (ph2 > 0) pulse += 0.55 * smoothstep(0.3, 0.8, P.fry) * this.shape(ph2, oq * 0.8, P.skew, P.closureSharpness);
- }
- const effortScale = 0.45 + 0.75 * P.effort;
- const sc = this.smCoef;
- this.ampSm += sc * (P.amplitude * effortScale - this.ampSm);
- this.closureSm += sc * (P.closure - this.closureSm);
- this.staticSm += sc * (P.abduction + P.chink - this.staticSm);
- const vib = this.ampSm * this.cycleAmp * this.voicingSm * pulse;
- const statics = this.staticSm * (1 - 0.92 * this.closureSm);
- const a = Math.max(0, vib + statics);
- this.area = a;
- return a;
- }
-
- /** Normalised area pulse (0..1) at cycle phase ph. */
- private shape(ph: number, oq: number, skew: number, sharp: number): number {
- if (ph >= oq) return 0;
- const t = ph / oq;
- const s = clamp(skew, 0.3, 0.9);
- if (t < s) return 0.5 - 0.5 * Math.cos((Math.PI * t) / s);
- const u = (t - s) / (1 - s);
- const soft = 0.5 + 0.5 * Math.cos(Math.PI * u);
- const hard = Math.cos(0.5 * Math.PI * u);
- return soft + (hard - soft) * sharp;
- }
-
- get cyclePhase(): number {
- return this.phase;
- }
-}
diff --git a/src/engine/sources/syrinx.ts b/src/engine/sources/syrinx.ts
deleted file mode 100644
index df4ca29..0000000
--- a/src/engine/sources/syrinx.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-/**
- * Songbird syrinx: one labial pair modelled by the Gardner–Mindlin normal form
- * X' = Y, Y' = −α − βX − X³ − X²Y + X² − XY (τ = γ·t)
- * γ is a pure time scale for fixed (α, β), so pitch is exact: γ = f0·T(α, β), with the limit-cycle
- * period T tabulated offline (tools/gen-syrinx-table.ts). α (drive ≈ air-sac pressure) moves the
- * waveform from a near-sine (Hopf onset) to rich relaxation pulses; β (labial tension) shapes it.
- * The labial displacement maps to the valve opening of its bronchus.
- */
-import table from "./syrinxTable.generated.json";
-
-interface Table {
- alphas: number[];
- betas: number[];
- T: (number | null)[][];
- lo: number[][];
- hi: number[][];
-}
-const TB = table as unknown as Table;
-
-// fill cells without a limit cycle from their neighbours
-for (let bi = 0; bi < TB.betas.length; bi++)
- for (let ai = TB.alphas.length - 1; ai >= 0; ai--) {
- const v = TB.T[bi][ai];
- if (v === null || !Number.isFinite(v)) {
- TB.T[bi][ai] = TB.T[bi][ai + 1] ?? TB.T[bi + 1]?.[ai] ?? 10;
- TB.lo[bi][ai] = TB.lo[bi][ai + 1] ?? -1;
- TB.hi[bi][ai] = TB.hi[bi][ai + 1] ?? 1;
- }
- }
-
-function bilinear(grid: (number | null)[][], a: number, b: number): number {
- const as = TB.alphas, bs = TB.betas;
- const fa = Math.max(0, Math.min(as.length - 1.0001, ((a - as[0]) / (as[as.length - 1] - as[0])) * (as.length - 1)));
- const fb = Math.max(0, Math.min(bs.length - 1.0001, ((b - bs[0]) / (bs[bs.length - 1] - bs[0])) * (bs.length - 1)));
- const ia = Math.floor(fa), ib = Math.floor(fb);
- const u = fa - ia, w = fb - ib;
- const g = (i: number, j: number) => grid[j][i] as number;
- return (1 - w) * ((1 - u) * g(ia, ib) + u * g(ia + 1, ib)) + w * ((1 - u) * g(ia, ib + 1) + u * g(ia + 1, ib + 1));
-}
-
-export const ALPHA_RANGE: [number, number] = [0.09, 0.6];
-export const BETA_RANGE: [number, number] = [0.2, 1.3];
-
-export class SyrinxLabia {
- private x = 0.2;
- private y = 0;
- /** drive 0..1 → α; tension 0..1 → β */
- drive = 0.5;
- tension = 0.4;
- f0 = 3000;
- /** 0..1 gate (syringeal muscle opening this side) */
- gate = 1;
- private readonly fs: number;
- /** last opening 0..1 (telemetry) */
- opening = 0;
- private gateSm = 0;
-
- constructor(fs: number, seed = 0) {
- this.fs = fs;
- this.x = 0.2 + 0.05 * seed;
- }
-
- private static rhs(x: number, y: number, a: number, b: number, out: Float64Array): void {
- out[0] = y;
- out[1] = -a - b * x - x * x * x - x * x * y + x * x - x * y;
- }
-
- private k = new Float64Array(8);
-
- /** Advance one sample; returns the valve opening 0..1. */
- next(): number {
- const a = ALPHA_RANGE[0] + (ALPHA_RANGE[1] - ALPHA_RANGE[0]) * Math.max(0, Math.min(1, this.drive));
- const b = BETA_RANGE[0] + (BETA_RANGE[1] - BETA_RANGE[0]) * Math.max(0, Math.min(1, this.tension));
- const T = bilinear(TB.T, a, b);
- const dtau = (T * this.f0) / this.fs;
- const n = Math.max(1, Math.ceil(dtau / 0.06));
- const h = dtau / n;
- const k = this.k;
- let x = this.x, y = this.y;
- for (let i = 0; i < n; i++) {
- // RK4 (allocation-free)
- SyrinxLabia.rhs(x, y, a, b, k);
- const k1x = k[0], k1y = k[1];
- SyrinxLabia.rhs(x + 0.5 * h * k1x, y + 0.5 * h * k1y, a, b, k);
- const k2x = k[0], k2y = k[1];
- SyrinxLabia.rhs(x + 0.5 * h * k2x, y + 0.5 * h * k2y, a, b, k);
- const k3x = k[0], k3y = k[1];
- SyrinxLabia.rhs(x + h * k3x, y + h * k3y, a, b, k);
- x += (h / 6) * (k1x + 2 * k2x + 2 * k3x + k[0]);
- y += (h / 6) * (k1y + 2 * k2y + 2 * k3y + k[1]);
- }
- if (!Number.isFinite(x) || Math.abs(x) > 10) {
- x = 0.2;
- y = 0;
- }
- this.x = x;
- this.y = y;
- const lo = bilinear(TB.lo, a, b), hi = bilinear(TB.hi, a, b);
- const u = Math.max(0, Math.min(1, (x - lo) / Math.max(1e-3, hi - lo)));
- this.gateSm += (this.gate - this.gateSm) * 0.002;
- const open = u * u * this.gateSm;
- this.opening = open;
- return open;
- }
-}
diff --git a/src/engine/sources/syrinxTable.generated.json b/src/engine/sources/syrinxTable.generated.json
deleted file mode 100644
index 4e0efeb..0000000
--- a/src/engine/sources/syrinxTable.generated.json
+++ /dev/null
@@ -1 +0,0 @@
-{"alphas":[0.07,0.11416666666666667,0.15833333333333333,0.2025,0.24666666666666667,0.2908333333333334,0.335,0.3791666666666667,0.42333333333333334,0.4675,0.5116666666666667,0.5558333333333334,0.6000000000000001],"betas":[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.8999999999999999,0.9999999999999999,1.1,1.2,1.3],"T":[[null,17.204,12.545,10.62,9.463,8.66,8.055,7.577,7.184,6.853,6.568,6.319,6.098],[13.114,11.162,9.88,8.986,8.32,7.8,7.378,7.026,6.726,6.465,6.236,6.032,5.848],[10.239,9.332,8.611,8.041,7.582,7.202,6.881,6.605,6.364,6.151,5.961,5.788,5.632],[8.909,8.308,7.808,7.394,7.046,6.749,6.493,6.267,6.067,5.888,5.726,5.578,5.442],[8.059,7.61,7.23,6.907,6.629,6.387,6.175,5.985,5.815,5.661,5.521,5.392,5.272],[7.44,7.086,6.781,6.518,6.289,6.087,5.906,5.744,5.597,5.463,5.34,5.225,5.119],[6.958,6.668,6.417,6.197,6.003,5.83,5.675,5.534,5.405,5.286,5.177,5.075,4.98],[6.565,6.323,6.111,5.924,5.757,5.607,5.471,5.347,5.233,5.128,5.03,4.938,4.852],[6.235,6.03,5.849,5.687,5.542,5.41,5.29,5.18,5.078,4.983,4.895,4.812,4.734],[5.953,5.776,5.619,5.478,5.35,5.234,5.127,5.028,4.936,4.851,4.771,4.696,4.625],[5.707,5.553,5.416,5.291,5.178,5.074,4.978,4.889,4.806,4.729,4.656,4.588,4.523],[5.489,5.355,5.234,5.123,5.022,4.929,4.842,4.762,4.687,4.616,4.549,4.486,4.427],[5.296,5.177,5.069,4.971,4.88,4.796,4.717,4.644,4.575,4.511,4.45,4.392,4.337]],"lo":[[0.734,-0.616,-0.712,-0.79,-0.856,-0.914,-0.966,-1.012,-1.055,-1.094,-1.13,-1.163,-1.195],[-0.472,-0.596,-0.691,-0.769,-0.836,-0.894,-0.946,-0.992,-1.035,-1.074,-1.11,-1.144,-1.175],[-0.459,-0.579,-0.673,-0.75,-0.816,-0.874,-0.926,-0.973,-1.016,-1.055,-1.091,-1.125,-1.157],[-0.446,-0.564,-0.656,-0.733,-0.798,-0.856,-0.908,-0.954,-0.997,-1.036,-1.073,-1.107,-1.138],[-0.434,-0.55,-0.64,-0.716,-0.781,-0.839,-0.89,-0.937,-0.979,-1.019,-1.055,-1.089,-1.121],[-0.423,-0.536,-0.626,-0.7,-0.765,-0.822,-0.873,-0.92,-0.962,-1.001,-1.038,-1.072,-1.104],[-0.413,-0.524,-0.612,-0.685,-0.749,-0.806,-0.857,-0.903,-0.946,-0.985,-1.021,-1.055,-1.087],[-0.403,-0.512,-0.598,-0.671,-0.735,-0.791,-0.841,-0.887,-0.93,-0.969,-1.005,-1.039,-1.071],[-0.394,-0.501,-0.586,-0.658,-0.721,-0.776,-0.826,-0.872,-0.914,-0.953,-0.989,-1.023,-1.055],[-0.385,-0.49,-0.574,-0.645,-0.707,-0.762,-0.812,-0.857,-0.899,-0.938,-0.974,-1.008,-1.04],[-0.376,-0.48,-0.563,-0.633,-0.694,-0.749,-0.798,-0.843,-0.885,-0.924,-0.96,-0.994,-1.025],[-0.369,-0.47,-0.552,-0.621,-0.682,-0.736,-0.785,-0.83,-0.871,-0.91,-0.946,-0.979,-1.011],[-0.361,-0.461,-0.541,-0.61,-0.67,-0.723,-0.772,-0.817,-0.858,-0.896,-0.932,-0.965,-0.997]],"hi":[[0.734,0.622,0.653,0.679,0.697,0.711,0.72,0.726,0.729,0.729,0.728,0.724,0.719],[0.473,0.555,0.606,0.641,0.666,0.684,0.697,0.706,0.712,0.715,0.716,0.715,0.712],[0.433,0.519,0.574,0.613,0.641,0.662,0.678,0.689,0.697,0.702,0.705,0.706,0.704],[0.409,0.494,0.55,0.591,0.621,0.644,0.662,0.675,0.684,0.691,0.695,0.697,0.698],[0.392,0.475,0.531,0.573,0.604,0.628,0.647,0.662,0.672,0.68,0.686,0.689,0.691],[0.378,0.459,0.515,0.557,0.589,0.615,0.634,0.65,0.662,0.671,0.677,0.682,0.685],[0.366,0.445,0.501,0.544,0.576,0.602,0.622,0.639,0.652,0.662,0.669,0.675,0.678],[0.355,0.433,0.489,0.531,0.564,0.59,0.612,0.629,0.642,0.653,0.661,0.668,0.672],[0.346,0.423,0.478,0.52,0.553,0.58,0.601,0.619,0.633,0.645,0.654,0.661,0.667],[0.338,0.413,0.468,0.51,0.543,0.57,0.592,0.61,0.625,0.637,0.647,0.655,0.661],[0.33,0.404,0.458,0.5,0.534,0.561,0.583,0.602,0.617,0.63,0.64,0.648,0.655],[0.323,0.396,0.45,0.491,0.525,0.552,0.575,0.594,0.609,0.623,0.633,0.642,0.65],[0.316,0.388,0.441,0.483,0.516,0.544,0.567,0.586,0.602,0.616,0.627,0.636,0.644]]}
\ No newline at end of file
diff --git a/src/engine/sources/valves.ts b/src/engine/sources/valves.ts
deleted file mode 100644
index 128c675..0000000
--- a/src/engine/sources/valves.ts
+++ /dev/null
@@ -1,230 +0,0 @@
-/**
- * Flow-induced and driven sources beyond the vocal folds.
- * - LipReed: outward-striking "brass player's lips" valve (elephant trumpet, beatbox lip buzz)
- * - Whistle: aerodynamic whistle at a narrow constriction (elk bugle), a van der Pol oscillator
- * coupled to the local acoustic pressure so it pulls toward and locks onto tract resonances
- * - ClickTrain: impulsive sources (sperm-whale phonic lips, cicada tymbal ribs)
- * - Bubble: cavitation bubble (Rayleigh–Plesset) for the snapping shrimp
- */
-
-/** Outward-striking lip valve: m·h'' + r·h' + k·(h − h0) = S·(p_up − p_down). Opening area = w·max(h, 0). */
-export class LipReed {
- private h = 0;
- private v = 0;
- /** natural frequency (Hz) of the lip mass–spring */
- f = 400;
- /** damping ratio */
- zeta = 0.12;
- /** rest opening (cm): >0 leaks, <0 pressed together */
- h0 = -0.01;
- /** lip width (cm) */
- width = 1.2;
- /** effective pressure surface per unit mass (cm²/g) */
- surfacePerMass = 0.08;
- private readonly dt: number;
- opening = 0;
-
- constructor(fs: number) {
- this.dt = 1 / fs;
- }
-
- /** Advance one sample with the pressure difference across the lips; returns the opening area (cm²). */
- next(dp: number): number {
- const w = 2 * Math.PI * this.f;
- const acc = this.surfacePerMass * dp - 2 * this.zeta * w * this.v - w * w * (this.h - this.h0);
- // semi-implicit Euler (stable for w·dt < 1 at the internal rate)
- this.v += acc * this.dt;
- this.h += this.v * this.dt;
- // the lips cannot interpenetrate: inelastic collision at h = 0 with tissue compliance
- if (this.h < -0.05) {
- this.h = -0.05;
- if (this.v < 0) this.v = 0;
- }
- if (this.h > 0.8) {
- this.h = 0.8;
- if (this.v > 0) this.v = 0;
- }
- const a = this.h > 0 ? this.h * this.width : 0;
- this.opening = a;
- return a;
- }
-}
-
-/**
- * Supraglottal whistle: van der Pol oscillator excited by the jet (flow through the constriction)
- * and coupled to the local acoustic pressure, so its frequency is pulled toward the tract's
- * resonances (the elk bugle's G0 hops between formants as the tract lengthens).
- */
-export class Whistle {
- private x = 0.01;
- private v = 0;
- /** target frequency (Hz) */
- f = 2200;
- /** coupling to the local pressure (frequency pulling) */
- coupling = 0.6;
- private readonly dt: number;
- out = 0;
-
- constructor(fs: number) {
- this.dt = 1 / fs;
- }
-
- /** drive 0..1 (jet strength), pLocal = acoustic pressure at the whistle (dyn/cm²). Returns a pressure source (dyn/cm²). */
- next(drive: number, pLocal: number, gain: number): number {
- const w = 2 * Math.PI * this.f;
- const mu = 0.15 * drive;
- // x'' − μ w (1 − x²) x' + w² x = c·w²·p̂
- const pn = Math.max(-1, Math.min(1, pLocal / 2000));
- const acc = mu * w * (1 - this.x * this.x) * this.v - w * w * this.x + this.coupling * w * w * pn * drive;
- this.v += acc * this.dt;
- this.x += this.v * this.dt;
- if (!Number.isFinite(this.x) || Math.abs(this.x) > 5) {
- this.x = 0.01;
- this.v = 0;
- }
- if (drive < 0.02) {
- this.x *= 0.999;
- this.v *= 0.999;
- }
- this.out = this.x * gain * drive;
- return this.out;
- }
-}
-
-/** Impulse source: smooth pulses (raised cosine) triggered by events, optionally ringing (tymbal ribs). */
-export class ClickTrain {
- private readonly fs: number;
- private pending: { at: number; amp: number }[] = [];
- private t = 0;
- /** click width (s) */
- width = 0.0004;
- /** ring frequency (Hz) and decay (s) for each click; ring = 0 → plain pulse */
- ring = 0;
- ringDecay = 0.002;
- private active: { start: number; amp: number }[] = [];
-
- constructor(fs: number) {
- this.fs = fs;
- }
-
- /** Schedule a click after `delay` seconds. */
- click(delay: number, amp = 1): void {
- this.pending.push({ at: this.t + delay, amp });
- }
-
- clear(): void {
- this.pending.length = 0;
- this.active.length = 0;
- }
-
- /** Advance one sample; returns the source value (unit-ish). */
- next(): number {
- const t = this.t;
- if (this.pending.length) {
- for (let i = this.pending.length - 1; i >= 0; i--) {
- if (this.pending[i].at <= t) {
- this.active.push({ start: this.pending[i].at, amp: this.pending[i].amp });
- this.pending.splice(i, 1);
- }
- }
- }
- let y = 0;
- for (let i = this.active.length - 1; i >= 0; i--) {
- const c = this.active[i];
- const age = t - c.start;
- const life = this.ring > 0 ? this.width + 6 * this.ringDecay : this.width;
- if (age > life) {
- this.active.splice(i, 1);
- continue;
- }
- if (this.ring > 0) {
- const env = age < this.width ? age / this.width : Math.exp(-(age - this.width) / this.ringDecay);
- y += c.amp * env * Math.sin(2 * Math.PI * this.ring * age);
- } else {
- y += c.amp * 0.5 * (1 - Math.cos((2 * Math.PI * age) / this.width));
- }
- }
- this.t += 1 / this.fs;
- return y;
- }
-}
-
-/**
- * Cavitation bubble in water (Rayleigh–Plesset):
- * R R'' + 1.5 R'² = (p_gas(R) − p∞(t) − 2σ/R − 4μ R'/R) / ρ
- * A "snap" drops the ambient pressure (the claw's jet), the bubble grows, then collapses violently.
- * Radiated pressure ∝ d²V/dt² = 4π(R²R'' + 2RR'²).
- */
-export class Bubble {
- private R: number;
- private Rd = 0;
- /** equilibrium radius (m) */
- R0 = 0.0005;
- private readonly dt: number;
- private tension = 0.072;
- private viscosity = 0.0015; // effective, includes thermal/acoustic damping
- private rho = 1000;
- private p0 = 101325;
- private kappa = 1.33;
- /** ambient pressure drop (Pa) while the jet passes, and its time course */
- private dropUntil = 0;
- private dropAmount = 0;
- private t = 0;
- out = 0;
-
- constructor(fs: number) {
- this.dt = 1 / fs;
- this.R = this.R0;
- }
-
- /** Trigger a snap: the ambient pressure falls for `dur` seconds (larger drop → larger bubble). */
- snap(strength: number, dur = 0.0012): void {
- this.dropAmount = this.p0 * (0.9 + 0.09 * Math.max(0, Math.min(1, strength)));
- this.dropUntil = this.t + dur;
- this.R = Math.max(this.R, this.R0);
- }
-
- private acc(R: number, Rd: number, pinf: number): number {
- const pg = (this.p0 + (2 * this.tension) / this.R0) * Math.pow(this.R0 / R, 3 * this.kappa);
- return ((pg - pinf - (2 * this.tension) / R - (4 * this.viscosity * Rd) / R) / this.rho - 1.5 * Rd * Rd) / R;
- }
-
- /** Advance one audio sample (with adaptive sub-stepping for the collapse); returns radiated pressure (arb.). */
- next(): number {
- const pinf = this.t < this.dropUntil ? this.p0 - this.dropAmount : this.p0;
- let R = this.R, Rd = this.Rd;
- // sub-steps: the collapse is stiff
- const speed = Math.abs(Rd) / Math.max(R, 1e-6);
- const n = Math.min(64, Math.max(2, Math.ceil(speed * this.dt * 20)));
- const h = this.dt / n;
- let a = 0;
- for (let i = 0; i < n; i++) {
- // velocity-Verlet-like midpoint step
- const a1 = this.acc(R, Rd, pinf);
- const Rm = R + 0.5 * h * Rd;
- const Rdm = Rd + 0.5 * h * a1;
- a = this.acc(Math.max(Rm, this.R0 * 0.02), Rdm, pinf);
- R += h * Rdm;
- Rd += h * a;
- if (R < this.R0 * 0.02) {
- R = this.R0 * 0.02;
- Rd = Math.abs(Rd) * 0.3; // lossy rebound
- }
- }
- if (!Number.isFinite(R) || !Number.isFinite(Rd)) {
- R = this.R0;
- Rd = 0;
- }
- this.R = R;
- this.Rd = Rd;
- this.t += this.dt;
- // d²V/dt² / 4π
- const y = R * R * a + 2 * R * Rd * Rd;
- this.out = y;
- return y;
- }
-
- get radius(): number {
- return this.R;
- }
-}
diff --git a/src/engine/util/math.ts b/src/engine/util/math.ts
deleted file mode 100644
index dd98f2d..0000000
--- a/src/engine/util/math.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-export const TAU = Math.PI * 2;
-
-export const clamp = (x: number, lo: number, hi: number): number => (x < lo ? lo : x > hi ? hi : x);
-export const lerp = (a: number, b: number, t: number): number => a + (b - a) * t;
-export const smoothstep = (e0: number, e1: number, x: number): number => {
- const t = clamp((x - e0) / (e1 - e0), 0, 1);
- return t * t * (3 - 2 * t);
-};
-export const dbToGain = (db: number): number => Math.pow(10, db / 20);
-export const gainToDb = (g: number): number => 20 * Math.log10(Math.max(1e-12, g));
-export const midiToHz = (m: number): number => 440 * Math.pow(2, (m - 69) / 12);
-export const hzToMidi = (f: number): number => 69 + 12 * Math.log2(Math.max(1e-6, f) / 440);
-export const centsToRatio = (c: number): number => Math.pow(2, c / 1200);
-
-/** Fast deterministic PRNG (mulberry32 core with 32-bit state), uniform in [0,1). */
-export class Rng {
- private s: number;
- constructor(seed = 0x9e3779b9) {
- this.s = seed >>> 0 || 1;
- }
- next(): number {
- let t = (this.s = (this.s + 0x6d2b79f5) | 0);
- t = Math.imul(t ^ (t >>> 15), t | 1);
- t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
- return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
- }
- /** Uniform in [-1, 1). */
- bipolar(): number {
- return this.next() * 2 - 1;
- }
- /** Approximately standard normal (sum of 4 uniforms, scaled). Cheap and bounded. */
- gauss(): number {
- return (this.next() + this.next() + this.next() + this.next() - 2) * 1.7320508;
- }
-}
-
-/** One-pole smoother, time constant in samples. */
-export class Smoother {
- value: number;
- private a: number;
- constructor(initial: number, tauSamples: number) {
- this.value = initial;
- this.a = tauSamples > 0 ? Math.exp(-1 / tauSamples) : 0;
- }
- setTau(tauSamples: number): void {
- this.a = tauSamples > 0 ? Math.exp(-1 / tauSamples) : 0;
- }
- step(target: number): number {
- this.value = target + (this.value - target) * this.a;
- return this.value;
- }
-}
-
-/**
- * 1/f-ish slow random drift (sum of three filtered noises at octave-spaced rates).
- * step() is called at control rate; returns roughly unit-variance output.
- */
-export class Drift {
- private y = [0, 0, 0];
- private readonly a: number[];
- private readonly rng: Rng;
- constructor(controlRate: number, baseHz: number, seed: number) {
- this.rng = new Rng(seed);
- this.a = [baseHz, baseHz * 3, baseHz * 9].map((f) => Math.exp((-TAU * f) / controlRate));
- }
- step(): number {
- let s = 0;
- for (let i = 0; i < 3; i++) {
- const a = this.a[i];
- // normalise so each band has ~unit variance
- this.y[i] = a * this.y[i] + Math.sqrt(1 - a * a) * this.rng.gauss();
- s += this.y[i] / (i + 1);
- }
- return s / 1.4;
- }
-}
diff --git a/src/engine/util/optimize.ts b/src/engine/util/optimize.ts
deleted file mode 100644
index fe38574..0000000
--- a/src/engine/util/optimize.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-/** Nelder–Mead simplex minimiser with box bounds (clamped). */
-export function nelderMead(
- f: (x: number[]) => number,
- x0: number[],
- opts: { step?: number[]; lo?: number[]; hi?: number[]; maxIter?: number; tol?: number } = {},
-): { x: number[]; fx: number; iters: number } {
- const n = x0.length;
- const lo = opts.lo ?? x0.map(() => -Infinity);
- const hi = opts.hi ?? x0.map(() => Infinity);
- const clampX = (x: number[]) => x.map((v, i) => Math.min(hi[i], Math.max(lo[i], v)));
- const step = opts.step ?? x0.map((v) => (Math.abs(v) > 1e-3 ? 0.1 * Math.abs(v) : 0.05));
- const maxIter = opts.maxIter ?? 400 * n;
- const tol = opts.tol ?? 1e-7;
- let simplex: number[][] = [clampX(x0)];
- for (let i = 0; i < n; i++) {
- const p = x0.slice();
- p[i] += step[i];
- simplex.push(clampX(p));
- }
- let values = simplex.map(f);
- let it = 0;
- for (; it < maxIter; it++) {
- const idx = values.map((_, i) => i).sort((a, b) => values[a] - values[b]);
- simplex = idx.map((i) => simplex[i]);
- values = idx.map((i) => values[i]);
- if (Math.abs(values[n] - values[0]) < tol * (Math.abs(values[0]) + 1e-12)) break;
- const centroid = new Array(n).fill(0);
- for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) centroid[j] += simplex[i][j] / n;
- const worst = simplex[n];
- const xr = clampX(centroid.map((c, j) => c + (c - worst[j])));
- const fr = f(xr);
- if (fr < values[0]) {
- const xe = clampX(centroid.map((c, j) => c + 2 * (c - worst[j])));
- const fe = f(xe);
- if (fe < fr) {
- simplex[n] = xe;
- values[n] = fe;
- } else {
- simplex[n] = xr;
- values[n] = fr;
- }
- } else if (fr < values[n - 1]) {
- simplex[n] = xr;
- values[n] = fr;
- } else {
- const xc = clampX(centroid.map((c, j) => c + 0.5 * (worst[j] - c)));
- const fc = f(xc);
- if (fc < values[n]) {
- simplex[n] = xc;
- values[n] = fc;
- } else {
- for (let i = 1; i <= n; i++) {
- simplex[i] = clampX(simplex[i].map((v, j) => simplex[0][j] + 0.5 * (v - simplex[0][j])));
- values[i] = f(simplex[i]);
- }
- }
- }
- }
- let best = 0;
- for (let i = 1; i <= n; i++) if (values[i] < values[best]) best = i;
- return { x: simplex[best], fx: values[best], iters: it };
-}
diff --git a/src/engine/voice/humanAirway.ts b/src/engine/voice/humanAirway.ts
deleted file mode 100644
index e9be1b9..0000000
--- a/src/engine/voice/humanAirway.ts
+++ /dev/null
@@ -1,249 +0,0 @@
-/**
- * Human airway: lungs → trachea → glottis → pharynx ─┬─ oral → lips
- * └─ velum port → nasal (+maxillary sinus) → nostrils
- * plus piriform fossae (closed side branch above the epilarynx).
- * Applies HumanArtic configurations (geometry → area function → tube targets) and manages
- * the turbulence noise sources at constrictions and the teeth.
- */
-import { AirwayNetwork, type Tube } from "../airway/network.ts";
-import { HumanVocalTract, type HumanArtic, type HumanBody, type HumanFrame, BODY_MALE } from "../anatomy/human.ts";
-import { WALL_SOFT, WALL_TRACHEA, WALL_NASAL, RHO, C_SOUND } from "../physics.ts";
-import { smoothstep as smooth } from "../util/math.ts";
-
-export interface HumanAirwayOptions {
- body?: HumanBody;
- /** internal sample rate (Hz) */
- fs: number;
-}
-
-export class HumanAirway {
- readonly net: AirwayNetwork;
- readonly tract: HumanVocalTract;
- readonly body: HumanBody;
- readonly trachea: Tube;
- readonly pharynx: Tube;
- readonly oral: Tube;
- readonly nasal: Tube;
- readonly fossa: Tube;
- readonly lungs: number;
- readonly glottisPort: number;
- readonly velumPort: number;
- readonly radLips: number;
- readonly radNose: number;
- readonly nPh: number;
- readonly nOr: number;
- readonly phAreas: Float64Array;
- readonly orAreas: Float64Array;
- readonly phMin: Float64Array;
- readonly orMin: Float64Array;
- frame: HumanFrame | null = null;
- phLen = 8.8;
- orLen = 8.3;
- /** noise gains (tunable) */
- noiseGain = { glottis: 3.2e-6, constriction: 2.2e-6, teeth: 3.0e-6 };
-
- constructor(opts: HumanAirwayOptions) {
- const body = (this.body = opts.body ?? BODY_MALE);
- const k = body.scale;
- const fs = opts.fs;
- this.tract = new HumanVocalTract(body);
- const net = (this.net = new AirwayNetwork(fs));
- const dxMin = (C_SOUND / fs) / 0.93;
- // node counts from the shortest expected lengths (larynx raised, lips retracted)
- const phMin = 8.7 * k * (0.55 + 0.45 * body.pharynx) - 1.6 * k;
- const orMin = 8.3 * k - 1.0 * k;
- this.nPh = Math.max(8, Math.floor(phMin / dxMin));
- this.nOr = Math.max(8, Math.floor(orMin / dxMin));
- this.phAreas = new Float64Array(this.nPh);
- this.orAreas = new Float64Array(this.nOr);
- this.phMin = new Float64Array(this.nPh);
- this.orMin = new Float64Array(this.nOr);
-
- const trLen = 12 * k;
- this.trachea = net.addTube({ name: "trachea", n: Math.max(6, Math.floor(trLen / Math.max(dxMin, 0.9 * k))), length: trLen, area: 2.5 * k * k, wall: WALL_TRACHEA });
- this.pharynx = net.addTube({ name: "pharynx", n: this.nPh, length: 8.8 * k, area: 3 * k * k, wall: WALL_SOFT, wallRadiation: 0.25, perimeterFactor: 1.25 });
- this.oral = net.addTube({ name: "oral", n: this.nOr, length: 8.3 * k, area: 3 * k * k, wall: WALL_SOFT, wallRadiation: 0.25, perimeterFactor: 1.5 });
- const naLen = 11.4 * k;
- const nNa = Math.max(8, Math.floor(naLen / Math.max(dxMin, 0.5 * k)));
- const naAreas = Array.from({ length: nNa }, (_, i) => {
- const u = (i + 0.5) / nNa;
- const a = u < 0.18 ? 2.6 : u < 0.75 ? 2.0 - 0.6 * (u - 0.18) : u < 0.9 ? 1.4 : 1.0;
- return a * k * k;
- });
- this.nasal = net.addTube({ name: "nasal", n: nNa, length: naLen, area: naAreas, wall: WALL_NASAL, perimeterFactor: 3.2, viscousFactor: 2.5 });
- this.fossa = net.addTube({ name: "piriform", n: 3, length: 2.0 * k, area: 0.9 * k * k, wall: WALL_SOFT, perimeterFactor: 1.3 });
-
- this.lungs = net.addPressureNode("lungs");
- const trA = 2.5 * k * k;
- net.addPort(this.lungs, this.trachea.firstNode, { area: trA, length: 1, kEntrance: 0, kExit: 0, extraResistance: (0.5 * RHO * C_SOUND) / trA });
- this.glottisPort = net.addPort(this.trachea.lastNode, this.pharynx.firstNode, { area: 0, length: 0.3 * k, kEntrance: 0.37, kExit: 1.0, slitWidth: 1.4 * k });
- net.connect(this.pharynx.lastNode, this.oral.firstNode);
- this.velumPort = net.addPort(this.pharynx.lastNode, this.nasal.firstNode, { area: 0, length: 1.0 * k, kEntrance: 0.3, kExit: 0.8 });
- // piriform fossae branch off ≈2.6 cm above the glottis
- const fossaNode = this.pharynx.node(Math.min(this.nPh - 1, Math.round((2.6 / 8.8) * this.nPh)));
- net.connect(fossaNode, this.fossa.firstNode);
- // maxillary sinus (Helmholtz) on the nasal cavity
- const sinus = net.addCavity("sinus", 14 * k * k * k, null);
- net.addPort(this.nasal.node(Math.round(nNa * 0.45)), sinus, { area: 0.12 * k * k, length: 0.5 * k, kEntrance: 0, kExit: 0, includeHalfSections: false });
- this.radLips = net.addRadiation(this.oral.lastNode);
- this.radNose = net.addRadiation(this.nasal.lastNode);
- net.finalize();
- }
-
- /** Internal branch index helpers */
- branchOf(t: Tube, i: number): number {
- return t.branch(Math.max(0, Math.min(t.n - 2, i)));
- }
-
- /** max area change rate (cm²/s, body-scaled): a physiological guard against geometric jumps */
- maxAreaRate = 45;
- /** additional rate per cm² of current area (1/s) */
- areaRateGain = 40;
- /**
- * The last part of a closure is slower than a release: contact spreads over the palate as
- * tissue compresses, while a release is ballistic. Sealing at the opening rate drove the air
- * the articulator displaces through a slit that shut within ~1 ms (an audible click). Below
- * sealHi cm² the closing rate eases from maxAreaRate down to sealRate, and below sealEase it
- * slows further (∝ √A) so the seal itself is reached smoothly.
- */
- sealRate = 5;
- sealLo = 0.03;
- sealHi = 0.4;
- /** below this area (cm²) the closing rate slows with √A, so the seal is reached smoothly */
- sealEase = 0.03;
-
- /** areas committed at the start of the current control step (slew-limit baseline) */
- private basePh: Float64Array | null = null;
- private baseOr: Float64Array | null = null;
- private basePhMin: Float64Array | null = null;
- private baseOrMin: Float64Array | null = null;
- private baseDt = 0;
-
- /** Geometry → targets for the next block. Returns the computed frame. `dt` enables slew limiting. */
- apply(a: HumanArtic, dt = 0): HumanFrame {
- if (dt > 0) {
- if (!this.basePh) {
- this.basePh = new Float64Array(this.nPh);
- this.baseOr = new Float64Array(this.nOr);
- this.basePhMin = new Float64Array(this.nPh);
- this.baseOrMin = new Float64Array(this.nOr);
- }
- this.basePh.set(this.phAreas);
- this.baseOr!.set(this.orAreas);
- this.basePhMin!.set(this.phMin);
- this.baseOrMin!.set(this.orMin);
- }
- this.baseDt = dt;
- return this.commit(a, dt);
- }
-
- /**
- * Recompute the geometry within the same control step (after a contact correction moved an
- * articulator), still slew-limited against the areas the step started from: re-applying
- * without the limit let closures appear within one block, a pressure and output spike.
- */
- reapply(a: HumanArtic): HumanFrame {
- return this.commit(a, this.baseDt);
- }
-
- private commit(a: HumanArtic, dt: number): HumanFrame {
- const f = (this.frame = this.tract.compute(a));
- const { phLen, orLen } = this.tract.resample(a, f, this.nPh, this.nOr, this.phAreas, this.orAreas, this.phMin, this.orMin);
- const oldPh = this.basePh, oldOr = this.baseOr, oldPhMin = this.basePhMin, oldOrMin = this.baseOrMin;
- if (dt > 0 && oldPh && oldOr && oldPhMin && oldOrMin) {
- // both section areas and sub-section minima are rate-limited: the minima set the jet
- // (Borda–Carnot) losses ∝ 1/A², so a fast drop chokes the flow within a block
- // rate limit grows with cross-section: wide cavities reshape fast, narrow constrictions
- // (lateral extent ~1–2 cm) open and close at physiological rates (sets burst sharpness)
- const k2 = this.body.scale * this.body.scale;
- const clampArr = (cur: Float64Array, old: Float64Array, mins: Float64Array, oldMins: Float64Array) => {
- const openR = this.maxAreaRate * k2, gain = this.areaRateGain;
- const sealR = this.sealRate * k2, lo = this.sealLo * k2, hi = this.sealHi * k2, ease = this.sealEase * k2;
- // closing rate at area A: the release rate eased down to the seal rate near contact,
- // and in the last part slowing with √A, so the area (and the jet through it, ∝ A) comes
- // to rest at the seal instead of stopping dead: at a constant rate the flow's slope
- // dropped to zero at once, a step in the radiated pressure (an audible click)
- const closeR = (A: number) => {
- if (A < ease) return sealR * Math.sqrt(Math.max(0, A) / ease);
- const u = A <= lo ? 0 : A >= hi ? 1 : (A - lo) / (hi - lo);
- return sealR + (openR - sealR) * u * u * (3 - 2 * u);
- };
- for (let i = 0; i < cur.length; i++) {
- const d = cur[i] - old[i];
- if (d > 0) {
- const lim = (openR + gain * cur[i]) * dt;
- if (d > lim) cur[i] = old[i] + lim;
- } else {
- const lim = (closeR(old[i]) + gain * old[i]) * dt;
- if (d < -lim) cur[i] = old[i] - lim;
- }
- const dm = mins[i] - oldMins[i];
- if (dm > 0) {
- const limM = (openR + gain * mins[i]) * dt;
- if (dm > limM) mins[i] = oldMins[i] + limM;
- } else {
- const limM = (closeR(oldMins[i]) + gain * oldMins[i]) * dt;
- if (dm < -limM) mins[i] = oldMins[i] - limM;
- }
- if (mins[i] > cur[i]) mins[i] = cur[i];
- if (mins[i] < 0) mins[i] = 0;
- }
- };
- clampArr(this.phAreas, oldPh, this.phMin, oldPhMin);
- clampArr(this.orAreas, oldOr, this.orMin, oldOrMin);
- }
- this.phLen = phLen;
- this.orLen = orLen;
- this.net.setTubeTargets(this.pharynx, this.phAreas, phLen, this.phMin);
- this.net.setTubeTargets(this.oral, this.orAreas, orLen, this.orMin);
- this.net.setPortTarget(this.velumPort, f.velumPort);
- this.updateNoise(f);
- return f;
- }
-
- /** Register turbulence sources: glottis, narrowest supraglottal constriction, teeth obstacle. */
- private updateNoise(f: HumanFrame): void {
- const g = this.noiseGain;
- const list: { src: number; fwd: number; bwd: number; gain: number; lowpassHz?: number; highpassHz?: number }[] = [];
- // aspiration: jet from the glottis hits the epilarynx/ventricular region
- list.push({ src: this.glottisPort, fwd: this.branchOf(this.pharynx, 1), bwd: this.branchOf(this.trachea, this.trachea.n - 2), gain: g.glottis, lowpassHz: 3500, highpassHz: 300 });
- // narrowest open point in pharynx+oral (global position index p over concatenated tubes)
- const nPh = this.nPh, nOr = this.nOr;
- let minA = Infinity, minI = -1;
- for (let i = 0; i < nPh + nOr; i++) {
- const A = i < nPh ? this.phMin[i] : this.orMin[i - nPh];
- if (A > 0 && A < minA) {
- minA = A;
- minI = i;
- }
- }
- // narrowest open point: its jet makes frication noise. Every weight below is a smooth function
- // of geometry so sources fade in/out instead of toggling (toggling = audible noise bursts).
- const k2 = this.body.scale * this.body.scale;
- const wArea = minI >= 0 ? 1 - smooth(0.35 * k2, 0.9 * k2, minA) : 0;
- if (wArea > 0) {
- const dxPh = this.phLen / nPh, dxOr = this.orLen / nOr;
- const toBranch = (gi: number): number => (gi < nPh ? this.branchOf(this.pharynx, gi) : gi === nPh ? -1 : this.branchOf(this.oral, gi - nPh));
- const dx = minI < nPh ? dxPh : dxOr;
- const off = Math.max(1, Math.round((0.9 * this.body.scale) / dx));
- const src = toBranch(Math.min(minI, nPh + nOr - 2));
- const fwd = toBranch(Math.min(nPh + nOr - 2, minI + off));
- const bwd = toBranch(Math.max(0, minI - off));
- if (src >= 0 && fwd >= 0 && bwd >= 0) {
- list.push({ src, fwd, bwd, gain: g.constriction * wArea, lowpassHz: 2600, highpassHz: 350 });
- // obstacle source: a narrow anterior jet impinging on the incisors (sibilants)
- const sMin = minI < nPh ? (minI + 0.5) * dxPh : this.phLen + (minI - nPh + 0.5) * dxOr;
- const behind = (f.teethS - sMin) / this.body.scale;
- const wDist = smooth(0.15, 0.5, behind) * (1 - smooth(2.6, 4.0, behind));
- const wJet = 1 - smooth(0.2 * k2, 0.5 * k2, minA);
- const wt = wDist * wJet;
- if (wt > 1e-3) {
- const teethI = nPh + Math.min(nOr - 2, Math.max(0, Math.round((f.teethS - this.phLen) / dxOr)));
- const tb = toBranch(teethI);
- if (tb >= 0) list.push({ src, fwd: tb, bwd, gain: g.teeth * wt, lowpassHz: 5000, highpassHz: 1200 });
- }
- }
- }
- this.net.setNoiseSources(list);
- }
-}
diff --git a/src/engine/voice/humanVoice.ts b/src/engine/voice/humanVoice.ts
deleted file mode 100644
index 3299998..0000000
--- a/src/engine/voice/humanVoice.ts
+++ /dev/null
@@ -1,440 +0,0 @@
-/**
- * Real-time human voice: lungs → parametric glottis → articulated airway, rendered at an
- * oversampled internal rate and decimated. Runs identically in the AudioWorklet and in Bun.
- */
-import { HumanAirway } from "./humanAirway.ts";
-import { ParametricGlottis } from "../sources/glottis.ts";
-import { ArticulatorBank, ARTIC_KEYS } from "../control/articulators.ts";
-import { Decimator } from "../airway/decimator.ts";
-import { BODY_MALE, type HumanArtic, type HumanBody } from "../anatomy/human.ts";
-import { CM_H2O } from "../physics.ts";
-import { clamp } from "../util/math.ts";
-import { GestureScore, type Blended, type Gesture } from "../control/score.ts";
-
-export interface VoiceSource {
- /** target fundamental frequency (Hz) */
- f0: number;
- /** pitch glide time constant (s) */
- glide: number;
- /** lung pressure while breathing out (cmH2O); negative = ingressive */
- pressure: number;
- /** 0..1 breathy (abducted, chink) */
- breathiness: number;
- /** 0 lax … 1 pressed */
- tension: number;
- /** vocal fry 0..1 */
- fry: number;
- /** jitter / shimmer / period doubling 0..1 */
- roughness: number;
- vibratoDepth: number;
- vibratoRate: number;
- /** random pitch drift (cents) */
- drift: number;
- /** false → whisper (no fold vibration) */
- voiced: boolean;
-}
-
-export const DEFAULT_SOURCE: VoiceSource = {
- f0: 110,
- glide: 0.06,
- pressure: 8,
- breathiness: 0.15,
- tension: 0.5,
- fry: 0,
- roughness: 0.1,
- vibratoDepth: 0,
- vibratoRate: 5.5,
- drift: 5,
- voiced: true,
-};
-
-export interface VoiceTelemetry {
- artic: Float32Array;
- phAreas: Float32Array;
- orAreas: Float32Array;
- phLen: number;
- orLen: number;
- pressureRms: Float32Array;
- flow: Float32Array;
- velumPort: number;
- glottalArea: Float32Array;
- glottalFlow: Float32Array;
- f0: number;
- voicing: number;
- pLung: number;
- outRms: number;
- noiseLevel: number;
- noiseNode: number;
- gate: number;
- /** voice clock (s) for score playheads */
- clock: number;
- /** labels of gestures active now (most recent first) */
- active: string[];
-}
-
-const SCOPE_LEN = 4096;
-const SCOPE_POINTS = 256;
-
-export class HumanVoice {
- readonly fsOut: number;
- readonly M: number;
- readonly fs: number;
- readonly airway: HumanAirway;
- readonly glottis: ParametricGlottis;
- readonly artic = new ArticulatorBank();
- readonly source: VoiceSource = { ...DEFAULT_SOURCE };
- private readonly dec: Decimator;
- private readonly ctrlEvery: number; // internal samples per control step
- private ctrlCounter = 0;
- /** breath gate 0..1 (note on/off) */
- gate = 0;
- private gateTarget = 0;
- /** time left (s) during which a release of the gate follows the score's own breath ramp */
- private scoreBreathHold = 0;
- private pLung = 0;
- private f0 = DEFAULT_SOURCE.f0;
- outputGain = 5.5e-7;
- private dcX = 0;
- private dcY = 0;
- private readonly dcCoef: number;
- // telemetry accumulators
- private readonly rmsAcc: Float64Array;
- private rmsCount = 0;
- private readonly flowSm: Float64Array;
- private readonly scopeArea = new Float32Array(SCOPE_LEN);
- private readonly scopeFlow = new Float32Array(SCOPE_LEN);
- private scopePos = 0;
- private readonly cycleStarts = new Int32Array(8);
- private cycleIdx = 0;
- private lastPhase = 0;
- private outAcc = 0;
- private outCount = 0;
- private sub = 0;
- /** gestural score and voice clock (s) */
- readonly score = new GestureScore();
- clock = 0;
- private readonly tmpBlend: Blended = { value: 0, weight: 0, speed: 1 };
- private baseAbduction = 0;
- private baseClosure = 0;
- private scoreF0: number | null = null;
-
- constructor(opts: { fsOut: number; body?: HumanBody; oversample?: number }) {
- this.fsOut = opts.fsOut;
- this.M = opts.oversample ?? 2;
- this.fs = this.fsOut * this.M;
- this.airway = new HumanAirway({ fs: this.fs, body: opts.body ?? BODY_MALE });
- this.glottis = new ParametricGlottis(this.fs);
- this.dec = new Decimator(this.M);
- this.ctrlEvery = 64 * this.M;
- this.dcCoef = Math.exp((-2 * Math.PI * 25) / this.fsOut);
- this.limHoldN = Math.round(0.025 * this.fsOut);
- this.limRelease = Math.exp(-1 / (0.2 * this.fsOut));
- const nTract = this.airway.nPh + this.airway.nOr;
- this.rmsAcc = new Float64Array(nTract);
- this.flowSm = new Float64Array(nTract);
- this.airway.apply(this.artic.x);
- this.airway.net.snapToTargets();
- // smaller bodies radiate more high-frequency (derivative) energy at their higher f0
- this.outputGain *= this.airway.body.scale < 0.95 ? 0.55 : 1;
- this.applySource();
- }
-
- setArticulation(values: Partial<HumanArtic>, tipFree?: boolean): void {
- if (tipFree !== undefined) this.artic.tipFree = tipFree;
- this.artic.setTarget(values);
- }
-
- setSource(values: Partial<VoiceSource>): void {
- Object.assign(this.source, values);
- this.applySource();
- }
-
- /** Add gestures (times on the voice clock). */
- schedule(gestures: Gesture[]): void {
- this.score.addAll(gestures);
- }
-
- /** End the open-ended gestures with this tag now (a sung note's key was released). */
- release(tag: number): void {
- this.score.release(tag, this.clock);
- }
-
- /** Cancel scheduled gestures (speech stops; the voice returns to the performer's posture). */
- cancelScore(): void {
- this.score.clear();
- }
-
- /** breath/voice on (1) or off (0); intermediate values scale the pressure */
- setGate(level: number): void {
- this.gateTarget = clamp(level, 0, 1.5);
- }
-
- private applySource(): void {
- const s = this.source;
- const g = this.glottis.params;
- const k2 = this.airway.body.scale * this.airway.body.scale;
- g.amplitude = 0.17 * k2 * (s.voiced ? 1 : 0);
- g.abduction = (s.voiced ? 0.1 * s.breathiness * s.breathiness : 0.2 + 0.1 * s.breathiness) * k2;
- this.baseAbduction = g.abduction;
- this.baseClosure = 0;
- g.chink = (0.004 + 0.03 * s.breathiness) * k2;
- g.openQuotient = 0.78 - 0.36 * s.tension;
- g.closureSharpness = 0.25 + 0.7 * s.tension;
- g.skew = 0.56 + 0.16 * s.tension;
- g.fry = s.fry;
- g.jitter = 0.003 + 0.035 * s.roughness;
- g.shimmer = 0.02 + 0.22 * s.roughness;
- g.diplophonia = s.roughness > 0.5 ? (s.roughness - 0.5) * 1.4 : 0;
- g.vibratoDepth = s.vibratoDepth;
- g.vibratoRate = s.vibratoRate;
- g.drift = s.drift;
- g.effort = clamp((Math.abs(s.pressure) - 3) / 10, 0, 1);
- }
-
- private limEnv = 0;
- private limHold = 0;
- private readonly limHoldN: number;
- private readonly limRelease: number;
-
- /** Render n output samples into out[offset..]. */
- render(out: Float32Array, offset: number, n: number): void {
- const air = this.airway;
- const net = air.net;
- const M = this.M;
- const lungs = air.lungs;
- const sub = air.trachea.lastNode;
- const supra = air.pharynx.firstNode;
- const gp = air.glottisPort;
- const glot = this.glottis;
- const nPh = air.nPh;
- const nOr = air.nOr;
- const phFirst = air.pharynx.firstNode;
- const orFirst = air.oral.firstNode;
- const p = net.p;
- for (let i = 0; i < n; i++) {
- for (let m = 0; m < M; m++) {
- if (this.ctrlCounter <= 0) this.control();
- this.ctrlCounter--;
- net.setFixedPressure(lungs, this.pLung);
- const a = glot.next(p[sub] - p[supra]);
- net.setPortArea(gp, a);
- const y = net.step();
- if (this.dec.push(y)) {
- // output sample
- let v = this.dec.value * this.outputGain;
- // DC blocker
- const hp = v - this.dcX + this.dcCoef * this.dcY;
- this.dcX = v;
- this.dcY = hp;
- v = hp;
- // output limiter: a peak envelope held for longer than a glottal period, so a loud
- // sung vowel is turned down by a steady gain instead of being squared off; only a
- // rising level touches the soft clip
- const av = Math.abs(v);
- if (av >= this.limEnv) {
- this.limEnv = av;
- this.limHold = this.limHoldN;
- } else if (this.limHold > 0) this.limHold--;
- else this.limEnv *= this.limRelease;
- if (this.limEnv > 0.75) v *= 0.75 / this.limEnv;
- const al = Math.abs(v);
- if (al > 0.85) v = Math.sign(v) * (0.85 + 0.15 * Math.tanh((al - 0.85) / 0.15));
- out[offset + i] = v;
- this.outAcc += v * v;
- this.outCount++;
- // glottal scope at output rate
- this.scopeArea[this.scopePos] = a;
- this.scopeFlow[this.scopePos] = net.U[gp];
- const ph = glot.cyclePhase;
- if (ph < this.lastPhase) {
- this.cycleStarts[this.cycleIdx & 7] = this.scopePos;
- this.cycleIdx++;
- }
- this.lastPhase = ph;
- this.scopePos = (this.scopePos + 1) % SCOPE_LEN;
- }
- // decimated RMS accumulation for the pressure visualisation
- if ((++this.sub & 3) === 0) {
- for (let k = 0; k < nPh; k++) {
- const v = p[phFirst + k];
- this.rmsAcc[k] += v * v;
- }
- for (let k = 0; k < nOr; k++) {
- const v = p[orFirst + k];
- this.rmsAcc[nPh + k] += v * v;
- }
- this.rmsCount++;
- }
- }
- }
- }
-
- /** Control-rate update: articulator dynamics, geometry → areas, breath, pitch. */
- private control(): void {
- const dt = this.ctrlEvery / this.fs;
- const t = this.clock;
- const score = this.score;
- const tmp = this.tmpBlend;
- let breathAct = 0, breathVal = 0;
- let f0Target = this.source.f0;
- const gp = this.glottis.params;
- if (score.size > 0) {
- // performer's base posture keeps a small say on keys the score controls
- this.artic.step(dt, (k) => score.blend(k, t, tmp), 0.05);
- const k2 = this.airway.body.scale * this.airway.body.scale;
- const ab = score.blend("abduction", t, tmp);
- const abAct = ab.weight > 0 ? Math.min(1, ab.weight / 2) : 0;
- gp.abduction = this.baseAbduction + ab.value * abAct * k2;
- const cl = score.blend("closure", t, tmp);
- gp.closure = Math.max(this.baseClosure, cl.weight > 0 ? cl.value * Math.min(1, cl.weight / 2) : 0);
- const br = score.blend("breath", t, tmp);
- if (br.weight > 0) {
- breathAct = Math.min(1, br.weight);
- breathVal = br.value;
- }
- const vb = score.blend("vibrato", t, tmp);
- gp.vibratoDepth = vb.weight > 0 ? (this.source.vibratoDepth * 0.05 + vb.value * vb.weight) / (0.05 + vb.weight) : this.source.vibratoDepth;
- const pf = score.blend("f0", t, tmp);
- if (pf.weight > 0) {
- f0Target = (this.source.f0 * 0.02 + pf.value * pf.weight) / (0.02 + pf.weight);
- this.scoreF0 = f0Target;
- } else this.scoreF0 = null;
- if (((this.clock * 10) | 0) !== (((this.clock - dt) * 10) | 0)) score.prune(t - 0.2);
- } else {
- this.artic.step(dt);
- gp.abduction = this.baseAbduction;
- gp.closure = this.baseClosure;
- this.scoreF0 = null;
- }
- this.clock += dt;
- // contact constraint on the frame computed anyway; re-apply only if a correction was made
- this.airway.apply(this.artic.x, dt);
- if (this.enforceContacts()) this.airway.reapply(this.artic.x);
- this.airway.net.beginBlock(this.ctrlEvery);
- this.ctrlCounter = this.ctrlEvery;
- // breath: fast attack, slower release; a speaking score breathes on its own
- // a negative breath gesture (ingressive: inward K snares, gasps) overrides the performer's breath
- const scoreBreath = breathVal * breathAct;
- const gateGoal = scoreBreath < 0 ? scoreBreath : Math.max(this.gateTarget, scoreBreath);
- // a score shapes its own breath ramps (beatbox hits end their breath abruptly, phrases end
- // into silence), including the moments just after its breath gesture has ended; the slow
- // release is for the performer's note-offs
- this.scoreBreathHold = breathAct > 0 ? 0.15 : Math.max(0, this.scoreBreathHold - dt);
- const tau = gateGoal > this.gate ? 0.025 : this.scoreBreathHold > 0 ? 0.02 : 0.07;
- this.gate += (gateGoal - this.gate) * (1 - Math.exp(-dt / tau));
- this.pLung = this.source.pressure * CM_H2O * this.gate;
- // vocal effort follows the pressure actually applied: a harder breath (a louder sung note)
- // gives wider, sharper-closing pulses, as in real phonation, not just more flow
- this.glottis.params.effort = clamp((Math.abs(this.source.pressure * this.gate) - 3) / 10, 0, 1);
- // pitch glide
- const g = Math.max(0.002, this.scoreF0 !== null ? 0.03 : this.source.glide);
- this.f0 *= Math.pow(f0Target / this.f0, 1 - Math.exp(-dt / g));
- this.glottis.params.f0 = this.f0;
- // smoothed mean flow per tract node (for particle speeds)
- const U = this.airway.net.U;
- const a = 1 - Math.exp(-dt / 0.03);
- const nPh = this.airway.nPh;
- for (let k = 0; k < nPh + this.airway.nOr; k++) {
- const br = k < nPh ? this.airway.branchOf(this.airway.pharynx, k) : this.airway.branchOf(this.airway.oral, k - nPh);
- this.flowSm[k] += a * (U[br] - this.flowSm[k]);
- }
- }
-
- /** tissue may compress this far (cm) before the palate stops the articulator */
- maxPenetration = 0.1;
-
- /**
- * Contact constraint: articulators cannot travel into the palate. Beyond `maxPenetration` of
- * tissue compression, the tongue tip/body is projected back along the contact normal and its
- * inward velocity removed (inelastic). Keeps held closures still (no air pumping), makes
- * releases start at the surface, and keeps the drawn anatomy physical.
- */
- private enforceContacts(): boolean {
- const tract = this.airway.tract;
- const x = this.artic.x, vel = this.artic.v;
- const k = tract.scale;
- let changed = false;
- const lim = -this.maxPenetration * k;
- const fix = (d: number, n: { x: number; y: number }, kx: "ttX" | "tbX", ky: "ttY" | "tbY") => {
- if (!(d < lim)) return;
- changed = true;
- const depth = lim - d; // > 0, body cm
- // body → template displacement (oral x is compressed by 0.86 in the template map)
- const sx = (x[kx] > 0.5 ? 1 / 0.86 : 1) / k;
- const sy = 1 / k;
- x[kx] += n.x * depth * sx;
- x[ky] += n.y * depth * sy;
- const vn = vel[kx] * n.x / sx + vel[ky] * n.y / sy; // normal velocity (body units)
- if (vn < 0) {
- vel[kx] -= vn * n.x * sx;
- vel[ky] -= vn * n.y * sy;
- }
- };
- fix(tract.contactTip, tract.contactTipN, "ttX", "ttY");
- fix(tract.contactBody, tract.contactBodyN, "tbX", "tbY");
- return changed;
- }
-
- telemetry(): VoiceTelemetry {
- const air = this.airway;
- const nT = air.nPh + air.nOr;
- const artic = new Float32Array(ARTIC_KEYS.length);
- ARTIC_KEYS.forEach((k, i) => (artic[i] = this.artic.x[k]));
- const rms = new Float32Array(nT);
- const c = Math.max(1, this.rmsCount);
- for (let k = 0; k < nT; k++) rms[k] = Math.sqrt(this.rmsAcc[k] / c);
- this.rmsAcc.fill(0);
- this.rmsCount = 0;
- // phase-locked glottal scope: two most recent complete cycles
- const ga = new Float32Array(SCOPE_POINTS);
- const gf = new Float32Array(SCOPE_POINTS);
- let start = (this.scopePos - 1024 + SCOPE_LEN) % SCOPE_LEN;
- let len = 1024;
- if (this.cycleIdx >= 3 && this.glottis.voicing > 0.2) {
- const c2 = this.cycleStarts[(this.cycleIdx - 3) & 7];
- const c0 = this.cycleStarts[(this.cycleIdx - 1) & 7];
- const span = (c0 - c2 + SCOPE_LEN) % SCOPE_LEN;
- if (span > 8 && span < SCOPE_LEN / 2) {
- start = c2;
- len = span;
- }
- }
- for (let i = 0; i < SCOPE_POINTS; i++) {
- const idx = (start + Math.floor((i * len) / SCOPE_POINTS)) % SCOPE_LEN;
- ga[i] = this.scopeArea[idx];
- gf[i] = this.scopeFlow[idx];
- }
- let noiseLevel = 0;
- let noiseNode = -1;
- for (const s of air.net.noiseSources) {
- if (s.level > noiseLevel) {
- noiseLevel = s.level;
- noiseNode = s.src;
- }
- }
- const outRms = Math.sqrt(this.outAcc / Math.max(1, this.outCount));
- this.outAcc = 0;
- this.outCount = 0;
- return {
- artic,
- phAreas: Float32Array.from(air.phAreas),
- orAreas: Float32Array.from(air.orAreas),
- phLen: air.phLen,
- orLen: air.orLen,
- pressureRms: rms,
- flow: Float32Array.from(this.flowSm),
- velumPort: air.frame?.velumPort ?? 0,
- glottalArea: ga,
- glottalFlow: gf,
- f0: this.glottis.f0Now,
- voicing: this.glottis.voicing,
- pLung: this.pLung / CM_H2O,
- outRms,
- noiseLevel,
- noiseNode,
- gate: this.gate,
- clock: this.clock,
- active: this.score.activeAt(this.clock).filter((g) => g.label && g.label !== "breath" && g.label !== "pitch").map((g) => g.label as string).slice(0, 4),
- };
- }
-}
diff --git a/tests/airway-adversarial.test.ts b/tests/airway-adversarial.test.ts
deleted file mode 100644
index c70bc8b..0000000
--- a/tests/airway-adversarial.test.ts
+++ /dev/null
@@ -1,187 +0,0 @@
-import { test, expect } from "bun:test";
-import { AirwayNetwork } from "../src/engine/airway/network.ts";
-import { transferFunction, findPeaks, linspace } from "../src/engine/airway/frequency.ts";
-import { FFT } from "../src/engine/analysis/fft.ts";
-import { RHO, RHO_C2, CM_H2O, WALL_SOFT } from "../src/engine/physics.ts";
-
-const FS = 96000;
-
-test("nearly closed three-way junction stays stable at the working CFL", () => {
- const net = new AirwayNetwork(FS);
- const n = 20, len = 8; // Δ = 0.4 cm → CFL ≈ 0.91
- const a = net.addTube({ name: "a", n, length: len, area: 3 });
- const b = net.addTube({ name: "b", n, length: len, area: 3 });
- const c = net.addTube({ name: "c", n, length: len, area: 3 });
- // junction = last node of a, which we squeeze to a tiny area
- net.connect(a.lastNode, b.firstNode);
- net.connect(a.lastNode, c.firstNode);
- net.addRadiation(b.lastNode);
- net.addRadiation(c.lastNode);
- net.finalize();
- const areas = new Float64Array(n).fill(3);
- areas[n - 1] = 0.002;
- net.setTubeTargets(a, areas);
- net.beginBlock(64);
- let peak = 0;
- for (let i = 0; i < FS; i++) {
- if (i % 64 === 0) net.beginBlock(64);
- if (i < 400) net.extFlow[a.firstNode] = 200 * Math.sin(i * 0.3);
- const y = net.step();
- expect(Number.isFinite(y)).toBe(true);
- peak = Math.max(peak, Math.abs(net.p[a.lastNode]));
- }
- expect(peak).toBeLessThan(1e7);
- // decays once excitation stops
- let tail = 0;
- for (let i = 0; i < FS / 10; i++) tail = Math.max(tail, Math.abs(net.p[a.lastNode] + net.step() * 0));
- expect(tail).toBeLessThan(peak);
-});
-
-test("sealed cavity compression follows the (linearised) adiabatic law", () => {
- const net = new AirwayNetwork(FS);
- const t = net.addTube({ name: "cav", n: 10, length: 4, area: 2 });
- net.finalize();
- // shrink volume by 5 % over 20 ms
- const steps = FS * 0.02;
- const block = 64;
- for (let i = 0; i < steps; i++) {
- if (i % block === 0) {
- const f = Math.min(1, (i + block) / steps);
- net.setTubeTargets(t, new Float64Array(10).fill(2 * (1 - 0.05 * f)));
- net.beginBlock(block);
- }
- net.step();
- }
- for (let i = 0; i < FS * 0.02; i++) {
- if (i % block === 0) net.beginBlock(block);
- net.step();
- }
- const expected = RHO_C2 * Math.log(1 / 0.95); // ∫ρc² dV/V
- let mean = 0;
- for (let k = 0; k < 10; k++) mean += net.p[t.node(k)] / 10;
- expect(Math.abs(mean - expected) / expected).toBeLessThan(0.03);
-});
-
-test("steady flow through a short constriction obeys Bernoulli with jet loss", () => {
- for (const lengthFrac of [1, 0.25]) {
- const net = new AirwayNetwork(FS);
- const n = 30;
- const t = net.addTube({ name: "t", n, length: 12, area: 3 });
- const lung = net.addPressureNode("lung");
- net.addPort(lung, t.firstNode, { area: 3, length: 1, kEntrance: 0, kExit: 0 });
- net.addRadiation(t.lastNode);
- net.finalize();
- const Ac = 0.08;
- const areas = new Float64Array(n).fill(3);
- const mins = new Float64Array(n).fill(3);
- // constriction occupying a whole section, or only a quarter of it (sub-grid)
- const harmonic = 1 / (lengthFrac / Ac + (1 - lengthFrac) / 3);
- areas[20] = harmonic;
- mins[20] = Ac;
- net.setTubeTargets(t, areas, undefined, mins);
- const P = 6 * CM_H2O;
- for (let i = 0; i < FS * 0.25; i++) {
- if (i % 64 === 0) net.beginBlock(64);
- net.setFixedPressure(lung, P * Math.min(1, i / (FS * 0.02)));
- net.step();
- }
- const U = Math.abs(net.U[t.branch(20)]);
- const bernoulli = Ac * Math.sqrt((2 * P) / RHO);
- expect(Math.abs(U - bernoulli) / bernoulli).toBeLessThan(0.15);
- }
-});
-
-test("formant bandwidths agree between FDTD and the frequency-domain model", () => {
- const net = new AirwayNetwork(FS);
- const t = net.addTube({ name: "t", n: 40, length: 17.5, area: Array.from({ length: 40 }, (_, i) => 1.5 + 2.5 * Math.sin((i / 39) * 2.5) ** 2), wall: WALL_SOFT });
- net.addRadiation(t.lastNode);
- net.finalize();
- const fr = linspace(80, 4500, 6000);
- const ref = findPeaks(fr, transferFunction(net.linearElements(), t.firstNode, fr).mag).filter((p) => p.freq < 4000);
- const n = FS;
- const nfft = 1 << 17;
- const re = new Float64Array(nfft), im = new Float64Array(nfft);
- net.beginBlock(1);
- for (let i = 0; i < n; i++) {
- if (i === 0) net.extFlow[t.firstNode] = FS;
- re[i] = net.step();
- }
- new FFT(nfft).transform(re, im);
- const freqs = new Float64Array(nfft / 2), mag = new Float64Array(nfft / 2);
- for (let k = 0; k < nfft / 2; k++) {
- freqs[k] = (k * FS) / nfft;
- mag[k] = Math.hypot(re[k], im[k]) / (2 * Math.PI * Math.max(freqs[k], 1));
- }
- const got = findPeaks(freqs, mag, 80).filter((p) => p.freq < 4200);
- for (const r of ref) {
- const g = got.reduce((b, c) => (Math.abs(c.freq - r.freq) < Math.abs(b.freq - r.freq) ? c : b));
- expect(Math.abs(g.freq - r.freq) / r.freq).toBeLessThan(0.012);
- if (Number.isFinite(r.bw) && Number.isFinite(g.bw)) expect(Math.abs(g.bw - r.bw) / r.bw).toBeLessThan(0.2);
- }
-});
-
-test("a realistic sliding closure with trapped pressure releases without spikes", () => {
- // closure forms over 25 ms (as articulator dynamics produce), slides 6 sections back toward the
- // lungs while held (trapped pressure behind it), then releases over 12 ms
- const net = new AirwayNetwork(FS);
- const n = 40;
- const t = net.addTube({ name: "t", n, length: 17, area: 3, wall: WALL_SOFT });
- const lung = net.addPressureNode("lung");
- net.addPort(lung, t.firstNode, { area: 3, length: 1 });
- net.addRadiation(t.lastNode);
- net.finalize();
- const block = 64;
- let peakP = 0, peakOut = 0, peakOpenOut = 0, peakSlide = 0, peakRelease = 0;
- const total = FS * 0.6;
- const P = 8 * CM_H2O;
- for (let i = 0; i < total; i++) {
- const time = i / FS;
- if (i % block === 0) {
- const tt = (i + block) / FS;
- const depth = tt < 0.05 ? 0 : tt < 0.075 ? 1.3 * (tt - 0.05) / 0.025 : tt < 0.4 ? 1.3 : Math.max(0, 1.3 - (1.3 * (tt - 0.4)) / 0.012);
- const pos = 30 - 6 * Math.min(1, Math.max(0, (tt - 0.1) / 0.25));
- const areas = new Float64Array(n);
- for (let k = 0; k < n; k++) areas[k] = Math.max(0, 3 * (1 - depth * Math.exp(-(((k - pos) / 1.6) ** 2))));
- net.setTubeTargets(t, areas);
- net.beginBlock(block);
- }
- net.setFixedPressure(lung, P * Math.min(1, time / 0.03));
- const y = net.step();
- expect(Number.isFinite(y)).toBe(true);
- if (time > 0.03) peakOut = Math.max(peakOut, Math.abs(y));
- if (time > 0.03 && time < 0.05) peakOpenOut = Math.max(peakOpenOut, Math.abs(y));
- if (time > 0.09 && time < 0.39) peakSlide = Math.max(peakSlide, Math.abs(y));
- if (time > 0.395 && time < 0.45) peakRelease = Math.max(peakRelease, Math.abs(y));
- // acoustically open cells only: squeeze-film pressure inside a closing gap is physical
- for (let k = 0; k < n; k++) if (net.area[t.node(k)] > 0.1) peakP = Math.max(peakP, Math.abs(net.p[t.node(k)]));
- }
- expect(peakP).toBeLessThan(2.5 * P);
- // a held, sliding closure must stay quiet (no spurious pops); the release burst is the
- // largest event and is of physical size (comparable to the breathing onset, not orders above)
- expect(peakSlide).toBeLessThan(0.25 * peakRelease);
- expect(peakRelease).toBeLessThan(10 * peakOpenOut);
- void peakOut;
-});
-
-test("fast (but articulator-limited) closure gives bounded piston pressure", () => {
- // closing 3 cm² → 0 over 8 ms is near the fastest lip/tongue motion; pressure must stay sane
- const net = new AirwayNetwork(FS);
- const n = 40;
- const t = net.addTube({ name: "t", n, length: 17, area: 3, wall: WALL_SOFT });
- net.addRadiation(t.lastNode);
- net.finalize();
- let peakP = 0;
- for (let i = 0; i < FS * 0.1; i++) {
- if (i % 64 === 0) {
- const tt = (i + 64) / FS;
- const depth = Math.min(1.2, (1.2 * tt) / 0.008);
- const areas = new Float64Array(n);
- for (let k = 0; k < n; k++) areas[k] = Math.max(0, 3 * (1 - depth * Math.exp(-(((k - 30) / 1.6) ** 2))));
- net.setTubeTargets(t, areas);
- net.beginBlock(64);
- }
- expect(Number.isFinite(net.step())).toBe(true);
- for (let k = 0; k < n; k++) if (net.area[t.node(k)] > 0.1) peakP = Math.max(peakP, Math.abs(net.p[t.node(k)]));
- }
- expect(peakP).toBeLessThan(20 * CM_H2O);
-});
diff --git a/tests/airway.test.ts b/tests/airway.test.ts
deleted file mode 100644
index fb40437..0000000
--- a/tests/airway.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { test, expect } from "bun:test";
-import { AirwayNetwork } from "../src/engine/airway/network.ts";
-import { transferFunction, findPeaks, linspace } from "../src/engine/airway/frequency.ts";
-import { FFT } from "../src/engine/analysis/fft.ts";
-import { C_SOUND } from "../src/engine/physics.ts";
-
-function uniformTube(fs: number, opts: { walls?: boolean; length?: number; area?: number; n?: number } = {}) {
- const net = new AirwayNetwork(fs);
- const L = opts.length ?? 17.5;
- const tube = net.addTube({ name: "tract", n: opts.n ?? 40, length: L, area: opts.area ?? 3, wall: opts.walls ? { mass: 1.5, resistance: 1600, stiffness: 3e5 } : null });
- net.addRadiation(tube.lastNode);
- net.finalize();
- return { net, tube };
-}
-
-/** FDTD impulse response → |spectrum| peaks. */
-function fdtdPeaks(net: AirwayNetwork, inject: number, seconds = 0.5) {
- const n = Math.round(net.fs * seconds);
- const nfft = 1 << Math.ceil(Math.log2(n));
- const re = new Float64Array(nfft);
- const im = new Float64Array(nfft);
- net.beginBlock(1);
- for (let i = 0; i < n; i++) {
- if (i === 0) net.extFlow[inject] = 1 * net.fs; // unit volume impulse
- re[i] = net.step();
- if (!Number.isFinite(re[i])) throw new Error(`non-finite at ${i}`);
- }
- new FFT(nfft).transform(re, im);
- const freqs = new Float64Array(nfft / 2);
- const mag = new Float64Array(nfft / 2);
- for (let k = 0; k < nfft / 2; k++) {
- freqs[k] = (k * net.fs) / nfft;
- // divide by ω to compare with |U_rad| (output is dU/dt)
- mag[k] = Math.hypot(re[k], im[k]) / (2 * Math.PI * Math.max(freqs[k], 1));
- }
- return findPeaks(freqs, mag, 100).filter((p) => p.freq < 5000);
-}
-
-test("uniform tube resonances match quarter-wave theory (with end correction)", () => {
- const { net, tube } = uniformTube(96000);
- const el = net.linearElements();
- const fr = linspace(50, 5000, 4000);
- const H = transferFunction(el, tube.firstNode, fr);
- const peaks = findPeaks(fr, H.mag);
- const a = Math.sqrt(3 / Math.PI);
- // node-centred discretisation: radiation load sits at the last node centre (Δ/2 inside)
- const Leff = 17.5 - 17.5 / 40 / 2 + (8 * a) / (3 * Math.PI) + 17.5 / 40 / 2;
- for (let n = 1; n <= 4; n++) {
- const fTheory = ((2 * n - 1) * C_SOUND) / (4 * Leff);
- const p = peaks.reduce((b, c) => (Math.abs(c.freq - fTheory) < Math.abs(b.freq - fTheory) ? c : b));
- expect(Math.abs(p.freq - fTheory) / fTheory).toBeLessThan(0.03);
- }
-});
-
-test("FDTD impulse response agrees with frequency-domain model", () => {
- for (const walls of [false, true]) {
- const { net, tube } = uniformTube(96000, { walls });
- const el = net.linearElements();
- const fr = linspace(50, 5000, 6000);
- const ref = findPeaks(fr, transferFunction(el, tube.firstNode, fr).mag).filter((p) => p.freq < 4800);
- const got = fdtdPeaks(net, tube.firstNode);
- expect(got.length).toBeGreaterThanOrEqual(ref.length);
- for (const r of ref) {
- const g = got.reduce((b, c) => (Math.abs(c.freq - r.freq) < Math.abs(b.freq - r.freq) ? c : b));
- expect(Math.abs(g.freq - r.freq) / r.freq).toBeLessThan(0.012);
- }
- }
-});
-
-test("FDTD stays stable with a non-uniform tube and tiny constriction", () => {
- const net = new AirwayNetwork(96000);
- const areas = Array.from({ length: 40 }, (_, i) => (i === 25 ? 0.0005 : 0.5 + 4 * Math.sin((i / 39) * Math.PI) ** 2));
- const t = net.addTube({ name: "t", n: 40, length: 17, area: areas, wall: { mass: 1.5, resistance: 1600, stiffness: 3e5 } });
- net.addRadiation(t.lastNode);
- net.finalize();
- net.beginBlock(1);
- let peak = 0;
- for (let i = 0; i < 96000; i++) {
- if (i < 2000) net.extFlow[t.firstNode] = 300 * Math.sin(i * 0.05);
- const y = net.step();
- peak = Math.max(peak, Math.abs(y));
- expect(Number.isFinite(y)).toBe(true);
- }
- // energy must decay after excitation stops
- let tail = 0;
- for (let i = 0; i < 9600; i++) tail = Math.max(tail, Math.abs(net.step()));
- expect(tail).toBeLessThan(peak * 0.01);
-});
diff --git a/tests/analysis.test.ts b/tests/analysis.test.ts
deleted file mode 100644
index 6a73e16..0000000
--- a/tests/analysis.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { test, expect } from "bun:test";
-import { estimateFormants } from "../src/engine/analysis/lpc.ts";
-import { yinPitch } from "../src/engine/analysis/pitch.ts";
-
-/** Impulse train at f0 through cascaded 2-pole resonators at known formants. */
-function synthVowel(sr: number, f0: number, formants: [number, number][], dur: number): Float64Array {
- const n = Math.round(sr * dur);
- let x = new Float64Array(n);
- const period = sr / f0;
- for (let k = 0; k * period < n; k++) x[Math.round(k * period)] = 1;
- for (const [f, bw] of formants) {
- const r = Math.exp((-Math.PI * bw) / sr);
- const a1 = 2 * r * Math.cos((2 * Math.PI * f) / sr);
- const a2 = -r * r;
- const y = new Float64Array(n);
- for (let i = 0; i < n; i++) y[i] = x[i] + a1 * (i > 0 ? y[i - 1] : 0) + a2 * (i > 1 ? y[i - 2] : 0);
- x = y;
- }
- return x;
-}
-
-test("LPC recovers known formants", () => {
- const sr = 16000;
- const target: [number, number][] = [[730, 60], [1090, 80], [2440, 120], [3400, 150]];
- const x = synthVowel(sr, 110, target, 0.3);
- const frame = x.subarray(1600, 1600 + 512);
- const fm = estimateFormants(frame, sr, { order: 14, preEmph: 0 }); // flat-spectrum source: no pre-emphasis
- for (const [f] of target) {
- const nearest = fm.reduce((b, c) => (Math.abs(c.freq - f) < Math.abs(b.freq - f) ? c : b));
- expect(Math.abs(nearest.freq - f) / f).toBeLessThan(0.05);
- }
-});
-
-test("YIN recovers f0", () => {
- const sr = 48000;
- for (const f0 of [82, 110, 220, 440, 880]) {
- const x = synthVowel(sr, f0, [[500, 80], [1500, 100]], 0.2);
- const { f0: est } = yinPitch(x.subarray(2000, 2000 + 2400), sr, { minF0: 60 });
- expect(Math.abs(est - f0) / f0).toBeLessThan(0.01);
- }
-});
diff --git a/tests/beatbox.test.ts b/tests/beatbox.test.ts
deleted file mode 100644
index 819f492..0000000
--- a/tests/beatbox.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import { BEAT_PRESETS, BEAT_SOUNDS, formatBeat, parseBeat } from "../src/engine/phonetics/beatbox.ts";
-import { BeatPlayer } from "../src/engine/control/beatPlayer.ts";
-import type { Gesture } from "../src/engine/control/score.ts";
-
-/** Hit time of each scheduled sound: the planned hit is where its gestures were shifted to. */
-function run(p: BeatPlayer, from: number, to: number, dt = 128 / 48000): { t: number; label: string }[] {
- const hits: { t: number; label: string }[] = [];
- for (let clock = from; clock < to; clock += dt)
- p.tick(clock, (gs: Gesture[]) => {
- const ref = p.gestures({ id: gs[0].label === "m" ? "m" : (gs[0].label as string) }, 0);
- hits.push({ t: gs[0].t0 - ref[0].t0, label: gs[0].label as string });
- });
- return hits;
-}
-
-describe("beat notation", () => {
- test("parses symbols, rests, notes, accents and bar lines", () => {
- const s = parseBeat("B . t | Pf m:43 ^K> -");
- expect(s.map((x) => x?.id ?? null)).toEqual(["B", null, "t", "Pf", "m", "^K", null]);
- expect(s[4]?.note).toBe(43);
- expect(s[5]?.accent).toBeGreaterThan(1);
- });
- test("format and parse round-trip every preset", () => {
- for (const p of BEAT_PRESETS) {
- const steps = parseBeat(p.text);
- expect(steps.length).toBe(16);
- expect(parseBeat(formatBeat(steps))).toEqual(steps);
- }
- });
- test("every sound builds gestures that start before and end after its hit", () => {
- for (const s of BEAT_SOUNDS)
- for (const body of ["male", "female", "child"]) {
- const gs = s.build(body, { f0: 82, len: 0.15, accent: 1 });
- expect(gs.length).toBeGreaterThan(0);
- expect(Math.min(...gs.map((g) => g.t0 - g.rampIn))).toBeLessThan(0);
- expect(Math.max(...gs.map((g) => g.t1 + g.rampOut))).toBeGreaterThan(0);
- // everything a sound needs fits inside the sequencer's look-ahead
- expect(BeatPlayer.leadIn(s.id, body)).toBeLessThan(new BeatPlayer().horizon);
- }
- });
-});
-
-describe("beat player", () => {
- test("schedules each step once, on the grid, with swing on the off-beats", () => {
- const p = new BeatPlayer();
- p.steps = parseBeat("B t B t");
- p.setTempo(120, 0.5);
- p.start(0);
- const hits = run(p, 0, 2.2);
- const step = 60 / 120 / 4;
- // 2 s of sixteenths at 120 bpm = 16 steps, starting one horizon in
- expect(hits.length).toBeGreaterThanOrEqual(15);
- hits.slice(0, 8).forEach((h, n) => {
- const want = p.horizon + n * step + (n % 2 ? 0.25 * step : 0);
- expect(Math.abs(h.t - want)).toBeLessThan(1e-9);
- });
- });
- test("tempo changes keep the next step's time (no jump)", () => {
- const p = new BeatPlayer();
- p.steps = parseBeat("t t t t");
- p.setTempo(100, 0);
- p.start(0);
- const before = run(p, 0, 0.6);
- const last = before[before.length - 1].t;
- p.setTempo(160, 0);
- const after = run(p, 0.6, 1.2);
- const gap = after[0].t - last;
- // the first step after the change is spaced by at most one old step, then the new tempo
- expect(gap).toBeGreaterThan(0);
- expect(gap).toBeLessThanOrEqual(60 / 100 / 4 + 1e-9);
- expect(after[2].t - after[1].t).toBeCloseTo(60 / 160 / 4, 9);
- });
- test("the playhead follows the scheduled hits, swing included, and nothing when stopped", () => {
- const p = new BeatPlayer();
- p.steps = parseBeat("B . t .");
- p.setTempo(120, 0.6);
- expect(p.stepAt(1)).toBe(-1);
- p.start(0);
- run(p, 0, 1.2);
- const step = 0.125, late = 0.3 * step;
- expect(p.stepAt(p.horizon - 0.01)).toBe(-1);
- expect(p.stepAt(p.horizon + 0.01)).toBe(0);
- // step 1 is swung: until its hit the playhead stays on step 0
- expect(p.stepAt(p.horizon + step + late - 0.005)).toBe(0);
- expect(p.stepAt(p.horizon + step + late + 0.005)).toBe(1);
- expect(p.stepAt(p.horizon + 4 * step + 0.01)).toBe(0);
- p.stop();
- expect(p.stepAt(1)).toBe(-1);
- });
- test("after the voice is replaced, steps not yet heard are scheduled again at their times", () => {
- const p = new BeatPlayer();
- p.steps = parseBeat("B t Pf t");
- p.setTempo(120, 0.3);
- p.start(0);
- const first = run(p, 0, 0.5);
- // a new voice whose clock restarts at 0 while the old one was at 0.5
- p.rebase(-0.5);
- p.rewind(0);
- const again = run(p, 0, 0.3);
- const pending = first.filter((h) => h.t > 0.5).map((h) => h.t - 0.5);
- expect(again.length).toBeGreaterThanOrEqual(pending.length);
- pending.forEach((t, i) => expect(again[i].t).toBeCloseTo(t, 9));
- });
-});
diff --git a/tests/english.test.ts b/tests/english.test.ts
deleted file mode 100644
index 75b41a3..0000000
--- a/tests/english.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import { test, expect } from "bun:test";
-import { gunzipSync } from "node:zlib";
-import { readFileSync } from "node:fs";
-import { EnglishG2P, letterToSound } from "../src/engine/phonetics/english.ts";
-
-const g2p = new EnglishG2P();
-g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));
-const ipa = (s: { ipa: string }[]) => s.map((x) => x.ipa).join("");
-
-test("dictionary words with stress and allophones", () => {
- const [p] = g2p.toPhrases("Hello world");
- expect(ipa(p.segments)).toBe("həloʊwɝɫd");
- expect(p.segments.find((s) => s.ipa === "oʊ")?.stress).toBe(1);
- const [w] = g2p.toPhrases("water");
- expect(ipa(w.segments)).toBe("wɔɾɚ");
-});
-
-test("punctuation makes phrases and question intonation", () => {
- const ph = g2p.toPhrases("Is it on? Yes, it is.");
- expect(ph.length).toBe(3);
- expect(ph[0].intonation).toBe("question");
- expect(ph[2].intonation).toBe("statement");
-});
-
-test("numbers are spelled out and unknown words fall back to rules", () => {
- const [p] = g2p.toPhrases("42");
- expect(p.words).toEqual(["forty", "two"]);
- expect(ipa(letterToSound("zorblat")).length).toBeGreaterThan(4);
-});
-
-test("words that are also object property names do not break the front end", () => {
- for (const w of ["constructor", "toString", "valueOf", "hasOwnProperty", "__proto__", "prototype"]) {
- const [p] = g2p.toPhrases(`The ${w} is ready.`);
- expect(p.segments.length).toBeGreaterThan(5);
- }
- expect(new EnglishG2P().toPhrases("constructor")[0].segments.length).toBeGreaterThan(3); // no dictionary
-});
diff --git a/tests/geometry-continuity.test.ts b/tests/geometry-continuity.test.ts
deleted file mode 100644
index b40f103..0000000
--- a/tests/geometry-continuity.test.ts
+++ /dev/null
@@ -1,171 +0,0 @@
-/**
- * The area function must change smoothly as the articulators move: a jump in a section's area
- * is heard as a tick and a formant jump. Sweeps each articulator through its speech range from
- * several vowel postures and flags any step far above its neighbours.
- */
-import { describe, expect, test } from "bun:test";
-import { HumanVocalTract, NEUTRAL, BODY_MALE, BODY_FEMALE, BODY_CHILD, restTip, type HumanArtic } from "../src/engine/anatomy/human.ts";
-import { vowelArtic } from "../src/engine/phonetics/planner.ts";
-import { Polyline, rayCrossings } from "../src/engine/anatomy/geom.ts";
-import TARGETS from "../src/engine/phonetics/vowelTargets.generated.json";
-
-
-/**
- * The largest change that survives refinement of [u0, u1] to 2⁻²⁰ of its width: every half
- * still changing by more than `tol` is refined (keeping only the larger half could follow a
- * steep ramp and miss a real jump in the other). A true discontinuity keeps its size; a steep
- * but continuous ramp shrinks away.
- */
-export function jumpSize(areas: (u: number) => number[], u0: number, u1: number, tol = 0.05): number {
- const memo = new Map<number, number[]>();
- const at = (u: number) => {
- let v = memo.get(u);
- if (!v) memo.set(u, (v = areas(u)));
- return v;
- };
- const diff = (a: number, b: number) => {
- const x = at(a), y = at(b);
- let m = 0;
- for (let j = 0; j < x.length; j++) m = Math.max(m, Math.abs(x[j] - y[j]));
- return m;
- };
- let worst = 0;
- const visit = (lo: number, hi: number, depth: number, d: number) => {
- if (depth === 20) {
- worst = Math.max(worst, d);
- return;
- }
- const mid = (lo + hi) / 2;
- const d1 = diff(lo, mid), d2 = diff(mid, hi);
- if (d1 > tol) visit(lo, mid, depth + 1, d1);
- if (d2 > tol) visit(mid, hi, depth + 1, d2);
- };
- const d = diff(u0, u1);
- if (d > tol) visit(u0, u1, 0, d);
- return worst;
-}
-
-const SWEEPS: [keyof HumanArtic, number, number][] = [
- ["tbY", 5.5, 8.5],
- ["tbX", 1.5, 4.2],
- ["jaw", 0, 2],
- ["ttY", 6, 9.5],
- ["ttX", 5, 7],
- ["root", -0.9, 0.9],
- ["lipAp", -0.2, 2],
- ["velum", -0.25, 1.2],
-];
-
-describe("tract geometry continuity", () => {
- test("no area jumps anywhere in the articulators' speech ranges", () => {
- const jumps: string[] = [];
- const N = 400;
- for (const [bodyName, body] of [["male", BODY_MALE], ["female", BODY_FEMALE], ["child", BODY_CHILD]] as const) {
- const tract = new HumanVocalTract(body);
- const ph = new Float64Array(20), or = new Float64Array(24);
- const areas = (a: HumanArtic) => {
- tract.resample(a, tract.compute(a), 20, 24, ph, or);
- return [...ph, ...or];
- };
- for (const vw of ["i", "ɑ", "u", "ə"]) {
- const v = vowelArtic(vw, bodyName)!;
- const tip = restTip(v.jaw ?? NEUTRAL.jaw, v.tbX!, v.tbY!);
- const base: HumanArtic = { ...NEUTRAL, ...v, ttX: tip.x, ttY: tip.y };
- for (const [key, lo, hi] of SWEEPS) {
- const steps: number[] = [];
- let prev = areas({ ...base, [key]: lo });
- for (let i = 1; i <= N; i++) {
- const cur = areas({ ...base, [key]: lo + ((hi - lo) * i) / N });
- let m = 0;
- for (let j = 0; j < cur.length; j++) m = Math.max(m, Math.abs(cur[j] - prev[j]));
- steps.push(m);
- prev = cur;
- }
- steps.forEach((s, i) => {
- const nb = steps.slice(Math.max(0, i - 8), i + 9).filter((_, k) => k !== Math.min(8, i)).sort((a, b) => a - b);
- const med = nb[Math.floor(nb.length / 2)] ?? 0;
- if (!(s > 0.25 && s > 6 * Math.max(med, 0.01))) return;
- const f = (u: number) => areas({ ...base, [key]: lo + (hi - lo) * u });
- const j = jumpSize(f, i / N, (i + 1) / N);
- if (j > 0.05) jumps.push(`${bodyName} ${vw} ${key}=${(lo + ((hi - lo) * (i + 1)) / N).toFixed(3)}: ${j.toFixed(2)} cm²`);
- });
- }
- }
- }
- expect(jumps).toEqual([]);
- });
-
- test("no area jumps on the way between calibrated vowels (all articulators at once, every body)", () => {
- const PAIRS = [["o", "ɝ"], ["i", "ɝ"], ["ɑ", "ɝ"], ["ə", "ɝ"], ["ɑ", "i"], ["u", "i"], ["æ", "u"], ["ʊ", "e"]];
- const jumps: string[] = [];
- const N = 300;
- for (const [bodyName, body] of [["male", BODY_MALE], ["female", BODY_FEMALE], ["child", BODY_CHILD]] as const) {
- const tract = new HumanVocalTract(body);
- const ph = new Float64Array(20), or = new Float64Array(24);
- const areas = (a: HumanArtic) => {
- tract.resample(a, tract.compute(a), 20, 24, ph, or);
- return [...ph, ...or];
- };
- // the full calibrated posture, tongue tip included (the rhotic's raised, curled tip)
- const posture = (vw: string): HumanArtic => ({ ...NEUTRAL, ...(TARGETS as Record<string, Record<string, { artic: Partial<HumanArtic> }>>)[bodyName][vw].artic }) as HumanArtic;
- for (const [x, y] of PAIRS) {
- const a = posture(x), b = posture(y);
- const at = (u: number) => Object.fromEntries(Object.keys(a).map((k) => [k, (a as unknown as Record<string, number>)[k] + ((b as unknown as Record<string, number>)[k] - (a as unknown as Record<string, number>)[k]) * u])) as unknown as HumanArtic;
- const steps: number[] = [];
- let prev = areas(at(0));
- for (let i = 1; i <= N; i++) {
- const cur = areas(at(i / N));
- let m = 0;
- for (let j = 0; j < cur.length; j++) m = Math.max(m, Math.abs(cur[j] - prev[j]));
- steps.push(m);
- prev = cur;
- }
- steps.forEach((s, i) => {
- const nb = steps.slice(Math.max(0, i - 8), i + 9).filter((_, k) => k !== Math.min(8, i)).sort((p, q) => p - q);
- const med = nb[Math.floor(nb.length / 2)] ?? 0;
- if (!(s > 0.2 && s > 6 * Math.max(med, 0.01))) return;
- const j = jumpSize((u) => areas(at(u)), i / N, (i + 1) / N);
- if (j > 0.05) jumps.push(`${bodyName} ${x}→${y} at ${((i + 1) / N).toFixed(3)}: ${j.toFixed(2)} cm²`);
- });
- }
- }
- expect(jumps).toEqual([]);
- });
-
- test("refinement finds a small jump beside a steep ramp", () => {
- const f = (u: number) => [Math.min(1.6 * u, 0.8) + (u >= 0.75 ? 0.1 : 0)];
- expect(jumpSize(f, 0, 1)).toBeCloseTo(0.1, 3);
- expect(jumpSize((u) => [Math.min(1.6 * u, 0.8)], 0, 1)).toBe(0); // a ramp alone is no jump
- });
-
- test("a ray grazing a polyline vertex sees no tissue layer that is not there", () => {
- // a polyline touching the ray's line at a vertex (from either side): no crossing, or an
- // entry and its exit at the same point, never one unmatched crossing
- const t: number[] = new Array(8), ex = new Uint8Array(8);
- for (const side of [-1, 1]) {
- const touch = new Polyline();
- touch.push({ x: side, y: -1 }).push({ x: 0, y: 0 }).push({ x: side, y: 1 });
- const n = rayCrossings(0, -5, 0, 1, touch, 0, 10, t, ex);
- expect(n === 0 || (n === 2 && t[0] === t[1] && ex[0] !== ex[1])).toBe(true);
- }
- // a polyline passing through the line at a vertex crosses it once
- const through = new Polyline();
- through.push({ x: -1, y: -1 }).push({ x: 0, y: 0 }).push({ x: 1, y: 1 });
- expect(rayCrossings(0, -5, 0, 1, through, 0, 10, t, ex)).toBe(1);
- // the reviewer's posture: a fan ray grazing the tip of a calibrated /ɝ/ exactly at a vertex
- const tract = new HumanVocalTract(BODY_MALE);
- const base = { ...NEUTRAL, ...(TARGETS as Record<string, Record<string, { artic: Partial<HumanArtic> }>>).male["ɝ"].artic, ttX: 5.625 } as HumanArtic;
- const ph = new Float64Array(20), or = new Float64Array(24);
- const areas = (ttY: number) => {
- const a = { ...base, ttY };
- tract.resample(a, tract.compute(a), 20, 24, ph, or);
- return [...ph, ...or];
- };
- const y = 8.588839057347066;
- const [a, b, c] = [areas(y - 1e-9), areas(y), areas(y + 1e-9)];
- for (let j = 0; j < a.length; j++) {
- expect(Math.abs(b[j] - a[j])).toBeLessThan(1e-3);
- expect(Math.abs(c[j] - b[j])).toBeLessThan(1e-3);
- }
- });
-});
diff --git a/tests/speech-quality.test.ts b/tests/speech-quality.test.ts
deleted file mode 100644
index 63b1dc6..0000000
--- a/tests/speech-quality.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import { describe, expect, test } from "bun:test";
-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 { HumanVocalTract, NEUTRAL, BODY_MALE } from "../src/engine/anatomy/human.ts";
-
-const FS = 48000;
-
-function render(ipa: string, tail = 0.15) {
- const v = new HumanVoice({ fsOut: FS });
- const plan = planUtterance(tokenizeIpa(ipa), { body: "male", t0: 0.05, f0: 110 });
- v.schedule(plan.gestures);
- const N = Math.round(FS * (plan.end + tail));
- const out = new Float32Array(N);
- const port: number[] = [], voicing: number[] = [];
- for (let i = 0; i < N; i += 128) {
- v.render(out, i, Math.min(128, N - i));
- port.push(v.airway.frame?.velumPort ?? 0);
- voicing.push(v.glottis.voicing);
- }
- const frame = (t: number) => Math.min(port.length - 1, Math.round((t * FS) / 128));
- return { plan, out, port, voicing, frame, at: (t: number) => port[frame(t)] };
-}
-
-/** RMS level (dB re the utterance's peak) over [t0, t1). */
-function levelDb(out: Float32Array, t0: number, t1: number): number {
- let peak = 0, e = 0, n = 0;
- for (const x of out) peak = Math.max(peak, Math.abs(x));
- for (let i = Math.round(t0 * FS); i < Math.min(out.length, Math.round(t1 * FS)); i++, n++) e += out[i] * out[i];
- return 20 * Math.log10(Math.sqrt(e / Math.max(1, n)) / peak + 1e-12);
-}
-
-describe("running-speech quality guards", () => {
- test("nasality does not spread into oral vowels (Bunton & Story: audible from ~0.01 cm²)", () => {
- // [ɑ n ə b ɑ b ɑ]: the last two vowels have no nasal neighbour
- const { plan, at } = render("ˈɑnəbɑbɑ");
- const vowels = plan.segments.filter((s) => s.kind === "vowel");
- expect(vowels.length).toBe(4);
- for (const v of vowels.slice(2)) for (let t = v.t0; t <= v.t1; t += 0.005) expect(at(t)).toBeLessThan(0.01);
- // and the nasal itself is nasal
- const n = plan.segments.find((s) => s.ipa === "n")!;
- expect(at((n.t0 + n.t1) / 2)).toBeGreaterThan(0.2);
- });
- test("phrase-final lengthening and stressed vs unstressed contrast (Klatt rules)", () => {
- const { plan } = render("ˈbɑbəˈbɑb");
- const v = plan.segments.filter((s) => s.kind === "vowel");
- const [first, mid, last] = [v[0], v[1], v[2]];
- const d = (s: { t0: number; t1: number }) => s.t1 - s.t0;
- expect(d(last) / d(first)).toBeGreaterThan(1.25);
- expect(d(first) / d(mid)).toBeGreaterThan(1.4);
- });
- test("a phrase ends in silence: no vowel added after a final consonant, no lingering breath", () => {
- for (const ipa of ["ˈbæd", "ˈkæt", "ˈsi", "ˈðɛm"]) {
- const { plan, out, voicing, frame } = render(ipa, 0.45);
- const final = plan.segments[plan.segments.length - 1];
- const sonorant = final.kind === "vowel" || final.kind === "nasal";
- // the folds stop at a final obstruent's release; a final vowel or nasal fades out
- const voicedFor = sonorant ? 0.05 : 0.015;
- for (let f = frame(plan.end + voicedFor); f < voicing.length; f++) expect(voicing[f]).toBeLessThan(0.3);
- expect(levelDb(out, plan.end + 0.15, plan.end + 0.45)).toBeLessThan(-50);
- }
- });
-});
-
-describe("tract geometry continuity", () => {
- test("the tongue-palate contact model engages smoothly (no area jump as the gap closes past 6 mm)", () => {
- // the tongue on its way from a final /d/ back to rest: the body's gap to the roof crosses
- // the contact regime's edge (0.6 cm) at tbY ≈ 6.90
- const A = { ...NEUTRAL, jaw: 0.604, tbX: 2.935, ttX: 6.272, ttY: 6.89, lipAp: 0.703, lipProt: 0.2, lipWidth: 0.5 };
- const tract = new HumanVocalTract(BODY_MALE);
- const ph = new Float64Array(20), or = new Float64Array(24);
- let prev: number[] | null = null;
- let worst = 0;
- for (let y = 6.85; y <= 6.95; y += 0.001) {
- const a = { ...A, tbY: y };
- tract.resample(a, tract.compute(a), 20, 24, ph, or);
- const cur = [...ph, ...or];
- if (prev) for (let j = 0; j < cur.length; j++) worst = Math.max(worst, Math.abs(cur[j] - prev[j]));
- prev = cur;
- }
- expect(worst).toBeLessThan(0.05); // cm² per 0.01 mm of tongue travel (was 0.87 at the edge)
- });
-});
diff --git a/tests/syllables.test.ts b/tests/syllables.test.ts
deleted file mode 100644
index 630c3ba..0000000
--- a/tests/syllables.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-import { describe, expect, test } from "bun:test";
-import { arpabetToSegments } from "../src/engine/phonetics/english.ts";
-import { lyricsToSyllables, splitSpelling, syllabifySegments } from "../src/engine/phonetics/syllables.ts";
-
-// a few CMUdict entries, enough to test without loading the dictionary
-const DICT: Record<string, string> = {
- twinkle: "T W IH1 NG K AH0 L",
- little: "L IH1 T AH0 L",
- star: "S T AA1 R",
- how: "HH AW1",
- i: "AY1",
- wonder: "W AH1 N D ER0",
- what: "W AH1 T",
- you: "Y UW1",
- are: "AA1 R",
- extra: "EH1 K S T R AH0",
- of: "AH1 V",
-};
-const g2p = { word: (w: string) => (DICT[w] ? arpabetToSegments(DICT[w]) : []) };
-const ipa = (xs: { ipa: string }[]) => xs.map((x) => x.ipa).join("");
-
-describe("syllables", () => {
- test("maximal onset with legal English clusters", () => {
- const tw = syllabifySegments(g2p.word("twinkle"));
- expect(tw.map((s) => [ipa(s.onset), s.nucleus.ipa, ipa(s.coda)])).toEqual([
- ["tw", "ɪ", "ŋ"],
- ["k", "ə", "l"],
- ]);
- // "extra": k + str → ek-stra (str is a legal onset)
- const ex = syllabifySegments(g2p.word("extra"));
- expect(ex.map((s) => ipa(s.onset))).toEqual(["", "stɹ"]);
- expect(ipa(ex[0].coda)).toBe("k");
- });
- test("spelling splits to match", () => {
- expect(splitSpelling("twinkle", 2)).toEqual(["twin", "kle"]);
- expect(splitSpelling("little", 2)).toEqual(["lit", "tle"]);
- expect(splitSpelling("wonder", 2)).toEqual(["won", "der"]);
- expect(splitSpelling("are", 1)).toEqual(["are"]);
- });
- test("lyrics: words, melisma, phrase ends, unreduced function words", () => {
- const syl = lyricsToSyllables("Twinkle little star, how I - wonder", g2p);
- expect(syl.map((s) => s.text)).toEqual(["Twin", "kle", "lit", "tle", "star", "how", "I", "~", "won", "der"]);
- expect(syl[4].phraseEnd).toBe(true);
- expect(syl[7].melisma).toBe(true);
- expect(syl[7].nucleus.ipa).toBe("aɪ");
- expect(syl[1].wordEnd && !syl[0].wordEnd).toBe(true);
- });
-});
diff --git a/tools/bench-wasm.ts b/tools/bench-wasm.ts
index c1256bc..efbae47 100644
--- a/tools/bench-wasm.ts
+++ b/tools/bench-wasm.ts
@@ -1,8 +1,8 @@
/**
- * Real-time factor of the human voice: the wasm build (as the AudioWorklet runs it) next to the
- * TypeScript engine, on the same speech. Usage: bun tools/bench-wasm.ts (after `bun run wasm`).
+ * Real-time factor of the human voice in the wasm build (as the AudioWorklet runs it), on a
+ * fixed utterance. Usage: bun tools/bench-wasm.ts (after `bun run wasm`).
*/
-import { readFileSync, existsSync } from "node:fs";
+import { readFileSync } from "node:fs";
import { writeGestures } from "../src/wasm/wire.ts";
const ROOT = new URL("..", import.meta.url).pathname;
@@ -10,24 +10,15 @@ const scenario = JSON.parse(readFileSync(`${ROOT}crates/chimera/tests/golden/voi
const gestures = scenario.ops[0].gestures;
const FS = 48000, SECS = 4, BLOCKS = (FS * SECS) / 128;
-const x = new WebAssembly.Instance(new WebAssembly.Module(readFileSync(`${ROOT}target/wasm32-unknown-unknown/release/chimera_wasm.wasm`)), {}).exports as Record<string, (...a: number[]) => number> & { memory: WebAssembly.Memory };
+const x = new WebAssembly.Instance(new WebAssembly.Module(readFileSync(`${ROOT}src/wasm/chimera.wasm`)), {}).exports as Record<string, (...a: number[]) => number> & { memory: WebAssembly.Memory };
const h = x.engine_new(FS);
writeGestures(x.memory.buffer, x.engine_records(h), gestures, 4000);
x.engine_schedule(h, gestures.length, 0.03, 0);
x.engine_set_gate(h, 1);
-let t0 = performance.now();
+const t0 = performance.now();
for (let i = 0; i < BLOCKS; i++) x.engine_render(h, 128);
const wasm = (performance.now() - t0) / 1000;
console.log(`wasm human male os=2: ${((100 * wasm) / SECS).toFixed(1)}% of one core`);
-if (existsSync(`${ROOT}src/engine/voice/humanVoice.ts`)) {
- const { HumanVoice } = await import(`${ROOT}src/engine/voice/humanVoice.ts`);
- const v = new HumanVoice({ fsOut: FS });
- v.schedule(gestures.map((g: { t0: number; t1: number }) => ({ ...g, t0: g.t0 + 0.03, t1: g.t1 + 0.03 })));
- v.setGate(1);
- const out = new Float32Array(128);
- t0 = performance.now();
- for (let i = 0; i < BLOCKS; i++) v.render(out, 0, 128);
- const ts = (performance.now() - t0) / 1000;
- console.log(`TS human male os=2: ${((100 * ts) / SECS).toFixed(1)}% of one core (wasm is ${(ts / wasm).toFixed(2)}× faster)`);
-}
+// The TypeScript engine this replaced measured, on the same speech (Ryzen 7 8745HS, 2026-11-05):
+// 29% of a core in Bun (JavaScriptCore) and 46% in Chromium (V8), where the wasm build takes 32%.
diff --git a/tools/calibrate-consonants.ts b/tools/calibrate-consonants.ts
deleted file mode 100644
index 366cc12..0000000
--- a/tools/calibrate-consonants.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * Calibrate the main coordinate of fricatives so the constriction area matches its target
- * (adult-male target × body scale²), in an /a/-like context. Bisection on the monotonic
- * contact model. Writes src/engine/phonetics/consonantTargets.generated.json
- */
-import { writeFileSync } from "node:fs";
-import { HumanAirway } from "../src/engine/voice/humanAirway.ts";
-import { NEUTRAL, BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanArtic } from "../src/engine/anatomy/human.ts";
-import { CONSONANTS } from "../src/engine/phonetics/inventory.ts";
-import vowels from "../src/engine/phonetics/vowelTargets.generated.json";
-
-const out: Record<string, Record<string, Partial<HumanArtic>>> = {};
-for (const [name, body] of [["male", BODY_MALE], ["female", BODY_FEMALE], ["child", BODY_CHILD]] as const) {
- const air = new HumanAirway({ fs: 96000, body });
- const ctx = { ...NEUTRAL, ...(vowels as any)[name]["ɑ"].artic, jaw: 0.55 } as HumanArtic;
- out[name] = {};
- for (const p of CONSONANTS) {
- if (!p.area || !p.calKey) continue;
- const target = p.area * body.scale * body.scale;
- const key = p.calKey;
- const minArea = (v: number) => {
- const a = { ...ctx, ...p.targets, [key]: v } as HumanArtic;
- air.apply(a);
- let m = Infinity;
- for (const x of air.phMin) if (x < m) m = x;
- for (const x of air.orMin) if (x < m) m = x;
- return m;
- };
- // search direction: area decreases as the coordinate moves toward closure
- const base = p.targets[key] as number;
- let lo = base - 1.2, hi = base + 1.2;
- const decreasing = minArea(hi) < minArea(lo); // area falls as value rises?
- for (let i = 0; i < 40; i++) {
- const mid = (lo + hi) / 2;
- const A = minArea(mid);
- if ((A > target) === decreasing) lo = mid;
- else hi = mid;
- }
- const v = (lo + hi) / 2;
- const got = minArea(v);
- out[name][p.ipa] = { [key]: Math.round(v * 1000) / 1000 };
- console.log(`${name.padEnd(6)} ${p.ipa.padEnd(3)} ${key}=${v.toFixed(3)} area ${got.toFixed(3)} (target ${target.toFixed(3)})`);
- }
-}
-writeFileSync("src/engine/phonetics/consonantTargets.generated.json", JSON.stringify(out, null, 1));
diff --git a/tools/calibrate-vowels.ts b/tools/calibrate-vowels.ts
deleted file mode 100644
index 41edd77..0000000
--- a/tools/calibrate-vowels.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * Calibrate articulatory vowel targets against reference formants with the frequency-domain
- * airway model. Writes src/engine/phonetics/vowelTargets.generated.json
- * Usage: bun tools/calibrate-vowels.ts [male|female|child|all]
- */
-import { writeFileSync, existsSync, readFileSync } from "node:fs";
-import { HumanAirway } from "../src/engine/voice/humanAirway.ts";
-import { NEUTRAL, restTip, BODY_MALE, BODY_FEMALE, BODY_CHILD, type HumanArtic, type HumanBody } from "../src/engine/anatomy/human.ts";
-import { transferFunction, findPeaks } from "../src/engine/airway/frequency.ts";
-import { nelderMead } from "../src/engine/util/optimize.ts";
-import { VOWELS } from "../src/engine/phonetics/vowelData.ts";
-
-const which = process.argv[2] ?? "all";
-const OUT = "src/engine/phonetics/vowelTargets.generated.json";
-const bodies: [string, HumanBody][] = [["male", BODY_MALE], ["female", BODY_FEMALE], ["child", BODY_CHILD]];
-
-const freqs = (() => {
- const n = 700;
- const out = new Float64Array(n);
- for (let i = 0; i < n; i++) out[i] = 120 * Math.pow(4600 / 120, i / (n - 1));
- return out;
-})();
-
-type Params = number[]; // tbX tbY jaw lipAp lipProt lipWidth root larynx curl
-const LO: Params = [1.2, 5.0, 0.05, 0.12, 0.0, 0.0, -0.9, -1.3, 0];
-const HI: Params = [4.6, 8.8, 2.3, 2.0, 1.4, 1.0, 0.9, 1.3, 1];
-
-function toArtic(p: number[]): HumanArtic {
- const [tbX, tbY, jaw, lipAp, lipProt, lipWidth, root, larynx, curl] = p;
- const tip = restTip(jaw, tbX, tbY);
- // rhotic curl raises the tip toward the post-alveolar region
- const ttX = tip.x - 0.4 * curl;
- const ttY = tip.y + 2.0 * curl;
- return { ...NEUTRAL, tbX, tbY, jaw, lipAp, lipProt, lipWidth, root, larynx, ttX, ttY, ttCurl: curl };
-}
-
-function formants(air: HumanAirway, a: HumanArtic): { F: number[]; minArea: number } {
- air.apply(a);
- const el = air.net.linearElements();
- const H = transferFunction(el, air.pharynx.firstNode, freqs, [air.glottisPort]);
- const pk = findPeaks(freqs, H.mag, 150).map((p) => p.freq);
- let minArea = Infinity;
- for (const A of air.phAreas) minArea = Math.min(minArea, A);
- for (const A of air.orAreas) minArea = Math.min(minArea, A);
- return { F: pk, minArea };
-}
-
-const results: Record<string, Record<string, { artic: Partial<HumanArtic>; formants: number[]; target: number[]; err: number[] }>> = existsSync(OUT) ? JSON.parse(readFileSync(OUT, "utf8")) : {};
-
-for (const [bname, body] of bodies) {
- if (which !== "all" && which !== bname) continue;
- const air = new HumanAirway({ body, fs: 96000 });
- const k = body.scale;
- results[bname] = {};
- for (const vw of VOWELS) {
- const T = bname === "male" ? vw.male : bname === "female" ? vw.female : vw.child;
- // initial guess from vowel-space position
- const x0: Params = [
- 3.5 - 1.3 * vw.back + 0.2 * vw.height * (1 - vw.back),
- 8.0 - 2.0 * vw.height - 0.25 * vw.back,
- 0.25 + 1.4 * vw.height,
- vw.round ? 0.35 + 0.6 * vw.height : 0.6 + 1.0 * vw.height,
- vw.round ? 0.9 : 0.1,
- vw.round ? 0.12 : 0.85,
- 0.4 * (1 - vw.back) - 0.5 * vw.height * vw.back,
- 0.4 * (1 - vw.height) * (1 - vw.back) - (vw.round ? 0.4 : 0),
- vw.ipa === "ɝ" ? 0.6 : 0,
- ];
- if (vw.ipa === "ɯ") x0.splice(0, x0.length, 2.6, 7.35, 0.25, 0.5, 0.1, 0.65, 0.4, 0.2, 0);
- const jawPrior = 0.2 + 1.5 * vw.height;
- const cost = (p: number[]): number => {
- const a = toArtic(p);
- const { F, minArea } = formants(air, a);
- if (F.length < 3) return 50;
- let c = 0;
- const w = [1.0, 1.0, vw.ipa === "ɝ" ? 1.2 : 0.45];
- for (let i = 0; i < 3; i++) c += w[i] * Math.pow(Math.log(F[i] / T[i]), 2);
- // physiology priors (soft)
- const minOk = 0.22 * k * k;
- if (minArea < minOk) c += 0.4 * Math.pow((minOk - minArea) / minOk, 2);
- c += 0.004 * Math.pow(p[2] - jawPrior, 2);
- const open = vw.height > 0.6;
- if (vw.round) {
- const wMax = open ? 0.45 : 0.3, pMin = open ? 0.35 : 0.6, apMax = 0.3 + 0.7 * vw.height;
- c += 0.05 * Math.pow(Math.max(0, p[5] - wMax), 2) + 0.05 * Math.pow(Math.max(0, pMin - p[4]), 2) + 0.05 * Math.pow(Math.max(0, p[3] - apMax), 2);
- } else {
- const apPrior = 0.35 + 0.75 * p[2];
- c += 0.05 * Math.pow(Math.max(0, 0.55 - p[5]), 2) + 0.05 * Math.pow(Math.max(0, p[4] - 0.35), 2) + 0.03 * Math.pow(Math.max(0, Math.abs(p[3] - apPrior) - 0.35), 2);
- }
- c += 0.002 * p[6] * p[6] + 0.006 * p[7] * p[7];
- // the tongue body near where the vowel's height and backness put it: many postures give
- // the same formants, and without this the fit wandered (a schwa with the tongue as low as
- // /ɑ/), making every transition through it needlessly long
- c += 0.006 * (Math.pow(p[0] - x0[0], 2) + Math.pow(p[1] - x0[1], 2));
- if (vw.ipa !== "ɝ") c += 0.5 * p[8] * p[8];
- return c;
- };
- let best = nelderMead(cost, x0, { lo: LO, hi: HI, step: [0.4, 0.4, 0.3, 0.25, 0.3, 0.25, 0.3, 0.3, 0.2], maxIter: 1800 });
- // restart from the best point to escape shallow minima
- for (let r = 0; r < 2; r++) {
- const nb = nelderMead(cost, best.x, { lo: LO, hi: HI, step: [0.2, 0.2, 0.15, 0.12, 0.15, 0.12, 0.15, 0.15, 0.1], maxIter: 1000 });
- if (nb.fx < best.fx) best = nb;
- }
- const a = toArtic(best.x);
- const { F } = formants(air, a);
- const err = [0, 1, 2].map((i) => (F[i] ? (100 * (F[i] - T[i])) / T[i] : NaN));
- const round3 = (x: number) => Math.round(x * 1000) / 1000;
- results[bname][vw.ipa] = {
- artic: { tbX: round3(a.tbX), tbY: round3(a.tbY), jaw: round3(a.jaw), lipAp: round3(a.lipAp), lipProt: round3(a.lipProt), lipWidth: round3(a.lipWidth), root: round3(a.root), larynx: round3(a.larynx), ttX: round3(a.ttX), ttY: round3(a.ttY), ttCurl: round3(a.ttCurl) },
- formants: F.slice(0, 4).map(Math.round),
- target: T.map(Math.round),
- err: err.map((e) => Math.round(e * 10) / 10),
- };
- console.log(`${bname.padEnd(6)} ${vw.ipa.padEnd(2)} F=${F.slice(0, 3).map((f) => f.toFixed(0).padStart(5)).join("")} T=${T.map((f) => f.toFixed(0).padStart(5)).join("")} err%=${err.map((e) => e.toFixed(1).padStart(6)).join("")} tb=(${a.tbX.toFixed(2)},${a.tbY.toFixed(2)}) jaw=${a.jaw.toFixed(2)} lip=${a.lipAp.toFixed(2)}/${a.lipProt.toFixed(2)}/${a.lipWidth.toFixed(2)} root=${a.root.toFixed(2)} lx=${a.larynx.toFixed(2)} curl=${a.ttCurl.toFixed(2)}`);
- }
-}
-writeFileSync(OUT, JSON.stringify(results, null, 1));
-console.log("wrote", OUT);
diff --git a/tools/draw-anatomy.ts b/tools/draw-anatomy.ts
deleted file mode 100644
index c408bd4..0000000
--- a/tools/draw-anatomy.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Debug render of the human articulatory model: contours, measurement grid, area function.
- * Usage: bun tools/draw-anatomy.ts [out.png]
- */
-import { HumanVocalTract, NEUTRAL, type HumanArtic } from "../src/engine/anatomy/human.ts";
-import type { Vec } from "../src/engine/anatomy/geom.ts";
-import { Image } from "./lib/image.ts";
-
-const out = process.argv[2] ?? "out/anatomy.png";
-const tract = new HumanVocalTract();
-
-const poses: [string, Partial<HumanArtic>][] = [
- ["NEUTRAL", {}],
- ["I (HEED)", { tbX: 3.75, tbY: 8.25, jaw: 0.35, lipAp: 0.55, lipWidth: 0.95, lipProt: 0 }],
- ["A (FATHER)", { tbX: 2.05, tbY: 5.85, jaw: 1.6, lipAp: 1.6, lipWidth: 0.6 }],
- ["U (WHO)", { tbX: 2.25, tbY: 8.0, jaw: 0.4, lipAp: 0.35, lipWidth: 0.1, lipProt: 1.0 }],
- ["T CLOSURE", { ttX: 6.3, ttY: 9.8 }],
- ["K CLOSURE", { tbX: 2.3, tbY: 8.4 }],
-];
-
-const cellW = 420, cellH = 520;
-const img = new Image(cellW * 3, cellH * 2, [14, 14, 20]);
-poses.forEach(([name, pose], idx) => {
- const a = { ...NEUTRAL, ...pose };
- const f = tract.compute(a);
- const ox = (idx % 3) * cellW, oy = Math.floor(idx / 3) * cellH;
- const S = 32; // px per cm
- const X = (p: Vec) => ox + 90 + p.x * S;
- const Y = (p: Vec) => oy + 30 + (12 - p.y) * S;
- const poly = (pts: Vec[], c: [number, number, number]) => {
- for (let i = 0; i < pts.length - 1; i++) img.line(X(pts[i]), Y(pts[i]), X(pts[i + 1]), Y(pts[i + 1]), c);
- };
- img.text(ox + 8, oy + 8, name, [230, 230, 230]);
- for (const g of f.grid) {
- const col: [number, number, number] = g.region === 1 ? [70, 120, 200] : g.region === 2 ? [70, 170, 120] : [200, 150, 70];
- img.line(X(g.inner), Y(g.inner), X(g.outer), Y(g.outer), col, 0.6);
- }
- poly(f.outer, [235, 235, 235]);
- poly(f.inner, [255, 120, 140]);
- poly(f.velum, [200, 140, 200]);
- poly(f.jawBone, [160, 160, 160]);
- poly(f.upperTeeth, [250, 250, 210]);
- poly(f.lowerTeeth, [250, 250, 210]);
- img.rect(X(f.glottis) - 2, Y(f.glottis) - 2, 5, 5, [255, 220, 0]);
- // area function
- const ax = ox + 20, ay = oy + cellH - 110, aw = cellW - 40, ah = 90;
- img.rect(ax, ay, aw, ah, [24, 24, 32]);
- const maxS = 19, maxA = 8;
- const ph = new Float64Array(20), or = new Float64Array(20);
- const { phLen, orLen } = tract.resample(a, f, 20, 20, ph, or);
- const bars = [...Array.from(ph, (A, i) => [((i + 0.5) / 20) * phLen, A, phLen / 20]), ...Array.from(or, (A, i) => [phLen + ((i + 0.5) / 20) * orLen, A, orLen / 20])];
- for (const [s, A, w] of bars) {
- const x0 = ax + ((s - w / 2) / maxS) * aw, x1 = ax + ((s + w / 2) / maxS) * aw;
- const h = Math.min(1, A / maxA) * ah;
- img.rect(x0, ay + ah - h, Math.max(1, x1 - x0 - 1), h, s < phLen ? [70, 120, 200] : [200, 120, 90]);
- }
- img.text(ax + 4, ay + 4, `L ${f.length.toFixed(1)} PH ${phLen.toFixed(1)} LIP ${f.lipArea.toFixed(2)}`, [220, 220, 220]);
-});
-img.savePng(out);
-console.log("wrote", out);
diff --git a/tools/explore-syrinx.ts b/tools/explore-syrinx.ts
deleted file mode 100644
index b1b2dfb..0000000
--- a/tools/explore-syrinx.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * Explore the Gardner–Mindlin labial normal form in normalised time τ:
- * X' = Y, Y' = −α − βX − X³ − X²Y + X² − XY
- * For a grid of (α, β): does a limit cycle exist? period in τ, amplitude, harmonic richness.
- * Usage: bun tools/explore-syrinx.ts
- */
-function rhs(x: number, y: number, a: number, b: number): [number, number] {
- return [y, -a - b * x - x * x * x - x * x * y + x * x - x * y];
-}
-function simulate(a: number, b: number) {
- let x = 0.1, y = 0.0;
- const h = 0.002;
- const N = 400000;
- const xs: number[] = [];
- for (let i = 0; i < N; i++) {
- const [k1x, k1y] = rhs(x, y, a, b);
- const [k2x, k2y] = rhs(x + 0.5 * h * k1x, y + 0.5 * h * k1y, a, b);
- const [k3x, k3y] = rhs(x + 0.5 * h * k2x, y + 0.5 * h * k2y, a, b);
- const [k4x, k4y] = rhs(x + h * k3x, y + h * k3y, a, b);
- x += (h / 6) * (k1x + 2 * k2x + 2 * k3x + k4x);
- y += (h / 6) * (k1y + 2 * k2y + 2 * k3y + k4y);
- if (!Number.isFinite(x) || Math.abs(x) > 50) return null;
- if (i > N / 2) xs.push(x);
- }
- let mn = Infinity, mx = -Infinity, mean = 0;
- for (const v of xs) { mn = Math.min(mn, v); mx = Math.max(mx, v); mean += v; }
- mean /= xs.length;
- if (mx - mn < 1e-3) return { osc: false, fix: mean };
- // period from upward mean crossings
- const cr: number[] = [];
- for (let i = 1; i < xs.length; i++) if (xs[i - 1] < mean && xs[i] >= mean) cr.push(i);
- if (cr.length < 3) return { osc: false, fix: mean };
- const period = ((cr[cr.length - 1] - cr[0]) / (cr.length - 1)) * h;
- // crude richness: ratio of time spent in the top 20% of the swing (spiky = rich)
- let top = 0; for (const v of xs) if (v > mn + 0.8 * (mx - mn)) top++;
- return { osc: true, period, amp: mx - mn, min: mn, max: mx, duty: top / xs.length };
-}
-const rows: string[] = [];
-for (const b of [0.1, 0.2, 0.3, 0.45, 0.6, 0.8, 1.0, 1.3]) {
- const cells: string[] = [];
- for (const a of [0.0, 0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.6]) {
- const r = simulate(a, b);
- cells.push(!r ? " diverge " : !r.osc ? " · " : `T${r.period!.toFixed(1).padStart(5)} A${r.amp!.toFixed(2)}`);
- }
- rows.push(`β=${b.toFixed(2).padStart(5)} | ${cells.join(" ")}`);
-}
-console.log("α = 0.00 0.05 0.10 0.15 0.20 0.30 0.40 0.60");
-console.log(rows.join("\n"));
diff --git a/tools/gen-ipa-nfc.ts b/tools/gen-ipa-nfc.ts
index 69717e2..aea7bf8 100644
--- a/tools/gen-ipa-nfc.ts
+++ b/tools/gen-ipa-nfc.ts
@@ -13,8 +13,12 @@
* The data comes from the JS engine's own ICU, so it matches what the TypeScript engine did.
* Usage: bun tools/gen-ipa-nfc.ts
*/
-import { writeFileSync } from "node:fs";
-import { CONSONANT_SYMBOLS } from "../src/engine/phonetics/inventory.ts";
+import { readFileSync, writeFileSync } from "node:fs";
+import { initChimera, call } from "../src/wasm/chimera.ts";
+
+// the consonant inventory, from the engine (run `bun run wasm` first)
+await initChimera(readFileSync(new URL("../src/wasm/chimera.wasm", import.meta.url)));
+const CONSONANT_SYMBOLS = call<{ consonantSymbols: string[] }>("catalog").consonantSymbols;
const VOWEL_CHARS = "iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶɑɒɝɚ";
const MULTI = ["tʃ", "dʒ", "ts", "dz", "pf", "aɪ", "aʊ", "ɔɪ", "eɪ", "oʊ"];
diff --git a/tools/gen-syrinx-table.ts b/tools/gen-syrinx-table.ts
index f665022..4b21c03 100644
--- a/tools/gen-syrinx-table.ts
+++ b/tools/gen-syrinx-table.ts
@@ -1,6 +1,6 @@
/**
* Tabulate the Gardner–Mindlin normal form's limit cycle over (α, β): period T (in τ), and the
- * X range (for mapping labial displacement to valve opening). Output: src/engine/sources/syrinxTable.generated.json
+ * X range (for mapping labial displacement to valve opening). Output: crates/chimera/src/sources/syrinxTable.generated.json
*/
import { writeFileSync } from "node:fs";
const rhs = (x: number, y: number, a: number, b: number): [number, number] => [y, -a - b * x - x * x * x - x * x * y + x * x - x * y];
@@ -41,5 +41,5 @@ for (const b of betas) {
}
T.push(rT); lo.push(rl); hi.push(rh);
}
-writeFileSync("src/engine/sources/syrinxTable.generated.json", JSON.stringify({ alphas, betas, T, lo, hi }));
+writeFileSync("crates/chimera/src/sources/syrinxTable.generated.json", JSON.stringify({ alphas, betas, T, lo, hi }));
console.log("T range", Math.min(...T.flat().filter(Number.isFinite)), Math.max(...T.flat()), "NaN cells", T.flat().filter((v) => !Number.isFinite(v)).length);
diff --git a/tools/golden/analysis.ts b/tools/golden/analysis.ts
deleted file mode 100644
index f4ec0cb..0000000
--- a/tools/golden/analysis.ts
+++ /dev/null
@@ -1,262 +0,0 @@
-/**
- * Frequency-domain oracle and analysis fixtures: transfer functions (the UI's formant pipeline on
- * the human airway, and simple tube networks), findPeaks, FFT/spectra/windows, LPC, YIN and
- * Nelder–Mead. Input signals are stored with the results, so the Rust side runs each function
- * on exactly the same numbers.
- */
-import { readFileSync } from "node:fs";
-import { AirwayNetwork } from "../../src/engine/airway/network.ts";
-import { transferFunction, findPeaks, linspace, type Peak } from "../../src/engine/airway/frequency.ts";
-import { HumanAirway } from "../../src/engine/voice/humanAirway.ts";
-import { NEUTRAL, type HumanArtic } from "../../src/engine/anatomy/human.ts";
-import { FFT, hann, hamming, powerSpectrumDb, nextPow2 } from "../../src/engine/analysis/fft.ts";
-import { autocorr, levinson, polyRoots, estimateFormants, lpcEnvelopeDb } from "../../src/engine/analysis/lpc.ts";
-import { yinPitch } from "../../src/engine/analysis/pitch.ts";
-import { nelderMead } from "../../src/engine/util/optimize.ts";
-import { WALL_SOFT, RHO } from "../../src/engine/physics.ts";
-import { Rng } from "../../src/engine/util/math.ts";
-import TARGETS from "../../src/engine/phonetics/vowelTargets.generated.json";
-import { BODIES, OUT, write, num } from "./lib.ts";
-
-const arr = (x: ArrayLike<number>) => Array.from(x, num);
-const peaks = (ps: Peak[]) => ps.map((p) => [p.freq, p.bw, p.db].map(num));
-
-// ------------------------------------------------------------ the UI's transfer function
-// src/ui/analysis.ts VoiceModel.transfer: 360 log-spaced frequencies, injection at the first
-// pharynx node, the glottis port cut, dB with a 1e-12 floor, findPeaks(…, 150) → 5 formants.
-const UI_FREQS = (() => {
- const n = 360;
- const out = new Float64Array(n);
- for (let i = 0; i < n; i++) out[i] = 60 * Math.pow(8000 / 60, i / (n - 1));
- return out;
-})();
-
-function postures(body: string): { name: string; artic: HumanArtic }[] {
- const T = TARGETS as unknown as Record<string, Record<string, { artic: Partial<HumanArtic> }>>;
- const v = (ipa: string, extra: Partial<HumanArtic> = {}) => ({ ...NEUTRAL, ...T[body][ipa].artic, ...extra }) as HumanArtic;
- return [
- { name: "neutral", artic: { ...NEUTRAL } },
- { name: "i", artic: v("i") },
- { name: "ɑ", artic: v("ɑ") },
- { name: "u", artic: v("u") },
- { name: "ɝ", artic: v("ɝ") },
- { name: "nasal ə", artic: v("ə", { velum: 0.9 }) },
- { name: "m (lips closed)", artic: { ...NEUTRAL, lipAp: -0.2, velum: 1.0 } },
- ];
-}
-
-const human = Object.keys(BODIES).map((body) => {
- // one airway per body, applied posture after posture (as the UI's VoiceModel is)
- const airway = new HumanAirway({ fs: 96000, body: BODIES[body] });
- return {
- body,
- cases: postures(body).map(({ name, artic }) => {
- airway.apply(artic);
- const el = airway.net.linearElements();
- const H = transferFunction(el, airway.pharynx.firstNode, UI_FREQS, [airway.glottisPort]);
- const db = new Float64Array(UI_FREQS.length);
- for (let i = 0; i < UI_FREQS.length; i++) db[i] = 20 * Math.log10(H.mag[i] + 1e-12);
- const ps = findPeaks(UI_FREQS, H.mag, 150);
- return { name, artic, mag: arr(H.mag), pressureDb: arr(H.pressureDb), db: arr(db), peaks: peaks(ps), formants: ps.map((p) => p.freq).slice(0, 5) };
- }),
- };
-});
-
-// ------------------------------------------------------------ simple networks
-function networks() {
- const out: { name: string; inject: number; cut: number[]; net: AirwayNetwork }[] = [];
- for (const walls of [false, true]) {
- const net = new AirwayNetwork(96000);
- const t = net.addTube({ name: "tract", n: 40, length: 17.5, area: 3, wall: walls ? WALL_SOFT : null });
- net.addRadiation(t.lastNode);
- net.finalize();
- out.push({ name: walls ? "uniform, soft walls" : "uniform, rigid", inject: t.firstNode, cut: [], net });
- }
- {
- // three-way junction, two radiating ends, one squeezed section
- const net = new AirwayNetwork(48000);
- const a = net.addTube({ name: "a", n: 12, length: 8, area: Array.from({ length: 12 }, (_, i) => 1 + 0.3 * i), wall: WALL_SOFT, wallRadiation: 0.25 });
- const b = net.addTube({ name: "b", n: 10, length: 7, area: 2 });
- const c = net.addTube({ name: "c", n: 14, length: 11, area: 1.2, wall: WALL_SOFT });
- net.connect(a.lastNode, b.firstNode);
- net.connect(a.lastNode, c.firstNode);
- net.addRadiation(b.lastNode);
- net.addRadiation(c.lastNode);
- net.finalize();
- out.push({ name: "branched", inject: a.firstNode, cut: [], net });
- }
- {
- // lungs (fixed pressure) → port → tube with a Helmholtz side cavity; then the port cut
- const net = new AirwayNetwork(48000);
- const lung = net.addPressureNode("lung");
- const t = net.addTube({ name: "t", n: 20, length: 15, area: 2.5, wall: WALL_SOFT });
- const port = net.addPort(lung, t.firstNode, { area: 0.4, length: 0.5, extraResistance: (0.5 * RHO * 35000) / 0.4 });
- const cav = net.addCavity("sinus", 12);
- net.addPort(t.node(8), cav, { area: 0.15, length: 0.6, kEntrance: 0, kExit: 0, includeHalfSections: false });
- net.addRadiation(t.lastNode);
- net.finalize();
- out.push({ name: "lungs + side cavity", inject: t.firstNode, cut: [], net });
- out.push({ name: "lungs cut + side cavity", inject: t.firstNode, cut: [port], net });
- }
- return out;
-}
-
-const NET_FREQS = linspace(20, 6000, 700);
-const nets = networks().map(({ name, inject, cut, net }) => {
- const H = transferFunction(net.linearElements(), inject, NET_FREQS, cut);
- return { name, mag: arr(H.mag), pressureDb: arr(H.pressureDb), peaks: peaks(findPeaks(NET_FREQS, H.mag)) };
-});
-
-// ------------------------------------------------------------ findPeaks edge cases
-const rng = new Rng(77);
-const peakCases = (() => {
- const f = linspace(0, 4000, 801);
- const res = (fr: number, f0: number, bw: number) => 1 / Math.hypot(1 - (fr / f0) ** 2, (bw / f0) * (fr / f0));
- const smooth = Array.from(f, (x) => res(x, 600, 60) + 0.5 * res(x, 1700, 120) + 0.3 * res(x, 3990, 90));
- const noisy = Array.from(f, (_, i) => smooth[i] * (1 + 0.05 * rng.bipolar()));
- // a flat plateau (equal neighbours) and a peak at the last-but-one bin
- const plateau = Array.from(f, (_, i) => (i >= 300 && i < 310 ? 5 : i === 799 ? 9 : 1 + i * 1e-4));
- return [
- { name: "smooth", freqs: arr(f), mag: arr(smooth), minFreq: 80 },
- { name: "noisy", freqs: arr(f), mag: arr(noisy), minFreq: 200 },
- { name: "plateau", freqs: arr(f), mag: arr(plateau), minFreq: 0 },
- ].map((c) => ({ ...c, peaks: peaks(findPeaks(c.freqs as number[], c.mag as number[], c.minFreq)) }));
-})();
-
-// ------------------------------------------------------------ signals
-/** Impulse train at f0 through cascaded 2-pole resonators at known formants (as tests/analysis). */
-function synthVowel(sr: number, f0: number, formants: [number, number][], dur: number): Float64Array {
- const n = Math.round(sr * dur);
- let x = new Float64Array(n);
- const period = sr / f0;
- for (let k = 0; k * period < n; k++) x[Math.round(k * period)] = 1;
- for (const [f, bw] of formants) {
- const r = Math.exp((-Math.PI * bw) / sr);
- const a1 = 2 * r * Math.cos((2 * Math.PI * f) / sr);
- const a2 = -r * r;
- const y = new Float64Array(n);
- for (let i = 0; i < n; i++) y[i] = x[i] + a1 * (i > 0 ? y[i - 1] : 0) + a2 * (i > 1 ? y[i - 2] : 0);
- x = y;
- }
- return x;
-}
-const voice = (name: string) => {
- const b = readFileSync(`${OUT}/voice-${name}.f32`);
- return new Float32Array(b.buffer, b.byteOffset, b.byteLength / 4);
-};
-// a TS render of the human voice: the sustained male vowel, 48 kHz (frame read from the .f32 in Rust)
-const VOICE = { name: "sustain-male", sr: 48000, offset: 9600, len: 2048 };
-const voiceFrame = Array.from(voice(VOICE.name).subarray(VOICE.offset, VOICE.offset + VOICE.len));
-
-const vowel16 = Array.from(synthVowel(16000, 110, [[730, 60], [1090, 80], [2440, 120], [3400, 150]], 0.3).subarray(1600, 2112));
-const noise = Array.from({ length: 1000 }, () => rng.bipolar());
-
-// ------------------------------------------------------------ FFT
-const fftCases = (() => {
- const n = 1024;
- const sig = Array.from({ length: n }, (_, i) => Math.sin(0.05 * i) + 0.3 * Math.cos(0.71 * i + 0.2) + 0.1 * rng.bipolar());
- const re = Float64Array.from(sig), im = new Float64Array(n);
- new FFT(n).transform(re, im);
- const small = new FFT(8), sr = Float64Array.from([1, -2, 3, 0.5, 0, 0, -1, 4]), si = Float64Array.from([0, 1, 0, -1, 2, 0, 0, 0.25]);
- const sIn = { re: [...sr], im: [...si] };
- small.transform(sr, si);
- return {
- input: arr(sig),
- re: arr(re),
- im: arr(im),
- small: { ...sIn, outRe: arr(sr), outIm: arr(si) },
- hann: arr(hann(64)),
- hamming: arr(hamming(101)),
- // frame shorter than the FFT and the window (zero-padded), and a voice frame
- psdNoise: arr(powerSpectrumDb(noise, new FFT(1024), hann(1000))),
- psdVoice: arr(powerSpectrumDb(voiceFrame, new FFT(2048), hamming(2048))),
- nextPow2: [1, 2, 3, 1000, 1024, 1025, 0.5].map((x) => [x, nextPow2(x)]),
- };
-})();
-
-// ------------------------------------------------------------ LPC
-function lpcCase(name: string, frame: number[], sr: number, order: number, opts: Parameters<typeof estimateFormants>[2]) {
- const r = autocorr(frame, order);
- const { a, err } = levinson(r, order);
- const roots = polyRoots(a);
- const envFreqs = linspace(0, sr / 2, 200);
- return {
- name,
- sr,
- order,
- opts,
- autocorr: arr(r),
- a: arr(a),
- err: num(err),
- rootsRe: arr(roots.re),
- rootsIm: arr(roots.im),
- envelope: arr(lpcEnvelopeDb(a, err, sr, envFreqs)),
- formants: estimateFormants(frame, sr, opts).map((f) => [f.freq, f.bw].map(num)),
- };
-}
-const lpc = {
- vowel16: arr(vowel16),
- noise: arr(noise),
- cases: [
- lpcCase("vowel16 order 14, no pre-emphasis", vowel16, 16000, 14, { order: 14, preEmph: 0 }),
- lpcCase("vowel16 defaults", vowel16, 16000, 18, {}),
- lpcCase("noise order 10", noise, 16000, 10, { order: 10, maxBw: 5000, minFreq: 0 }),
- lpcCase("voice order 24", voiceFrame, 48000, 24, { order: 24 }),
- lpcCase("voice defaults (order 50)", voiceFrame, 48000, 50, {}),
- ],
- // a polynomial with known roots: (z − 0.5)(z + 0.25)(z² − z + 0.5)(z² + 0.81)
- known: (() => {
- let c = [1];
- for (const q of [[1, -0.5], [1, 0.25], [1, -1, 0.5], [1, 0, 0.81]]) {
- const next = new Array(c.length + q.length - 1).fill(0);
- c.forEach((x, i) => q.forEach((y, j) => (next[i + j] += x * y)));
- c = next;
- }
- const r = polyRoots(c);
- return { c, re: arr(r.re), im: arr(r.im), short: (() => { const s = polyRoots(c, 5); return { re: arr(s.re), im: arr(s.im) }; })() };
- })(),
-};
-
-// ------------------------------------------------------------ YIN
-const yinCases = [
- ...[82, 110, 220, 440, 880].map((f0) => ({ name: `vowel ${f0}`, sr: 48000, frame: Array.from(synthVowel(48000, f0, [[500, 80], [1500, 100]], 0.2).subarray(2000, 4400)), opts: { minF0: 60 } })),
- { name: "noise (unvoiced)", sr: 16000, frame: noise, opts: {} },
- { name: "too short", sr: 48000, frame: noise.slice(0, 40), opts: { minF0: 60 } },
- { name: "voice", sr: 48000, frame: null, opts: { minF0: 70, maxF0: 500, threshold: 0.1 } },
-].map((c) => {
- const p = yinPitch(c.frame ?? voiceFrame, c.sr, c.opts);
- return { ...c, frame: c.frame && arr(c.frame), f0: num(p.f0), aperiodicity: num(p.aperiodicity) };
-});
-
-// ------------------------------------------------------------ Nelder–Mead
-const nm = (() => {
- const rosen = (x: number[]) => (1 - x[0]) ** 2 + 100 * (x[1] - x[0] ** 2) ** 2;
- const bowl = (x: number[]) => (x[0] - 3) ** 2 + 2 * (x[1] + 1) ** 2 + 0.5 * (x[2] - 0.2) ** 2 + Math.sin(3 * x[0]) * 0.1;
- const counted = (f: (x: number[]) => number) => {
- let n = 0;
- return { f: (x: number[]) => (n++, f(x)), calls: () => n };
- };
- const run = (name: string, fn: (x: number[]) => number, x0: number[], opts: Parameters<typeof nelderMead>[2]) => {
- const c = counted(fn);
- const r = nelderMead(c.f, x0, opts);
- return { name, x0, opts, x: arr(r.x), fx: num(r.fx), iters: r.iters, calls: c.calls() };
- };
- return [
- run("rosenbrock", rosen, [-1.2, 1], {}),
- run("rosenbrock, few iterations", rosen, [-1.2, 1], { maxIter: 25 }),
- run("bounded bowl", bowl, [0, 0, 0], { lo: [-1, -0.5, 0.5], hi: [2, 2, 2], step: [0.3, 0.3, 0.1], tol: 1e-10 }),
- ];
-})();
-
-write("analysis", {
- uiFreqs: arr(UI_FREQS),
- human,
- netFreqs: arr(NET_FREQS),
- nets,
- peakCases,
- voice: VOICE,
- fft: fftCases,
- lpc,
- yin: yinCases,
- nelderMead: nm,
-});
diff --git a/tools/golden/creatures.ts b/tools/golden/creatures.ts
deleted file mode 100644
index 3ca62ee..0000000
--- a/tools/golden/creatures.ts
+++ /dev/null
@@ -1,256 +0,0 @@
-/**
- * Creature fixtures: timed operations on a CreatureVoice (calls, gates, parameter changes, stops),
- * the audio it rendered and telemetry snapshots; plus unit sequences for the valve sources.
- *
- * Audio is long (every call of every creature), so the .f32 file keeps 10 ms windows selectively:
- * the first five, every twelfth, and the two around each operation. The JSON lists the kept
- * windows and the RMS of every window, so the whole render's envelope is still compared.
- */
-import { writeFileSync } from "node:fs";
-import { CREATURES } from "../../src/engine/creatures/index.ts";
-import { CreatureVoice, type CreatureTelemetry } from "../../src/engine/creatures/voice.ts";
-import type { CreatureDef } from "../../src/engine/creatures/types.ts";
-import { LipReed, Whistle, ClickTrain, Bubble } from "../../src/engine/sources/valves.ts";
-import { SyrinxLabia } from "../../src/engine/sources/syrinx.ts";
-import { OUT, write, num } from "./lib.ts";
-
-type Op =
- | { at: number; op: "params"; values: Record<string, number | string> }
- | { at: number; op: "gate"; level: number }
- | { at: number; op: "call"; id: string; pitch?: number; amp?: number }
- | { at: number; op: "stop" }
- | { at: number; op: "telemetry" };
-
-interface Scenario {
- name: string;
- creature: string;
- fsOut: number;
- samples: number;
- initial?: Record<string, number | string>;
- ops: Op[];
-}
-
-const parse = (x: number | string) => (typeof x === "string" ? Number(x) : x);
-const parseRec = (r: Record<string, number | string>) => Object.fromEntries(Object.entries(r).map(([k, v]) => [k, parse(v)]));
-
-function snap(t: CreatureTelemetry) {
- const tubes: Record<string, { areas: number[]; rms: number[] }> = {};
- for (const [k, v] of Object.entries(t.tubes)) tubes[k] = { areas: Array.from(v.areas), rms: Array.from(v.rms) };
- return { ...t, tubes };
-}
-
-function run(s: Scenario, def: CreatureDef) {
- const v = new CreatureVoice(def, s.fsOut, s.initial ? parseRec(s.initial) : undefined);
- const out = new Float32Array(s.samples);
- const ops = [...s.ops].sort((a, b) => a.at - b.at);
- const snaps: unknown[] = [];
- let i = 0, oi = 0;
- while (i < s.samples) {
- while (oi < ops.length && ops[oi].at <= i) {
- const o = ops[oi++];
- if (o.op === "params") v.setParams(parseRec(o.values));
- else if (o.op === "gate") v.setGate(o.level);
- else if (o.op === "call") v.playCall(o.id, o.pitch, o.amp);
- else if (o.op === "stop") v.stopCall();
- else snaps.push(snap(v.telemetry()));
- }
- 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;
- }
- // telemetry ops at the very end
- while (oi < ops.length) {
- if (ops[oi++].op === "telemetry") snaps.push(snap(v.telemetry()));
- }
- return { out, snaps };
-}
-
-const callLength = (def: CreatureDef, id: string) => Math.max(...def.calls.find((c) => c.id === id)!.keys.map((k) => k.t));
-
-// per creature: a pitched call, a param that its calls own, and a param they leave alone
-const EXTRA: Record<string, { pitched: [string, number, number]; stop: string; owned: [string, number]; free: [string, number]; held: Record<string, number>[]; initial: Record<string, number | string> }> = {
- songbird: { pitched: ["trill", 4100, 0.7], stop: "flute", owned: ["pitch", 3100], free: ["gape", 0.9], held: [{ pitch: 3400, interval: -5 }, { drive: 0.8, tension: 0.7, voices: 0.9 }, { purity: 0.1, oec: 1.2, pressure: 1.6 }], initial: { pitch: 5200, drive: 2, voices: "NaN", gape: 0.2 } },
- seal: { pitched: ["zap", 4200, 0.8], stop: "trill", owned: ["pitch", 700], free: ["bright", 0.95], held: [{ pitch: 2400, pulse: 0.1 }, { pulseRate: 40, duty: 0.3, rough: 0.6 }, { mouth: 0.9, pressure: 20 }], initial: { pitch: 300, pulseRate: 1, rough: "NaN", mouth: 0.8 } },
- alligator: { pitched: ["growl", 70, 0.6], stop: "bellow", owned: ["chaos", 0.2], free: ["nostrils", 0.1], held: [{ pitch: 45, chaos: 0.3 }, { hiss: 0.6, mouth: 0.5 }, { pressure: 35, nostrils: 0.2 }], initial: { pitch: 60, chaos: 0.1, hiss: 5, pressure: "NaN" } },
- elephant: { pitched: ["rumble", 22, 0.8], stop: "trumpet", owned: ["lipPitch", 600], free: ["trunk", 0.3], held: [{ mode: 1, lipPitch: 420, pressure: 30 }, { chaos: 0.7, lipPitch: 610 }, { mode: 0.4, trunk: 0.2 }], initial: { mode: 1, lipPitch: 350, trunk: -3, chaos: "NaN" } },
-};
-
-function scenarios(): Scenario[] {
- const FS = 48000;
- const sec = (x: number, fs = FS) => Math.round(x * fs);
- const list: Scenario[] = [];
- for (const def of CREATURES) {
- const x = EXTRA[def.id];
- def.calls.forEach((c, ci) => {
- const len = callLength(def, c.id) + 0.17;
- const ops: Op[] = [{ at: 0, op: "call", id: c.id }, { at: sec(len * 0.5), op: "telemetry" }];
- // the very first scenario of each creature also captures the preview (telemetry before audio)
- if (ci === 0) ops.unshift({ at: 0, op: "telemetry" });
- list.push({ name: `${def.id}-call-${c.id}`, creature: def.id, fsOut: FS, samples: sec(len), ops });
- });
- const [pid, pitch, amp] = x.pitched;
- list.push({ name: `${def.id}-pitched`, creature: def.id, fsOut: FS, samples: sec(Math.min(0.9, callLength(def, pid) + 0.17)), ops: [{ at: 0, op: "call", id: pid, pitch, amp }, { at: sec(0.3), op: "telemetry" }] });
- list.push({
- name: `${def.id}-held`,
- creature: def.id,
- fsOut: FS,
- samples: sec(0.7),
- ops: [
- { at: 0, op: "gate", level: 1 },
- { at: sec(0.12), op: "params", values: x.held[0] },
- { at: sec(0.12), op: "telemetry" },
- { at: sec(0.25) + 37, op: "params", values: x.held[1] },
- { at: sec(0.4) + 5, op: "params", values: x.held[2] },
- { at: sec(0.4) + 5, op: "telemetry" },
- { at: sec(0.5), op: "gate", level: 0 },
- { at: sec(0.7), op: "telemetry" },
- ],
- });
- // a call replaced by another, performer changes to an owned and a free param during the call, then a stop
- list.push({
- name: `${def.id}-stop`,
- creature: def.id,
- fsOut: FS,
- samples: sec(0.6),
- ops: [
- { at: 0, op: "call", id: def.calls[def.calls.length - 1].id },
- { at: sec(0.08), op: "call", id: x.stop, amp: 1.2 },
- { at: sec(0.15) + 11, op: "params", values: Object.fromEntries([x.owned, x.free]) },
- { at: sec(0.3) + 3, op: "stop" },
- { at: sec(0.3) + 3, op: "telemetry" },
- { at: sec(0.32), op: "gate", level: 0.8 },
- { at: sec(0.45), op: "gate", level: 0 },
- ],
- });
- list.push({ name: `${def.id}-initial`, creature: def.id, fsOut: FS, samples: sec(0.4), initial: x.initial, ops: [{ at: 0, op: "telemetry" }, { at: 0, op: "gate", level: 2 }, { at: sec(0.3), op: "gate", level: 0 }, { at: sec(0.4), op: "telemetry" }] });
- }
- // 96 kHz: the oversampling factor halves
- list.push({ name: "songbird-96k", creature: "songbird", fsOut: 96000, samples: sec(0.5, 96000), ops: [{ at: 0, op: "call", id: "chirps", pitch: 3800 }, { at: sec(0.25, 96000), op: "telemetry" }] });
- list.push({ name: "elephant-96k", creature: "elephant", fsOut: 96000, samples: sec(0.4, 96000), ops: [{ at: 0, op: "call", id: "squeak" }, { at: sec(0.3, 96000), op: "telemetry" }] });
- return list;
-}
-
-function keptWindows(s: Scenario, win: number): number[] {
- const n = Math.ceil(s.samples / win);
- const keep = new Set<number>();
- for (let w = 0; w < n; w++) if (w < 5 || w % 12 === 0) keep.add(w);
- for (const o of s.ops) {
- const w = Math.floor(o.at / win);
- if (w < n) keep.add(w);
- if (w + 1 < n) keep.add(w + 1);
- }
- return [...keep].sort((a, b) => a - b);
-}
-
-{
- const all = scenarios();
- const fixtures: unknown[] = [];
- const chunks: Float32Array[] = [];
- let offset = 0;
- for (const s of all) {
- const def = CREATURES.find((c) => c.id === s.creature)!;
- const { out, snaps } = run(s, def);
- const win = Math.round(s.fsOut / 100);
- const windows = keptWindows(s, win);
- const env: number[] = [];
- for (let a = 0; a < s.samples; a += win) {
- let e = 0;
- const b = Math.min(s.samples, a + win);
- for (let i = a; i < b; i++) e += out[i] * out[i];
- env.push(Math.sqrt(e / (b - a)));
- }
- let len = 0;
- for (const w of windows) {
- const part = out.subarray(w * win, Math.min(s.samples, (w + 1) * win));
- chunks.push(part);
- len += part.length;
- }
- fixtures.push({ ...s, win, windows, offset, length: len, env, snaps });
- offset += len;
- }
- const audio = new Float32Array(offset);
- let o = 0;
- for (const c of chunks) {
- audio.set(c, o);
- o += c.length;
- }
- writeFileSync(`${OUT}/creatures.f32`, Buffer.from(audio.buffer));
- console.log(`creatures.f32 ${(audio.byteLength / 1024).toFixed(0)} KB`);
- write("creatures", fixtures);
-}
-
-// --- valve sources: per-sample sequences ---------------------------------------------------------
-{
- const N = 2000;
- const NB = 4000;
- const seq = (n: number, f: (i: number) => number) => Array.from({ length: n }, (_, i) => num(f(i)));
- const out: Record<string, unknown> = {};
- {
- const fs = 48000;
- const a = new LipReed(fs);
- out.lipDefault = seq(N, (i) => a.next(2500 + 3000 * Math.sin((2 * Math.PI * 180 * i) / fs)));
- const b = new LipReed(fs);
- b.f = 470;
- b.zeta = 0.08;
- b.h0 = 0.003;
- b.width = 2.4;
- b.surfacePerMass = 40;
- // a buzzing valve: the pressure drop follows the opening (a crude tube load)
- let y = 0;
- out.lipBuzz = seq(N, (i) => {
- const dp = (i < Math.floor((N * 2) / 3) ? 400 : -300) - 2e3 * y;
- y = b.next(dp);
- return y;
- });
- }
- {
- const fs = 96000;
- const w = new Whistle(fs);
- w.f = 1800;
- out.whistle = seq(N, (i) => w.next(i < Math.floor((N * 11) / 15) ? 0.8 : 0.01, 900 * Math.sin((2 * Math.PI * 1750 * i) / fs), 1.5));
- }
- {
- const fs = 48000;
- const c = new ClickTrain(fs);
- c.click(0.001);
- c.click(0.0012, 0.5);
- c.click(0.004, -0.8);
- out.clicksPlain = seq(400, () => c.next());
- c.ring = 3200;
- c.ringDecay = 0.0015;
- c.click(0.0005, 1);
- c.click(0.003, 0.6);
- c.click(0.0031, 0.3);
- const ring = seq(1200, () => c.next());
- c.click(0.002);
- c.clear();
- out.clicksRing = [...ring, ...seq(200, () => c.next())];
- }
- {
- const fs = 96000;
- const b = new Bubble(fs);
- const ys: (number | string)[] = [];
- const rs: (number | string)[] = [];
- for (let i = 0; i < NB; i++) {
- if (i === 100) b.snap(0.8);
- if (i === Math.floor((NB * 7) / 12)) b.snap(0.3, 0.002);
- ys.push(num(b.next()));
- rs.push(num(b.radius));
- }
- out.bubble = ys;
- out.bubbleRadius = rs;
- }
- {
- const fs = 192000;
- const l = new SyrinxLabia(fs, 1);
- out.syrinx = seq(N, (i) => {
- l.drive = i < Math.floor(N / 2) ? 0.3 : 0.9;
- l.tension = i < Math.floor(N / 3) ? 0.4 : 0.05;
- l.f0 = 2500 + i;
- l.gate = i < Math.floor((N * 5) / 6) ? 1 : 0.2;
- return l.next();
- });
- }
- out.defs = JSON.parse(JSON.stringify(CREATURES.map(({ visual, create, ...rest }) => rest)));
- write("creature-units", out);
-}
diff --git a/tools/golden/geometry.ts b/tools/golden/geometry.ts
deleted file mode 100644
index c1d6c03..0000000
--- a/tools/golden/geometry.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-/** 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.ts
deleted file mode 100644
index 11521b8..0000000
--- a/tools/golden/lib.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * 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/phonetics-text.ts b/tools/golden/phonetics-text.ts
deleted file mode 100644
index 389dd62..0000000
--- a/tools/golden/phonetics-text.ts
+++ /dev/null
@@ -1,117 +0,0 @@
-/**
- * Text-side phonetics fixtures: IPA tokenizing (including decomposed diacritics, which NFC
- * composes), G2P with and without the dictionary, phrases, lyrics → syllables, spelling splits,
- * and the demo songs and vowel reference tables.
- */
-import { gunzipSync } from "node:zlib";
-import { readFileSync } from "node:fs";
-import { tokenizeIpa } from "../../src/engine/phonetics/ipa.ts";
-import { EnglishG2P, arpabetToSegments, letterToSound } from "../../src/engine/phonetics/english.ts";
-import { lyricsToSyllables, splitSpelling, syllabifySegments } from "../../src/engine/phonetics/syllables.ts";
-import { DEMO_SONGS } from "../../src/engine/phonetics/songs.ts";
-import { VOWELS } from "../../src/engine/phonetics/vowelData.ts";
-import { Rng } from "../../src/engine/util/math.ts";
-import { write } from "./lib.ts";
-
-const DICT_TEXT = gunzipSync(readFileSync(new URL("../../public/data/cmudict.txt.gz", import.meta.url))).toString("utf8");
-const withDict = new EnglishG2P();
-withDict.setDictionaryText(DICT_TEXT);
-const noDict = new EnglishG2P();
-const rng = new Rng(77);
-const pick = <T>(xs: T[]) => xs[Math.floor(rng.next() * xs.length)];
-
-// ---------------------------------------------------------------- IPA
-const IPA_FIXED = [
- "", " ", "ˈhɛloʊ ˈwɝld", "ʃi sɛlz ˈɑpɑ", "ˈθɪŋk ə ˈbæd ˈkæt", "ˈmʌni ˈtʃɪp ˈʒu ˈvæn", "ˈlɑ", "ˈbɑbɑbɑbɑ",
- "ˌɪntɚˈnæʃənəl", "'ata", "a:ta", "aːːt", "ː", "tʃ dʒ ts dz pf", "aɪ aʊ ɔɪ eɪ oʊ", "t͡ʃa d͡ʒa t͡sa d͡za", "t͜ʃa", "ʧa ʤa", "ɡæp",
- "r̥ɐ̯", "ɐ̯", "a, b | c . d", ",,||", "ˈaˌbˈc", "ɸβθðʂʐçʝxɣχʁħʕhɦɬɮ", "ʈɖcɟkgqɢʔ", "mɱnɳɲŋɴ", "wʋɹɻjɰlɫɭʎɾɽrʀʙ",
- "iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶɑɒɝɚ", "ã ẽ õ", "ã ẽ", "n̩", "ça", "ça", "ḉa", "ḉa",
- "ḉa", "ç̴a", "á", "áb", "a͐́", "á̕", "ệ", "ŕ̥",
- "r̴̥", "t́͡ʃ", "t́͡ʃ", "ǯ", "ǯa", "ɔ̃", "ö", "ü", "ÿ", "i̇",
- "ŋ̊", "s̪", "d̺", "kʰa", "tʰa", "pʼa", "ə˞", "ɑ̃̀", "́a", "a\u{1d165}b", "😀a😀",
- "a͏́", "A B C", "HELLO", "ˈtʃˈdʒ", "t ʃ", "taɪm", "aɪɪ", "oʊː", "ʊə", "a;b", "a\tb", "a\nb", "kʷa", "ⁿda", "ᵐba",
- "ę", "ɛ̨", "ơ", "ứ", "ặ", "ặ", "ī̱", "ǿ", "ǽ",
- "ǣ", "ǯ́", "ǵ", "ɡ́", "Å", "K", "Åx", "Kx", "ä́", "à", "ç̨", "ç̴",
-];
-const IPA_ALPHABET = [..."iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶɑɒɝɚpbtdʈɖcɟkgqɢʔmɱnɳɲŋɴɸβfvθðszʃʒʂʐçʝxɣχʁħʕhɦɬɮwʋɹɻjɰlɫɭʎɾɽrʀʙɡʧʤ", "ˈ", "ˌ", "'", " ", ".", "|", ",", "ː", ":", "͡", "͜", "̃", "́", "̀", "̂", "̈", "̧", "̥", "̯", "̩", "̣", "̱", "̌", "̆", "̄", "̨", "̴", "͐", "̕", "́", "ʰ", "ʷ", "x", "Q", "é", "ñ", "ü"];
-const ipaCases: string[] = [...IPA_FIXED];
-for (let k = 0; k < 400; k++) {
- const n = 1 + Math.floor(rng.next() * 14);
- let s = "";
- for (let i = 0; i < n; i++) s += pick(IPA_ALPHABET);
- ipaCases.push(s);
-}
-write("phonetics-ipa", ipaCases.map((input) => ({ input, segments: tokenizeIpa(input) })));
-
-// ---------------------------------------------------------------- G2P
-const dictWords = DICT_TEXT.split("\n").map((l) => l.slice(0, l.indexOf("\t"))).filter(Boolean);
-const COMMON = (
- "hello world water ladder butter little bottle better city party letter matter metal pedal total model " +
- "the a an of to in on at by for from with as and or but nor so if is am are was were be been do does did has have had will " +
- "would can could should shall may might must it its i you he she we they me him her us them my your his our their this that " +
- "than then there not no who what where when why how one two three ten eleven twenty hundred thousand " +
- "wind read live lead close wound tear bass bow row sow minute object present record " +
- "people time year way day thing man woman child life hand part place case week company system program question work " +
- "government number night point home room mother area money story fact month lot right study book eye job word business " +
- "issue side kind head house service friend father power hour game line end member law car city community name president " +
- "team minute idea kid body information back parent face others level office door health person art war history party result " +
- "change morning reason research girl guy moment air teacher force education singing anywhere breathe tongue lips throat " +
- "twinkle star wonder made fire hour our flower"
-).split(" ");
-const UNKNOWN = "zorblat quixotical fnord blorptastic snergle wugs glimmerish thropple kniggle wrabbit phlogistic xylophonic chairsch tioner sionel ture ough augh eigh dge ngle bring rings queen yoyo crazyy cye gye cee jello hyphen-ated well-known re-read x-ray don't won't o'clock 'tis rock'n'roll".split(" ");
-const ODD = ["", "'", "''", "-", "--", "a-", "-a", "'hello'", "HELLO", "Hello", "WiNd", "constructor", "toString", "valueOf", "hasOwnProperty", "__proto__", "prototype", "naïve", "café", "İstanbul", "straße", "Ωmega", "Kelvin", "jalapeño", "日本", "😀smile", "ab😀ab", "x́x", "tion", "s", "y", "e", "le", "es", "ed", "er", "ers", "ng"];
-const g2pWords = [...COMMON, ...UNKNOWN, ...ODD];
-for (let i = 0; i < dictWords.length; i += 600) g2pWords.push(dictWords[i]);
-const segsOf = (g: EnglishG2P, w: string) => ({ reduce: g.word(w), full: g.word(w, false) });
-write(
- "phonetics-g2p",
- {
- words: g2pWords.map((w) => ({ w, dict: segsOf(withDict, w), noDict: segsOf(noDict, w), lts: letterToSound(w) })),
- arpabet: ["", " ", "HH AH0 L OW1", " W ER1 L D ", "AH0\tB\r", "XX Y1 AY12 aa1 AH3 ER0 ER2 AH2", "AY1 B\u0085CD", "K AE1 T", "B0 D1 NG2 ZH"].map((p) => ({ p, segments: arpabetToSegments(p) })),
- },
-);
-
-const SENTENCES = [
- "Hello world", "water", "Is it on? Yes, it is.", "42", "The constructor is ready.", "The __proto__ is ready.",
- "What time is it? It's 3:45, I think.", "I have 1,000,000 reasons; you have 7.", "Read the lead, then close the door!",
- "Got it? Got it.", "We were disputing the matter.", "Little bottles of water, in a row...", "She said: “don't!” — and left.",
- "Is the wind live?? Really?!", "", " ", "...", "?", "a", "The year 2026 was odd; 1999 was odder.", "0 1 19 20 21 99 100 101 110 999 1000 1001 10000 99999 100000 999999",
- "1000000 1234567 12345678901234567890 123456789012345678901234567890", "9".repeat(400), "007 and 0042", "x1y2z3",
- "Rock'n'roll isn't dead, it’s well-known.", "Twinkle twinkle little star, how I wonder what you are.",
- "Breathe in, breathe out, I am made of air. Tongue and lips and throat, singing anywhere.",
- "ZORBLAT quixotical fnord!", "Call me at 555-1234.", "İstanbul and naïve café.", "Tabs\tand\nnewlines\r\nhere.",
- "the of and to a in", "He'll go; she'd stay: they've left, we're here.", "Who? You. Do it, not me, no.",
- "The rattle at the little hotel, tell all.", "A battle; a ladder: a rider, a writer.", "Mr. Smith vs. Dr. Jones.",
-];
-write(
- "phonetics-phrases",
- SENTENCES.map((text) => ({ text, dict: withDict.toPhrases(text), noDict: noDict.toPhrases(text) })),
-);
-
-// ---------------------------------------------------------------- syllables
-const LYRICS = [
- "Twinkle little star, how I - wonder", "Twinkle twinkle little star, how I wonder what you are.",
- "Breathe in, breathe out, I am made of air. Tongue and lips and throat, singing anywhere.",
- "ti-ger ti-ger burn-ing bright", "Oh - - say can you ~ see\nby the dawn's ear-ly light", "- leading dash", "~", "a -b c- d - e ~f g~ ~",
- "fire hour flower", "extra little twinkle", "Hello, world! Is it on? Yes; no: maybe.\n\nNew line", "don’t stop believin'",
- "constructor toString __proto__", "zorblat fnord-ish", "AMAZING grace HOW sweet", "a-", "-", "--", "x - y", "x -- y",
- "naïve café İstanbul", "yesterday all my troubles seemed so far away", "the wind and the read and the lead",
- "123 numbers 4 you", "every everything everywhere", "strength twelfths rhythm", "queue quiet quite", "",
- "la la la - - la", "Ah~ ah ~ ah", "\tTab\tseparated - words\t", "one - two", "one ~ two",
-];
-const SPELL: [string, number][] = [
- ["twinkle", 2], ["little", 2], ["wonder", 2], ["are", 1], ["like", 1], ["like", 2], ["fire", 2], ["anywhere", 3], ["father", 2],
- ["everything", 3], ["everything", 2], ["everything", 4], ["beautiful", 3], ["queue", 1], ["queue", 2], ["rhythm", 2], ["table", 2],
- ["able", 2], ["apple", 2], ["simple", 2], ["file", 2], ["smile", 1], ["Twinkle", 2], ["LITTLE", 2], ["CAKE", 2], ["", 2], ["a", 3],
- ["aeiou", 1], ["aeiou", 2], ["strengths", 1], ["strengths", 2], ["rocket", 2], ["hockey", 2], ["laughing", 2], ["telephone", 3],
- ["telephone", 4], ["naïve", 2], ["İstanbul", 3], ["İstanbul", 2], ["Shine", 2], ["ACHE", 2], ["thrhe", 2], ["babybaby", 4], ["x", 0],
-];
-const dictSource = withDict;
-const noDictSource = noDict;
-write("phonetics-syllables", {
- lyrics: LYRICS.map((text) => ({ text, dict: lyricsToSyllables(text, dictSource), noDict: lyricsToSyllables(text, noDictSource) })),
- spelling: SPELL.map(([word, n]) => ({ word, n, parts: splitSpelling(word, n) })),
- syllabify: ["twinkle", "extra", "strengths", "anywhere", "rhythm", "zorblat", "a", "b"].map((w) => ({ w, parts: syllabifySegments(withDict.word(w, false)) })),
-});
-
-write("phonetics-data", { songs: DEMO_SONGS, vowels: VOWELS });
diff --git a/tools/golden/planning.ts b/tools/golden/planning.ts
deleted file mode 100644
index 176b010..0000000
--- a/tools/golden/planning.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-/**
- * Planning fixtures: the gestural planner, Klatt durations, phrases, singing, the beatbox sounds
- * and the beat sequencer, plus one beatbox bar rendered through the human voice. Input segments
- * and syllables are produced here (tokenizeIpa, G2P, lyricsToSyllables) so the Rust side tests
- * the planners alone.
- * bun tools/golden/planning.ts
- */
-import { readFileSync } from "node:fs";
-import { gunzipSync } from "node:zlib";
-import { planUtterance, planPhrases, isVowel, type Segment, type PlanOptions } from "../../src/engine/phonetics/planner.ts";
-import { klattDurations, type SegInfo } from "../../src/engine/phonetics/durations.ts";
-import { tokenizeIpa } from "../../src/engine/phonetics/ipa.ts";
-import { EnglishG2P } from "../../src/engine/phonetics/english.ts";
-import { lyricsToSyllables } from "../../src/engine/phonetics/syllables.ts";
-import { planSong, planNoteOn, planNoteOff, planMelisma, midiToHz, type SungNote } from "../../src/engine/phonetics/sing.ts";
-import { DEMO_SONGS } from "../../src/engine/phonetics/songs.ts";
-import { CONSONANT_SYMBOLS, phoneme } from "../../src/engine/phonetics/inventory.ts";
-import { BEAT_SOUNDS, BEAT_PRESETS, parseBeat, formatBeat, beatReady, type BeatStep } from "../../src/engine/phonetics/beatbox.ts";
-import { BeatPlayer } from "../../src/engine/control/beatPlayer.ts";
-import { HumanVoice } from "../../src/engine/voice/humanVoice.ts";
-import type { Gesture } from "../../src/engine/control/score.ts";
-import { BODIES, write, writeF32 } from "./lib.ts";
-
-const BODY_NAMES = ["male", "female", "child"] as const;
-const g2p = new EnglishG2P();
-g2p.setDictionaryText(gunzipSync(readFileSync(new URL("../../public/data/cmudict.txt.gz", import.meta.url).pathname)).toString("utf8"));
-
-// ---------------------------------------------------------------- planUtterance
-type Opts = PlanOptions;
-const utterances: { name: string; segments: Segment[]; opts: Opts; plan: unknown }[] = [];
-const OPTION_SETS: Partial<Opts>[] = [
- {},
- { rate: 1.3, f0: 120 },
- { intonation: "question" },
- { intonation: "flat", f0: 205, accent: 0.3 },
- { rate: 0.8, openEnd: true },
- { t0: 0.5, intonation: "statement", openEnd: false },
- { f0: 260, rate: 1.1, intonation: "question", accent: 0 },
-];
-let oi = 0;
-function addUtterance(name: string, segments: Segment[], extra: Partial<Opts> = {}, body?: string): void {
- const k = oi++;
- const opts: Opts = { body: body ?? BODY_NAMES[k % 3], t0: 0, ...OPTION_SETS[k % OPTION_SETS.length], ...extra };
- // clone: the planner must not see (or keep) the fixture's objects
- const plan = planUtterance(segments.map((s) => ({ ...s })), opts);
- utterances.push({ name, segments, opts, plan });
-}
-// every consonant in the inventory, between vowels, word-initially and word-finally
-CONSONANT_SYMBOLS.forEach((c, i) => {
- const pos = i % 3;
- const ipa = pos === 0 ? `ˈa${c}ə` : pos === 1 ? `${c}ˈi` : `ˈu${c}`;
- addUtterance(`cons ${c}`, tokenizeIpa(ipa));
-});
-const PHRASES = [
- "ˈaɪ ˈaʊ ˈɔɪ",
- "ˈeɪ ˈoʊ ˈbeɪbi",
- "ˈbɝd ˈfɑɹɚ",
- "ɚ ˈwɝkɚ",
- "ˈstɹɛŋkθs",
- "ˈspɪt ˈskaɪ ˈstɑp",
- "ˌɪntɚˈnæʃənəl",
- "ˈhɛloʊ ˈwɝld",
- "ʃi ˈsɛlz ˈsiʃɛlz",
- "ˈpero ˈpeɾo",
- "ʔaʔ ʔoʊ",
- "ha ˈɦa",
- "ˈmʌni ˈtʃɪp ˈʒu ˈvæn",
- "ˈθɪŋk ə ˈbæd ˈkæt",
- "ˈjɛs, ˈnoʊ",
- "ˌkæləˈfɔɹnjə",
- "y ø ˈɨ",
- "ˈɑː ˈsiː",
- "ˈŋaŋ ˈmama ˈnana",
- "ˈwɪndoʊ ˈjɛloʊ",
- "ˈtsa ˈdza ˈpfa",
- "ˈɫul ˈlʊk",
- "ˈæ",
- "ˈstɹ",
- "",
-];
-PHRASES.forEach((p, i) => addUtterance(`phrase ${i}: ${p}`, tokenizeIpa(p)));
-// G2P phrases (allophones: flaps, glottal stops, dark l)
-for (const text of ["Little bottles of water.", "Button it up, Peter!", "Is it going to rain tomorrow?"]) {
- for (const ph of g2p.toPhrases(text)) addUtterance(`g2p ${text}`, ph.segments, { intonation: ph.intonation });
-}
-// per-segment overrides: explicit pitch (0 is "none" in TS), explicit durations
-{
- const base = tokenizeIpa("ˈlɑlə ˈmiˌnoʊ ˈsaɪ");
- const f0s = base.map((s, i) => (isVowel(s.ipa) ? { ...s, f0: [196, 0, 220, 247, 262][i % 5] } : s));
- addUtterance("override f0", f0s);
- addUtterance("override f0 male", f0s, { intonation: "statement" }, "male");
- const durs = base.map((s, i) => (i % 2 ? { ...s, dur: 0.05 + 0.03 * i } : s));
- addUtterance("override dur", durs, {}, "female");
- addUtterance("override both", base.map((s, i) => ({ ...s, dur: 0.11, ...(isVowel(s.ipa) ? { f0: 150 + i } : {}) })), { openEnd: true }, "child");
- addUtterance("override diphthong", [{ ipa: "aɪ", dur: 0.4, f0: 180, stress: 1 }, { ipa: "s" }, { ipa: "oʊ", stress: 2, wordEnd: true }], {}, "male");
-}
-
-// ---------------------------------------------------------------- klattDurations
-const MANNERS = [undefined, "stop", "nasal", "fricative", "affricate", "approximant", "lateral", "tap", "trill", "glottal"];
-let seed = 12345;
-const rnd = () => ((seed = (seed * 1103515245 + 12345) % 2147483648) / 2147483648);
-const klatt: { segments: Segment[]; infos: SegInfo[]; durs: number[] }[] = [];
-for (let c = 0; c < 24; c++) {
- const n = 1 + Math.floor(rnd() * 12);
- const syms = ["a", "i", "ə", "aɪ", "p", "t", "s", "z", "m", "l", "ɹ", "x", "ʔ", "q", "ŋ", "ɾ", "oʊ", "ɨ"];
- const segments: Segment[] = [];
- const infos: SegInfo[] = [];
- for (let i = 0; i < n; i++) {
- const ipa = syms[Math.floor(rnd() * syms.length)];
- const s: Segment = { ipa };
- if (rnd() < 0.5) s.stress = Math.floor(rnd() * 3);
- if (rnd() < 0.25) s.wordEnd = true;
- if (rnd() < 0.1) s.dur = 0.05 + rnd() * 0.1;
- segments.push(s);
- const vowel = rnd() < 0.4;
- const info: SegInfo = { vowel };
- if (!vowel) {
- const m = MANNERS[Math.floor(rnd() * MANNERS.length)];
- if (m) info.manner = m;
- if (rnd() < 0.7) info.voiced = rnd() < 0.5;
- if (rnd() < 0.3) info.dur = 0.04 + rnd() * 0.1;
- }
- infos.push(info);
- }
- const byObj = new Map(segments.map((s, i) => [s, infos[i]]));
- klatt.push({ segments, infos, durs: klattDurations(segments, (s) => byObj.get(s)!) });
-}
-
-// ---------------------------------------------------------------- planPhrases
-const phrases: { phrases: unknown[]; opts: unknown; plan: unknown }[] = [];
-for (const [text, opts] of [
- ["Hello there, how are you? I am fine; thanks.", { body: "male", t0: 0 }],
- ["One, two, three!", { body: "female", t0: 0.2, f0: 205, rate: 1.2 }],
- ["The quick brown fox: jumps over the lazy dog?", { body: "child", t0: 0, f0: 260, accent: 0.2, openEnd: true }],
-] as const) {
- const ps = g2p.toPhrases(text).map((p, i) => ({ segments: p.segments, intonation: p.intonation, ...(i === 1 ? { pause: 0 } : i === 2 ? {} : { pause: p.pause }) }));
- phrases.push({ phrases: ps, opts, plan: planPhrases(structuredClone(ps), opts) });
-}
-phrases.push({ phrases: [], opts: { body: "male", t0: 0.3 }, plan: planPhrases([], { body: "male", t0: 0.3 }) });
-
-// ---------------------------------------------------------------- planSong
-const songs: { name: string; notes: SungNote[]; opts: unknown; plan: unknown }[] = [];
-for (const song of DEMO_SONGS) {
- const syl = lyricsToSyllables(song.lyrics, g2p);
- for (const body of BODY_NAMES) {
- const shift = song.octave[body] * 12;
- const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));
- const opts = { body, bpm: song.bpm, t0: 0.35, vibrato: 35 };
- songs.push({ name: `${song.name} (${body})`, notes, opts, plan: planSong(structuredClone(notes), opts) });
- }
-}
-{
- // melismas, diphthongs and codas across phrase breaks
- const syl = lyricsToSyllables("I - love my - - time. Strengths, night ~ sky!", g2p);
- const notes = syl.map((s, i) => ({ midi: 57 + ((i * 5) % 12), beats: [1, 0.5, 2, 0.25][i % 4], syl: s }));
- const opts = { body: "female", bpm: 120, t0: 0.2, vibrato: 50 };
- songs.push({ name: "melisma", notes, opts, plan: planSong(structuredClone(notes), opts) });
-}
-
-// ---------------------------------------------------------------- live notes
-const notes: unknown[] = [];
-{
- const syl = lyricsToSyllables("night sky to strengths a oh", g2p);
- syl.forEach((s, i) => {
- const body = BODY_NAMES[i % 3];
- const midi = 52 + 3 * i;
- const from = i > 0 ? { syl: syl[i - 1], midi: midi - 2 } : undefined;
- const on = { body, vibrato: 30, tag: 10 * i };
- notes.push({ kind: "on", syl: s, midi, opts: on, gestures: planNoteOn(structuredClone(s), midi, on) });
- if (from) {
- const onL = { ...on, legatoFrom: from };
- notes.push({ kind: "on", syl: s, midi, opts: onL, gestures: planNoteOn(structuredClone(s), midi, structuredClone(onL)) });
- }
- notes.push({ kind: "off", syl: s, midi, body, gestures: planNoteOff(structuredClone(s), midi, body) });
- notes.push({ kind: "melisma", midi: midi + 0.5, opts: { vibrato: 20, tag: i }, gestures: planMelisma(midi + 0.5, { vibrato: 20, tag: i }) });
- });
-}
-
-// ---------------------------------------------------------------- beatbox sounds
-const BUILDS = [{ f0: 82, len: 0.15, accent: 1 }, { f0: midiToHz(43), len: 0.05, accent: 1.3 }, { f0: 200, len: 0.4, accent: 0.7 }];
-const sounds = BEAT_SOUNDS.map((s) => ({
- id: s.id,
- name: s.name,
- role: s.role,
- airstream: s.airstream,
- hint: s.hint,
- latency: s.latency,
- builds: BODY_NAMES.flatMap((body) => BUILDS.map((o) => ({ body, o, gestures: s.build(body, o) }))),
- leadIn: Object.fromEntries(BODY_NAMES.map((b) => [b, BeatPlayer.leadIn(s.id, b)])),
-}));
-const ready = Object.fromEntries(BODY_NAMES.map((b) => [b, beatReady(b)]));
-const notation = {
- presets: BEAT_PRESETS,
- texts: ["B . t | Pf m:43 ^K> -", "b T pf k | ^k> M:40> x:3 :4 m:4:3 > . -", "B t
Pf\tkch\nm:043", "", "|||", ...BEAT_PRESETS.map((p) => p.text)].map((text) => {
- const steps = parseBeat(text);
- return { text, steps, formatted: formatBeat(steps) };
- }),
- format: [
- [{ id: "m", note: 43.5, accent: 0.5 }, null, { id: "B", accent: 1.0001 }, { id: "t", note: 0 }, null],
- ].map((steps) => ({ steps, formatted: formatBeat(steps as (BeatStep | null)[]) })),
-};
-
-// ---------------------------------------------------------------- beat player
-type PlayerOp =
- | { op: "steps"; text: string }
- | { op: "tempo"; bpm: number; swing: number }
- | { op: "start"; clock: number }
- | { op: "stop" }
- | { op: "body"; body: string }
- | { op: "run"; from: number; to: number; dt: number }
- | { op: "rebase"; delta: number }
- | { op: "rewind"; clock: number }
- | { op: "stepAt"; clocks: number[] }
- | { op: "gestures"; cell: BeatStep; hit: number; len?: number };
-function runPlayer(ops: PlayerOp[]): unknown[] {
- const p = new BeatPlayer();
- const out: unknown[] = [];
- for (const o of ops) {
- if (o.op === "steps") p.steps = parseBeat(o.text).slice(0, 128);
- else if (o.op === "tempo") p.setTempo(o.bpm, o.swing);
- else if (o.op === "start") p.start(o.clock);
- else if (o.op === "stop") p.stop();
- else if (o.op === "body") p.body = o.body;
- else if (o.op === "rebase") p.rebase(o.delta);
- else if (o.op === "rewind") p.rewind(o.clock);
- else if (o.op === "stepAt") out.push(o.clocks.map((c) => p.stepAt(c)));
- else if (o.op === "gestures") out.push(o.len === undefined ? p.gestures(o.cell, o.hit) : p.gestures(o.cell, o.hit, o.len));
- else {
- const batches: { clock: number; gestures: Gesture[] }[] = [];
- for (let clock = o.from; clock < o.to; clock += o.dt) p.tick(clock, (gs) => batches.push({ clock, gestures: gs }));
- out.push(batches);
- }
- }
- return out;
-}
-const many = (a: number, b: number, n: number) => Array.from({ length: n }, (_, i) => a + ((b - a) * i) / (n - 1));
-const DT = 128 / 48000;
-const playerScenarios: PlayerOp[][] = [
- // start, swing, playhead
- [{ op: "steps", text: "B t B t" }, { op: "tempo", bpm: 120, swing: 0.5 }, { op: "stepAt", clocks: [1] }, { op: "start", clock: 0 }, { op: "run", from: 0, to: 1.2, dt: DT }, { op: "stepAt", clocks: many(0, 1.4, 120) }, { op: "stop" }, { op: "stepAt", clocks: [0.5] }],
- // tempo change mid-pattern, then a pattern edit with rests (sustained sounds)
- [{ op: "steps", text: "t t t t" }, { op: "tempo", bpm: 100, swing: 0 }, { op: "start", clock: 0.1 }, { op: "run", from: 0.1, to: 0.6, dt: DT }, { op: "tempo", bpm: 160, swing: 0.3 }, { op: "run", from: 0.6, to: 1.1, dt: DT }, { op: "steps", text: "m:43 . . tss | . m . kch" }, { op: "tempo", bpm: 300, swing: 0.9 }, { op: "run", from: 1.1, to: 1.9, dt: DT }, { op: "stepAt", clocks: many(0.1, 2.0, 90) }],
- // body change: rebase + rewind (as the worklet does), with every sound
- [{ op: "steps", text: "B t Pf t | K ^K ! P! | kch m:40> tss ." }, { op: "tempo", bpm: 120, swing: 0.3 }, { op: "start", clock: 0 }, { op: "run", from: 0, to: 0.5, dt: DT }, { op: "body", body: "female" }, { op: "rebase", delta: -0.5 }, { op: "rewind", clock: 0 }, { op: "run", from: 0, to: 0.6, dt: DT }, { op: "stepAt", clocks: many(-0.1, 0.8, 60) }, { op: "body", body: "child" }, { op: "rebase", delta: 0.25 }, { op: "rewind", clock: 0.85 }, { op: "run", from: 0.85, to: 1.3, dt: 0.01 }],
- // coarse ticks (several steps per tick, some already past), stop/start, empty pattern
- [{ op: "steps", text: "B . t ." }, { op: "tempo", bpm: 180, swing: 0.6 }, { op: "start", clock: 0 }, { op: "run", from: 0, to: 2, dt: 0.37 }, { op: "stepAt", clocks: many(0, 2.2, 40) }, { op: "stop" }, { op: "run", from: 2, to: 2.5, dt: 0.1 }, { op: "start", clock: 2.5 }, { op: "steps", text: "" }, { op: "run", from: 2.5, to: 3, dt: 0.1 }, { op: "stepAt", clocks: [2.8] }, { op: "rewind", clock: 10 }],
- // single sounds (pad hits)
- [{ op: "body", body: "child" }, { op: "gestures", cell: { id: "m", note: 45, accent: 1.2 }, hit: 1.5, len: 0.18 }, { op: "gestures", cell: { id: "kch" }, hit: 0.3 }, { op: "gestures", cell: { id: "nope" }, hit: 0.3 }, { op: "tempo", bpm: 30, swing: -1 }, { op: "gestures", cell: { id: "tss", accent: 0 }, hit: 0 }],
-];
-const player = playerScenarios.map((ops) => ({ ops, out: runPlayer(ops) }));
-
-// ---------------------------------------------------------------- audio: a beatbox bar
-{
- const FS = 48000;
- const text = "B t tss Pf | K ^K ! P! | kch m:43 . m | B> t Pf> t";
- const v = new HumanVoice({ fsOut: FS, body: BODIES.male, oversample: 2 });
- v.setSource({ f0: 110 });
- v.setArticulation(beatReady("male"));
- const p = new BeatPlayer();
- p.steps = parseBeat(text);
- p.setTempo(110, 0.2);
- p.start(v.clock);
- const n = Math.round(2.0 * FS);
- const out = new Float32Array(n);
- const tempoAt = 400; // block
- for (let b = 0, i = 0; i < n; b++, i += 128) {
- if (b === tempoAt) p.setTempo(130, 0.1);
- p.tick(v.clock, (gs) => v.schedule(gs));
- v.render(out, i, Math.min(128, n - i));
- }
- writeF32("beatbox-bar", out);
- write("planning", { utterances, klatt, phrases, songs, notes, sounds, ready, notation, player, audio: { text, bpm: 110, swing: 0.2, tempoAt, tempo: [130, 0.1], f0: 110, samples: n, fs: FS } });
-}
-void phoneme;
diff --git a/tools/golden/voice.ts b/tools/golden/voice.ts
deleted file mode 100644
index 545c0b1..0000000
--- a/tools/golden/voice.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-/** 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);
-}
diff --git a/src/engine/analysis/fft.ts b/tools/lib/fft.ts
similarity index 96%
rename from src/engine/analysis/fft.ts
rename to tools/lib/fft.ts
index e8ca80f..405f715 100644
--- a/src/engine/analysis/fft.ts
+++ b/tools/lib/fft.ts
@@ -1,4 +1,5 @@
/**
+ * FFT and windows for the plotting tools (the engine has its own, in Rust: chimera::analysis::fft).
* In-place iterative radix-2 complex FFT on separate real/imag Float64Arrays.
* Size must be a power of two. Pure TS, allocation-free after plan creation.
*/
diff --git a/tools/lib/spectrogram.ts b/tools/lib/spectrogram.ts
index b9d4ba3..365d8c3 100644
--- a/tools/lib/spectrogram.ts
+++ b/tools/lib/spectrogram.ts
@@ -1,4 +1,4 @@
-import { FFT, hann, nextPow2 } from "../../src/engine/analysis/fft.ts";
+import { FFT, hann, nextPow2 } from "./fft.ts";
import { Image, inferno } from "./image.ts";
export interface SpectrogramOptions {
diff --git a/tools/measure-closures.ts b/tools/measure-closures.ts
deleted file mode 100644
index df6fd6e..0000000
--- a/tools/measure-closures.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-/**
- * Closure-onset transients in VCV syllables: the largest output step (sample-to-sample
- * difference, a click detector) around the closure onset, relative to the vowel's own.
- * A physical closure is quieter than the vowel it ends; a teleporting one clicks.
- * Usage: bun tools/measure-closures.ts [p,t,k,b,d,g]
- */
-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
-import { planUtterance } from "../src/engine/phonetics/planner.ts";
-import { tokenizeIpa } from "../src/engine/phonetics/ipa.ts";
-
-const FS = 48000;
-const items = (process.argv[2] ?? "p,t,k,b,d,g,s,n").split(",");
-const rows: string[] = [];
-for (const c of items) {
- const v = new HumanVoice({ fsOut: FS });
- const plan = planUtterance(tokenizeIpa(`ˈɑ${c}ɑ`), { body: "male", t0: 0.05, f0: 110 });
- v.schedule(plan.gestures);
- const N = Math.round(FS * (plan.end + 0.2));
- const out = new Float32Array(N);
- for (let i = 0; i < N; i += 128) v.render(out, i, Math.min(128, N - i));
- const seg = plan.segments[1];
- const step = (a: number, b: number) => {
- let m = 0;
- for (let i = Math.max(1, Math.round(a * FS)); i < Math.round(b * FS); i++) m = Math.max(m, Math.abs(out[i] - out[i - 1]));
- return m;
- };
- const vowelStep = step(0.14, 0.26);
- // the vowel's own pulses just before the closure window (they sharpen as the tract narrows)
- const lateStep = step(seg.t0 - 0.045, seg.t0 - 0.015);
- const closeStep = step(seg.t0 - 0.015, seg.t0 + 0.04);
- rows.push(`${c} closure-onset max step / vowel max step ${(closeStep / vowelStep).toFixed(2)} (/ late-vowel step ${(closeStep / lateStep).toFixed(2)})`);
-}
-console.log(rows.join("\n"));
diff --git a/tools/measure-consonants.ts b/tools/measure-consonants.ts
deleted file mode 100644
index f89b115..0000000
--- a/tools/measure-consonants.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * Objective consonant metrics from rendered VCV syllables (adult male):
- * - frication level relative to the vowel (RMS, dB) and spectral centroid / peak
- * - release transient peak relative to the vowel peak
- * Usage: bun tools/measure-consonants.ts
- */
-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 { FFT, hann } from "../src/engine/analysis/fft.ts";
-
-const FS = 48000;
-const items = (process.argv[2] ?? "s,ʃ,f,θ,x,h,p,t,k,b,d,g,m,n").split(",");
-const fft = new FFT(1024);
-const win = hann(1024);
-for (const c of items) {
- const v = new HumanVoice({ fsOut: FS });
- const plan = planUtterance(tokenizeIpa(`ˈɑ${c}ɑ`), { body: "male", t0: 0.05, f0: 110 });
- v.schedule(plan.gestures);
- const N = Math.round(FS * (plan.end + 0.2));
- const out = new Float32Array(N);
- for (let i = 0; i < N; i += 128) v.render(out, i, Math.min(128, N - i));
- const seg = plan.segments[1];
- const rms = (a: number, b: number) => {
- let s = 0;
- for (let i = Math.round(a * FS); i < Math.round(b * FS); i++) s += out[i] * out[i];
- return Math.sqrt(s / Math.max(1, Math.round((b - a) * FS)));
- };
- const vowel = rms(0.14, 0.26);
- const mid = (seg.t0 + seg.t1) / 2;
- const fric = rms(seg.t0 + 0.02, seg.t1 - 0.01);
- let vpk = 0;
- for (let i = Math.round(0.14 * FS); i < Math.round(0.26 * FS); i++) vpk = Math.max(vpk, Math.abs(out[i]));
- let rpk = 0;
- for (let i = Math.round(seg.t1 * FS); i < Math.round((seg.t1 + 0.04) * FS); i++) rpk = Math.max(rpk, Math.abs(out[i]));
- // spectrum of the consonant middle
- const re = new Float64Array(1024), im = new Float64Array(1024);
- const s0 = Math.round(mid * FS) - 512;
- for (let i = 0; i < 1024; i++) re[i] = (out[s0 + i] ?? 0) * win[i];
- fft.transform(re, im);
- let num = 0, den = 0, pkBin = 1, pkVal = 0;
- for (let k = 4; k < 512; k++) {
- const p = re[k] * re[k] + im[k] * im[k];
- const f = (k * FS) / 1024;
- num += f * p;
- den += p;
- if (f > 1000 && p > pkVal) { pkVal = p; pkBin = k; }
- }
- const db = (x: number) => (20 * Math.log10(Math.max(1e-9, x))).toFixed(1);
- const burst = rms(seg.t1, seg.t1 + 0.012);
- const asp = rms(seg.t1 + 0.012, seg.t1 + 0.04);
- console.log(`${c.padEnd(2)} level ${db(fric / vowel).padStart(6)} dB centroid ${(num / den / 1000).toFixed(2)} kHz peak ${((pkBin * FS) / 1024 / 1000).toFixed(2)} kHz release/vowel peak ${(rpk / vpk).toFixed(2)} burst ${db(burst / vowel).padStart(6)} dB post ${db(asp / vowel).padStart(6)} dB`);
-}
diff --git a/tools/proto-vowel.ts b/tools/proto-vowel.ts
deleted file mode 100644
index 5030027..0000000
--- a/tools/proto-vowel.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * Prototype: hand-made vowel area functions through the full airway (lungs → trachea →
- * glottis → pharynx → oral + nasal) with the parametric glottis. Writes WAV + spectrogram.
- * Usage: bun tools/proto-vowel.ts [outdir]
- */
-import { AirwayNetwork } from "../src/engine/airway/network.ts";
-import { Decimator } from "../src/engine/airway/decimator.ts";
-import { ParametricGlottis } from "../src/engine/sources/glottis.ts";
-import { WALL_SOFT, WALL_TRACHEA, WALL_NASAL, CM_H2O } from "../src/engine/physics.ts";
-import { estimateFormants } from "../src/engine/analysis/lpc.ts";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram, renderPlot } from "./lib/spectrogram.ts";
-
-const outDir = process.argv[2] ?? "out/proto";
-const FS_OUT = 48000;
-const M = 2;
-const FS = FS_OUT * M;
-
-// Area functions sampled glottis→lips (17 cm), loosely after Fant/Story shapes.
-function shapeA(x: number): number {
- // x in [0,1]: narrow pharynx, wide front cavity
- return 0.6 + (x < 0.45 ? 0.6 + 0.4 * Math.sin(x * 7) ** 2 : 3 + 3.5 * Math.sin(((x - 0.45) / 0.55) * Math.PI * 0.85));
-}
-function shapeI(x: number): number {
- if (x < 0.1) return 1.5;
- if (x < 0.55) return 5 + 2 * Math.sin(((x - 0.1) / 0.45) * Math.PI);
- if (x < 0.85) return Math.max(0.3, 5 - (x - 0.55) * 30);
- return 1.5;
-}
-function shapeU(x: number): number {
- if (x < 0.1) return 1.5;
- if (x < 0.5) return 3 + 2 * Math.sin(((x - 0.1) / 0.4) * Math.PI);
- if (x < 0.7) return Math.max(0.4, 3 - (x - 0.5) * 15);
- if (x < 0.92) return 3.5;
- return 0.35;
-}
-
-const vowels: [string, (x: number) => number][] = [["a", shapeA], ["i", shapeI], ["u", shapeU]];
-
-const net = new AirwayNetwork(FS);
-const trachea = net.addTube({ name: "trachea", n: 16, length: 14, area: 2.5, wall: WALL_TRACHEA });
-const ph = net.addTube({ name: "pharynx", n: 22, length: 8.8, area: 3, wall: WALL_SOFT, wallRadiation: 0.3 });
-const or = net.addTube({ name: "oral", n: 21, length: 8.4, area: 3, wall: WALL_SOFT, wallRadiation: 0.3, perimeterFactor: 1.3 });
-const na = net.addTube({ name: "nasal", n: 26, length: 11.4, area: Array.from({ length: 26 }, (_, i) => (i < 4 ? 2.5 : i > 22 ? 0.9 : 1.6)), wall: WALL_NASAL, perimeterFactor: 2.2, viscousFactor: 2 });
-const lung = net.addPressureNode("lungs");
-net.connect(lung, trachea.firstNode);
-const glot = net.addPort(trachea.lastNode, ph.firstNode, { area: 0, length: 0.3, kEntrance: 0.37, kExit: 1.0, slitWidth: 1.4 });
-net.connect(ph.lastNode, or.firstNode);
-const velum = net.addPort(ph.lastNode, na.firstNode, { area: 0, length: 1.0, kEntrance: 0.4, kExit: 1.0 });
-net.addRadiation(or.lastNode);
-net.addRadiation(na.lastNode);
-net.finalize();
-net.setNoiseSources([{ src: glot, fwd: ph.branch(1), bwd: trachea.branch(14), gain: 4e-6 }]);
-
-const glottis = new ParametricGlottis(FS);
-glottis.params.f0 = 110;
-const dec = new Decimator(M);
-const segDur = 0.8;
-const total = Math.round(FS_OUT * segDur * vowels.length);
-const out = new Float32Array(total);
-const flowTrace = new Float64Array(Math.round(FS * 0.04));
-const areaTrace = new Float64Array(flowTrace.length);
-let o = 0;
-let step = 0;
-const block = 64 * M;
-for (let v = 0; v < vowels.length; v++) {
- const [, fn] = vowels[v];
- const areasPh = Array.from({ length: ph.n }, (_, i) => fn(((i + 0.5) / ph.n) * 0.52));
- const areasOr = Array.from({ length: or.n }, (_, i) => fn(0.52 + ((i + 0.5) / or.n) * 0.48));
- const nSeg = Math.round(FS * segDur);
- for (let i = 0; i < nSeg; i++, step++) {
- if (step % block === 0) {
- net.setTubeTargets(ph, areasPh);
- net.setTubeTargets(or, areasOr);
- net.beginBlock(block);
- }
- const t = step / FS;
- // breath envelope per vowel
- const local = i / FS;
- const env = Math.min(1, local / 0.05) * Math.min(1, (segDur - local) / 0.08);
- net.setFixedPressure(lung, 8 * CM_H2O * Math.max(0, env));
- const dp = net.p[trachea.lastNode] - net.p[ph.firstNode];
- net.setPortArea(glot, glottis.next(dp));
- const y = net.step();
- if (v === 0 && i >= FS * 0.4 && i < FS * 0.4 + flowTrace.length) {
- flowTrace[i - FS * 0.4] = net.U[glot];
- areaTrace[i - FS * 0.4] = net.portArea[glot];
- }
- if (dec.push(y) && o < total) out[o++] = dec.value;
- void t;
- }
-}
-// normalise
-let pk = 0;
-for (let i = 0; i < out.length; i++) pk = Math.max(pk, Math.abs(out[i]));
-for (let i = 0; i < out.length; i++) out[i] = (out[i] / pk) * 0.9;
-writeWav(`${outDir}/vowels.wav`, [out], FS_OUT);
-renderSpectrogram(`${outDir}/vowels.png`, out, FS_OUT, { title: "PROTO VOWELS A I U F0 110", maxFreq: 5000, windowMs: 5 });
-renderPlot(`${outDir}/glottal.png`, [
- { y: flowTrace, color: [120, 220, 255], label: "FLOW U" },
- { y: Array.from(areaTrace, (a) => a * 1500), color: [255, 160, 90], label: "AREA X1500" },
-], { title: "GLOTTAL FLOW (A)" });
-for (let v = 0; v < vowels.length; v++) {
- const c = Math.round(FS_OUT * (v * segDur + 0.4));
- const frame = out.subarray(c, c + 1024);
- // analyse at 10 kHz-ish resolution: downsample by 4 via averaging for LPC robustness
- const ds = new Float64Array(256);
- for (let i = 0; i < 256; i++) ds[i] = (frame[4 * i] + frame[4 * i + 1] + frame[4 * i + 2] + frame[4 * i + 3]) / 4;
- const fm = estimateFormants(ds, FS_OUT / 4, { order: 12 });
- console.log(vowels[v][0], fm.slice(0, 4).map((f) => `${f.freq.toFixed(0)}(${f.bw.toFixed(0)})`).join(" "));
-}
-console.log("peak", pk.toExponential(3));
diff --git a/tools/render-beatbox.ts b/tools/render-beatbox.ts
deleted file mode 100644
index 8754d72..0000000
--- a/tools/render-beatbox.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-/**
- * Render the beatbox kit through the real-time voice.
- * - each sound alone: acoustic onset relative to the planned hit (calibrates `latency`), peak,
- * and a spectrogram strip
- * - a preset pattern (two bars) as WAV + spectrogram with step marks
- * Usage: bun tools/render-beatbox.ts outdir [preset name] [male|female|child]
- */
-import { mkdirSync } from "node:fs";
-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
-import { BODY_MALE, BODY_FEMALE, BODY_CHILD } from "../src/engine/anatomy/human.ts";
-import { BEAT_SOUNDS, BEAT_PRESETS, beatReady, parseBeat } from "../src/engine/phonetics/beatbox.ts";
-import { BeatPlayer } from "../src/engine/control/beatPlayer.ts";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram } from "./lib/spectrogram.ts";
-
-const outDir = process.argv[2] ?? "out/beatbox";
-const presetName = process.argv[3] ?? "Boots and cats";
-const bodyName = (process.argv[4] ?? "male") as "male" | "female" | "child";
-const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];
-mkdirSync(outDir, { recursive: true });
-const FS = 48000;
-
-function voice(): HumanVoice {
- const v = new HumanVoice({ fsOut: FS, body });
- v.setArticulation(beatReady(bodyName));
- v.setSource({ f0: 100, voiced: true, pressure: 8 });
- v.setGate(0);
- return v;
-}
-
-// ---- each sound alone
-const player = new BeatPlayer();
-player.body = bodyName;
-const rows: string[] = [];
-const strip = new Float32Array(Math.round(FS * 0.5 * BEAT_SOUNDS.length));
-BEAT_SOUNDS.forEach((s, idx) => {
- const v = voice();
- const hit = 0.25;
- v.schedule(player.gestures({ id: s.id }, hit, 0.15));
- const N = Math.round(FS * 0.5);
- const out = new Float32Array(N);
- for (let i = 0; i < N; i += 128) v.render(out, i, Math.min(128, N - i));
- // the event: its peak within [hit − 30 ms, hit + 80 ms]; onset = first sample from hit − 40 ms
- // that reaches a quarter of that peak
- let pk = 0;
- for (let i = Math.round((hit - 0.03) * FS); i < Math.round((hit + 0.08) * FS); i++) pk = Math.max(pk, Math.abs(out[i]));
- let on = Math.round(hit * FS);
- for (let i = Math.round((hit - 0.04) * FS); i < Math.round((hit + 0.08) * FS); i++) if (Math.abs(out[i]) > 0.25 * pk) { on = i; break; }
- // energy before the hit (set-up noise) relative to the hit
- let pre = 0;
- for (let i = Math.round((hit - 0.15) * FS); i < Math.round((hit - 0.04) * FS); i++) pre = Math.max(pre, Math.abs(out[i]));
- // what follows: level 60–150 ms after the hit (unwanted voicing shows up here)
- let tail = 0;
- for (let i = Math.round((hit + 0.06) * FS); i < Math.round((hit + 0.15) * FS); i++) tail = Math.max(tail, Math.abs(out[i]));
- rows.push(`${s.id.padEnd(4)} ${s.name.padEnd(13)} onset ${((on / FS - hit) * 1000).toFixed(1).padStart(6)} ms peak ${pk.toFixed(3)} set-up ${(20 * Math.log10(Math.max(1e-6, pre) / pk)).toFixed(1)} dB tail ${(20 * Math.log10(Math.max(1e-6, tail) / pk)).toFixed(1)} dB lead-in ${(BeatPlayer.leadIn(s.id, bodyName) * 1000).toFixed(0)} ms`);
- strip.set(out, idx * N);
- writeWav(`${outDir}/${s.id.replace(/[^A-Za-z]/g, "_")}.wav`, [out], FS);
-});
-console.log(rows.join("\n"));
-renderSpectrogram(`${outDir}/kit.png`, strip, FS, { title: `kit (${bodyName}): ${BEAT_SOUNDS.map((s) => s.id).join(" ")}`.replace(/[^\x20-\x7e]/g, "?"), maxFreq: 12000, windowMs: 4, marks: BEAT_SOUNDS.map((_, i) => ({ t: i * 0.5 + 0.25, label: "" })) });
-writeWav(`${outDir}/kit.wav`, [strip], FS);
-
-// ---- a pattern, two bars, through the sequencer exactly as the worklet runs it
-const preset = BEAT_PRESETS.find((p) => p.name.toLowerCase() === presetName.toLowerCase()) ?? BEAT_PRESETS[0];
-const v = voice();
-const seq = new BeatPlayer();
-seq.body = bodyName;
-seq.steps = parseBeat(preset.text);
-seq.setTempo(preset.bpm, preset.swing);
-seq.start(v.clock);
-const bars = 2;
-const total = Math.round(FS * (seq.horizon + bars * seq.steps.length * seq.stepDur + 0.3));
-const out = new Float32Array(total);
-for (let i = 0; i < total; i += 128) {
- seq.tick(v.clock, (gs) => v.schedule(gs));
- v.render(out, i, Math.min(128, total - i));
-}
-let pk = 0;
-for (const x of out) pk = Math.max(pk, Math.abs(x));
-const slug = preset.name.toLowerCase().replace(/[^a-z]+/g, "-");
-writeWav(`${outDir}/${slug}.wav`, [out], FS);
-const marks = Array.from({ length: bars * seq.steps.length }, (_, n) => ({ t: seq.horizon + n * seq.stepDur + (n % 2 ? seq.swing * 0.5 * seq.stepDur : 0), label: "" }));
-renderSpectrogram(`${outDir}/${slug}.png`, out, FS, { title: `${preset.name} ${preset.bpm} bpm`, maxFreq: 12000, windowMs: 4, marks });
-console.log(`pattern "${preset.name}": ${(total / FS).toFixed(2)} s, peak ${pk.toFixed(3)} -> ${outDir}/${slug}.wav`);
diff --git a/tools/render-creature.ts b/tools/render-creature.ts
deleted file mode 100644
index ffe1a4b..0000000
--- a/tools/render-creature.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-/**
- * Render a creature's calls (and a sustained note) offline; report level, stability and pitch.
- * Usage: bun tools/render-creature.ts <creatureId> [outdir]
- */
-import { CreatureVoice } from "../src/engine/creatures/voice.ts";
-import { CREATURES } from "../src/engine/creatures/index.ts";
-import { yinPitch } from "../src/engine/analysis/pitch.ts";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram } from "./lib/spectrogram.ts";
-
-const id = process.argv[2] ?? "songbird";
-const outDir = process.argv[3] ?? "out/creatures";
-const def = CREATURES.find((c) => c.id === id);
-if (!def) throw new Error(`unknown creature ${id}; have ${CREATURES.map((c) => c.id).join(", ")}`);
-const FS = 48000;
-const v = new CreatureVoice(def, FS);
-const segs: { t: number; label: string }[] = [];
-const chunks: Float32Array[] = [];
-let tCursor = 0;
-const t0 = performance.now();
-const renderFor = (sec: number) => {
- const n = Math.round(sec * FS);
- const buf = new Float32Array(n);
- for (let i = 0; i < n; i += 128) v.render(buf, i, Math.min(128, n - i));
- chunks.push(buf);
- tCursor += sec;
- return buf;
-};
-// sustained note at the default pitch
-const pitchParam = def.params.find((p) => p.role === "pitch");
-segs.push({ t: tCursor, label: "sustain" });
-if (def.params.some((p) => p.key === "voices")) v.setParams({ voices: 0 }); // single voice for the pitch check
-v.setGate(1);
-const sus = renderFor(1.2);
-v.setGate(0);
-renderFor(0.4);
-if (def.params.some((p) => p.key === "voices")) v.setParams({ voices: 0.5 });
-let pitchReport = "";
-if (pitchParam) {
- const est = yinPitch(sus.subarray(Math.round(0.6 * FS), Math.round(0.6 * FS) + 4096), FS, { minF0: Math.max(20, pitchParam.min * 0.5), maxF0: Math.min(12000, pitchParam.max * 2) });
- pitchReport = `target ${pitchParam.default} Hz, measured ${est.f0.toFixed(1)} Hz (aperiodicity ${est.aperiodicity.toFixed(2)})`;
-}
-for (const call of def.calls) {
- segs.push({ t: tCursor, label: call.id });
- v.playCall(call.id);
- const dur = call.keys[call.keys.length - 1].t + 0.5;
- renderFor(dur);
-}
-const ms = performance.now() - t0;
-const total = chunks.reduce((a, c) => a + c.length, 0);
-const out = new Float32Array(total);
-let o = 0;
-for (const c of chunks) {
- out.set(c, o);
- o += c.length;
-}
-let pk = 0, bad = 0;
-for (const x of out) {
- if (!Number.isFinite(x)) bad++;
- pk = Math.max(pk, Math.abs(x));
-}
-writeWav(`${outDir}/${id}.wav`, [out], FS);
-renderSpectrogram(`${outDir}/${id}.png`, out, FS, { title: `${def.name} (${def.latin})`.toUpperCase().replace(/[^\x20-\x7e]/g, "?"), maxFreq: id === "songbird" ? 12000 : 6000, windowMs: id === "songbird" ? 4 : 12, marks: segs });
-console.log(`${def.name}: ${(total / FS).toFixed(1)} s in ${ms.toFixed(0)} ms (${((ms / 1000 / (total / FS)) * 100).toFixed(1)}% RT, internal ${v.fs} Hz) peak ${pk.toFixed(3)} non-finite ${bad}`);
-console.log(` ${pitchReport}`);
diff --git a/tools/render-song.ts b/tools/render-song.ts
deleted file mode 100644
index cdd1d1a..0000000
--- a/tools/render-song.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-/**
- * Render a sung melody through the real-time voice (the Sing mode's demo, or a live-style
- * key sequence), with a spectrogram.
- * Usage: bun tools/render-song.ts outdir [male|female|child]
- */
-import { mkdirSync, readFileSync } from "node:fs";
-import { gunzipSync } from "node:zlib";
-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
-import { BODY_MALE, BODY_FEMALE, BODY_CHILD } from "../src/engine/anatomy/human.ts";
-import { EnglishG2P } from "../src/engine/phonetics/english.ts";
-import { lyricsToSyllables } from "../src/engine/phonetics/syllables.ts";
-import { planSong, planNoteOn, planNoteOff, midiToHz } from "../src/engine/phonetics/sing.ts";
-import { DEMO_SONGS } from "../src/engine/phonetics/songs.ts";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram } from "./lib/spectrogram.ts";
-
-const outDir = process.argv[2] ?? "out/song";
-const bodyName = (process.argv[3] ?? "male") as "male" | "female" | "child";
-const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];
-mkdirSync(outDir, { recursive: true });
-const FS = 48000;
-const g2p = new EnglishG2P();
-g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));
-
-for (const song of DEMO_SONGS) {
- const syl = lyricsToSyllables(song.lyrics, g2p);
- const shift = song.octave[bodyName] * 12;
- const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));
- const v = new HumanVoice({ fsOut: FS, body });
- v.setSource({ f0: midiToHz(notes[0].midi), voiced: true, pressure: 9, tension: 0.55 });
- const plan = planSong(notes, { body: bodyName, bpm: song.bpm, t0: 0.3, vibrato: 35 });
- v.schedule(plan.gestures);
- const N = Math.round(FS * (plan.end + 0.4));
- const out = new Float32Array(N);
- for (let i = 0; i < N; i += 128) v.render(out, i, Math.min(128, N - i));
- let pk = 0;
- for (const x of out) pk = Math.max(pk, Math.abs(x));
- const slug = song.name.toLowerCase().replace(/[^a-z]+/g, "-");
- writeWav(`${outDir}/${slug}-${bodyName}.wav`, [out], FS);
- const beat = 60 / song.bpm;
- let t = 0.3;
- const marks = notes.map((n) => { const m = { t, label: "" }; t += n.beats * beat; return m; });
- renderSpectrogram(`${outDir}/${slug}-${bodyName}.png`, out, FS, { title: `${song.name} (${bodyName})`, maxFreq: 6000, windowMs: 25, marks });
- console.log(`${song.name}: ${(N / FS).toFixed(1)} s, peak ${pk.toFixed(3)}, syllables ${syl.map((s) => s.text).join(" ")}`);
-}
-
-// live-style: key presses with gaps and one legato pair, as the keyboard would send them
-{
- const syl = lyricsToSyllables("hello there my friend", g2p);
- const v = new HumanVoice({ fsOut: FS, body });
- v.setSource({ f0: 130, voiced: true, pressure: 9 });
- const keys: [number, number, number][] = [[0.2, 0.55, 57], [0.6, 1.0, 59], [1.1, 1.8, 62], [1.75, 2.6, 60]]; // [down, up, midi]
- const N = Math.round(FS * 3);
- const out = new Float32Array(N);
- let tag = 2;
- let held: { syl: (typeof syl)[number]; midi: number; tag: number; up: number } | null = null;
- const events = keys.flatMap(([d, u, m], i) => [{ t: d, on: true, m, i }, { t: u, on: false, m, i }]).sort((a, b) => a.t - b.t);
- let e = 0;
- for (let i = 0; i < N; i += 128) {
- const now = v.clock;
- while (e < events.length && events[e].t <= now) {
- const ev = events[e++];
- const shift = (gs: import("../src/engine/control/score.ts").Gesture[]) => gs.map((g) => ({ ...g, t0: g.t0 + now + 0.006, t1: g.t1 + now + 0.006 }));
- if (ev.on) {
- const s = syl[ev.i];
- if (held) v.release(held.tag), v.release(held.tag + 1);
- v.schedule(shift(planNoteOn(s, ev.m, { body: bodyName, vibrato: 35, tag, legatoFrom: held ? { syl: held.syl, midi: held.midi } : undefined })));
- held = { syl: s, midi: ev.m, tag, up: 0 };
- tag += 2;
- } else if (held && held.midi === ev.m) {
- v.release(held.tag);
- v.release(held.tag + 1);
- v.schedule(shift(planNoteOff(held.syl, held.midi, bodyName)));
- held = null;
- }
- }
- v.render(out, i, Math.min(128, N - i));
- }
- writeWav(`${outDir}/live-${bodyName}.wav`, [out], FS);
- renderSpectrogram(`${outDir}/live-${bodyName}.png`, out, FS, { title: `live: hello there my friend (${bodyName})`, maxFreq: 6000, windowMs: 25, marks: keys.map(([d]) => ({ t: d, label: "" })) });
- console.log(`live: syllables ${syl.map((s) => s.text).join(" ")}`);
-}
diff --git a/tools/render-speech.ts b/tools/render-speech.ts
deleted file mode 100644
index f8d14ed..0000000
--- a/tools/render-speech.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-/**
- * Render IPA utterances through the real-time voice with the gestural planner.
- * Usage: bun tools/render-speech.ts out/name "ˈɑpɑ ˈɑbɑ" [male|female|child]
- * Writes <name>.wav and <name>.png (spectrogram with segment marks).
- */
-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
-import { BODY_MALE, BODY_FEMALE, BODY_CHILD } from "../src/engine/anatomy/human.ts";
-import { planUtterance } from "../src/engine/phonetics/planner.ts";
-import { tokenizeIpa } from "../src/engine/phonetics/ipa.ts";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram } from "./lib/spectrogram.ts";
-
-const name = process.argv[2] ?? "out/speech";
-const text = process.argv[3] ?? "ˈɑpɑ";
-const bodyName = (process.argv[4] ?? "male") as "male" | "female" | "child";
-const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];
-const f0 = { male: 110, female: 200, child: 250 }[bodyName];
-const FS = 48000;
-const voice = new HumanVoice({ fsOut: FS, body });
-voice.setSource({ f0 });
-const utterances = text.split("/").map((u) => u.trim()).filter(Boolean);
-const marks: { t: number; label: string }[] = [];
-let t0 = 0.05;
-for (const u of utterances) {
- const segs = tokenizeIpa(u);
- const plan = planUtterance(segs, { body: bodyName, t0, f0 });
- voice.schedule(plan.gestures);
- for (const s of plan.segments) marks.push({ t: s.t0, label: s.ipa });
- t0 = plan.end + 0.35;
-}
-const total = Math.round(FS * (t0 + 0.2));
-const out = new Float32Array(total);
-for (let i = 0; i < total; i += 128) voice.render(out, i, Math.min(128, total - i));
-let pk = 0;
-for (const x of out) pk = Math.max(pk, Math.abs(x));
-writeWav(`${name}.wav`, [out], FS);
-renderSpectrogram(`${name}.png`, out, FS, { title: `${text} (${bodyName})`.replace(/[^\x20-\x7e]/g, "?"), maxFreq: 9000, windowMs: 5, marks: marks.map((m) => ({ t: m.t, label: "" })) });
-console.log(`wrote ${name}.wav/.png ${(total / FS).toFixed(2)} s peak ${pk.toFixed(3)}`);
-console.log(marks.map((m) => `${m.label}@${m.t.toFixed(3)}`).join(" "));
diff --git a/tools/render-text.ts b/tools/render-text.ts
deleted file mode 100644
index 83e5342..0000000
--- a/tools/render-text.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-/**
- * English text → speech through the full pipeline. Usage: bun tools/render-text.ts out/name "Text." [male|female|child]
- */
-import { gunzipSync } from "node:zlib";
-import { readFileSync } from "node:fs";
-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
-import { BODY_MALE, BODY_FEMALE, BODY_CHILD } from "../src/engine/anatomy/human.ts";
-import { planPhrases } from "../src/engine/phonetics/planner.ts";
-import { EnglishG2P } from "../src/engine/phonetics/english.ts";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram } from "./lib/spectrogram.ts";
-
-const name = process.argv[2] ?? "out/text";
-const text = process.argv[3] ?? "Hello world.";
-const bodyName = (process.argv[4] ?? "male") as "male" | "female" | "child";
-const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];
-const f0 = { male: 112, female: 205, child: 250 }[bodyName];
-const g2p = new EnglishG2P();
-g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));
-const phrases = g2p.toPhrases(text);
-console.log(phrases.map((p) => p.segments.map((s) => (s.stress === 1 ? "ˈ" : "") + s.ipa).join("") + (p.intonation === "question" ? "?" : "")).join(" | "));
-const FS = 48000;
-const voice = new HumanVoice({ fsOut: FS, body });
-voice.setSource({ f0 });
-const plan = planPhrases(phrases, { body: bodyName, t0: 0.05, f0 });
-voice.schedule(plan.gestures);
-const total = Math.round(FS * (plan.end + 0.3));
-const out = new Float32Array(total);
-const t0 = performance.now();
-for (let i = 0; i < total; i += 128) voice.render(out, i, Math.min(128, total - i));
-const ms = performance.now() - t0;
-writeWav(`${name}.wav`, [out], FS);
-renderSpectrogram(`${name}.png`, out, FS, { title: text.toUpperCase().replace(/[^\x20-\x7e]/g, "?").slice(0, 120), maxFreq: 8000, windowMs: 5, marks: plan.segments.map((s) => ({ t: s.t0, label: "" })) });
-console.log(`wrote ${name}.wav ${(total / FS).toFixed(2)} s, rendered in ${ms.toFixed(0)} ms`);
diff --git a/tools/render-vowels.ts b/tools/render-vowels.ts
deleted file mode 100644
index a9cdab8..0000000
--- a/tools/render-vowels.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-/**
- * Render calibrated vowels through the real-time HumanVoice path, measure formants (LPC) and
- * f0 (YIN) from the audio, benchmark speed. Usage: bun tools/render-vowels.ts [male|female|child]
- */
-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
-import { BODY_MALE, BODY_FEMALE, BODY_CHILD } from "../src/engine/anatomy/human.ts";
-import { estimateFormants } from "../src/engine/analysis/lpc.ts";
-import { yinPitch } from "../src/engine/analysis/pitch.ts";
-import targets from "../src/engine/phonetics/vowelTargets.generated.json";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram } from "./lib/spectrogram.ts";
-
-const bodyName = (process.argv[2] ?? "male") as "male" | "female" | "child";
-const body = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD }[bodyName];
-const f0 = { male: 110, female: 205, child: 260 }[bodyName];
-const FS = 48000;
-const voice = new HumanVoice({ fsOut: FS, body });
-voice.setSource({ f0 });
-const list = ["i", "e", "ɛ", "æ", "ɑ", "ɔ", "o", "u", "ʌ", "ɝ"];
-const seg = 0.6;
-const out = new Float32Array(Math.round(FS * seg * list.length));
-const T = (targets as Record<string, Record<string, { artic: Record<string, number>; formants: number[] }>>)[bodyName];
-const t0 = performance.now();
-const block = 128;
-let pos = 0;
-for (let v = 0; v < list.length; v++) {
- voice.setArticulation(T[list[v]].artic, true);
- const n = Math.round(FS * seg);
- for (let i = 0; i < n; i += block) {
- const local = i / FS;
- voice.setGate(local < seg - 0.12 ? 1 : 0);
- voice.render(out, pos, Math.min(block, out.length - pos));
- pos += block;
- if (pos >= out.length) break;
- }
-}
-const ms = performance.now() - t0;
-let peak = 0;
-for (const x of out) peak = Math.max(peak, Math.abs(x));
-console.log(`${bodyName}: rendered ${(out.length / FS).toFixed(1)} s in ${ms.toFixed(0)} ms → ${((ms / 1000 / (out.length / FS)) * 100).toFixed(1)}% of real time; peak ${peak.toFixed(3)}`);
-for (let v = 0; v < list.length; v++) {
- const c = Math.round(FS * (v * seg + 0.3));
- const frame = out.subarray(c, c + 1536);
- const ds = new Float64Array(384);
- for (let i = 0; i < 384; i++) ds[i] = (frame[4 * i] + frame[4 * i + 1] + frame[4 * i + 2] + frame[4 * i + 3]) / 4;
- const fm = estimateFormants(ds, FS / 4, { order: 12 });
- const { f0: est } = yinPitch(out.subarray(c, c + 2400), FS, { minF0: 60 });
- const ref = T[list[v]].formants;
- console.log(` ${list[v].padEnd(2)} f0=${est.toFixed(1)} LPC ${fm.slice(0, 3).map((f) => f.freq.toFixed(0).padStart(5)).join("")} model ${ref.slice(0, 3).map((f) => String(f).padStart(5)).join("")}`);
-}
-writeWav(`out/vowels-${bodyName}.wav`, [out], FS);
-renderSpectrogram(`out/vowels-${bodyName}.png`, out, FS, { title: `CALIBRATED VOWELS ${bodyName.toUpperCase()}: ${list.join(" ")}`, maxFreq: 5000, windowMs: 5 });
diff --git a/tools/speech-diagnostics.ts b/tools/speech-diagnostics.ts
deleted file mode 100644
index d86b23d..0000000
--- a/tools/speech-diagnostics.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-/**
- * Running-speech diagnostics (the "marbles in the mouth" battery): renders sentences through the
- * full pipeline and measures, against published norms,
- * - nasal leakage: velopharyngeal port during vowels with no nasal neighbour
- * (heard as nasal from ~0.01 cm² for high vowels, ~0.15 cm² for low; Bunton & Story 2011)
- * - vowel undershoot: LPC F1/F2 at vowel midpoints vs the calibrated (Hillenbrand) targets
- * - formant bandwidths at vowel midpoints (Klatt defaults B1 60, B2 90, B3 150 Hz)
- * - spectral balance: octave-band long-term spectrum relative to 500 Hz
- * - duration contrasts: stressed vs unstressed, phrase-final vs not
- * - pitch: share of voiced time stuck at the baseline (snapping back between vowels)
- * Usage: bun tools/speech-diagnostics.ts [outdir]
- */
-import { readFileSync, mkdirSync } from "node:fs";
-import { gunzipSync } from "node:zlib";
-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";
-import { EnglishG2P } from "../src/engine/phonetics/english.ts";
-import { planPhrases, diphthongParts } from "../src/engine/phonetics/planner.ts";
-import { VOWELS } from "../src/engine/phonetics/vowelData.ts";
-import { estimateFormants } from "../src/engine/analysis/lpc.ts";
-import { FFT, hann } from "../src/engine/analysis/fft.ts";
-import { writeWav } from "./lib/wav.ts";
-import { renderSpectrogram } from "./lib/spectrogram.ts";
-
-const outDir = process.argv[2];
-if (outDir) mkdirSync(outDir, { recursive: true });
-const FS = 48000;
-const SENTENCES = [
- "The north wind and the sun were disputing which was the stronger.",
- "We were away a year ago.",
- "Should we chase those cowboys?",
- "Can you hear me now?",
- "She sells sea shells by the sea shore.",
-];
-const NASALS = new Set(["m", "n", "ŋ"]);
-const diphthongOf = (a: string, b: string) => ["aɪ", "aʊ", "ɔɪ", "eɪ", "oʊ"].some((d) => { const p = diphthongParts(d); return p && p[0] === a && p[1] === b; });
-const g2p = new EnglishG2P();
-g2p.setDictionaryText(gunzipSync(readFileSync("public/data/cmudict.txt.gz")).toString("utf8"));
-const REF = new Map(VOWELS.map((v) => [v.ipa, v.male]));
-
-interface VowelStat { ipa: string; stressed: boolean; final: boolean; dur: number; f1: number; f2: number; t1: number; t2: number; bw: number[] }
-const vowels: VowelStat[] = [];
-let oralFrames = 0, leak1 = 0, leak5 = 0, leak15 = 0, maxOralPort = 0;
-let voicedFrames = 0, atBase = 0;
-const f0s: number[] = [];
-const bands = [250, 500, 1000, 2000, 4000, 8000];
-const bandE = new Float64Array(bands.length);
-const fft = new FFT(2048), win = hann(2048);
-
-for (const [si, text] of SENTENCES.entries()) {
- const v = new HumanVoice({ fsOut: FS });
- const phrases = g2p.toPhrases(text);
- const plan = planPhrases(phrases, { body: "male", t0: 0.1, f0: 110 });
- v.schedule(plan.gestures);
- const N = Math.round(FS * (plan.end + 0.3));
- const out = new Float32Array(N);
- const port: number[] = [], f0t: number[] = [], voic: number[] = [];
- for (let i = 0; i < N; i += 128) {
- v.render(out, i, Math.min(128, N - i));
- port.push(v.airway.frame?.velumPort ?? 0);
- f0t.push(v.glottis.f0Now);
- voic.push(v.glottis.voicing);
- }
- const frameAt = (t: number) => Math.min(port.length - 1, Math.max(0, Math.round((t * FS) / 128)));
- const segs = plan.segments;
- segs.forEach((s, k) => {
- if (s.kind !== "vowel") return;
- // the second half of a diphthong is a glide, not a vowel that should reach its target
- const pv = segs[k - 1];
- if (pv && pv.kind === "vowel" && Math.abs(pv.t1 - s.t0) < 1e-6 && diphthongOf(pv.ipa, s.ipa)) return;
- const nasalNb = (segs[k - 1] && NASALS.has(segs[k - 1].ipa)) || (segs[k + 1] && NASALS.has(segs[k + 1].ipa));
- if (!nasalNb)
- for (let f = frameAt(s.t0); f <= frameAt(s.t1); f++) {
- oralFrames++;
- if (port[f] > 0.01) leak1++;
- if (port[f] > 0.05) leak5++;
- if (port[f] > 0.15) leak15++;
- maxOralPort = Math.max(maxOralPort, port[f]);
- }
- // formants at the midpoint (first target of a diphthong at 30 %)
- const parts = diphthongParts(s.ipa);
- const tgt = parts ? parts[0] : s.ipa;
- const ref = REF.get(tgt);
- const tm = parts ? s.t0 + 0.3 * (s.t1 - s.t0) : (s.t0 + s.t1) / 2;
- const dec = 4, len = Math.round(0.025 * FS);
- const c = Math.round(tm * FS);
- const fr: number[] = [];
- for (let i = c - len / 2; i < c + len / 2; i += dec) {
- let acc = 0;
- for (let j = 0; j < dec; j++) acc += out[i + j] ?? 0;
- fr.push(acc / dec);
- }
- const fm = estimateFormants(fr, FS / dec, { order: 14, maxBw: 700 });
- if (ref && fm.length >= 2) {
- const next = segs.slice(k + 1).find((x) => x.kind === "vowel");
- vowels.push({ ipa: s.ipa, stressed: s.stress === 1, final: !next || next.t0 - s.t1 > 0.2, dur: s.t1 - s.t0, f1: fm[0].freq, f2: fm[1].freq, t1: ref[0], t2: ref[1], bw: fm.slice(0, 3).map((x) => x.bw) });
- }
- });
- // pitch: voiced frames within 3 % of the 110 Hz baseline
- for (let f = 0; f < f0t.length; f++)
- if (voic[f] > 0.5) {
- voicedFrames++;
- f0s.push(f0t[f]);
- if (Math.abs(f0t[f] / 110 - 1) < 0.03) atBase++;
- }
- // long-term spectrum over frames with signal
- let peak = 0;
- for (const x of out) peak = Math.max(peak, Math.abs(x));
- for (let i = 0; i + 2048 < N; i += 1024) {
- let e = 0;
- for (let j = 0; j < 2048; j++) e += out[i + j] * out[i + j];
- if (Math.sqrt(e / 2048) < peak * 0.01) continue;
- const re = new Float64Array(2048), im = new Float64Array(2048);
- for (let j = 0; j < 2048; j++) re[j] = out[i + j] * win[j];
- fft.transform(re, im);
- for (let k = 1; k < 1024; k++) {
- const f = (k * FS) / 2048;
- const p = re[k] * re[k] + im[k] * im[k];
- bands.forEach((b, bi) => {
- if (f >= b / Math.SQRT2 && f < b * Math.SQRT2) bandE[bi] += p;
- });
- }
- }
- if (outDir) {
- writeWav(`${outDir}/s${si + 1}.wav`, [out], FS);
- renderSpectrogram(`${outDir}/s${si + 1}.png`, out, FS, { title: text.replace(/[^\x20-\x7e]/g, "?"), maxFreq: 8000, windowMs: 5, marks: segs.map((s) => ({ t: s.t0, label: "" })) });
- }
-}
-
-const pct = (a: number, b: number) => `${((100 * a) / Math.max(1, b)).toFixed(1)} %`;
-const mean = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / Math.max(1, xs.length);
-const median = (xs: number[]) => { const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)] ?? NaN; };
-console.log("== nasal leakage during vowels with no nasal neighbour");
-console.log(` frames with port > 0.01 cm²: ${pct(leak1, oralFrames)} > 0.05: ${pct(leak5, oralFrames)} > 0.15: ${pct(leak15, oralFrames)} max ${maxOralPort.toFixed(3)} cm² (norm: ~0 %)`);
-console.log("== vowel midpoints vs calibrated targets");
-// LPC fails on short vowels that came out voiceless (aspiration): drop frames with no F1 below 1.2 kHz
-const ok = (vs: VowelStat[]) => vs.filter((x) => x.f1 < 1200 && x.f2 < 3200);
-const err = (vs0: VowelStat[]) => {
- const vs = ok(vs0);
- return `F1 ${(100 * median(vs.map((x) => Math.abs(x.f1 / x.t1 - 1)))).toFixed(0)} % F2 ${(100 * median(vs.map((x) => Math.abs(x.f2 / x.t2 - 1)))).toFixed(0)} % median error (n=${vs.length}/${vs0.length} measurable)`;
-};
-// distance from schwa in (F1, log F2) relative to the target's
-const sch = [500, 1500];
-const reach = (vs: VowelStat[]) => median(ok(vs).filter((x) => Math.hypot(x.t1 - sch[0], 1000 * Math.log(x.t2 / sch[1])) > 80).map((x) => Math.hypot(x.f1 - sch[0], 1000 * Math.log(x.f2 / sch[1])) / Math.hypot(x.t1 - sch[0], 1000 * Math.log(x.t2 / sch[1]))));
-const S = vowels.filter((x) => x.stressed), U = vowels.filter((x) => !x.stressed);
-console.log(` stressed: ${err(S)}; distance from schwa reached ${(100 * reach(S)).toFixed(0)} % (norm ≥ 90 %)`);
-console.log(` unstressed: ${err(U)}; distance from schwa reached ${(100 * reach(U)).toFixed(0)} % (norm ≥ 75 %)`);
-if (process.env.DIAG_VERBOSE) for (const x of vowels) console.log(` ${x.stressed ? "S" : "u"} ${x.ipa.padEnd(3)} ${(1000 * x.dur).toFixed(0).padStart(4)} ms F1 ${x.f1.toFixed(0).padStart(4)}/${x.t1} F2 ${x.f2.toFixed(0).padStart(5)}/${x.t2} B1 ${x.bw[0].toFixed(0)}`);
-console.log("== formant bandwidths at vowel midpoints (median)");
-console.log(` B1 ${median(vowels.map((x) => x.bw[0])).toFixed(0)} Hz B2 ${median(vowels.map((x) => x.bw[1])).toFixed(0)} Hz B3 ${median(vowels.map((x) => x.bw[2] ?? NaN).filter(Number.isFinite)).toFixed(0)} Hz (Klatt defaults 60 / 90 / 150)`);
-console.log("== long-term spectrum, octave bands re 500 Hz");
-const ref500 = bandE[1];
-const ltass = [-2, 0, -6, -11, -16, -20]; // approximate natural male speech (Byrne et al. 1994 LTASS, octave-averaged)
-console.log(" " + bands.map((b, i) => `${b >= 1000 ? b / 1000 + "k" : b}: ${(10 * Math.log10(bandE[i] / ref500)).toFixed(1)} (≈${ltass[i]})`).join(" "));
-console.log("== durations");
-const fin = vowels.filter((x) => x.final), non = vowels.filter((x) => !x.final);
-console.log(` stressed ${(1000 * mean(S.map((x) => x.dur))).toFixed(0)} ms vs unstressed ${(1000 * mean(U.map((x) => x.dur))).toFixed(0)} ms (norm ≥ 2 ×); phrase-final ${(1000 * mean(fin.map((x) => x.dur))).toFixed(0)} ms vs non-final ${(1000 * mean(non.map((x) => x.dur))).toFixed(0)} ms (norm: final ≈ 1.3–1.4 ×)`);
-console.log("== pitch");
-const st = (a: number, b: number) => 12 * Math.log2(a / b);
-const sorted = [...f0s].sort((a, b) => a - b);
-console.log(` voiced time at the 110 Hz baseline (±3 %): ${pct(atBase, voicedFrames)} range (5–95 %) ${st(sorted[Math.floor(sorted.length * 0.95)], sorted[Math.floor(sorted.length * 0.05)]).toFixed(1)} semitones`);