Skip to content

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

Rust

Engine foundations: FDTD airway network, frequency-domain oracle, parametric glottis, human articulatory model, vowel calibration

Jameson Hodgeede7a4e0bb4a
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..d6799e3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+node_modules
+dist
+out
+*.wav
+.DS_Store
diff --git a/DESIGN.md b/DESIGN.md
new file mode 100644
index 0000000..9bc33c9
--- /dev/null
+++ b/DESIGN.md
@@ -0,0 +1,198 @@
+# CHIMERA — a physical-modeling voice synthesizer for many creatures
+
+## Brief (from the user)
+
+"Create the ultimate vocal synthesizer. Web app for now. Be extremely ambitious.
+Sophisticated throat, lips, tongue modeling. Different animals: human, bird,
+reptile, etc. Tonal and percussive (beatboxing). Beautiful visuals/diagrams,
+dynamic animations based on params." Long build is expected.
+
+## Product shape
+
+A browser instrument where every sound comes from a simulated airway, not samples.
+
+* **Creatures**: human (bass/tenor/alto/soprano/child), songbird (two-voice syrinx),
+ parrot (talking bird), owl, crow, cat (meow, purr), dog/wolf (bark, howl), lion (roar),
+ elephant (trunk trumpet, rumble), cow, frog (vocal sac), crocodile (bellow, hiss),
+ snake (hiss), gecko (chirp), dragon (fantasy). Morph between anatomies.
+* **Modes**:
+ * *Play* — drag the tongue/lips/jaw in a live anatomy view; XY vowel pad; on-screen and
+ computer keyboard; Web MIDI; phoneme pads (tap /t/ over a held vowel).
+ * *Speak* — English text (CMUdict + letter-to-sound fallback) or raw IPA → phonemes →
+ prosody → gestural score → speech. Timeline shows the gestural score.
+ * *Sing* — piano roll with lyrics per note; onset consonants placed before the beat.
+ * *Beatbox* — pads + 16-step sequencer; every drum is an articulatory gesture
+ (bilabial ejective kick, "pf" snare, alveolar hat, inward K-snare, lip roll, click roll,
+ throat bass). "One mouth" (physically honest, one tract) or "crew" (one tract per track).
+ * *IPA chart* — click any symbol on the full IPA chart (incl. ejectives, implosives,
+ clicks, trills) to hear/see it.
+ * *Creature lab* — anatomy parameters, morphing, call presets.
+* **Visuals (first-class)**: everything animates from live engine state at 60 fps.
+ * Midsagittal cutaway of the current creature: tongue, jaw, lips, velum, larynx,
+ epiglottis; acoustic pressure rendered as a colour field inside the airway;
+ airflow particles whose speed follows simulated volume velocity; turbulence
+ shown at constrictions where the Reynolds number exceeds threshold.
+ * Laryngoscope "stroboscope" (top view of vocal folds / syrinx labia) replayed
+ slowed down from the real simulated glottal area waveform.
+ * Area-function tube diagram (cylinders with pressure), glottal flow scope,
+ transfer function with formant markers, F1–F2 vowel chart with the live point,
+ scrolling spectrogram, gestural-score timeline with playhead.
+
+## Architecture
+
+```
+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)
+ ├─ Voice[] (pool)
+ │ ├─ Controller: gesture scheduler → articulator dynamics (control rate)
+ │ ├─ Anatomy: articulator state → geometry → area functions (control rate)
+ │ ├─ Sources: glottis (parametric area / two-mass), syrinx, valves (trills)
+ │ └─ Airway: branched FDTD tube network (internal rate = 2–4× output)
+ └─ FX: mic/proximity, EQ, compressor, saturation, reverb, limiter
+ │ telemetry ~60 Hz (articulators, areas, pressures, flows, glottal trace, formants)
+ ▼
+main thread renderers
+```
+
+Control rate: every 64–128 output samples, with per-sample linear interpolation of areas.
+
+### 1. Airway acoustics — branched staggered-grid FDTD transmission line
+
+Chosen over Kelly-Lochbaum because it handles, in one framework: variable section
+lengths (larynx height, lip protrusion, creature size), DC aerodynamics (pressure
+build-up behind closures, bursts), nonlinear kinetic losses at constrictions, yielding
+walls, moving-wall volume sources (needed for clicks, ejectives, implosives), arbitrary
+branching (nasal tract, sinuses, piriform fossae, two bronchi, vocal sacs, OEC).
+
+* Units CGS. ρ = 1.14e-3 g/cm³, c = 35 000 cm/s, μ = 1.86e-4 P.
+* Generic graph: pressure nodes (volume V = AΔ) and flow branches between nodes.
+ Branch inertance L = ρ(Δa/2Aa + Δb/2Ab) (series half-sections, so a tiny node is
+ bracketed by large inertances → stable at CFL ≤ 1 regardless of area ratio).
+* Leapfrog: branches update U(n+½) from p(n); nodes update p(n+1) from U(n+½).
+ Branch update is implicit in U for losses: viscous R, plus Borda–Carnot expansion
+ loss a·|U|U with a = ρk/2·(1/As − 1/Al)² chosen by flow direction; solved as an
+ exact quadratic per sample (avoids the period-2 instability of lagged |U|).
+* Continuity: (V/ρc²) dp/dt = ΣU_in − ΣU_out − U_wall − dV/dt (moving walls).
+* Walls: per-node mass–spring–damper (m≈1.5 g/cm², r≈1600, k≈3e5 CGS, ×perimeter·Δ).
+ Wall flow also radiates weakly (voice bar during voiced closures).
+* Radiation: Flanagan parallel R–L load at lips/nostrils/beak; output = d/dt of radiated
+ volume velocity (sum of mouth, nostrils, skin).
+* Turbulence: per branch Reynolds number Re = |U|·d_h/(A·ν); dipole pressure source
+ g·(Re² − Re_c²)·noise injected ~1 cm downstream of the constriction exit (flow-direction
+ aware), plus an obstacle source at the lower incisors when a jet reaches them (sibilants).
+ Aspiration is the same mechanism at the glottis.
+* Closure: branch area < ε ⇒ U = 0 (no leakage); node volumes floored for compliance.
+* Internal rate 96 kHz (adult human), 192 kHz (small birds/cats), 48 kHz allowed for
+ huge tracts; N chosen per anatomy so Δ ≥ c·T/0.95. Polyphase half-band decimation to
+ the output rate.
+* Cross-check: a frequency-domain chain-matrix model with the same loss terms computes
+ H(f) for analysis, UI formant display, and as a test oracle for the FDTD.
+
+### 2. Sources
+
+* **Parametric glottis (default, exact pitch)**: glottal *area* pulse (opening/closing
+ phases, open quotient, skew, max area, rest/abduction area, posterior chink) drives the
+ interactive glottal branch, so flow shape, skewing, F1 ripple and devoicing under
+ oral closure all emerge from the tract. Perturbations: jitter, shimmer, vibrato with
+ drift, 1/f flutter, diplophonia/period doubling, vocal fry (low f0, short OQ, double
+ pulses), falsetto (sinusoidal, incomplete closure).
+* **Two-mass vocal folds (advanced)**: Ishizaka–Flanagan with collision; self-oscillating;
+ pitch tracked by a feedback controller on the tension factor Q.
+* **Ventricular folds**: second valve above the glottis, entrains at f0/2 for growl /
+ kargyraa; static narrowing for harshness. **Epilarynx** narrowing for twang/ring.
+* **Syrinx (birds)**: two independent labial oscillators (Gardner–Mindlin normal form
+ ẋ=y, ẏ=−αγ²−βγ²x−γ²x³−γx²y+γ²x²−γxy). γ is a pure time scale, so pitch is exact:
+ γ = 2π f0 / F(α,β) with F tabulated offline; α (air-sac pressure) and β (tension)
+ shape the waveform (pure tone → pulses → period doubling/chaos). Each labium gates its
+ own bronchus; bronchi merge into the trachea → OEC (Helmholtz, volume tracks f0 for
+ pure tones) → beak (gape-dependent radiation).
+* **Flow-induced valves**: one mass–spring valve model driven by constriction pressure
+ (Bernoulli suction / upstream push) for lip trill, tongue-tip trill, uvular trill,
+ lip buzz (beatbox bass, elephant trumpet as a lip-reed at the trunk base). Optional
+ phase-locked drive if self-oscillation is not robust.
+* **Airstream mechanisms**: lung pressure may be negative (ingressive); glottal closure +
+ larynx raising/lowering (ejectives/implosives via dV/dt); velaric closure + tongue
+ dorsum lowering (clicks). All physical through the FDTD — no special-cased samples.
+
+### 3. Anatomy & articulation (human first, others as parametric variants)
+
+* 2D midsagittal geometry (cm, head frame): fixed outer wall (posterior pharynx, velum,
+ hard palate, alveolar ridge, upper incisors, upper lip) and moving inner wall
+ (epiglottis/larynx, tongue root, tongue body circle, blade, tip, lower incisors,
+ lower lip, jaw).
+* Articulators (state, all absolute head-frame so consonant constrictions are exact):
+ jaw, tongue body centre (x,y), tongue tip (x,y), tip curl (retroflex), central groove,
+ lateral channel, tongue root, lip aperture (negative = compression), lip protrusion,
+ lip width/rounding, labiodental, velum port area, larynx height, epilarynx, glottal
+ abduction / closure, lung pressure, f0, effort, ventricular, trill drives, dorsum
+ lowering (clicks).
+* Area function: semipolar grid (horizontal lines in pharynx, radial in oral cavity,
+ vertical at lips) intersected with inner/outer contours → midsagittal distance d →
+ A = α·d^β per region; tongue grooving/laterals modify A; lengths from midpoint chain.
+ Resampled to N uniform sections of current length L(t).
+* Calibration: optimise vowel targets against reference formants (Hillenbrand 1995 male
+ means, plus cardinal vowels for non-English) with the chain-matrix model. Female/child
+ via anatomical scaling (shorter pharynx proportion), not formant warping.
+* Other mammals/reptiles: same topology, species parameters (snout length, palate
+ shape, larynx position/descent, nasal length, lip shape, trunk = long nasal tube,
+ vocal sac = Helmholtz side branch). Birds: separate topology (syrinx/trachea/OEC/beak,
+ tongue for parrots).
+
+### 4. Control: gestures (Articulatory Phonology–style)
+
+* Phoneme = set of gestures, each controlling a subset of articulators with targets,
+ stiffness, blending strength and timing relative to the segment.
+* Gestural score: vowel gestures span vowel to vowel (tongue body keeps moving through
+ consonants — Öhman coarticulation); consonant gestures overlay their articulators
+ with higher strength; uncontrolled articulators relax to neutral.
+* Articulator dynamics: critically damped 2nd-order per articulator, physiological
+ speeds (lips/tip fast, tongue body/jaw slower, velum/larynx slow).
+* Consonant closures use overshoot targets clamped by the geometry (contact), so
+ closures are robust; fricatives specify exact gap.
+* Text: CMUdict (lazy-loaded, compact) + rule fallback → ARPAbet → IPA; stress;
+ syllabification; Klatt-style durations; intonation (declination, H* on stressed
+ syllables, final fall / question rise). Singing: notes+lyrics → syllable alignment.
+
+### 5. FX / output
+
+DC blocker → mic model (distance/proximity) → EQ → compressor → saturation → reverb →
+limiter. WAV export via the same engine in a Worker (unlimited voices, faster than RT).
+
+## Tech
+
+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.
+
+## Validation
+
+* `bun test`: 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.
+* Headless Chromium (Playwright) smoke tests: app loads, worklet runs, no console errors,
+ screenshots of each mode.
+* Hosted over HTTPS via `tailscale serve` (AudioWorklet needs a secure context).
+
+## Phases
+
+0. Scaffold, analysis tools (WAV, FFT, LPC, spectrogram PNG), test harness.
+1. Airway FDTD + parametric glottis + chain-matrix oracle.
+2. Human articulatory geometry, area function, calibration; nasal; fricatives/stops.
+3. Gestures, phoneme inventory (IPA), G2P, prosody → speech.
+4. Worklet + core UI (anatomy view with drag, controls, keyboard, vowel pad, speak).
+5. Extra sources (syrinx, valves/trills, ventricular, two-mass, purr) + creatures + visuals.
+6. Beatbox (airstream mechanisms, sounds, sequencer, mic FX).
+7. Singing (piano roll, lyrics, multi-voice, export).
+8. Polish: visuals, presets, performance, mobile, onboarding.
+
+## Known risks
+
+* Fricative/burst realism depends on noise-source calibration (gain, placement, spectrum).
+* Geometry→area calibration quality decides vowel quality.
+* Self-oscillating valves (two-mass, trills) can be finicky → parametric fallbacks.
+* CPU in the AudioWorklet (JS) with several voices; quality settings + offline render.
+* Scope: large; each phase must leave a working, polished app.
diff --git a/bun.lock b/bun.lock
new file mode 100644
index 0000000..7bdccac
--- /dev/null
+++ b/bun.lock
@@ -0,0 +1,172 @@
+{
+ "lockfileVersion": 2,
+ "configVersion": 1,
+ "workspaces": {
+ "": {
+ "name": "chimera-voice",
+ "dependencies": {
+ "react": "19.3.1",
+ "react-dom": "19.3.1",
+ "zustand": "5.0.16",
+ },
+ "devDependencies": {
+ "@types/bun": "1.4.4",
+ "@types/react": "19.3.0",
+ "@types/react-dom": "19.3.0",
+ "@vitejs/plugin-react": "6.2.1",
+ "playwright-core": "1.64.1",
+ "typescript": "7.0.2",
+ "vite": "8.3.6",
+ },
+ },
+ },
+ "packages": {
+ "@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw=="],
+
+ "@rolldown/binding-android-arm-eabi": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA=="],
+
+ "@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg=="],
+
+ "@rolldown/binding-darwin-arm64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ=="],
+
+ "@rolldown/binding-darwin-x64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ=="],
+
+ "@rolldown/binding-freebsd-x64": ["@rolldown/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q=="],
+
+ "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA=="],
+
+ "@rolldown/binding-linux-arm64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w=="],
+
+ "@rolldown/binding-linux-arm64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg=="],
+
+ "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "ppc64", "libc": "glibc" }, "sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA=="],
+
+ "@rolldown/binding-linux-s390x-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "s390x", "libc": "glibc" }, "sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg=="],
+
+ "@rolldown/binding-linux-x64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w=="],
+
+ "@rolldown/binding-linux-x64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA=="],
+
+ "@rolldown/binding-openharmony-arm64": ["@rolldown/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ=="],
+
+ "@rolldown/binding-win32-arm64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw=="],
+
+ "@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw=="],
+
+ "@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
+
+ "@types/bun": ["@types/[email protected]", "", { "dependencies": { "bun-types": "1.4.4" } }, "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ=="],
+
+ "@types/node": ["@types/[email protected]", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog=="],
+
+ "@types/react": ["@types/[email protected]", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg=="],
+
+ "@types/react-dom": ["@types/[email protected]", "", { "peerDependencies": { "@types/react": "^19.3.0" } }, "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q=="],
+
+ "@typescript/typescript-aix-ppc64": ["@typescript/[email protected]", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
+
+ "@typescript/typescript-darwin-arm64": ["@typescript/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
+
+ "@typescript/typescript-darwin-x64": ["@typescript/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
+
+ "@typescript/typescript-freebsd-arm64": ["@typescript/[email protected]", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
+
+ "@typescript/typescript-freebsd-x64": ["@typescript/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
+
+ "@typescript/typescript-linux-arm": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
+
+ "@typescript/typescript-linux-arm64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
+
+ "@typescript/typescript-linux-loong64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
+
+ "@typescript/typescript-linux-mips64el": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
+
+ "@typescript/typescript-linux-ppc64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
+
+ "@typescript/typescript-linux-riscv64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
+
+ "@typescript/typescript-linux-s390x": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
+
+ "@typescript/typescript-linux-x64": ["@typescript/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
+
+ "@typescript/typescript-netbsd-arm64": ["@typescript/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
+
+ "@typescript/typescript-netbsd-x64": ["@typescript/[email protected]", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
+
+ "@typescript/typescript-openbsd-arm64": ["@typescript/[email protected]", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
+
+ "@typescript/typescript-openbsd-x64": ["@typescript/[email protected]", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
+
+ "@typescript/typescript-sunos-x64": ["@typescript/[email protected]", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
+
+ "@typescript/typescript-win32-arm64": ["@typescript/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
+
+ "@typescript/typescript-win32-x64": ["@typescript/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
+
+ "@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0 || ^0.3.0", "babel-plugin-react-compiler": "^1.0.0", "oxc-transform-react": ">=0.152.0 <0.157.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler", "oxc-transform-react"] }, "sha512-9KyWCij3r0+qLG3Q62vBmv0VyevmYibAtxaCIVK9o0k6CXgaajZRIe8tpfchQcdZArJ5b/7OrIz4W3b2uxVRDA=="],
+
+ "bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*", "undici-types": "*" } }, "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ=="],
+
+ "csstype": ["[email protected]", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
+
+ "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
+
+ "fdir": ["[email protected]", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
+
+ "fsevents": ["[email protected]", "", { "os": "darwin", "hasInstallScript": true }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
+
+ "lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.33.0", "lightningcss-darwin-arm64": "1.33.0", "lightningcss-darwin-x64": "1.33.0", "lightningcss-freebsd-x64": "1.33.0", "lightningcss-linux-arm-gnueabihf": "1.33.0", "lightningcss-linux-arm64-gnu": "1.33.0", "lightningcss-linux-arm64-musl": "1.33.0", "lightningcss-linux-x64-gnu": "1.33.0", "lightningcss-linux-x64-musl": "1.33.0", "lightningcss-win32-arm64-msvc": "1.33.0", "lightningcss-win32-x64-msvc": "1.33.0" } }, "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA=="],
+
+ "lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg=="],
+
+ "lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg=="],
+
+ "lightningcss-darwin-x64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ=="],
+
+ "lightningcss-freebsd-x64": ["[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg=="],
+
+ "lightningcss-linux-arm-gnueabihf": ["[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ=="],
+
+ "lightningcss-linux-arm64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg=="],
+
+ "lightningcss-linux-arm64-musl": ["[email protected]", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ=="],
+
+ "lightningcss-linux-x64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg=="],
+
+ "lightningcss-linux-x64-musl": ["[email protected]", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw=="],
+
+ "lightningcss-win32-arm64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA=="],
+
+ "lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA=="],
+
+ "nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ=="],
+
+ "picocolors": ["[email protected]", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="],
+
+ "picomatch": ["[email protected]", "", {}, "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA=="],
+
+ "playwright-core": ["[email protected]", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ=="],
+
+ "postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.20", "picocolors": "^1.1.1", "source-map-js": "^1.2.2" } }, "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g=="],
+
+ "react": ["[email protected]", "", {}, "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw=="],
+
+ "react-dom": ["[email protected]", "", { "dependencies": { "scheduler": "^0.28.0" }, "peerDependencies": { "react": "^19.3.1" } }, "sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ=="],
+
+ "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.156.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm-eabi": "1.2.16", "@rolldown/binding-android-arm64": "1.2.16", "@rolldown/binding-darwin-arm64": "1.2.16", "@rolldown/binding-darwin-x64": "1.2.16", "@rolldown/binding-freebsd-x64": "1.2.16", "@rolldown/binding-linux-arm-gnueabihf": "1.2.16", "@rolldown/binding-linux-arm64-gnu": "1.2.16", "@rolldown/binding-linux-arm64-musl": "1.2.16", "@rolldown/binding-linux-ppc64-gnu": "1.2.16", "@rolldown/binding-linux-s390x-gnu": "1.2.16", "@rolldown/binding-linux-x64-gnu": "1.2.16", "@rolldown/binding-linux-x64-musl": "1.2.16", "@rolldown/binding-openharmony-arm64": "1.2.16", "@rolldown/binding-win32-arm64-msvc": "1.2.16", "@rolldown/binding-win32-x64-msvc": "1.2.16" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw=="],
+
+ "scheduler": ["[email protected]", "", {}, "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw=="],
+
+ "source-map-js": ["[email protected]", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="],
+
+ "tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
+
+ "typescript": ["[email protected]", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
+
+ "undici-types": ["[email protected]", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
+
+ "vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.32", "rolldown": "~1.2.16", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA=="],
+
+ "zustand": ["[email protected]", "", { "peerDependencies": { "@types/react": ">=18.0.0", "immer": ">=9.0.6", "react": ">=18.0.0", "use-sync-external-store": ">=1.2.0" }, "optionalPeers": ["@types/react", "immer", "react", "use-sync-external-store"] }, "sha512-Uv7e327ihlCfayfja3hDc0M64Upev1LWBKpRobdK4NyovDDPeeX4imWXc/wzC1yc6fkYPoAY/ncKVPAs2jrtQw=="],
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..5248275
--- /dev/null
+++ b/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "chimera-voice",
+ "private": true,
+ "version": "0.1.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite --host 127.0.0.1",
+ "build": "tsc --noEmit && vite build",
+ "preview": "vite preview --host 127.0.0.1",
+ "test": "bun test tests",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "react": "19.3.1",
+ "react-dom": "19.3.1",
+ "zustand": "5.0.16"
+ },
+ "devDependencies": {
+ "@types/bun": "1.4.4",
+ "@types/react": "19.3.0",
+ "@types/react-dom": "19.3.0",
+ "@vitejs/plugin-react": "6.2.1",
+ "playwright-core": "1.64.1",
+ "typescript": "7.0.2",
+ "vite": "8.3.6"
+ }
+}
diff --git a/public/data/CMUDICT-LICENSE.txt b/public/data/CMUDICT-LICENSE.txt
new file mode 100644
index 0000000..81a0ae8
--- /dev/null
+++ b/public/data/CMUDICT-LICENSE.txt
@@ -0,0 +1,33 @@
+Copyright (C) 1993-2015 Carnegie Mellon University. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ The contents of this file are deemed to be source code.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+This work was supported in part by funding from the Defense Advanced
+Research Projects Agency, the Office of Naval Research and the National
+Science Foundation of the United States of America, and by member
+companies of the Carnegie Mellon Sphinx Speech Consortium. We acknowledge
+the contributions of many volunteers to the expansion and improvement of
+this dictionary.
+
+THIS SOFTWARE IS PROVIDED BY CARNEGIE MELLON UNIVERSITY ``AS IS'' AND
+ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY
+NOR ITS EMPLOYEES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/public/data/cmudict.txt.gz b/public/data/cmudict.txt.gz
new file mode 100644
index 0000000..bdc9e4a
Binary files /dev/null and b/public/data/cmudict.txt.gz differ
diff --git a/src/engine/airway/decimator.ts b/src/engine/airway/decimator.ts
new file mode 100644
index 0000000..a0b6228
--- /dev/null
+++ b/src/engine/airway/decimator.ts
@@ -0,0 +1,64 @@
+/**
+ * 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
new file mode 100644
index 0000000..e13594c
--- /dev/null
+++ b/src/engine/airway/frequency.ts
@@ -0,0 +1,200 @@
+/**
+ * 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
new file mode 100644
index 0000000..dbaccec
--- /dev/null
+++ b/src/engine/airway/network.ts
@@ -0,0 +1,707 @@
+/**
+ * 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 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;
+ /** 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;
+ /** 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.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.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.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.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): void {
+ for (let i = 0; i < t.n; i++) this.areaTarget[t.node(i)] = Math.max(0, areas[i]);
+ 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);
+ }
+
+ 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;
+ }
+
+ /** Prepare per-sample linear ramps toward the targets over `samples` internal samples. */
+ beginBlock(samples: number): void {
+ const inv = 1 / Math.max(1, samples);
+ for (let k = 0; k < this.nNodes; k++) {
+ this.areaStep[k] = (this.areaTarget[k] - this.area[k]) * inv;
+ this.dxStep[k] = (this.dxTarget[k] - this.dx[k]) * inv;
+ }
+ 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;
+ }
+
+ 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 dx = this.dx;
+ const invA = this.invA;
+ const vol = this.vol;
+ const flowSum = this.flowSum;
+ const minA = this.minNodeArea;
+
+ // 1) geometry ramps; accumulate -dV/dt into the flow sums
+ for (let k = 0; k < N; k++) {
+ let a = area[k] + this.areaStep[k];
+ if (a < 0) a = 0;
+ area[k] = a;
+ const d = (dx[k] += this.dxStep[k]);
+ invA[k] = 1 / (a > 1e-6 ? a : 1e-6);
+ const v = (a > minA ? a : minA) * d;
+ flowSum[k] = -(v - vol[k]) * invT + this.extFlow[k];
+ this.extFlow[k] = 0;
+ vol[k] = v;
+ }
+
+ // 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 visc = Math.sqrt((RHO * MU * this.viscousOmega) / 2) * this.viscousScale;
+ const closed = this.closedArea;
+ 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];
+ aEff = Aa < Ab ? Aa : Ab;
+ if (aEff < closed) {
+ U[j] = 0;
+ mom[j] = 0;
+ this.branchArea[j] = aEff;
+ continue;
+ }
+ const ia = invA[a];
+ const ib = invA[b];
+ L = 0.5 * RHO * (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]);
+ const diff = ia - ib; // >0 when a is narrower
+ const bc = 0.5 * RHO * diff * diff;
+ // flow a→b expands if b wider (diff>0); flow b→a expands if a wider (diff<0)
+ kf = diff > 0 ? bc : 0.1 * bc;
+ kb = diff < 0 ? bc : 0.1 * bc;
+ } 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 += 0.5 * RHO * (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 ipa = invA[a];
+ const ipb = invA[b];
+ const exF = ip - ipb; // flow a→b exits into b
+ const exB = ip - ipa; // flow b→a exits into a
+ const kin = this.portKin[j] * 0.5 * RHO * ip * ip;
+ kf = kin + this.portKex[j] * 0.5 * RHO * (exF > 0 ? exF * exF : 0);
+ kb = kin + this.portKex[j] * 0.5 * RHO * (exB > 0 ? exB * exB : 0);
+ }
+ this.branchArea[j] = aEff;
+ const c = p[a] - p[b] + psrc[j] + mom[j] * 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;
+ flowSum[a] -= u;
+ flowSum[b] += u;
+ }
+
+ // 4) walls (velocity at half step from p(n), displacement integrates)
+ const wallU = this.wallU;
+ let wallRadSum = 0;
+ for (let k = 0; k < N; k++) {
+ if (!this.hasWall[k]) continue;
+ const m = this.wallM[k];
+ const r = this.wallR[k];
+ const v = ((m * invT - 0.5 * r) * this.wallV[k] + p[k] - this.wallK[k] * this.wallY[k]) / (m * invT + 0.5 * r);
+ this.wallV[k] = v;
+ this.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 * this.wallRad[k];
+ }
+
+ // 5) nodes (radiation loads handled semi-implicitly)
+ const radUL = this.radUL;
+ let radTotal = wallRadSum;
+ for (let k = 0; k < N; k++) {
+ if (this.fixed[k]) continue;
+ const C = vol[k] / RHO_C2;
+ 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];
+ const ul = radUL[r] + (T / Lr) * pOld;
+ radUL[r] = ul;
+ const g = 0.5 / Rr;
+ const pNew = (pOld * (C * invT - g) + flowSum[k] - ul) / (C * invT + g);
+ p[k] = pNew;
+ const ur = 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;
+ const scale = this.noiseScale;
+ 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) amp = s.gain * scale * (re * re - RE_CRIT * RE_CRIT);
+ }
+ // 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.wallY.fill(0);
+ this.wallV.fill(0);
+ this.radUL.fill(0);
+ this.radPrevTotal = 0;
+ }
+}
diff --git a/src/engine/analysis/fft.ts b/src/engine/analysis/fft.ts
new file mode 100644
index 0000000..e8ca80f
--- /dev/null
+++ b/src/engine/analysis/fft.ts
@@ -0,0 +1,90 @@
+/**
+ * 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.
+ */
+export class FFT {
+ readonly n: number;
+ private readonly cos: Float64Array;
+ private readonly sin: Float64Array;
+ private readonly rev: Uint32Array;
+
+ constructor(n: number) {
+ if ((n & (n - 1)) !== 0 || n < 2) throw new Error(`FFT size must be a power of two, got ${n}`);
+ this.n = n;
+ this.cos = new Float64Array(n / 2);
+ this.sin = new Float64Array(n / 2);
+ for (let i = 0; i < n / 2; i++) {
+ this.cos[i] = Math.cos((2 * Math.PI * i) / n);
+ this.sin[i] = -Math.sin((2 * Math.PI * i) / n);
+ }
+ this.rev = new Uint32Array(n);
+ const bits = Math.log2(n);
+ for (let i = 0; i < n; i++) {
+ let r = 0;
+ for (let b = 0; b < bits; b++) r |= ((i >> b) & 1) << (bits - 1 - b);
+ this.rev[i] = r;
+ }
+ }
+
+ /** Forward transform (sign -1). */
+ transform(re: Float64Array, im: Float64Array): void {
+ const n = this.n;
+ const rev = this.rev;
+ for (let i = 0; i < n; i++) {
+ const j = rev[i];
+ if (j > i) {
+ let t = re[i]; re[i] = re[j]; re[j] = t;
+ t = im[i]; im[i] = im[j]; im[j] = t;
+ }
+ }
+ for (let size = 2; size <= n; size <<= 1) {
+ const half = size >> 1;
+ const step = n / size;
+ for (let start = 0; start < n; start += size) {
+ for (let k = 0; k < half; k++) {
+ const wr = this.cos[k * step];
+ const wi = this.sin[k * step];
+ const a = start + k;
+ const b = a + half;
+ const xr = re[b] * wr - im[b] * wi;
+ const xi = re[b] * wi + im[b] * wr;
+ re[b] = re[a] - xr;
+ im[b] = im[a] - xi;
+ re[a] += xr;
+ im[a] += xi;
+ }
+ }
+ }
+ }
+}
+
+export function hann(n: number): Float64Array {
+ const w = new Float64Array(n);
+ for (let i = 0; i < n; i++) w[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (n - 1));
+ return w;
+}
+
+export function hamming(n: number): Float64Array {
+ const w = new Float64Array(n);
+ for (let i = 0; i < n; i++) w[i] = 0.54 - 0.46 * Math.cos((2 * Math.PI * i) / (n - 1));
+ return w;
+}
+
+/** Magnitude spectrum in dB (n/2+1 bins) of a real frame, windowed. */
+export function powerSpectrumDb(frame: ArrayLike<number>, fft: FFT, window: Float64Array): Float64Array {
+ const n = fft.n;
+ const re = new Float64Array(n);
+ const im = new Float64Array(n);
+ const m = Math.min(frame.length, window.length, n);
+ for (let i = 0; i < m; i++) re[i] = frame[i] * window[i];
+ fft.transform(re, im);
+ const out = new Float64Array(n / 2 + 1);
+ for (let k = 0; k <= n / 2; k++) out[k] = 10 * Math.log10(re[k] * re[k] + im[k] * im[k] + 1e-30);
+ return out;
+}
+
+export function nextPow2(x: number): number {
+ let n = 1;
+ while (n < x) n <<= 1;
+ return n;
+}
diff --git a/src/engine/analysis/lpc.ts b/src/engine/analysis/lpc.ts
new file mode 100644
index 0000000..051f64f
--- /dev/null
+++ b/src/engine/analysis/lpc.ts
@@ -0,0 +1,136 @@
+/**
+ * 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
new file mode 100644
index 0000000..9977974
--- /dev/null
+++ b/src/engine/analysis/pitch.ts
@@ -0,0 +1,56 @@
+/**
+ * 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
new file mode 100644
index 0000000..b6e2226
--- /dev/null
+++ b/src/engine/anatomy/geom.ts
@@ -0,0 +1,135 @@
+/** 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 ax = xs[i], ay = ys[i];
+ const ex = xs[i + 1] - ax, ey = ys[i + 1] - ay;
+ const den = dx * ey - dy * ex;
+ if (Math.abs(den) < 1e-12) continue;
+ const wx = ax - ox, wy = ay - oy;
+ const t = (wx * ey - wy * ex) / den;
+ const u = (wx * dy - wy * dx) / den;
+ if (u >= 0 && u < 1 && t >= tMin && t <= tMax) out[n++] = t;
+ }
+ 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
new file mode 100644
index 0000000..e0aa93a
--- /dev/null
+++ b/src/engine/anatomy/human.ts
@@ -0,0 +1,503 @@
+/**
+ * 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, bezier3, bezier2, arc, catmullRom, tangentAngle, dist, norm } from "./geom.ts";
+import { clamp, lerp } 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,
+ 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)
+}
+
+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;
+
+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);
+ /** 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 };
+ }
+
+ 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);
+ }
+ const uvula = vel[vel.length - 1];
+
+ // ---- outer contour: pharyngeal wall up to uvula height, then velum oral surface (tip→PNS), palate, incisors, upper lip
+ const outer = new Polyline();
+ const uvY = uvula.y;
+ for (const p of this.pharWall) {
+ if (p.y < uvY) outer.push(p);
+ }
+ // bridge to the uvula tip (velopharyngeal port window)
+ for (let i = velOral.length - 1; i >= 0; i--) outer.push(velOral[i]);
+ outer.append(this.palate, true);
+ // 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;
+ const arcPts = arc(B, r, thB, thF, Math.max(6, Math.round(((thB - thF) / DEG) / 6)));
+ 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): pull the middle of the blade/body down
+ const blade = bezier2(pF, ctrl, T, 7);
+ if (a.dorsum > 0) {
+ for (let i = 0; i < arcPts.length; i++) {
+ const t = i / (arcPts.length - 1);
+ const w = Math.sin(Math.min(1, t * 1.3) * Math.PI);
+ arcPts[i] = add(arcPts[i], v(0, -a.dorsum * 0.9 * k * w * w));
+ }
+ }
+ // 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);
+
+ const inner = new Polyline();
+ inner.push(epiBase).push(epiTip).push(vallecula);
+ inner.append(root, true);
+ inner.append(arcPts, 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;
+ const measure = (o: Vec, dir: Vec, maxLen: number): { 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]);
+ const nIn = rayPolyline(o.x, o.y, dir.x, dir.y, inner, 0, tOut + 1.5 * k, tmp);
+ let 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, 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);
+ 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, 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, region: 3 });
+ }
+
+ // ---- 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 k2 = this.k * this.k;
+ const u = s / epiLen;
+ const vent = 1 - 0.75 * clamp(a.ventricular, 0, 1);
+ if (u < 0.3) return 1.3 * k2; // laryngeal ventricle
+ if (u < 0.5) return 0.95 * k2 * vent; // ventricular folds
+ const top = lerp(1.9, 0.35, clamp(a.epilarynx, 0, 1)) * k2;
+ return lerp(1.2 * k2, top, (u - 0.5) / 0.5);
+ }
+
+ /**
+ * 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): { phLen: number; orLen: number } {
+ const epiLen = 2.4 * this.k * this.body.pharynx;
+ const g = f.grid;
+ const areaAt = (s: number): number => {
+ if (s <= epiLen) return this.epilarynxArea(a, s, epiLen);
+ if (s <= g[0].s) return lerp(this.epilarynxArea(a, epiLen, epiLen), g[0].area, (s - epiLen) / Math.max(1e-6, g[0].s - epiLen));
+ // 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) => {
+ const d = (s1 - s0) / n;
+ const sub = 8;
+ for (let i = 0; i < n; i++) {
+ let inv = 0;
+ let closed = false;
+ for (let j = 0; j < sub; j++) {
+ const A = areaAt(s0 + d * (i + (j + 0.5) / sub));
+ if (A <= 1e-5) {
+ closed = true;
+ break;
+ }
+ inv += 1 / A;
+ }
+ out[i] = closed ? 0 : sub / inv;
+ }
+ };
+ const sp = f.pharynxLength;
+ fill(0, sp, nPh, outPh);
+ fill(sp, f.lipS, nOr, outOr);
+ return { phLen: sp, orLen: f.lipS - sp };
+ }
+}
diff --git a/src/engine/phonetics/vowelData.ts b/src/engine/phonetics/vowelData.ts
new file mode 100644
index 0000000..7c2e336
--- /dev/null
+++ b/src/engine/phonetics/vowelData.ts
@@ -0,0 +1,51 @@
+/**
+ * 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
new file mode 100644
index 0000000..14666ae
--- /dev/null
+++ b/src/engine/phonetics/vowelTargets.generated.json
@@ -0,0 +1,2031 @@
+{
+ "male": {
+ "i": {
+ "artic": {
+ "tbX": 3.713,
+ "tbY": 7.752,
+ "jaw": 0.409,
+ "lipAp": 1.02,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": 0.584,
+ "larynx": 0.734,
+ "ttX": 6.555,
+ "ttY": 7.297,
+ "ttCurl": 0
+ },
+ "formants": [
+ 338,
+ 2237,
+ 2930,
+ 3878
+ ],
+ "target": [
+ 342,
+ 2322,
+ 3000
+ ],
+ "err": [
+ -1.3,
+ -3.7,
+ -2.3
+ ]
+ },
+ "ɪ": {
+ "artic": {
+ "tbX": 3.748,
+ "tbY": 7.347,
+ "jaw": 0.574,
+ "lipAp": 1.14,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": 0.083,
+ "larynx": 0.234,
+ "ttX": 6.506,
+ "ttY": 7.007,
+ "ttCurl": 0
+ },
+ "formants": [
+ 424,
+ 2014,
+ 2632,
+ 3728
+ ],
+ "target": [
+ 427,
+ 2034,
+ 2684
+ ],
+ "err": [
+ -0.7,
+ -1,
+ -1.9
+ ]
+ },
+ "e": {
+ "artic": {
+ "tbX": 3.625,
+ "tbY": 7.232,
+ "jaw": 0.825,
+ "lipAp": 1.346,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": 0.114,
+ "larynx": 0.592,
+ "ttX": 6.372,
+ "ttY": 6.745,
+ "ttCurl": 0
+ },
+ "formants": [
+ 467,
+ 2014,
+ 2602,
+ 3790
+ ],
+ "target": [
+ 476,
+ 2089,
+ 2691
+ ],
+ "err": [
+ -1.9,
+ -3.6,
+ -3.3
+ ]
+ },
+ "ɛ": {
+ "artic": {
+ "tbX": 3.912,
+ "tbY": 5.899,
+ "jaw": 1.073,
+ "lipAp": 1.509,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.03,
+ "larynx": 0.107,
+ "ttX": 6.357,
+ "ttY": 6.064,
+ "ttCurl": 0.001
+ },
+ "formants": [
+ 578,
+ 1778,
+ 2655,
+ 3811
+ ],
+ "target": [
+ 580,
+ 1799,
+ 2605
+ ],
+ "err": [
+ -0.3,
+ -1.2,
+ 1.9
+ ]
+ },
+ "æ": {
+ "artic": {
+ "tbX": 3.382,
+ "tbY": 5.995,
+ "jaw": 1.503,
+ "lipAp": 1.841,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.1,
+ "larynx": 0.212,
+ "ttX": 6.011,
+ "ttY": 5.727,
+ "ttCurl": 0
+ },
+ "formants": [
+ 632,
+ 1714,
+ 2583,
+ 3790
+ ],
+ "target": [
+ 640,
+ 1760,
+ 2500
+ ],
+ "err": [
+ -1.2,
+ -2.6,
+ 3.3
+ ]
+ },
+ "a": {
+ "artic": {
+ "tbX": 2.19,
+ "tbY": 5.661,
+ "jaw": 1.808,
+ "lipAp": 2,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.479,
+ "larynx": 0.336,
+ "ttX": 5.511,
+ "ttY": 5.352,
+ "ttCurl": 0
+ },
+ "formants": [
+ 751,
+ 1435,
+ 2540,
+ 3971
+ ],
+ "target": [
+ 780,
+ 1450,
+ 2550
+ ],
+ "err": [
+ -3.7,
+ -1.1,
+ -0.4
+ ]
+ },
+ "ɑ": {
+ "artic": {
+ "tbX": 1.949,
+ "tbY": 5.713,
+ "jaw": 1.751,
+ "lipAp": 2,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.428,
+ "larynx": 0.19,
+ "ttX": 5.466,
+ "ttY": 5.418,
+ "ttCurl": 0
+ },
+ "formants": [
+ 755,
+ 1331,
+ 2537,
+ 3922
+ ],
+ "target": [
+ 768,
+ 1333,
+ 2522
+ ],
+ "err": [
+ -1.7,
+ -0.2,
+ 0.6
+ ]
+ },
+ "ɒ": {
+ "artic": {
+ "tbX": 1.308,
+ "tbY": 5.809,
+ "jaw": 1.573,
+ "lipAp": 0.932,
+ "lipProt": 0.586,
+ "lipWidth": 0.454,
+ "root": -0.187,
+ "larynx": 0.026,
+ "ttX": 5.357,
+ "ttY": 5.602,
+ "ttCurl": 0
+ },
+ "formants": [
+ 615,
+ 884,
+ 2527,
+ 3915
+ ],
+ "target": [
+ 620,
+ 880,
+ 2500
+ ],
+ "err": [
+ -0.7,
+ 0.5,
+ 1.1
+ ]
+ },
+ "ɔ": {
+ "artic": {
+ "tbX": 1.476,
+ "tbY": 5.76,
+ "jaw": 1.254,
+ "lipAp": 0.775,
+ "lipProt": 0.326,
+ "lipWidth": 0.488,
+ "root": -0.22,
+ "larynx": 0.063,
+ "ttX": 5.55,
+ "ttY": 5.857,
+ "ttCurl": 0
+ },
+ "formants": [
+ 643,
+ 999,
+ 2520,
+ 3933
+ ],
+ "target": [
+ 652,
+ 997,
+ 2538
+ ],
+ "err": [
+ -1.3,
+ 0.2,
+ -0.7
+ ]
+ },
+ "o": {
+ "artic": {
+ "tbX": 1.457,
+ "tbY": 5.707,
+ "jaw": 0.725,
+ "lipAp": 0.535,
+ "lipProt": 1.156,
+ "lipWidth": 0.133,
+ "root": 0,
+ "larynx": 0,
+ "ttX": 5.761,
+ "ttY": 6.3,
+ "ttCurl": 0
+ },
+ "formants": [
+ 497,
+ 910,
+ 2459,
+ 3914
+ ],
+ "target": [
+ 497,
+ 910,
+ 2459
+ ],
+ "err": [
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "ʊ": {
+ "artic": {
+ "tbX": 1.839,
+ "tbY": 5.697,
+ "jaw": 0.5,
+ "lipAp": 0.357,
+ "lipProt": 0.703,
+ "lipWidth": 0.012,
+ "root": 0,
+ "larynx": 0,
+ "ttX": 5.96,
+ "ttY": 6.496,
+ "ttCurl": 0
+ },
+ "formants": [
+ 469,
+ 1122,
+ 2434,
+ 3877
+ ],
+ "target": [
+ 469,
+ 1122,
+ 2434
+ ],
+ "err": [
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "u": {
+ "artic": {
+ "tbX": 2.602,
+ "tbY": 7.348,
+ "jaw": 0.205,
+ "lipAp": 0.12,
+ "lipProt": 1.4,
+ "lipWidth": 0,
+ "root": 0.436,
+ "larynx": 0.281,
+ "ttX": 6.293,
+ "ttY": 7.338,
+ "ttCurl": 0
+ },
+ "formants": [
+ 378,
+ 998,
+ 2260,
+ 3696
+ ],
+ "target": [
+ 378,
+ 997,
+ 2343
+ ],
+ "err": [
+ 0,
+ 0.1,
+ -3.5
+ ]
+ },
+ "ʌ": {
+ "artic": {
+ "tbX": 1.396,
+ "tbY": 6.473,
+ "jaw": 1.192,
+ "lipAp": 1.627,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": 0.307,
+ "larynx": 0.004,
+ "ttX": 5.552,
+ "ttY": 6.165,
+ "ttCurl": 0.003
+ },
+ "formants": [
+ 628,
+ 1181,
+ 2394,
+ 3794
+ ],
+ "target": [
+ 623,
+ 1200,
+ 2550
+ ],
+ "err": [
+ 0.8,
+ -1.6,
+ -6.1
+ ]
+ },
+ "ə": {
+ "artic": {
+ "tbX": 2.575,
+ "tbY": 7.153,
+ "jaw": 0.848,
+ "lipAp": 0.626,
+ "lipProt": 0.357,
+ "lipWidth": 0.541,
+ "root": 0.533,
+ "larynx": 0.365,
+ "ttX": 6.048,
+ "ttY": 6.698,
+ "ttCurl": 0
+ },
+ "formants": [
+ 501,
+ 1455,
+ 2308,
+ 3682
+ ],
+ "target": [
+ 500,
+ 1450,
+ 2450
+ ],
+ "err": [
+ 0.3,
+ 0.3,
+ -5.8
+ ]
+ },
+ "ɐ": {
+ "artic": {
+ "tbX": 2.24,
+ "tbY": 5.522,
+ "jaw": 1.35,
+ "lipAp": 1.006,
+ "lipProt": 0.355,
+ "lipWidth": 0.542,
+ "root": 0.007,
+ "larynx": -0.02,
+ "ttX": 5.737,
+ "ttY": 5.691,
+ "ttCurl": 0
+ },
+ "formants": [
+ 641,
+ 1351,
+ 2504,
+ 3875
+ ],
+ "target": [
+ 640,
+ 1350,
+ 2500
+ ],
+ "err": [
+ 0.2,
+ 0.1,
+ 0.1
+ ]
+ },
+ "ɝ": {
+ "artic": {
+ "tbX": 2.194,
+ "tbY": 7.146,
+ "jaw": 0.468,
+ "lipAp": 0.656,
+ "lipProt": 0.545,
+ "lipWidth": 0.39,
+ "root": -0.9,
+ "larynx": -0.653,
+ "ttX": 5.678,
+ "ttY": 9.032,
+ "ttCurl": 1
+ },
+ "formants": [
+ 467,
+ 1347,
+ 1783,
+ 2877
+ ],
+ "target": [
+ 474,
+ 1379,
+ 1710
+ ],
+ "err": [
+ -1.4,
+ -2.3,
+ 4.3
+ ]
+ },
+ "y": {
+ "artic": {
+ "tbX": 3.454,
+ "tbY": 7.858,
+ "jaw": 0.2,
+ "lipAp": 0.124,
+ "lipProt": 0.903,
+ "lipWidth": 0.204,
+ "root": 0.014,
+ "larynx": 0.007,
+ "ttX": 6.55,
+ "ttY": 7.522,
+ "ttCurl": 0
+ },
+ "formants": [
+ 300,
+ 1800,
+ 2147,
+ 3711
+ ],
+ "target": [
+ 300,
+ 1800,
+ 2150
+ ],
+ "err": [
+ 0,
+ 0,
+ -0.2
+ ]
+ },
+ "ø": {
+ "artic": {
+ "tbX": 3.664,
+ "tbY": 6.958,
+ "jaw": 0.65,
+ "lipAp": 0.167,
+ "lipProt": 1.265,
+ "lipWidth": 0.028,
+ "root": 0,
+ "larynx": 0,
+ "ttX": 6.452,
+ "ttY": 6.804,
+ "ttCurl": 0
+ },
+ "formants": [
+ 390,
+ 1550,
+ 2250,
+ 3342
+ ],
+ "target": [
+ 390,
+ 1550,
+ 2250
+ ],
+ "err": [
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "œ": {
+ "artic": {
+ "tbX": 3.048,
+ "tbY": 6.082,
+ "jaw": 1.025,
+ "lipAp": 0.568,
+ "lipProt": 0.881,
+ "lipWidth": 0.25,
+ "root": 0,
+ "larynx": 0,
+ "ttX": 6.118,
+ "ttY": 6.168,
+ "ttCurl": 0
+ },
+ "formants": [
+ 520,
+ 1450,
+ 2350,
+ 3577
+ ],
+ "target": [
+ 520,
+ 1450,
+ 2350
+ ],
+ "err": [
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "ɨ": {
+ "artic": {
+ "tbX": 3.005,
+ "tbY": 7.654,
+ "jaw": 0.05,
+ "lipAp": 0.12,
+ "lipProt": 0.364,
+ "lipWidth": 0.502,
+ "root": 0.883,
+ "larynx": 0.174,
+ "ttX": 6.465,
+ "ttY": 7.586,
+ "ttCurl": 0
+ },
+ "formants": [
+ 335,
+ 1620,
+ 2296,
+ 3655
+ ],
+ "target": [
+ 330,
+ 1600,
+ 2400
+ ],
+ "err": [
+ 1.5,
+ 1.3,
+ -4.3
+ ]
+ },
+ "ɯ": {
+ "artic": {
+ "tbX": 2.75,
+ "tbY": 7.486,
+ "jaw": 0.05,
+ "lipAp": 0.12,
+ "lipProt": 0.356,
+ "lipWidth": 0.405,
+ "root": 0.9,
+ "larynx": -0.03,
+ "ttX": 6.389,
+ "ttY": 7.527,
+ "ttCurl": 0
+ },
+ "formants": [
+ 357,
+ 1388,
+ 2249,
+ 3568
+ ],
+ "target": [
+ 340,
+ 1350,
+ 2400
+ ],
+ "err": [
+ 5,
+ 2.8,
+ -6.3
+ ]
+ },
+ "ɤ": {
+ "artic": {
+ "tbX": 2.243,
+ "tbY": 7.17,
+ "jaw": 0.438,
+ "lipAp": 0.288,
+ "lipProt": 0.37,
+ "lipWidth": 0.522,
+ "root": 0.66,
+ "larynx": 0.431,
+ "ttX": 6.104,
+ "ttY": 7.067,
+ "ttCurl": 0
+ },
+ "formants": [
+ 461,
+ 1259,
+ 2284,
+ 3726
+ ],
+ "target": [
+ 460,
+ 1250,
+ 2450
+ ],
+ "err": [
+ 0.2,
+ 0.7,
+ -6.8
+ ]
+ }
+ },
+ "female": {
+ "i": {
+ "artic": {
+ "tbX": 3.787,
+ "tbY": 7.646,
+ "jaw": 0.52,
+ "lipAp": 1.116,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": 0.296,
+ "larynx": 0.874,
+ "ttX": 6.537,
+ "ttY": 7.16,
+ "ttCurl": 0
+ },
+ "formants": [
+ 427,
+ 2630,
+ 3222,
+ 4501
+ ],
+ "target": [
+ 437,
+ 2761,
+ 3372
+ ],
+ "err": [
+ -2.2,
+ -4.7,
+ -4.5
+ ]
+ },
+ "ɪ": {
+ "artic": {
+ "tbX": 3.793,
+ "tbY": 7.348,
+ "jaw": 0.551,
+ "lipAp": 1.118,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": 0.023,
+ "larynx": 0.116,
+ "ttX": 6.528,
+ "ttY": 7.028,
+ "ttCurl": 0
+ },
+ "formants": [
+ 481,
+ 2348,
+ 3030,
+ 4345
+ ],
+ "target": [
+ 483,
+ 2365,
+ 3053
+ ],
+ "err": [
+ -0.3,
+ -0.7,
+ -0.8
+ ]
+ },
+ "e": {
+ "artic": {
+ "tbX": 3.602,
+ "tbY": 7.381,
+ "jaw": 0.897,
+ "lipAp": 1.406,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": 0.103,
+ "larynx": 0.729,
+ "ttX": 6.337,
+ "ttY": 6.734,
+ "ttCurl": 0
+ },
+ "formants": [
+ 522,
+ 2406,
+ 3000,
+ 4444
+ ],
+ "target": [
+ 536,
+ 2530,
+ 3047
+ ],
+ "err": [
+ -2.7,
+ -4.9,
+ -1.5
+ ]
+ },
+ "ɛ": {
+ "artic": {
+ "tbX": 3.357,
+ "tbY": 5.587,
+ "jaw": 1.179,
+ "lipAp": 1.602,
+ "lipProt": 0.002,
+ "lipWidth": 0.997,
+ "root": -0.045,
+ "larynx": 0.263,
+ "ttX": 6.146,
+ "ttY": 5.861,
+ "ttCurl": 0
+ },
+ "formants": [
+ 726,
+ 2027,
+ 3046,
+ 4519
+ ],
+ "target": [
+ 731,
+ 2058,
+ 2979
+ ],
+ "err": [
+ -0.7,
+ -1.5,
+ 2.3
+ ]
+ },
+ "æ": {
+ "artic": {
+ "tbX": 4.337,
+ "tbY": 5.237,
+ "jaw": 1.49,
+ "lipAp": 1.823,
+ "lipProt": 0.071,
+ "lipWidth": 1,
+ "root": -0.271,
+ "larynx": 0.477,
+ "ttX": 6.304,
+ "ttY": 5.472,
+ "ttCurl": 0
+ },
+ "formants": [
+ 665,
+ 2249,
+ 3232,
+ 4479
+ ],
+ "target": [
+ 669,
+ 2349,
+ 2972
+ ],
+ "err": [
+ -0.5,
+ -4.3,
+ 8.8
+ ]
+ },
+ "a": {
+ "artic": {
+ "tbX": 1.972,
+ "tbY": 5.52,
+ "jaw": 1.798,
+ "lipAp": 2,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.656,
+ "larynx": 0.713,
+ "ttX": 5.45,
+ "ttY": 5.312,
+ "ttCurl": 0.001
+ },
+ "formants": [
+ 875,
+ 1722,
+ 2936,
+ 4295
+ ],
+ "target": [
+ 913,
+ 1740,
+ 2933
+ ],
+ "err": [
+ -4.1,
+ -1,
+ 0.1
+ ]
+ },
+ "ɑ": {
+ "artic": {
+ "tbX": 1.796,
+ "tbY": 5.91,
+ "jaw": 1.828,
+ "lipAp": 2,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.639,
+ "larynx": 0.471,
+ "ttX": 5.383,
+ "ttY": 5.423,
+ "ttCurl": 0
+ },
+ "formants": [
+ 880,
+ 1541,
+ 2802,
+ 4488
+ ],
+ "target": [
+ 936,
+ 1551,
+ 2815
+ ],
+ "err": [
+ -6,
+ -0.6,
+ -0.4
+ ]
+ },
+ "ɒ": {
+ "artic": {
+ "tbX": 1.286,
+ "tbY": 5.607,
+ "jaw": 1.568,
+ "lipAp": 0.934,
+ "lipProt": 0.344,
+ "lipWidth": 0.46,
+ "root": -0.09,
+ "larynx": 0.055,
+ "ttX": 5.353,
+ "ttY": 5.535,
+ "ttCurl": 0
+ },
+ "formants": [
+ 722,
+ 1057,
+ 2880
+ ],
+ "target": [
+ 725,
+ 1056,
+ 2875
+ ],
+ "err": [
+ -0.4,
+ 0.1,
+ 0.2
+ ]
+ },
+ "ɔ": {
+ "artic": {
+ "tbX": 1.325,
+ "tbY": 5.966,
+ "jaw": 1.333,
+ "lipAp": 0.799,
+ "lipProt": 0.297,
+ "lipWidth": 0.522,
+ "root": -0.386,
+ "larynx": 0.363,
+ "ttX": 5.47,
+ "ttY": 5.861,
+ "ttCurl": 0
+ },
+ "formants": [
+ 757,
+ 1143,
+ 2784,
+ 4504
+ ],
+ "target": [
+ 781,
+ 1136,
+ 2824
+ ],
+ "err": [
+ -3.1,
+ 0.6,
+ -1.4
+ ]
+ },
+ "o": {
+ "artic": {
+ "tbX": 1.846,
+ "tbY": 7.032,
+ "jaw": 0.872,
+ "lipAp": 0.254,
+ "lipProt": 1.035,
+ "lipWidth": 0.072,
+ "root": 0.279,
+ "larynx": 0.527,
+ "ttX": 5.82,
+ "ttY": 6.634,
+ "ttCurl": 0
+ },
+ "formants": [
+ 550,
+ 1046,
+ 2643,
+ 4360
+ ],
+ "target": [
+ 555,
+ 1035,
+ 2828
+ ],
+ "err": [
+ -1,
+ 1,
+ -6.5
+ ]
+ },
+ "ʊ": {
+ "artic": {
+ "tbX": 2.378,
+ "tbY": 7.148,
+ "jaw": 0.533,
+ "lipAp": 0.44,
+ "lipProt": 1.4,
+ "lipWidth": 0.135,
+ "root": 0.309,
+ "larynx": 0.29,
+ "ttX": 6.109,
+ "ttY": 6.976,
+ "ttCurl": 0.001
+ },
+ "formants": [
+ 518,
+ 1228,
+ 2699,
+ 4293
+ ],
+ "target": [
+ 519,
+ 1225,
+ 2827
+ ],
+ "err": [
+ -0.2,
+ 0.2,
+ -4.5
+ ]
+ },
+ "u": {
+ "artic": {
+ "tbX": 2.368,
+ "tbY": 7.239,
+ "jaw": 0.231,
+ "lipAp": 0.12,
+ "lipProt": 1.4,
+ "lipWidth": 0.059,
+ "root": 0.222,
+ "larynx": 0.176,
+ "ttX": 6.214,
+ "ttY": 7.276,
+ "ttCurl": 0
+ },
+ "formants": [
+ 458,
+ 1106,
+ 2658,
+ 4359
+ ],
+ "target": [
+ 459,
+ 1105,
+ 2735
+ ],
+ "err": [
+ -0.1,
+ 0.1,
+ -2.8
+ ]
+ },
+ "ʌ": {
+ "artic": {
+ "tbX": 1.747,
+ "tbY": 5.29,
+ "jaw": 1.1,
+ "lipAp": 1.053,
+ "lipProt": 0.125,
+ "lipWidth": 0.671,
+ "root": 0,
+ "larynx": 0,
+ "ttX": 5.697,
+ "ttY": 5.825,
+ "ttCurl": 0
+ },
+ "formants": [
+ 753,
+ 1426,
+ 2933,
+ 4571
+ ],
+ "target": [
+ 753,
+ 1426,
+ 2933
+ ],
+ "err": [
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "ə": {
+ "artic": {
+ "tbX": 2.829,
+ "tbY": 7.14,
+ "jaw": 0.893,
+ "lipAp": 0.666,
+ "lipProt": 0.353,
+ "lipWidth": 0.546,
+ "root": 0.247,
+ "larynx": 0.199,
+ "ttX": 6.106,
+ "ttY": 6.654,
+ "ttCurl": 0
+ },
+ "formants": [
+ 586,
+ 1743,
+ 2728,
+ 4260
+ ],
+ "target": [
+ 585,
+ 1740,
+ 2818
+ ],
+ "err": [
+ 0.1,
+ 0.2,
+ -3.2
+ ]
+ },
+ "ɐ": {
+ "artic": {
+ "tbX": 2.164,
+ "tbY": 5.414,
+ "jaw": 1.4,
+ "lipAp": 1.359,
+ "lipProt": 0.256,
+ "lipWidth": 0.563,
+ "root": 0,
+ "larynx": 0,
+ "ttX": 5.692,
+ "ttY": 5.61,
+ "ttCurl": 0
+ },
+ "formants": [
+ 749,
+ 1620,
+ 2875
+ ],
+ "target": [
+ 749,
+ 1620,
+ 2875
+ ],
+ "err": [
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "ɝ": {
+ "artic": {
+ "tbX": 2.794,
+ "tbY": 7.352,
+ "jaw": 0.958,
+ "lipAp": 0.64,
+ "lipProt": 0.572,
+ "lipWidth": 0.356,
+ "root": -0.9,
+ "larynx": -0.841,
+ "ttX": 5.67,
+ "ttY": 8.671,
+ "ttCurl": 1
+ },
+ "formants": [
+ 514,
+ 1566,
+ 2183,
+ 3440
+ ],
+ "target": [
+ 523,
+ 1588,
+ 1929
+ ],
+ "err": [
+ -1.8,
+ -1.4,
+ 13.2
+ ]
+ },
+ "y": {
+ "artic": {
+ "tbX": 3.525,
+ "tbY": 7.873,
+ "jaw": 0.222,
+ "lipAp": 0.3,
+ "lipProt": 1.006,
+ "lipWidth": 0.301,
+ "root": -0.293,
+ "larynx": -0.139,
+ "ttX": 6.564,
+ "ttY": 7.507,
+ "ttCurl": 0
+ },
+ "formants": [
+ 351,
+ 2159,
+ 2527,
+ 4346
+ ],
+ "target": [
+ 351,
+ 2160,
+ 2473
+ ],
+ "err": [
+ -0.1,
+ -0.1,
+ 2.2
+ ]
+ },
+ "ø": {
+ "artic": {
+ "tbX": 3.246,
+ "tbY": 7.564,
+ "jaw": 0.656,
+ "lipAp": 0.51,
+ "lipProt": 0.766,
+ "lipWidth": 0.3,
+ "root": -0.065,
+ "larynx": -0.035,
+ "ttX": 6.324,
+ "ttY": 7.011,
+ "ttCurl": 0
+ },
+ "formants": [
+ 456,
+ 1860,
+ 2606,
+ 4172
+ ],
+ "target": [
+ 456,
+ 1860,
+ 2588
+ ],
+ "err": [
+ 0,
+ 0,
+ 0.7
+ ]
+ },
+ "œ": {
+ "artic": {
+ "tbX": 3.105,
+ "tbY": 6.441,
+ "jaw": 1.063,
+ "lipAp": 0.692,
+ "lipProt": 0.592,
+ "lipWidth": 0.318,
+ "root": -0.102,
+ "larynx": -0.002,
+ "ttX": 6.12,
+ "ttY": 6.261,
+ "ttCurl": 0
+ },
+ "formants": [
+ 606,
+ 1734,
+ 2721,
+ 4133
+ ],
+ "target": [
+ 608,
+ 1740,
+ 2703
+ ],
+ "err": [
+ -0.3,
+ -0.4,
+ 0.7
+ ]
+ },
+ "ɨ": {
+ "artic": {
+ "tbX": 3.025,
+ "tbY": 7.738,
+ "jaw": 0.185,
+ "lipAp": 0.138,
+ "lipProt": 0.243,
+ "lipWidth": 0.673,
+ "root": 0.189,
+ "larynx": 0.211,
+ "ttX": 6.427,
+ "ttY": 7.494,
+ "ttCurl": 0
+ },
+ "formants": [
+ 386,
+ 1920,
+ 2713,
+ 4553
+ ],
+ "target": [
+ 386,
+ 1920,
+ 2760
+ ],
+ "err": [
+ 0,
+ 0,
+ -1.7
+ ]
+ },
+ "ɯ": {
+ "artic": {
+ "tbX": 2.861,
+ "tbY": 7.6,
+ "jaw": 0.05,
+ "lipAp": 0.12,
+ "lipProt": 0.401,
+ "lipWidth": 0.489,
+ "root": 0.642,
+ "larynx": 0.024,
+ "ttX": 6.422,
+ "ttY": 7.567,
+ "ttCurl": 0
+ },
+ "formants": [
+ 403,
+ 1642,
+ 2713,
+ 4373
+ ],
+ "target": [
+ 398,
+ 1620,
+ 2760
+ ],
+ "err": [
+ 1.4,
+ 1.4,
+ -1.7
+ ]
+ },
+ "ɤ": {
+ "artic": {
+ "tbX": 2.393,
+ "tbY": 7.254,
+ "jaw": 0.663,
+ "lipAp": 0.487,
+ "lipProt": 0.357,
+ "lipWidth": 0.541,
+ "root": 0.313,
+ "larynx": 0.267,
+ "ttX": 6.065,
+ "ttY": 6.896,
+ "ttCurl": 0
+ },
+ "formants": [
+ 538,
+ 1504,
+ 2700,
+ 4454
+ ],
+ "target": [
+ 538,
+ 1500,
+ 2818
+ ],
+ "err": [
+ 0,
+ 0.3,
+ -4.2
+ ]
+ }
+ },
+ "child": {
+ "i": {
+ "artic": {
+ "tbX": 3.882,
+ "tbY": 7.712,
+ "jaw": 0.159,
+ "lipAp": 0.12,
+ "lipProt": 0.354,
+ "lipWidth": 0.547,
+ "root": 0.027,
+ "larynx": -0.043,
+ "ttX": 6.692,
+ "ttY": 7.509,
+ "ttCurl": 0.001
+ },
+ "formants": [
+ 453,
+ 3091,
+ 3701
+ ],
+ "target": [
+ 452,
+ 3081,
+ 3702
+ ],
+ "err": [
+ 0.2,
+ 0.3,
+ 0
+ ]
+ },
+ "ɪ": {
+ "artic": {
+ "tbX": 2.925,
+ "tbY": 7.705,
+ "jaw": 0.502,
+ "lipAp": 1.077,
+ "lipProt": 0.005,
+ "lipWidth": 1,
+ "root": -0.077,
+ "larynx": -0.046,
+ "ttX": 6.285,
+ "ttY": 7.197,
+ "ttCurl": 0
+ },
+ "formants": [
+ 511,
+ 2552,
+ 3436
+ ],
+ "target": [
+ 511,
+ 2552,
+ 3403
+ ],
+ "err": [
+ 0,
+ 0,
+ 1
+ ]
+ },
+ "e": {
+ "artic": {
+ "tbX": 3.144,
+ "tbY": 7.658,
+ "jaw": 0.668,
+ "lipAp": 1.202,
+ "lipProt": 0.35,
+ "lipWidth": 0.998,
+ "root": -0.209,
+ "larynx": -0.148,
+ "ttX": 6.289,
+ "ttY": 7.033,
+ "ttCurl": 0
+ },
+ "formants": [
+ 564,
+ 2654,
+ 3384
+ ],
+ "target": [
+ 564,
+ 2656,
+ 3323
+ ],
+ "err": [
+ -0.1,
+ -0.1,
+ 1.8
+ ]
+ },
+ "ɛ": {
+ "artic": {
+ "tbX": 2.617,
+ "tbY": 7.227,
+ "jaw": 1.049,
+ "lipAp": 1.488,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.233,
+ "larynx": -0.123,
+ "ttX": 5.979,
+ "ttY": 6.548,
+ "ttCurl": 0
+ },
+ "formants": [
+ 748,
+ 2263,
+ 3368
+ ],
+ "target": [
+ 749,
+ 2267,
+ 3310
+ ],
+ "err": [
+ -0.1,
+ -0.2,
+ 1.8
+ ]
+ },
+ "æ": {
+ "artic": {
+ "tbX": 2.934,
+ "tbY": 7.323,
+ "jaw": 1.43,
+ "lipAp": 1.775,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.346,
+ "larynx": -0.165,
+ "ttX": 5.909,
+ "ttY": 6.252,
+ "ttCurl": 0
+ },
+ "formants": [
+ 716,
+ 2494,
+ 3369
+ ],
+ "target": [
+ 717,
+ 2501,
+ 3289
+ ],
+ "err": [
+ -0.2,
+ -0.3,
+ 2.4
+ ]
+ },
+ "a": {
+ "artic": {
+ "tbX": 1.855,
+ "tbY": 6.601,
+ "jaw": 1.732,
+ "lipAp": 2,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.65,
+ "larynx": 0.006,
+ "ttX": 5.446,
+ "ttY": 5.745,
+ "ttCurl": 0
+ },
+ "formants": [
+ 1009,
+ 1922,
+ 3246
+ ],
+ "target": [
+ 1014,
+ 1929,
+ 3162
+ ],
+ "err": [
+ -0.5,
+ -0.3,
+ 2.7
+ ]
+ },
+ "ɑ": {
+ "artic": {
+ "tbX": 1.437,
+ "tbY": 6.735,
+ "jaw": 1.732,
+ "lipAp": 2,
+ "lipProt": 0.178,
+ "lipWidth": 1,
+ "root": -0.9,
+ "larynx": -0.051,
+ "ttX": 5.321,
+ "ttY": 5.791,
+ "ttCurl": 0
+ },
+ "formants": [
+ 995,
+ 1690,
+ 3013
+ ],
+ "target": [
+ 1002,
+ 1688,
+ 2950
+ ],
+ "err": [
+ -0.7,
+ 0.1,
+ 2.1
+ ]
+ },
+ "ɒ": {
+ "artic": {
+ "tbX": 1.2,
+ "tbY": 6.815,
+ "jaw": 1.702,
+ "lipAp": 0.525,
+ "lipProt": 1.4,
+ "lipWidth": 0.452,
+ "root": -0.429,
+ "larynx": 0.018,
+ "ttX": 5.264,
+ "ttY": 5.845,
+ "ttCurl": 0
+ },
+ "formants": [
+ 789,
+ 1198,
+ 3076
+ ],
+ "target": [
+ 806,
+ 1170,
+ 3100
+ ],
+ "err": [
+ -2.1,
+ 2.4,
+ -0.8
+ ]
+ },
+ "ɔ": {
+ "artic": {
+ "tbX": 1.2,
+ "tbY": 6.887,
+ "jaw": 1.255,
+ "lipAp": 0.727,
+ "lipProt": 1.4,
+ "lipWidth": 0.451,
+ "root": -0.557,
+ "larynx": 0.079,
+ "ttX": 5.467,
+ "ttY": 6.251,
+ "ttCurl": 0
+ },
+ "formants": [
+ 796,
+ 1218,
+ 3005
+ ],
+ "target": [
+ 803,
+ 1210,
+ 2982
+ ],
+ "err": [
+ -0.9,
+ 0.7,
+ 0.8
+ ]
+ },
+ "o": {
+ "artic": {
+ "tbX": 1.685,
+ "tbY": 7.171,
+ "jaw": 0.787,
+ "lipAp": 0.12,
+ "lipProt": 0.988,
+ "lipWidth": 0.261,
+ "root": -0.312,
+ "larynx": -0.11,
+ "ttX": 5.805,
+ "ttY": 6.758,
+ "ttCurl": 0
+ },
+ "formants": [
+ 598,
+ 1137,
+ 3049
+ ],
+ "target": [
+ 597,
+ 1137,
+ 2987
+ ],
+ "err": [
+ 0.1,
+ 0,
+ 2.1
+ ]
+ },
+ "ʊ": {
+ "artic": {
+ "tbX": 2.279,
+ "tbY": 7.367,
+ "jaw": 0.488,
+ "lipAp": 0.442,
+ "lipProt": 0.773,
+ "lipWidth": 0.304,
+ "root": -0.609,
+ "larynx": -0.174,
+ "ttX": 6.096,
+ "ttY": 7.091,
+ "ttCurl": 0
+ },
+ "formants": [
+ 569,
+ 1488,
+ 3130
+ ],
+ "target": [
+ 568,
+ 1490,
+ 3072
+ ],
+ "err": [
+ 0.2,
+ -0.1,
+ 1.9
+ ]
+ },
+ "u": {
+ "artic": {
+ "tbX": 2.425,
+ "tbY": 7.451,
+ "jaw": 0.083,
+ "lipAp": 0.181,
+ "lipProt": 1.356,
+ "lipWidth": 0.301,
+ "root": -0.543,
+ "larynx": -0.434,
+ "ttX": 6.279,
+ "ttY": 7.493,
+ "ttCurl": 0.004
+ },
+ "formants": [
+ 497,
+ 1341,
+ 3097
+ ],
+ "target": [
+ 494,
+ 1345,
+ 2988
+ ],
+ "err": [
+ 0.7,
+ -0.3,
+ 3.7
+ ]
+ },
+ "ʌ": {
+ "artic": {
+ "tbX": 1.573,
+ "tbY": 7.063,
+ "jaw": 1.1,
+ "lipAp": 0.876,
+ "lipProt": 0.337,
+ "lipWidth": 0.588,
+ "root": 0,
+ "larynx": 0,
+ "ttX": 5.645,
+ "ttY": 6.446,
+ "ttCurl": 0
+ },
+ "formants": [
+ 749,
+ 1546,
+ 3145
+ ],
+ "target": [
+ 749,
+ 1546,
+ 3145
+ ],
+ "err": [
+ 0,
+ 0,
+ 0
+ ]
+ },
+ "ə": {
+ "artic": {
+ "tbX": 2.089,
+ "tbY": 7.272,
+ "jaw": 0.968,
+ "lipAp": 1.428,
+ "lipProt": 0.122,
+ "lipWidth": 1,
+ "root": -0.582,
+ "larynx": -0.166,
+ "ttX": 5.854,
+ "ttY": 6.634,
+ "ttCurl": 0
+ },
+ "formants": [
+ 651,
+ 1926,
+ 3098
+ ],
+ "target": [
+ 650,
+ 1929,
+ 3038
+ ],
+ "err": [
+ 0.2,
+ -0.1,
+ 2
+ ]
+ },
+ "ɐ": {
+ "artic": {
+ "tbX": 1.564,
+ "tbY": 7.004,
+ "jaw": 1.418,
+ "lipAp": 1.769,
+ "lipProt": 0,
+ "lipWidth": 1,
+ "root": -0.206,
+ "larynx": -0.04,
+ "ttX": 5.504,
+ "ttY": 6.152,
+ "ttCurl": 0
+ },
+ "formants": [
+ 831,
+ 1790,
+ 3145
+ ],
+ "target": [
+ 832,
+ 1796,
+ 3100
+ ],
+ "err": [
+ -0.1,
+ -0.3,
+ 1.5
+ ]
+ },
+ "ɝ": {
+ "artic": {
+ "tbX": 2.003,
+ "tbY": 7.002,
+ "jaw": 0.053,
+ "lipAp": 0.617,
+ "lipProt": 1.218,
+ "lipWidth": 0.097,
+ "root": -0.9,
+ "larynx": -1.217,
+ "ttX": 5.764,
+ "ttY": 9.355,
+ "ttCurl": 1
+ },
+ "formants": [
+ 608,
+ 1635,
+ 2502,
+ 3708
+ ],
+ "target": [
+ 586,
+ 1719,
+ 2143
+ ],
+ "err": [
+ 3.8,
+ -4.9,
+ 16.7
+ ]
+ },
+ "y": {
+ "artic": {
+ "tbX": 3.447,
+ "tbY": 7.984,
+ "jaw": 0.229,
+ "lipAp": 0.3,
+ "lipProt": 1.17,
+ "lipWidth": 0.302,
+ "root": -0.9,
+ "larynx": -0.759,
+ "ttX": 6.538,
+ "ttY": 7.54,
+ "ttCurl": 0.001
+ },
+ "formants": [
+ 390,
+ 2392,
+ 2924
+ ],
+ "target": [
+ 390,
+ 2394,
+ 2666
+ ],
+ "err": [
+ 0,
+ -0.1,
+ 9.7
+ ]
+ },
+ "ø": {
+ "artic": {
+ "tbX": 2.974,
+ "tbY": 7.736,
+ "jaw": 0.624,
+ "lipAp": 0.519,
+ "lipProt": 0.587,
+ "lipWidth": 0.313,
+ "root": -0.9,
+ "larynx": -0.561,
+ "ttX": 6.253,
+ "ttY": 7.105,
+ "ttCurl": 0.003
+ },
+ "formants": [
+ 507,
+ 2051,
+ 2986
+ ],
+ "target": [
+ 507,
+ 2062,
+ 2790
+ ],
+ "err": [
+ 0,
+ -0.5,
+ 7
+ ]
+ },
+ "œ": {
+ "artic": {
+ "tbX": 2.783,
+ "tbY": 7.347,
+ "jaw": 1.021,
+ "lipAp": 0.693,
+ "lipProt": 0.589,
+ "lipWidth": 0.319,
+ "root": -0.9,
+ "larynx": -0.331,
+ "ttX": 6.04,
+ "ttY": 6.616,
+ "ttCurl": 0.001
+ },
+ "formants": [
+ 675,
+ 1921,
+ 3065
+ ],
+ "target": [
+ 676,
+ 1929,
+ 2914
+ ],
+ "err": [
+ -0.1,
+ -0.4,
+ 5.2
+ ]
+ },
+ "ɨ": {
+ "artic": {
+ "tbX": 2.996,
+ "tbY": 7.83,
+ "jaw": 0.111,
+ "lipAp": 0.12,
+ "lipProt": 0.382,
+ "lipWidth": 0.52,
+ "root": -0.56,
+ "larynx": -0.533,
+ "ttX": 6.442,
+ "ttY": 7.593,
+ "ttCurl": 0
+ },
+ "formants": [
+ 433,
+ 2141,
+ 3113
+ ],
+ "target": [
+ 429,
+ 2128,
+ 2976
+ ],
+ "err": [
+ 1,
+ 0.6,
+ 4.6
+ ]
+ },
+ "ɯ": {
+ "artic": {
+ "tbX": 2.803,
+ "tbY": 7.681,
+ "jaw": 0.168,
+ "lipAp": 0.12,
+ "lipProt": 0.486,
+ "lipWidth": 0.414,
+ "root": 0.007,
+ "larynx": -0.809,
+ "ttX": 6.366,
+ "ttY": 7.489,
+ "ttCurl": 0
+ },
+ "formants": [
+ 455,
+ 1839,
+ 3147
+ ],
+ "target": [
+ 442,
+ 1796,
+ 2976
+ ],
+ "err": [
+ 2.9,
+ 2.4,
+ 5.7
+ ]
+ },
+ "ɤ": {
+ "artic": {
+ "tbX": 2.183,
+ "tbY": 7.312,
+ "jaw": 0.702,
+ "lipAp": 0.522,
+ "lipProt": 0.359,
+ "lipWidth": 0.546,
+ "root": -0.356,
+ "larynx": -0.286,
+ "ttX": 5.986,
+ "ttY": 6.888,
+ "ttCurl": 0.003
+ },
+ "formants": [
+ 601,
+ 1663,
+ 3162
+ ],
+ "target": [
+ 598,
+ 1663,
+ 3038
+ ],
+ "err": [
+ 0.5,
+ 0,
+ 4.1
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/engine/physics.ts b/src/engine/physics.ts
new file mode 100644
index 0000000..5a53dcf
--- /dev/null
+++ b/src/engine/physics.ts
@@ -0,0 +1,36 @@
+/**
+ * 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
new file mode 100644
index 0000000..eef1b91
--- /dev/null
+++ b/src/engine/sources/glottis.ts
@@ -0,0 +1,178 @@
+/**
+ * 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;
+}
+
+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,
+};
+
+export class ParametricGlottis {
+ readonly fs: number;
+ params: GlottisParams = { ...DEFAULT_GLOTTIS };
+ private phase = 0;
+ private cycleAmp = 1;
+ private cyclePeriodScale = 1;
+ private cycleIndex = 0;
+ private vibPhase = 0;
+ private readonly rng = new Rng(777);
+ private readonly drift: Drift;
+ private driftValue = 0;
+ private driftCounter = 0;
+ /** 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;
+
+ constructor(fs: number) {
+ this.fs = fs;
+ this.drift = new Drift(fs / 64, 0.3, 4242);
+ this.dpCoef = 1 - Math.exp(-TAU * 30 / fs);
+ this.voiceCoef = 1 - Math.exp(-TAU * 25 / 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);
+
+ // slow drift updated at a decimated rate
+ if (--this.driftCounter <= 0) {
+ this.driftCounter = 64;
+ this.driftValue = this.drift.step();
+ }
+ this.vibPhase += (P.vibratoRate / 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;
+ let f0 = P.f0 * Math.pow(2, cents / 1200);
+ // 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, P.abduction);
+ const target = pressureGate * adductGate * (1 - P.closure);
+ 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;
+ this.cyclePeriodScale = 1 + P.jitter * this.rng.gauss() + P.diplophonia * 0.08 * alt;
+ this.cyclePeriodScale = clamp(this.cyclePeriodScale, 0.7, 1.4);
+ this.cycleAmp = Math.max(0.2, 1 + P.shimmer * this.rng.gauss() - P.diplophonia * 0.35 * (alt > 0 ? 1 : 0));
+ }
+
+ // 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 vib = P.amplitude * effortScale * this.cycleAmp * this.voicingSm * pulse;
+ const statics = (P.abduction + P.chink) * (1 - 0.92 * P.closure);
+ 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/util/math.ts b/src/engine/util/math.ts
new file mode 100644
index 0000000..dd98f2d
--- /dev/null
+++ b/src/engine/util/math.ts
@@ -0,0 +1,76 @@
+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
new file mode 100644
index 0000000..fe38574
--- /dev/null
+++ b/src/engine/util/optimize.ts
@@ -0,0 +1,62 @@
+/** 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
new file mode 100644
index 0000000..859f512
--- /dev/null
+++ b/src/engine/voice/humanAirway.ts
@@ -0,0 +1,147 @@
+/**
+ * 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";
+
+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;
+ frame: HumanFrame | null = null;
+ phLen = 8.8;
+ orLen = 8.3;
+ /** noise gains (tunable) */
+ noiseGain = { glottis: 2.4e-6, constriction: 3.0e-6, teeth: 9e-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);
+
+ 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)));
+ }
+
+ /** Geometry → targets for the next block. Returns the computed frame. */
+ apply(a: HumanArtic): 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.phLen = phLen;
+ this.orLen = orLen;
+ this.net.setTubeTargets(this.pharynx, this.phAreas, phLen);
+ this.net.setTubeTargets(this.oral, this.orAreas, orLen);
+ 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: 6000, highpassHz: 500 });
+ // 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.phAreas[i] : this.orAreas[i - nPh];
+ if (A > 0 && A < minA) {
+ minA = A;
+ minI = i;
+ }
+ }
+ // also consider closures adjacent to open sections (release bursts): the open neighbour of a zero
+ if (minI >= 0 && minA < 0.8 * this.body.scale * this.body.scale) {
+ 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 fwdI = Math.min(nPh + nOr - 2, minI + off);
+ const bwdI = Math.max(0, minI - off);
+ const fwd = toBranch(fwdI);
+ const bwd = toBranch(bwdI);
+ if (src >= 0 && fwd >= 0 && bwd >= 0) {
+ list.push({ src, fwd, bwd, gain: g.constriction, lowpassHz: 9000, highpassHz: 700 });
+ // obstacle source at the teeth for constrictions 0.3–3 cm behind the incisors
+ const sMin = minI < nPh ? (minI + 0.5) * dxPh : this.phLen + (minI - nPh + 0.5) * dxOr;
+ const behind = f.teethS - sMin;
+ if (behind > 0.3 * this.body.scale && behind < 3.2 * this.body.scale) {
+ 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: bwd, gain: g.teeth * (1 - Math.abs(behind - 1.2) / 3), lowpassHz: 11000, highpassHz: 1800 });
+ }
+ }
+ }
+ this.net.setNoiseSources(list);
+ }
+}
diff --git a/tests/airway.test.ts b/tests/airway.test.ts
new file mode 100644
index 0000000..fb40437
--- /dev/null
+++ b/tests/airway.test.ts
@@ -0,0 +1,88 @@
+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
new file mode 100644
index 0000000..6a73e16
--- /dev/null
+++ b/tests/analysis.test.ts
@@ -0,0 +1,41 @@
+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/tools/build-dict.ts b/tools/build-dict.ts
new file mode 100644
index 0000000..a7d18c5
--- /dev/null
+++ b/tools/build-dict.ts
@@ -0,0 +1,31 @@
+/**
+ * Build the compact pronunciation dictionary shipped to the browser.
+ * Usage: bun tools/build-dict.ts <path/to/cmudict.dict> <path/to/LICENSE>
+ * Output: public/data/cmudict.txt.gz (lines: "word<TAB>PHONES", first pronunciation only)
+ */
+import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
+import { gzipSync } from "node:zlib";
+
+const [dictPath, licensePath] = process.argv.slice(2);
+if (!dictPath || !licensePath) throw new Error("usage: bun tools/build-dict.ts <cmudict.dict> <LICENSE>");
+const lines = readFileSync(dictPath, "utf8").split("\n");
+const out: string[] = [];
+const seen = new Set<string>();
+for (const raw of lines) {
+ const line = raw.split("#")[0].trim();
+ if (!line) continue;
+ const sp = line.indexOf(" ");
+ if (sp < 0) continue;
+ let word = line.slice(0, sp).toLowerCase();
+ const variant = word.match(/\((\d+)\)$/);
+ if (variant) continue; // keep first pronunciation only
+ if (!/^[a-z'][a-z'.\-]*$/.test(word) || seen.has(word)) continue;
+ seen.add(word);
+ const phones = line.slice(sp + 1).trim().split(/\s+/).join(" ");
+ out.push(`${word}\t${phones}`);
+}
+mkdirSync("public/data", { recursive: true });
+const gz = gzipSync(Buffer.from(out.join("\n"), "utf8"), { level: 9 });
+writeFileSync("public/data/cmudict.txt.gz", gz);
+writeFileSync("public/data/CMUDICT-LICENSE.txt", readFileSync(licensePath, "utf8"));
+console.log(`${out.length} words, ${(gz.length / 1024).toFixed(0)} KiB gzipped`);
diff --git a/tools/calibrate-vowels.ts b/tools/calibrate-vowels.ts
new file mode 100644
index 0000000..8c4daf7
--- /dev/null
+++ b/tools/calibrate-vowels.ts
@@ -0,0 +1,114 @@
+/**
+ * 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];
+ 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
new file mode 100644
index 0000000..c408bd4
--- /dev/null
+++ b/tools/draw-anatomy.ts
@@ -0,0 +1,60 @@
+/**
+ * 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/lib/image.ts b/tools/lib/image.ts
new file mode 100644
index 0000000..96b0355
--- /dev/null
+++ b/tools/lib/image.ts
@@ -0,0 +1,190 @@
+import { deflateSync } from "node:zlib";
+import { writeFileSync, mkdirSync } from "node:fs";
+import { dirname } from "node:path";
+
+/** Minimal RGB raster with drawing primitives and a 5x7 bitmap font, encodable as PNG. */
+export class Image {
+ readonly w: number;
+ readonly h: number;
+ readonly data: Uint8Array;
+
+ constructor(w: number, h: number, bg: [number, number, number] = [0, 0, 0]) {
+ this.w = w;
+ this.h = h;
+ this.data = new Uint8Array(w * h * 3);
+ for (let i = 0; i < w * h; i++) {
+ this.data[i * 3] = bg[0];
+ this.data[i * 3 + 1] = bg[1];
+ this.data[i * 3 + 2] = bg[2];
+ }
+ }
+
+ set(x: number, y: number, c: [number, number, number], alpha = 1): void {
+ x = Math.round(x);
+ y = Math.round(y);
+ if (x < 0 || y < 0 || x >= this.w || y >= this.h) return;
+ const i = (y * this.w + x) * 3;
+ if (alpha >= 1) {
+ this.data[i] = c[0];
+ this.data[i + 1] = c[1];
+ this.data[i + 2] = c[2];
+ } else {
+ this.data[i] = Math.round(this.data[i] * (1 - alpha) + c[0] * alpha);
+ this.data[i + 1] = Math.round(this.data[i + 1] * (1 - alpha) + c[1] * alpha);
+ this.data[i + 2] = Math.round(this.data[i + 2] * (1 - alpha) + c[2] * alpha);
+ }
+ }
+
+ rect(x0: number, y0: number, w: number, h: number, c: [number, number, number], alpha = 1): void {
+ for (let y = Math.round(y0); y < Math.round(y0 + h); y++)
+ for (let x = Math.round(x0); x < Math.round(x0 + w); x++) this.set(x, y, c, alpha);
+ }
+
+ line(x0: number, y0: number, x1: number, y1: number, c: [number, number, number], alpha = 1): void {
+ const dx = x1 - x0;
+ const dy = y1 - y0;
+ const steps = Math.max(1, Math.ceil(Math.max(Math.abs(dx), Math.abs(dy))));
+ for (let i = 0; i <= steps; i++) this.set(x0 + (dx * i) / steps, y0 + (dy * i) / steps, c, alpha);
+ }
+
+ text(x: number, y: number, s: string, c: [number, number, number], scale = 1): void {
+ let cx = x;
+ for (const ch of s.toUpperCase()) {
+ const glyph = FONT[ch] ?? FONT["?"];
+ for (let row = 0; row < 7; row++) {
+ const bits = glyph[row];
+ for (let col = 0; col < 5; col++) {
+ if (bits & (1 << (4 - col))) this.rect(cx + col * scale, y + row * scale, scale, scale, c);
+ }
+ }
+ cx += 6 * scale;
+ }
+ }
+
+ savePng(path: string): void {
+ const raw = Buffer.alloc((this.w * 3 + 1) * this.h);
+ for (let y = 0; y < this.h; y++) {
+ raw[y * (this.w * 3 + 1)] = 0;
+ Buffer.from(this.data.buffer, this.data.byteOffset + y * this.w * 3, this.w * 3).copy(raw, y * (this.w * 3 + 1) + 1);
+ }
+ const chunks: Buffer[] = [Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])];
+ const ihdr = Buffer.alloc(13);
+ ihdr.writeUInt32BE(this.w, 0);
+ ihdr.writeUInt32BE(this.h, 4);
+ ihdr[8] = 8; // bit depth
+ ihdr[9] = 2; // RGB
+ ihdr[10] = 0;
+ ihdr[11] = 0;
+ ihdr[12] = 0;
+ chunks.push(chunk("IHDR", ihdr));
+ chunks.push(chunk("IDAT", deflateSync(raw, { level: 6 })));
+ chunks.push(chunk("IEND", Buffer.alloc(0)));
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, Buffer.concat(chunks));
+ }
+}
+
+const CRC_TABLE = (() => {
+ const t = new Uint32Array(256);
+ for (let n = 0; n < 256; n++) {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ t[n] = c >>> 0;
+ }
+ return t;
+})();
+
+function crc32(buf: Buffer): number {
+ let c = 0xffffffff;
+ for (let i = 0; i < buf.length; i++) c = CRC_TABLE[(c ^ buf[i]) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+}
+
+function chunk(type: string, body: Buffer): Buffer {
+ const len = Buffer.alloc(4);
+ len.writeUInt32BE(body.length, 0);
+ const tb = Buffer.from(type, "ascii");
+ const crc = Buffer.alloc(4);
+ crc.writeUInt32BE(crc32(Buffer.concat([tb, body])), 0);
+ return Buffer.concat([len, tb, body, crc]);
+}
+
+/** Perceptual-ish colormap (inferno-like) for t in [0,1]. */
+export function inferno(t: number): [number, number, number] {
+ t = Math.max(0, Math.min(1, t));
+ const stops: [number, number, number, number][] = [
+ [0.0, 0, 0, 4],
+ [0.15, 31, 12, 72],
+ [0.3, 85, 15, 109],
+ [0.45, 136, 34, 106],
+ [0.6, 186, 54, 85],
+ [0.72, 227, 89, 51],
+ [0.85, 249, 140, 10],
+ [0.95, 245, 219, 76],
+ [1.0, 252, 255, 164],
+ ];
+ for (let i = 1; i < stops.length; i++) {
+ if (t <= stops[i][0]) {
+ const a = stops[i - 1];
+ const b = stops[i];
+ const u = (t - a[0]) / (b[0] - a[0]);
+ return [a[1] + (b[1] - a[1]) * u, a[2] + (b[2] - a[2]) * u, a[3] + (b[3] - a[3]) * u].map(Math.round) as [number, number, number];
+ }
+ }
+ return [252, 255, 164];
+}
+
+// 5x7 font, rows top->bottom, 5 bits per row (MSB = leftmost column).
+const FONT: Record<string, number[]> = {
+ "0": [0x0e, 0x11, 0x13, 0x15, 0x19, 0x11, 0x0e],
+ "1": [0x04, 0x0c, 0x04, 0x04, 0x04, 0x04, 0x0e],
+ "2": [0x0e, 0x11, 0x01, 0x02, 0x04, 0x08, 0x1f],
+ "3": [0x1f, 0x02, 0x04, 0x02, 0x01, 0x11, 0x0e],
+ "4": [0x02, 0x06, 0x0a, 0x12, 0x1f, 0x02, 0x02],
+ "5": [0x1f, 0x10, 0x1e, 0x01, 0x01, 0x11, 0x0e],
+ "6": [0x06, 0x08, 0x10, 0x1e, 0x11, 0x11, 0x0e],
+ "7": [0x1f, 0x01, 0x02, 0x04, 0x08, 0x08, 0x08],
+ "8": [0x0e, 0x11, 0x11, 0x0e, 0x11, 0x11, 0x0e],
+ "9": [0x0e, 0x11, 0x11, 0x0f, 0x01, 0x02, 0x0c],
+ A: [0x0e, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11],
+ B: [0x1e, 0x11, 0x11, 0x1e, 0x11, 0x11, 0x1e],
+ C: [0x0e, 0x11, 0x10, 0x10, 0x10, 0x11, 0x0e],
+ D: [0x1c, 0x12, 0x11, 0x11, 0x11, 0x12, 0x1c],
+ E: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x1f],
+ F: [0x1f, 0x10, 0x10, 0x1e, 0x10, 0x10, 0x10],
+ G: [0x0e, 0x11, 0x10, 0x17, 0x11, 0x11, 0x0f],
+ H: [0x11, 0x11, 0x11, 0x1f, 0x11, 0x11, 0x11],
+ I: [0x0e, 0x04, 0x04, 0x04, 0x04, 0x04, 0x0e],
+ J: [0x07, 0x02, 0x02, 0x02, 0x02, 0x12, 0x0c],
+ K: [0x11, 0x12, 0x14, 0x18, 0x14, 0x12, 0x11],
+ L: [0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x1f],
+ M: [0x11, 0x1b, 0x15, 0x15, 0x11, 0x11, 0x11],
+ N: [0x11, 0x11, 0x19, 0x15, 0x13, 0x11, 0x11],
+ O: [0x0e, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e],
+ P: [0x1e, 0x11, 0x11, 0x1e, 0x10, 0x10, 0x10],
+ Q: [0x0e, 0x11, 0x11, 0x11, 0x15, 0x12, 0x0d],
+ R: [0x1e, 0x11, 0x11, 0x1e, 0x14, 0x12, 0x11],
+ S: [0x0f, 0x10, 0x10, 0x0e, 0x01, 0x01, 0x1e],
+ T: [0x1f, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04],
+ U: [0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x0e],
+ V: [0x11, 0x11, 0x11, 0x11, 0x11, 0x0a, 0x04],
+ W: [0x11, 0x11, 0x11, 0x15, 0x15, 0x15, 0x0a],
+ X: [0x11, 0x11, 0x0a, 0x04, 0x0a, 0x11, 0x11],
+ Y: [0x11, 0x11, 0x11, 0x0a, 0x04, 0x04, 0x04],
+ Z: [0x1f, 0x01, 0x02, 0x04, 0x08, 0x10, 0x1f],
+ " ": [0, 0, 0, 0, 0, 0, 0],
+ ".": [0, 0, 0, 0, 0, 0x0c, 0x0c],
+ ",": [0, 0, 0, 0, 0x0c, 0x04, 0x08],
+ "-": [0, 0, 0, 0x1f, 0, 0, 0],
+ "+": [0, 0x04, 0x04, 0x1f, 0x04, 0x04, 0],
+ ":": [0, 0x0c, 0x0c, 0, 0x0c, 0x0c, 0],
+ "/": [0x01, 0x01, 0x02, 0x04, 0x08, 0x10, 0x10],
+ "=": [0, 0, 0x1f, 0, 0x1f, 0, 0],
+ "(": [0x02, 0x04, 0x08, 0x08, 0x08, 0x04, 0x02],
+ ")": [0x08, 0x04, 0x02, 0x02, 0x02, 0x04, 0x08],
+ "%": [0x18, 0x19, 0x02, 0x04, 0x08, 0x13, 0x03],
+ "_": [0, 0, 0, 0, 0, 0, 0x1f],
+ "?": [0x0e, 0x11, 0x01, 0x02, 0x04, 0, 0x04],
+ "#": [0x0a, 0x0a, 0x1f, 0x0a, 0x1f, 0x0a, 0x0a],
+ "'": [0x04, 0x04, 0x08, 0, 0, 0, 0],
+};
diff --git a/tools/lib/spectrogram.ts b/tools/lib/spectrogram.ts
new file mode 100644
index 0000000..b9d4ba3
--- /dev/null
+++ b/tools/lib/spectrogram.ts
@@ -0,0 +1,163 @@
+import { FFT, hann, nextPow2 } from "../../src/engine/analysis/fft.ts";
+import { Image, inferno } from "./image.ts";
+
+export interface SpectrogramOptions {
+ title?: string;
+ maxFreq?: number; // Hz
+ windowMs?: number; // analysis window (5 = wideband/formants, 30 = narrowband/harmonics)
+ hopMs?: number;
+ dynamicRange?: number; // dB
+ width?: number; // px of the plot area (time axis resampled to fit)
+ height?: number; // px of the spectrogram area
+ overlays?: { points: [number, number][]; color: [number, number, number] }[]; // (time s, freq Hz)
+ marks?: { t: number; label: string }[];
+}
+
+/** Render waveform + spectrogram PNG with labelled axes. */
+export function renderSpectrogram(path: string, x: ArrayLike<number>, sr: number, opts: SpectrogramOptions = {}): void {
+ const maxFreq = Math.min(opts.maxFreq ?? 8000, sr / 2);
+ const winMs = opts.windowMs ?? 6;
+ const hopMs = opts.hopMs ?? 2;
+ const dr = opts.dynamicRange ?? 75;
+ const win = Math.max(16, Math.round((winMs / 1000) * sr));
+ const hop = Math.max(1, Math.round((hopMs / 1000) * sr));
+ const nfft = nextPow2(Math.max(win * 2, 512));
+ const fft = new FFT(nfft);
+ const w = hann(win);
+ const frames = Math.max(1, Math.floor((x.length - win) / hop) + 1);
+ const bins = Math.floor((maxFreq / sr) * nfft);
+ const spec: Float64Array[] = [];
+ let maxDb = -Infinity;
+ const re = new Float64Array(nfft);
+ const im = new Float64Array(nfft);
+ for (let f = 0; f < frames; f++) {
+ re.fill(0);
+ im.fill(0);
+ const off = f * hop;
+ for (let i = 0; i < win; i++) re[i] = (x[off + i] ?? 0) * w[i];
+ fft.transform(re, im);
+ const col = new Float64Array(bins);
+ for (let k = 0; k < bins; k++) {
+ const v = 10 * Math.log10(re[k] * re[k] + im[k] * im[k] + 1e-20);
+ col[k] = v;
+ if (v > maxDb) maxDb = v;
+ }
+ spec.push(col);
+ }
+ const plotW = opts.width ?? Math.min(1600, Math.max(400, frames));
+ const plotH = opts.height ?? 360;
+ const waveH = 70;
+ const left = 46, top = 22, gap = 6, bottom = 22, right = 10;
+ const img = new Image(left + plotW + right, top + waveH + gap + plotH + bottom, [14, 14, 20]);
+ if (opts.title) img.text(left, 6, opts.title, [230, 230, 230]);
+ // waveform (min/max per column)
+ const spc = x.length / plotW;
+ let peak = 1e-9;
+ for (let i = 0; i < x.length; i++) peak = Math.max(peak, Math.abs(x[i]));
+ img.rect(left, top, plotW, waveH, [24, 24, 32]);
+ for (let px = 0; px < plotW; px++) {
+ let mn = Infinity, mx = -Infinity;
+ const a = Math.floor(px * spc), b = Math.min(x.length, Math.floor((px + 1) * spc) + 1);
+ for (let i = a; i < b; i++) {
+ if (x[i] < mn) mn = x[i];
+ if (x[i] > mx) mx = x[i];
+ }
+ if (!Number.isFinite(mn)) continue;
+ const y0 = top + waveH / 2 - (mx / peak) * (waveH / 2 - 2);
+ const y1 = top + waveH / 2 - (mn / peak) * (waveH / 2 - 2);
+ img.line(left + px, y0, left + px, y1, [120, 200, 255]);
+ }
+ img.text(left + plotW - 90, top + 2, `PK ${peak.toFixed(3)}`, [150, 150, 170]);
+ // spectrogram
+ const sy = top + waveH + gap;
+ for (let px = 0; px < plotW; px++) {
+ const f = Math.min(frames - 1, Math.floor((px / plotW) * frames));
+ const col = spec[f];
+ for (let py = 0; py < plotH; py++) {
+ const k = Math.min(bins - 1, Math.floor(((plotH - 1 - py) / plotH) * bins));
+ const t = (col[k] - (maxDb - dr)) / dr;
+ img.set(left + px, sy + py, inferno(t));
+ }
+ }
+ // freq axis
+ const step = maxFreq > 10000 ? 2000 : maxFreq > 4000 ? 1000 : 500;
+ for (let fr = 0; fr <= maxFreq; fr += step) {
+ const py = sy + plotH - 1 - (fr / maxFreq) * (plotH - 1);
+ img.line(left - 4, py, left - 1, py, [200, 200, 200]);
+ img.text(2, py - 3, fr >= 1000 ? `${(fr / 1000).toFixed(fr % 1000 ? 1 : 0)}K` : `${fr}`, [200, 200, 200]);
+ for (let px = 0; px < plotW; px += 6) img.set(left + px, py, [255, 255, 255], 0.18);
+ }
+ // time axis
+ const dur = x.length / sr;
+ const tStep = dur > 6 ? 1 : dur > 2 ? 0.5 : dur > 0.8 ? 0.2 : 0.1;
+ for (let t = 0; t <= dur + 1e-9; t += tStep) {
+ const px = left + (t / dur) * plotW;
+ img.line(px, sy + plotH, px, sy + plotH + 4, [200, 200, 200]);
+ img.text(px - 8, sy + plotH + 7, t.toFixed(tStep < 0.5 ? 1 : 1), [200, 200, 200]);
+ }
+ for (const ov of opts.overlays ?? []) {
+ for (const [t, fr] of ov.points) {
+ if (fr <= 0 || fr > maxFreq) continue;
+ const px = left + (t / dur) * plotW;
+ const py = sy + plotH - 1 - (fr / maxFreq) * (plotH - 1);
+ img.rect(px - 1, py - 1, 3, 3, ov.color);
+ }
+ }
+ for (const m of opts.marks ?? []) {
+ const px = left + (m.t / dur) * plotW;
+ for (let py = sy; py < sy + plotH; py += 3) img.set(px, py, [255, 255, 255], 0.5);
+ img.text(px + 2, sy + 2, m.label, [255, 255, 255]);
+ }
+ img.savePng(path);
+}
+
+/** Simple line plot of one or more series (e.g. glottal flow). */
+export function renderPlot(
+ path: string,
+ series: { y: ArrayLike<number>; color: [number, number, number]; label?: string }[],
+ opts: { title?: string; width?: number; height?: number; xLabel?: string; xMax?: number; logY?: boolean; yMin?: number; yMax?: number } = {},
+): void {
+ const W = opts.width ?? 900, H = opts.height ?? 300;
+ const left = 60, top = 22, right = 10, bottom = 24;
+ const img = new Image(W, H, [14, 14, 20]);
+ if (opts.title) img.text(left, 6, opts.title, [230, 230, 230]);
+ let mn = opts.yMin ?? Infinity, mx = opts.yMax ?? -Infinity;
+ if (opts.yMin === undefined || opts.yMax === undefined) {
+ for (const s of series) for (let i = 0; i < s.y.length; i++) {
+ const v = s.y[i];
+ if (!Number.isFinite(v)) continue;
+ if (opts.yMin === undefined) mn = Math.min(mn, v);
+ if (opts.yMax === undefined) mx = Math.max(mx, v);
+ }
+ }
+ if (mx - mn < 1e-12) { mx += 1; mn -= 1; }
+ const pw = W - left - right, ph = H - top - bottom;
+ img.rect(left, top, pw, ph, [24, 24, 32]);
+ for (let k = 0; k <= 4; k++) {
+ const v = mn + ((mx - mn) * k) / 4;
+ const py = top + ph - (k / 4) * ph;
+ img.text(2, py - 3, v.toPrecision(3), [180, 180, 190]);
+ for (let px = 0; px < pw; px += 5) img.set(left + px, py, [255, 255, 255], 0.15);
+ }
+ if (opts.xMax !== undefined) {
+ for (let k = 0; k <= 5; k++) {
+ const px = left + (k / 5) * pw;
+ img.text(px - 10, top + ph + 6, ((opts.xMax * k) / 5).toPrecision(3), [180, 180, 190]);
+ }
+ }
+ let ly = top + 4;
+ for (const s of series) {
+ const n = s.y.length;
+ let prev: [number, number] | null = null;
+ for (let i = 0; i < n; i++) {
+ const v = s.y[i];
+ if (!Number.isFinite(v)) { prev = null; continue; }
+ const px = left + (i / Math.max(1, n - 1)) * pw;
+ const py = top + ph - ((v - mn) / (mx - mn)) * ph;
+ if (prev) img.line(prev[0], prev[1], px, py, s.color);
+ prev = [px, py];
+ }
+ if (s.label) { img.text(left + pw - 150, ly, s.label, s.color); ly += 10; }
+ }
+ img.savePng(path);
+}
diff --git a/tools/lib/wav.ts b/tools/lib/wav.ts
new file mode 100644
index 0000000..45bd6fc
--- /dev/null
+++ b/tools/lib/wav.ts
@@ -0,0 +1,69 @@
+import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
+import { dirname } from "node:path";
+
+/** Write mono or stereo 16-bit PCM WAV. Channels are Float32/64 arrays in [-1, 1]. */
+export function writeWav(path: string, channels: ArrayLike<number>[], sampleRate: number): void {
+ const nCh = channels.length;
+ const n = channels[0].length;
+ const bytesPerSample = 2;
+ const dataBytes = n * nCh * bytesPerSample;
+ const buf = Buffer.alloc(44 + dataBytes);
+ buf.write("RIFF", 0);
+ buf.writeUInt32LE(36 + dataBytes, 4);
+ buf.write("WAVE", 8);
+ buf.write("fmt ", 12);
+ buf.writeUInt32LE(16, 16);
+ buf.writeUInt16LE(1, 20);
+ buf.writeUInt16LE(nCh, 22);
+ buf.writeUInt32LE(sampleRate, 24);
+ buf.writeUInt32LE(sampleRate * nCh * bytesPerSample, 28);
+ buf.writeUInt16LE(nCh * bytesPerSample, 32);
+ buf.writeUInt16LE(16, 34);
+ buf.write("data", 36);
+ buf.writeUInt32LE(dataBytes, 40);
+ let o = 44;
+ for (let i = 0; i < n; i++) {
+ for (let c = 0; c < nCh; c++) {
+ let v = channels[c][i];
+ if (!Number.isFinite(v)) v = 0;
+ v = Math.max(-1, Math.min(1, v));
+ buf.writeInt16LE(Math.round(v * 32767), o);
+ o += 2;
+ }
+ }
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, buf);
+}
+
+export function readWav(path: string): { sampleRate: number; channels: Float32Array[] } {
+ const buf = readFileSync(path);
+ if (buf.toString("ascii", 0, 4) !== "RIFF" || buf.toString("ascii", 8, 12) !== "WAVE") throw new Error("not a WAV");
+ let off = 12;
+ let fmt: { ch: number; sr: number; bits: number; format: number } | null = null;
+ while (off + 8 <= buf.length) {
+ const id = buf.toString("ascii", off, off + 4);
+ const size = buf.readUInt32LE(off + 4);
+ const body = off + 8;
+ if (id === "fmt ") {
+ fmt = { format: buf.readUInt16LE(body), ch: buf.readUInt16LE(body + 2), sr: buf.readUInt32LE(body + 4), bits: buf.readUInt16LE(body + 14) };
+ } else if (id === "data" && fmt) {
+ const bps = fmt.bits / 8;
+ const frames = Math.floor(size / (bps * fmt.ch));
+ const channels = Array.from({ length: fmt.ch }, () => new Float32Array(frames));
+ for (let i = 0; i < frames; i++) {
+ for (let c = 0; c < fmt.ch; c++) {
+ const p = body + (i * fmt.ch + c) * bps;
+ let v = 0;
+ if (fmt.format === 3 && fmt.bits === 32) v = buf.readFloatLE(p);
+ else if (fmt.bits === 16) v = buf.readInt16LE(p) / 32768;
+ else if (fmt.bits === 24) v = (buf.readIntLE(p, 3)) / 8388608;
+ else if (fmt.bits === 32) v = buf.readInt32LE(p) / 2147483648;
+ channels[c][i] = v;
+ }
+ }
+ return { sampleRate: fmt.sr, channels };
+ }
+ off = body + size + (size & 1);
+ }
+ throw new Error("no data chunk");
+}
diff --git a/tools/proto-vowel.ts b/tools/proto-vowel.ts
new file mode 100644
index 0000000..5030027
--- /dev/null
+++ b/tools/proto-vowel.ts
@@ -0,0 +1,112 @@
+/**
+ * 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/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..827659a
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,19 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "jsx": "react-jsx",
+ "strict": true,
+ "noImplicitOverride": true,
+ "noFallthroughCasesInSwitch": true,
+ "skipLibCheck": true,
+ "isolatedModules": true,
+ "resolveJsonModule": true,
+ "allowImportingTsExtensions": true,
+ "noEmit": true,
+ "types": ["bun"]
+ },
+ "include": ["src", "tools", "tests"]
+}