the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
The web app runs on the Rust engine (wasm): worklet, UI facade, creatures; tests ported
Jameson Hodgefdf5441fb05b
diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rsindex a2706c3..8a62875 100644--- a/crates/chimera-wasm/src/api.rs+++ b/crates/chimera-wasm/src/api.rs@@ -6,11 +6,13 @@use chimera::airway::frequency::{find_peaks, transfer_function};use chimera::anatomy::human::{BodyName, HumanArtic, HumanFrame};use chimera::control::beat_player::BeatPlayer;+use chimera::creatures::voice::CreatureVoice;use chimera::math;use chimera::phonetics::beatbox::{self, BeatStep};use chimera::phonetics::planner::{self, PhraseInput, PlanOptions};use chimera::phonetics::sing::{self, MelismaOptions, NoteOnOptions, SongOptions, SungNote};-use chimera::phonetics::{Segment, Syllable};+use chimera::phonetics::english::EnglishG2P;+use chimera::phonetics::{Segment, Syllable, ipa, songs, syllables, vowel_data};use chimera::voice::human_airway::HumanAirway;use serde_json::{Value, json};use std::cell::RefCell;@@ -25,6 +27,8 @@ struct Model {struct State {result: Vec<u8>,models: Vec<Model>,+ /// the page's English G2P (one dictionary, loaded once)+ g2p: EnglishG2P,}thread_local! {@@ -102,6 +106,26 @@ fn dispatch(st: &mut State, req: &Value) -> Res {let formants: Vec<f64> = find_peaks(&freqs, &h.mag, 150.0).iter().map(|p| p.freq).take(5).collect();Ok(json!({ "freqs": freqs, "db": db, "formants": formants }))}+ // ---------------------------------------------------------------- text → phonemes+ "tokenizeIpa" => to_json(&ipa::tokenize_ipa(&arg::<String>(req, "text")?)),+ "g2pLoad" => {+ st.g2p.load_dict(&arg::<String>(req, "text")?);+ Ok(json!(true))+ }+ "g2pPhrases" => to_json(&st.g2p.to_phrases(&arg::<String>(req, "text")?)),+ "g2pWord" => to_json(&st.g2p.word(&arg::<String>(req, "word")?, arg::<Option<bool>>(req, "reduce")?.unwrap_or(true))),+ "lyricsToSyllables" => to_json(&syllables::lyrics_to_syllables(&arg::<String>(req, "text")?, &st.g2p)),+ // ---------------------------------------------------------------- creatures+ "creaturePreview" => {+ let id: String = arg(req, "id")?;+ let def = chimera::creatures::creature_by_id(&id).ok_or_else(|| format!("no creature {id}"))?;+ let params: std::collections::BTreeMap<String, f64> = arg::<Option<_>>(req, "params")?.unwrap_or_default();+ let initial: Vec<(usize, f64)> = params.iter().filter_map(|(k, v)| def.param_index(k).map(|i| (i, *v))).collect();+ let mut c = CreatureVoice::new(def, 48000.0, &initial);+ let mut t = c.new_telemetry();+ c.telemetry(&mut t);+ to_json(&t)+ }// ---------------------------------------------------------------- planning (speech, song)"planUtterance" => to_json(&planner::plan_utterance(&arg::<Vec<Segment>>(req, "segments")?, &arg::<PlanOptions>(req, "options")?)),"planPhrases" => to_json(&planner::plan_phrases(&arg::<Vec<PhraseInput>>(req, "phrases")?, &arg::<PlanOptions>(req, "options")?)),@@ -139,9 +163,22 @@ fn catalog() -> Res {"beatSounds": &beatbox::BEAT_SOUNDS[..],"beatPresets": &beatbox::BEAT_PRESETS[..],"vowelTargets": vowels,+ "demoSongs": songs::DEMO_SONGS,+ "vowels": vowel_data::VOWELS,+ "creatures": &chimera::creatures::CREATURES[..],}))}+/// Put a call's result (or error) in the result buffer; 0 on success, 1 on error.+pub(crate) fn set_result(out: Res) -> u32 {+ let (code, v) = match out {+ Ok(v) => (0, v),+ Err(e) => (1, json!({ "error": e })),+ };+ STATE.with(|s| s.borrow_mut().result = serde_json::to_vec(&v).unwrap_or_else(|_| b"{\"error\":\"unserialisable result\"}".to_vec()));+ code+}+/// Run one JSON call (see the module docs). Returns 0 on success, 1 if the result is an error.////// # Safetydiff --git a/crates/chimera-wasm/src/lib.rs b/crates/chimera-wasm/src/lib.rsindex 6c9390e..de7da84 100644--- a/crates/chimera-wasm/src/lib.rs+++ b/crates/chimera-wasm/src/lib.rs@@ -129,6 +129,9 @@ pub struct Handle {tele_block: Vec<f64>,/// active gesture labels: up to 4 × (length byte + 24 bytes)tele_labels: Vec<u8>,+ /// the creature's telemetry (sized when it is chosen) and its flat block+ ctele: Option<chimera::creatures::voice::CreatureTelemetry>,+ ctele_block: Vec<f64>,}fn bodies(i: u32) -> BodyName {@@ -150,6 +153,8 @@ pub extern "C" fn engine_new(sample_rate: f64) -> *mut Handle {tele: VoiceTelemetry::default(),tele_block: Vec::with_capacity(TELE_HEADER + 1024),tele_labels: vec![0u8; 4 * 25],+ ctele: None,+ ctele_block: Vec::new(),});// size every telemetry buffer once, so later snapshots reuse themh.engine.telemetry(&mut h.tele);@@ -450,3 +455,124 @@ pub unsafe extern "C" fn engine_beat_hit(h: *mut Handle) {pub unsafe extern "C" fn engine_beat_step(h: *mut Handle) -> f64 {handle!(h).engine.beat_step() as f64}++// ------------------------------------------------------------------ creatures++/// Switch to a creature: `{"id": …, "params": {name: value}}` as UTF-8 JSON at `ptr..ptr+len`.+/// Allocates (not real-time). The result buffer (`chimera_result_ptr`) receives what the worklet+/// needs to address it by index: `{id, params: [key], calls: [id], tubes: [{name, n}], sources: [key]}`.+/// Returns 0, or 1 with `{error}` (unknown creature: the human voice keeps playing).+///+/// # Safety+/// `h` must be a live handle; `ptr..ptr+len` readable.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_set_creature(h: *mut Handle, ptr: *const u8, len: usize) -> u32 {+ let h = handle!(h);+ let bytes = unsafe { core::slice::from_raw_parts(ptr, len) };+ let req: serde_json::Value = match serde_json::from_slice(bytes) {+ Ok(v) => v,+ Err(e) => return api::set_result(Err(format!("bad request: {e}"))),+ };+ let id = req.get("id").and_then(|v| v.as_str()).unwrap_or("");+ let Some(def) = chimera::creatures::creature_by_id(id) else {+ return api::set_result(Err(format!("no creature {id}")));+ };+ let mut initial = Vec::new();+ if let Some(m) = req.get("params").and_then(|v| v.as_object()) {+ for (k, v) in m {+ if let (Some(i), Some(x)) = (def.param_index(k), v.as_f64()) {+ initial.push((i, x));+ }+ }+ }+ h.engine.set_creature(Some(def), &initial);+ let c = h.engine.creature().unwrap();+ let t = c.new_telemetry();+ let info = serde_json::json!({+ "id": def.id,+ "params": def.params.iter().map(|p| p.key).collect::<Vec<_>>(),+ "calls": def.calls.iter().map(|c| c.id).collect::<Vec<_>>(),+ "tubes": t.tubes.iter().map(|tb| serde_json::json!({ "name": tb.name, "n": tb.areas.len() })).collect::<Vec<_>>(),+ "sources": t.source.iter().map(|(k, _)| *k).collect::<Vec<_>>(),+ });+ let n = 4 + t.params.len() + t.tubes.iter().map(|tb| 2 * tb.areas.len()).sum::<usize>() + t.source.len();+ h.ctele_block = Vec::with_capacity(n);+ h.ctele = Some(t);+ api::set_result(Ok(info))+}++/// Back to the human voice (its clock resumes where it stopped).+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_set_human(h: *mut Handle) {+ let h = handle!(h);+ h.engine.set_creature(None, &[]);+ h.ctele = None;+}++/// Set one of the creature's params (its index in the def).+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_creature_param(h: *mut Handle, index: usize, value: f64) {+ handle!(h).engine.set_creature_params(&[(index, value)]);+}++/// Play the creature's call `index`; `pitch`/`amp` NaN: the call's own.+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_play_call(h: *mut Handle, index: usize, pitch: f64, amp: f64) {+ handle!(h).engine.play_call(index, opt(pitch), opt(amp));+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_stop_call(h: *mut Handle) {+ handle!(h).engine.stop_call();+}++/// Take the creature's telemetry (resets its RMS measurements) into a flat f64 block: gate,+/// outRms, clock, the active call's index (−1: none), the params in def order, then per tube (in+/// the switch's `tubes` order) its areas then its RMS, then the source values. Null when the human+/// voice is playing.+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_creature_telemetry(h: *mut Handle) -> *const f64 {+ let h = handle!(h);+ let Some(t) = h.ctele.as_mut() else { return core::ptr::null() };+ if !h.engine.creature_telemetry(t) {+ return core::ptr::null();+ }+ let b = &mut h.ctele_block;+ b.clear();+ let call = match (t.call, h.engine.creature()) {+ (Some(id), Some(c)) => c.def.call_index(id).map_or(-1.0, |i| i as f64),+ _ => -1.0,+ };+ b.extend_from_slice(&[t.gate, t.out_rms, t.clock, call]);+ b.extend(t.params.iter().map(|(_, v)| *v));+ for tb in &t.tubes {+ b.extend(tb.areas.iter().map(|x| *x as f64));+ b.extend(tb.rms.iter().map(|x| *x as f64));+ }+ b.extend(t.source.iter().map(|(_, v)| *v));+ b.as_ptr()+}++/// The human voice's gesture score as JSON in the result buffer (diagnostics and tests; allocates).+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_score_json(h: *mut Handle) -> u32 {+ let h = handle!(h);+ api::set_result(serde_json::to_value(h.engine.score().gestures()).map_err(|e| e.to_string()))+}diff --git a/crates/chimera/src/engine.rs b/crates/chimera/src/engine.rsindex f0de0f8..e976d5a 100644--- a/crates/chimera/src/engine.rs+++ b/crates/chimera/src/engine.rs@@ -12,6 +12,8 @@use crate::anatomy::human::{ArticPatch, BodyName};use crate::control::beat_player::BeatPlayer;use crate::control::score::{Gesture, GestureScore};+use crate::creatures::types::CreatureDef;+use crate::creatures::voice::{CreatureTelemetry, CreatureVoice};use crate::phonetics::beatbox::{BeatStep, MAX_SOUND_GESTURES};use crate::voice::human_voice::{HumanVoice, SourcePatch, VoiceTelemetry};@@ -47,13 +49,15 @@ pub struct Engine {pos: u64,scratch: Vec<Gesture>,beat: BeatPlayer,+ /// a creature playing instead of the human voice (whose clock then stands still)+ creature: Option<CreatureVoice>,}impl Engine {pub fn new(sample_rate: f64) -> Engine {crate::init();let body = BodyName::Male;- Engine { sample_rate, body, voice: Self::make_voice(sample_rate, body), gate_level: 0.0, pos: 0, scratch: Vec::with_capacity(MAX_SCHEDULE), beat: BeatPlayer::new() }+ Engine { sample_rate, body, voice: Self::make_voice(sample_rate, body), gate_level: 0.0, pos: 0, scratch: Vec::with_capacity(MAX_SCHEDULE), beat: BeatPlayer::new(), creature: None }}fn make_voice(fs: f64, body: BodyName) -> HumanVoice {@@ -108,6 +112,57 @@ impl Engine {pub fn set_gate(&mut self, level: f64) {self.gate_level = level;self.voice.set_gate(level);+ if let Some(c) = self.creature.as_mut() {+ c.set_gate(level);+ }+ }++ // ---------------------------------------------------------------- creatures++ /// Play a creature instead of the human voice (`None`: back to the human), starting from+ /// these settings (param index, value). Returns its definition. Allocates (a new airway).+ pub fn set_creature(&mut self, def: Option<&'static CreatureDef>, initial: &[(usize, f64)]) -> Option<&'static CreatureDef> {+ self.creature = def.map(|d| {+ let mut c = CreatureVoice::new(d, self.sample_rate, initial);+ c.set_gate(self.gate_level);+ c+ });+ def+ }++ pub fn creature(&self) -> Option<&CreatureVoice> {+ self.creature.as_ref()+ }++ /// The performer's settings for the creature (param index, value).+ pub fn set_creature_params(&mut self, values: &[(usize, f64)]) {+ if let Some(c) = self.creature.as_mut() {+ c.set_params(values);+ }+ }++ /// Play a call of the creature (its index in the def); `pitch` scales its pitch params.+ pub fn play_call(&mut self, call: usize, pitch: Option<f64>, amp: Option<f64>) {+ if let Some(c) = self.creature.as_mut() {+ c.play_call(call, pitch, amp.unwrap_or(1.0));+ }+ }++ pub fn stop_call(&mut self) {+ if let Some(c) = self.creature.as_mut() {+ c.stop_call();+ }+ }++ /// The creature's telemetry (see [`CreatureVoice::telemetry`]); false when the human plays.+ pub fn creature_telemetry(&mut self, out: &mut CreatureTelemetry) -> bool {+ match self.creature.as_mut() {+ Some(c) => {+ c.telemetry(out);+ true+ }+ None => false,+ }}/// Schedule gestures planned with times relative to "now": they are shifted onto the voice@@ -155,7 +210,10 @@ impl Engine {self.sub_block_start();}let n = (SUB_BLOCK - phase).min(out.len() - i);- self.voice.render(&mut out[i..i + n]);+ match self.creature.as_mut() {+ Some(c) => c.render(&mut out[i..i + n]),+ None => self.voice.render(&mut out[i..i + n]),+ }i += n;self.pos += n as u64;}@@ -163,6 +221,9 @@ impl Engine {/// Per-sub-block bookkeeping: the sequencer schedules the hits within its horizon.fn sub_block_start(&mut self) {+ if self.creature.is_some() {+ return; // the human voice (and its sequencer) waits while a creature plays+ }let voice = &mut self.voice;let clock = voice.clock;self.beat.tick(clock, &mut |gs| voice.schedule(gs));diff --git a/crates/chimera/src/lib.rs b/crates/chimera/src/lib.rsindex 1225033..102accc 100644--- a/crates/chimera/src/lib.rs+++ b/crates/chimera/src/lib.rs@@ -55,4 +55,6 @@ pub fn init() {phonetics::planner::init();phonetics::inventory::init();phonetics::beatbox::init();+ phonetics::ipa::init();+ creatures::init();}diff --git a/crates/chimera/src/phonetics/ipa.rs b/crates/chimera/src/phonetics/ipa.rsindex eef79f1..8337b68 100644--- a/crates/chimera/src/phonetics/ipa.rs+++ b/crates/chimera/src/phonetics/ipa.rs@@ -9,16 +9,11 @@ const VOWEL_CHARS: &str = "iyɨʉɯuɪʏʊeøɘɵɤoəɛœɜɞʌɔæɐaɶɑɒɝconst MULTI: [&str; 10] = ["tʃ", "dʒ", "ts", "dz", "pf", "aɪ", "aʊ", "ɔɪ", "eɪ", "oʊ"];const ALIASES: [(&str, &str); 9] = [("t͡ʃ", "tʃ"), ("d͡ʒ", "dʒ"), ("t͡s", "ts"), ("d͡z", "dz"), ("ɡ", "g"), ("ʧ", "tʃ"), ("ʤ", "dʒ"), ("r̥", "r"), ("ɐ̯", "ɐ")];-/// `CONSONANT_SYMBOLS` of `inventory.ts` (the IPA of every consonant definition, in order).-/// Kept here until `inventory.rs` is ported; it must stay equal to that list.-pub(crate) const CONSONANT_SYMBOLS: [&str; 64] = [- "p", "b", "t", "d", "ʈ", "ɖ", "c", "ɟ", "k", "g", "q", "ɢ", "ʔ", "m", "ɱ", "n", "ɳ", "ɲ", "ŋ", "ɴ", "ɸ", "β", "f", "v", "θ", "ð", "s", "z", "ʃ", "ʒ", "ʂ", "ʐ", "ç", "ʝ", "x", "ɣ", "χ", "ʁ", "ħ", "ʕ", "h", "ɦ", "ɬ", "ɮ", "ts", "dz", "tʃ", "dʒ", "pf", "w", "ʋ", "ɹ", "ɻ", "j", "ɰ", "l", "ɫ", "ɭ", "ʎ", "ɾ", "ɽ", "r", "ʀ", "ʙ",-];fn known() -> &'static HashSet<&'static str> {static K: OnceLock<HashSet<&'static str>> = OnceLock::new();K.get_or_init(|| {- let mut k: HashSet<&'static str> = CONSONANT_SYMBOLS.iter().copied().collect();+ let mut k: HashSet<&'static str> = super::inventory::consonant_symbols().iter().copied().collect();for (i, c) in VOWEL_CHARS.char_indices() {k.insert(&VOWEL_CHARS[i..i + c.len_utf8()]);}@@ -91,7 +86,7 @@ pub fn tokenize_ipa(input: &str) -> Vec<Segment> {if !known.contains(tok.as_str()) {continue;}- let is_v = tok.chars().next().is_some_and(|c| VOWEL_CHARS.contains(c)) && !CONSONANT_SYMBOLS.contains(&tok.as_str());+ let is_v = tok.chars().next().is_some_and(|c| VOWEL_CHARS.contains(c)) && !super::inventory::consonant_symbols().contains(&tok.as_str());out.push(Segment { ipa: tok, stress: Some(if is_v { stress } else { 0 }), ..Default::default() });if is_v {stress = 0;diff --git a/crates/chimera/tests/live_control.rs b/crates/chimera/tests/live_control.rsnew file mode 100644index 0000000..f554d0b--- /dev/null+++ b/crates/chimera/tests/live_control.rs@@ -0,0 +1,42 @@+//! Port of the tagged-release part of tests/live-control.test.ts: a note released early drops+//! what has not begun and fades what has, never rising again.+use chimera::control::score::{GestureScore, activation};+use chimera::phonetics::sing::{NoteOnOptions, plan_note_on};+use chimera::phonetics::{Segment, Syllable};++#[test]+fn a_released_note_never_rises_again() {+ // /strɑ/ held, released 30 ms in: the vowel and its pitch have not begun yet+ let syl = Syllable { text: "stra".into(), onset: vec![Segment::new("s"), Segment::new("t"), Segment::new("ɹ")], nucleus: Segment { stress: Some(1), ..Segment::new("ɑ") }, coda: vec![], melisma: None, word_end: true, phrase_end: false };+ let gs = plan_note_on(&syl, 57.0, &NoteOnOptions { body: "male".into(), vibrato: 30.0, tag: 4.0, legato_from: None });+ let mut score = GestureScore::new();+ for g in &gs {+ let mut g = *g;+ g.t0 += 0.05;+ g.t1 += 0.05;+ score.add(g);+ }+ let t = 0.08;+ // activation of each gesture before the release. A release only drops gestures (those of the+ // released tags not yet begun) and keeps the order, so the survivors line up with `was`.+ let dropped = |g: &chimera::control::score::Gesture| (g.tag == Some(4.0) || g.tag == Some(5.0)) && !(t > g.t0 - g.ramp_in);+ let was: Vec<f64> = score.gestures().iter().filter(|g| !dropped(g)).map(|g| activation(g, t)).collect();+ score.release(4.0, t);+ score.release(5.0, t);+ assert_eq!(score.size(), was.len());+ for (i, g) in score.gestures().iter().enumerate() {+ assert!((activation(g, t) - was[i]).abs() < 1e-6, "continuous at the release");+ }+ // after the release, no released gesture's activation exceeds what it had at the release+ let mut tt = t;+ while tt < t + 0.5 {+ for (i, g) in score.gestures().iter().enumerate() {+ if (g.tag == Some(4.0) || g.tag == Some(5.0)) && activation(g, tt) > 0.0 {+ assert!(activation(g, tt) <= was[i] + 1e-9, "{:?} rose again at {tt}", g.label);+ }+ }+ tt += 0.002;+ }+ // the vowel (not begun at 80 ms) is gone, and everything is over soon after+ assert_eq!(score.active_at(0.3).count(), 0);+}diff --git a/crates/chimera/tests/speech_quality.rs b/crates/chimera/tests/speech_quality.rsnew file mode 100644index 0000000..7707829--- /dev/null+++ b/crates/chimera/tests/speech_quality.rs@@ -0,0 +1,120 @@+//! Port of tests/speech-quality.test.ts: running-speech guards (nasality, Klatt durations,+//! phrases ending in silence) and contact-model continuity.+use chimera::anatomy::human::{BODY_MALE, HumanArtic, HumanVocalTract, NEUTRAL};+use chimera::phonetics::Plan;+use chimera::phonetics::ipa::tokenize_ipa;+use chimera::phonetics::planner::{PlanOptions, plan_utterance};+use chimera::voice::human_voice::HumanVoice;++const FS: f64 = 48000.0;++struct Render {+ plan: Plan,+ out: Vec<f32>,+ port: Vec<f64>,+ voicing: Vec<f64>,+}++impl Render {+ fn frame(&self, t: f64) -> usize {+ ((self.port.len() - 1) as f64).min(((t * FS) / 128.0).round()) as usize+ }+ fn at(&self, t: f64) -> f64 {+ self.port[self.frame(t)]+ }+}++fn render(ipa: &str, tail: f64) -> Render {+ let mut v = HumanVoice::with_defaults(FS);+ let plan = plan_utterance(&tokenize_ipa(ipa), &PlanOptions { body: "male".into(), t0: 0.05, f0: Some(110.0), ..Default::default() });+ v.schedule(&plan.gestures);+ let n = (FS * (plan.end + tail)).round() as usize;+ let mut out = vec![0.0f32; n];+ let (mut port, mut voicing) = (vec![], vec![]);+ let mut i = 0;+ while i < n {+ let m = 128.min(n - i);+ v.render(&mut out[i..i + m]);+ port.push(v.airway.frame.as_ref().map_or(0.0, |f| f.velum_port));+ voicing.push(v.glottis.voicing);+ i += m;+ }+ Render { plan, out, port, voicing }+}++/// RMS level (dB re the utterance's peak) over [t0, t1).+fn level_db(out: &[f32], t0: f64, t1: f64) -> f64 {+ let peak = out.iter().fold(0.0f64, |m, x| m.max(x.abs() as f64));+ let (a, b) = (((t0 * FS).round() as usize).min(out.len()), ((t1 * FS).round() as usize).min(out.len()));+ let e: f64 = out[a..b].iter().map(|x| (*x as f64).powi(2)).sum();+ 20.0 * ((e / (b - a).max(1) as f64).sqrt() / peak + 1e-12).log10()+}++#[test]+fn nasality_does_not_spread_into_oral_vowels() {+ // [ɑ n ə b ɑ b ɑ]: the last two vowels have no nasal neighbour (Bunton & Story: audible from ~0.01 cm²)+ let r = render("ˈɑnəbɑbɑ", 0.15);+ let vowels: Vec<_> = r.plan.segments.iter().filter(|s| s.kind == "vowel").collect();+ assert_eq!(vowels.len(), 4);+ for v in &vowels[2..] {+ let mut t = v.t0;+ while t <= v.t1 {+ assert!(r.at(t) < 0.01, "velum port {} at {t}", r.at(t));+ t += 0.005;+ }+ }+ // and the nasal itself is nasal+ let n = r.plan.segments.iter().find(|s| s.ipa == "n").unwrap();+ assert!(r.at((n.t0 + n.t1) / 2.0) > 0.2);+}++#[test]+fn phrase_final_lengthening_and_stress_contrast() {+ let r = render("ˈbɑbəˈbɑb", 0.15);+ let v: Vec<_> = r.plan.segments.iter().filter(|s| s.kind == "vowel").collect();+ let d = |s: &chimera::phonetics::PlannedSegment| s.t1 - s.t0;+ assert!(d(v[2]) / d(v[0]) > 1.25);+ assert!(d(v[0]) / d(v[1]) > 1.4);+}++#[test]+fn a_phrase_ends_in_silence() {+ // no vowel added after a final consonant, no lingering breath+ for ipa in ["ˈbæd", "ˈkæt", "ˈsi", "ˈðɛm"] {+ let r = render(ipa, 0.45);+ let fin = r.plan.segments.last().unwrap();+ let sonorant = fin.kind == "vowel" || fin.kind == "nasal";+ // the folds stop at a final obstruent's release; a final vowel or nasal fades out+ let voiced_for = if sonorant { 0.05 } else { 0.015 };+ for f in r.frame(r.plan.end + voiced_for)..r.voicing.len() {+ assert!(r.voicing[f] < 0.3, "{ipa}: voicing {} at frame {f}", r.voicing[f]);+ }+ assert!(level_db(&r.out, r.plan.end + 0.15, r.plan.end + 0.45) < -50.0, "{ipa}");+ }+}++#[test]+fn the_contact_model_engages_smoothly() {+ // the tongue on its way from a final /d/ back to rest: the body's gap to the roof crosses+ // the contact regime's edge (0.6 cm) at tbY ≈ 6.90+ let base = HumanArtic { jaw: 0.604, tb_x: 2.935, tt_x: 6.272, tt_y: 6.89, lip_ap: 0.703, lip_prot: 0.2, lip_width: 0.5, ..NEUTRAL };+ let mut tract = HumanVocalTract::new(BODY_MALE);+ let (mut ph, mut or) = (vec![0.0; 20], vec![0.0; 24]);+ let mut prev: Option<Vec<f64>> = None;+ let mut worst = 0.0f64;+ let mut y = 6.85;+ while y <= 6.95 {+ let a = HumanArtic { tb_y: y, ..base };+ let f = tract.compute_new(&a);+ tract.resample(&a, &f, &mut ph, &mut or, None, None);+ let cur: Vec<f64> = ph.iter().chain(&or).copied().collect();+ if let Some(p) = &prev {+ for j in 0..cur.len() {+ worst = worst.max((cur[j] - p[j]).abs());+ }+ }+ prev = Some(cur);+ y += 0.001;+ }+ assert!(worst < 0.05, "{worst} cm² per 0.01 mm of tongue travel (was 0.87 at the edge)");+}diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.tsindex 640c604..fdee95e 100644--- a/src/audio/AudioEngine.ts+++ b/src/audio/AudioEngine.ts@@ -3,9 +3,10 @@* parameter messages (at most one per animation frame per kind) and telemetry fan-out.*/import workletUrl from "../worklet/processor.ts?worker&url";+import { chimeraModule } from "../wasm/chimera.ts";import type { ToWorklet, FromWorklet, TelemetryMessage, BodyName, PlannedMessage, CreatureTelemetryMessage } from "../worklet/protocol.ts";-import type { HumanArtic } from "../engine/anatomy/human.ts";-import type { VoiceSource } from "../engine/voice/humanVoice.ts";+import type { HumanArtic } from "../wasm/types.ts";+import type { VoiceSource } from "../wasm/types.ts";type Listener = (t: TelemetryMessage) => void;@@ -60,7 +61,8 @@ export class AudioEngine {this.ctx = ctx;this.sampleRate = ctx.sampleRate;await ctx.audioWorklet.addModule(workletUrl);- const node = new AudioWorkletNode(ctx, "chimera", { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2] });+ // the worklet instantiates the engine from the module compiled at startup (main.tsx)+ const node = new AudioWorkletNode(ctx, "chimera", { numberOfInputs: 0, numberOfOutputs: 1, outputChannelCount: [2], processorOptions: { module: chimeraModule() } });this.node = node;const master = ctx.createGain();master.gain.value = 0.8;@@ -137,7 +139,7 @@ export class AudioEngine {}/** Send a gestural plan (times relative to now). Returns the request id. */- schedule(plan: { gestures: import("../engine/control/score.ts").Gesture[]; segments: import("../engine/phonetics/planner.ts").PlannedSegment[]; end: number }, replace = true): number {+ schedule(plan: { gestures: import("../wasm/types.ts").Gesture[]; segments: import("../wasm/types.ts").PlannedSegment[]; end: number }, replace = true): number {const id = ++this.speakId;this.send({ type: "schedule", gestures: plan.gestures, segments: plan.segments, end: plan.end, id, replace });return id;@@ -185,7 +187,7 @@ export class AudioEngine {this.node.connect(on ? this.micIn : this.master);}- setBeat(m: { steps?: import("../engine/phonetics/beatbox.ts").BeatStep[] | (import("../engine/phonetics/beatbox.ts").BeatStep | null)[]; bpm?: number; swing?: number; playing?: boolean }): void {+ setBeat(m: { steps?: import("../wasm/types.ts").BeatStep[] | (import("../wasm/types.ts").BeatStep | null)[]; bpm?: number; swing?: number; playing?: boolean }): void {this.send({ type: "beat", ...m });}@@ -195,7 +197,7 @@ export class AudioEngine {}/** Gestures planned on the main thread, times relative to arrival + lead (live playing). */- scheduleGestures(gestures: import("../engine/control/score.ts").Gesture[], lead = 0.006): void {+ scheduleGestures(gestures: import("../wasm/types.ts").Gesture[], lead = 0.006): void {this.send({ type: "schedule", gestures, segments: [], end: 0, id: ++this.speakId, replace: false, lead });}diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 11fb869..13ed3c5 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -16,7 +16,7 @@ import { CreatureView } from "./components/CreatureView.tsx";import { Spectrogram } from "./components/Spectrogram.tsx";import { Scope } from "./components/Scope.tsx";import { CreatureTubes } from "./components/CreatureTubes.tsx";-import { creatureById } from "../engine/creatures/index.ts";+import { creatureById } from "../wasm/engine.ts";import { BeatboxPanel, BeatOverlay } from "./components/BeatboxPanel.tsx";import { SingPanel } from "./components/SingPanel.tsx";import { playDemo, DEMO_SONGS } from "./singing.ts";diff --git a/src/ui/analysis.ts b/src/ui/analysis.tsindex e32c1c3..4e55cdb 100644--- a/src/ui/analysis.ts+++ b/src/ui/analysis.ts@@ -1,21 +1,13 @@/**- * Main-thread acoustic model mirroring the worklet's airway (same topology & node counts):- * geometry frames for drawing, frequency-domain transfer function and formants for display,- * and vowel-space interpolation for the vowel map. Never runs inside the audio thread.+ * Main-thread acoustic model mirroring the worklet's airway (same topology & node counts, in the+ * engine): geometry frames for drawing, the transfer function and formants for display, and+ * vowel-space interpolation for the vowel map. Never runs inside the audio thread.*/-import { HumanAirway } from "../engine/voice/humanAirway.ts";-import { BODY_MALE, BODY_FEMALE, BODY_CHILD, NEUTRAL, type HumanArtic, type HumanBody, type HumanFrame } from "../engine/anatomy/human.ts";-import { transferFunction, findPeaks } from "../engine/airway/frequency.ts";-import { ARTIC_KEYS } from "../engine/control/articulators.ts";-import { VOWELS } from "../engine/phonetics/vowelData.ts";-import targets from "../engine/phonetics/vowelTargets.generated.json";+import { airwayModel, airwayFrame, airwayAreas, airwayTransfer, TractMap, BODY_MALE, BODY_FEMALE, BODY_CHILD, NEUTRAL, ARTIC_KEYS, VOWELS, VOWEL_TARGETS, type AirwayModel, type HumanArtic, type HumanBody, type HumanFrame } from "../wasm/engine.ts";import type { BodyName } from "../worklet/protocol.ts";export const BODIES: Record<BodyName, HumanBody> = { male: BODY_MALE, female: BODY_FEMALE, child: BODY_CHILD };-type TargetTable = Record<string, Record<string, { artic: Partial<HumanArtic>; formants: number[] }>>;-const TARGETS = targets as unknown as TargetTable;-export interface VowelPoint {ipa: string;example: string;@@ -24,27 +16,29 @@ export interface VowelPoint {artic: Partial<HumanArtic>;}-const FREQS = (() => {- const n = 360;- const out = new Float64Array(n);- for (let i = 0; i < n; i++) out[i] = 60 * Math.pow(8000 / 60, i / (n - 1));- return out;-})();-export class VoiceModel {readonly body: BodyName;- readonly airway: HumanAirway;+ /** the body's dimensions */+ readonly bodyParams: HumanBody;+ /** template ↔ body coordinates */+ readonly tract: TractMap;readonly vowels: VowelPoint[];+ readonly nPh: number;+ readonly nOr: number;+ private readonly model: AirwayModel;private cacheKey = "";private cacheFrame: HumanFrame | null = null;private tfKey = "";- private tf: { freqs: Float64Array; db: Float64Array; formants: number[] } | null = null;+ private tf: { freqs: number[]; db: number[]; formants: number[] } | null = null;constructor(body: BodyName, sampleRate: number) {this.body = body;- const M = sampleRate > 60000 ? 1 : 2;- this.airway = new HumanAirway({ fs: sampleRate * M, body: BODIES[body] });- const table = TARGETS[body] ?? {};+ this.bodyParams = BODIES[body];+ this.tract = new TractMap(this.bodyParams);+ this.model = airwayModel(body, sampleRate);+ this.nPh = this.model.nPh;+ this.nOr = this.model.nOr;+ const table = VOWEL_TARGETS[body] ?? {};this.vowels = VOWELS.filter((v) => table[v.ipa]).map((v) => ({ipa: v.ipa,example: v.example,@@ -63,23 +57,22 @@ export class VoiceModel {frame(a: HumanArtic): HumanFrame {const key = ARTIC_KEYS.map((k) => a[k].toFixed(3)).join(",");if (key !== this.cacheKey || !this.cacheFrame) {- this.cacheFrame = this.airway.tract.compute(a);+ this.cacheFrame = airwayFrame(this.model, a);this.cacheKey = key;}return this.cacheFrame;}+ /** The area function the worklet's airway would get for this articulation. */+ areas(a: HumanArtic): { phAreas: number[]; orAreas: number[]; phLen: number; orLen: number } {+ return airwayAreas(this.model, a);+ }+/** Transfer function (dB) + formants for an articulation (cached on a coarse key). */- transfer(a: HumanArtic): { freqs: Float64Array; db: Float64Array; formants: number[] } {+ transfer(a: HumanArtic): { freqs: number[]; db: number[]; formants: number[] } {const key = ARTIC_KEYS.map((k) => a[k].toFixed(2)).join(",");if (key === this.tfKey && this.tf) return this.tf;- this.airway.apply(a);- const el = this.airway.net.linearElements();- const H = transferFunction(el, this.airway.pharynx.firstNode, FREQS, [this.airway.glottisPort]);- const db = new Float64Array(FREQS.length);- for (let i = 0; i < FREQS.length; i++) db[i] = 20 * Math.log10(H.mag[i] + 1e-12);- const formants = findPeaks(FREQS, H.mag, 150).map((p) => p.freq).slice(0, 5);- this.tf = { freqs: FREQS, db, formants };+ this.tf = airwayTransfer(this.model, a);this.tfKey = key;return this.tf;}@@ -107,7 +100,7 @@ export class VoiceModel {/** s-position (cm from glottis) of each tract node in the telemetry arrays */nodeS(phLen: number, orLen: number): Float64Array {- const nPh = this.airway.nPh, nOr = this.airway.nOr;+ const nPh = this.nPh, nOr = this.nOr;const s = new Float64Array(nPh + nOr);for (let i = 0; i < nPh; i++) s[i] = ((i + 0.5) / nPh) * phLen;for (let i = 0; i < nOr; i++) s[nPh + i] = phLen + ((i + 0.5) / nOr) * orLen;@@ -116,10 +109,10 @@ export class VoiceModel {/** s-position of a noise-source branch index (pharynx/oral internal branches) */branchS(branch: number, phLen: number, orLen: number): number {- const ph = this.airway.pharynx, or = this.airway.oral;- if (branch >= ph.branchBase && branch < ph.branchBase + ph.n - 1) return ((branch - ph.branchBase + 1) / ph.n) * phLen;- if (branch >= or.branchBase && branch < or.branchBase + or.n - 1) return phLen + ((branch - or.branchBase + 1) / or.n) * orLen;- if (branch === this.airway.glottisPort) return 0.2;+ const ph = this.model.pharynxBranches, or = this.model.oralBranches;+ if (branch >= ph.base && branch < ph.base + ph.n - 1) return ((branch - ph.base + 1) / ph.n) * phLen;+ if (branch >= or.base && branch < or.base + or.n - 1) return phLen + ((branch - or.base + 1) / or.n) * orLen;+ if (branch === this.model.glottisPort) return 0.2;return -1;}}diff --git a/src/ui/components/AnatomyView.tsx b/src/ui/components/AnatomyView.tsxindex 2abfc60..c6bd872 100644--- a/src/ui/components/AnatomyView.tsx+++ b/src/ui/components/AnatomyView.tsx@@ -4,7 +4,7 @@ import { engine } from "../../audio/AudioEngine.ts";import { useStore } from "../store.ts";import { VoiceModel } from "../analysis.ts";import { useModel } from "../useModel.ts";-import type { HumanArtic } from "../../engine/anatomy/human.ts";+import type { HumanArtic } from "../../wasm/types.ts";const BODY_LABEL = { male: "Human, adult male", female: "Human, adult female", child: "Human, child" } as const;@@ -98,7 +98,7 @@ export function AnatomyView() {if (!r || !m) return;const rect = canvasRef.current!.getBoundingClientRect();const p = r.toBody(e.clientX - rect.left, e.clientY - rect.top);- const t = m.airway.tract;+ const t = m.tract;const k = t.scale;const dx = (p.x - d.start.x) / k;const dy = (p.y - d.start.y) / k;diff --git a/src/ui/components/BeatboxPanel.tsx b/src/ui/components/BeatboxPanel.tsxindex 6d596ef..ad28f04 100644--- a/src/ui/components/BeatboxPanel.tsx+++ b/src/ui/components/BeatboxPanel.tsx@@ -1,7 +1,7 @@import { useEffect, useRef, useState } from "react";import { useStore } from "../store.ts";import { engine } from "../../audio/AudioEngine.ts";-import { BEAT_SOUNDS, BEAT_PRESETS, formatBeat, parseBeat, type Airstream } from "../../engine/phonetics/beatbox.ts";+import { BEAT_SOUNDS, BEAT_PRESETS, formatBeat, parseBeat, type Airstream } from "../../wasm/engine.ts";import { Slider, Toggle } from "./Controls.tsx";import { Keys } from "./Keys.tsx";diff --git a/src/ui/components/BestiaryPanel.tsx b/src/ui/components/BestiaryPanel.tsxindex 1ad7fa2..b577643 100644--- a/src/ui/components/BestiaryPanel.tsx+++ b/src/ui/components/BestiaryPanel.tsx@@ -1,7 +1,7 @@import { memo } from "react";import { useStore } from "../store.ts";-import { CREATURES, creatureById } from "../../engine/creatures/index.ts";-import type { CreatureDef } from "../../engine/creatures/types.ts";+import { CREATURES, creatureById } from "../../wasm/engine.ts";+import type { CreatureDef } from "../../wasm/types.ts";import { useLiveCreature } from "../creatureLive.ts";import { Slider } from "./Controls.tsx";import { Keys } from "./Keys.tsx";diff --git a/src/ui/components/CreatureTubes.tsx b/src/ui/components/CreatureTubes.tsxindex f04e1cf..ba90a0d 100644--- a/src/ui/components/CreatureTubes.tsx+++ b/src/ui/components/CreatureTubes.tsx@@ -1,6 +1,6 @@import { useCanvasLoop, font } from "../useCanvas.ts";import { useStore } from "../store.ts";-import { creatureById } from "../../engine/creatures/index.ts";+import { creatureById } from "../../wasm/engine.ts";import { liveTelemetry, previewTelemetry } from "../creatureLive.ts";import { C, hot, pressureLevel } from "../colors.ts";diff --git a/src/ui/components/CreatureView.tsx b/src/ui/components/CreatureView.tsxindex d0e238a..3d1182f 100644--- a/src/ui/components/CreatureView.tsx+++ b/src/ui/components/CreatureView.tsx@@ -1,8 +1,8 @@import { useRef } from "react";import { useCanvasLoop, font } from "../useCanvas.ts";import { useStore } from "../store.ts";-import { creatureById } from "../../engine/creatures/index.ts";-import type { CreatureDef } from "../../engine/creatures/types.ts";+import { creatureById } from "../../wasm/engine.ts";+import type { CreatureDef } from "../../wasm/types.ts";import { liveTelemetry, previewTelemetry } from "../creatureLive.ts";import { C, hot, pressureLevel } from "../colors.ts";diff --git a/src/ui/components/Scope.tsx b/src/ui/components/Scope.tsxindex e5a151e..02ebc93 100644--- a/src/ui/components/Scope.tsx+++ b/src/ui/components/Scope.tsx@@ -2,7 +2,7 @@ import { useRef } from "react";import { useCanvasLoop, font } from "../useCanvas.ts";import { engine } from "../../audio/AudioEngine.ts";import { useStore } from "../store.ts";-import { creatureById } from "../../engine/creatures/index.ts";+import { creatureById } from "../../wasm/engine.ts";import { liveTelemetry } from "../creatureLive.ts";import { C } from "../colors.ts";diff --git a/src/ui/components/ScoreView.tsx b/src/ui/components/ScoreView.tsxindex 338d269..d5b3539 100644--- a/src/ui/components/ScoreView.tsx+++ b/src/ui/components/ScoreView.tsx@@ -2,7 +2,7 @@ import { useEffect, useRef } from "react";import { useCanvasLoop, font } from "../useCanvas.ts";import { engine } from "../../audio/AudioEngine.ts";import { currentPlan, onPlan, type SpokenPlan } from "../speech.ts";-import { activation, type Gesture } from "../../engine/control/score.ts";+import { activation, type Gesture } from "../../wasm/engine.ts";import { C } from "../colors.ts";const ROWS: { name: string; keys: string[] }[] = [diff --git a/src/ui/components/SpeakPanel.tsx b/src/ui/components/SpeakPanel.tsxindex 80396a9..e8b648a 100644--- a/src/ui/components/SpeakPanel.tsx+++ b/src/ui/components/SpeakPanel.tsx@@ -1,7 +1,7 @@import { useEffect, useState } from "react";import { useStore } from "../store.ts";import { speakText, speakPhrases, stopSpeaking, onPlan, currentPlan } from "../speech.ts";-import { tokenizeIpa } from "../../engine/phonetics/ipa.ts";+import { tokenizeIpa } from "../../wasm/engine.ts";import { Slider, Toggle } from "./Controls.tsx";import { ScoreView } from "./ScoreView.tsx";diff --git a/src/ui/components/TubeView.tsx b/src/ui/components/TubeView.tsxindex e09b5a1..0f56634 100644--- a/src/ui/components/TubeView.tsx+++ b/src/ui/components/TubeView.tsx@@ -23,11 +23,11 @@ export function TubeView() {orLen = tele.t.orLen;rms = tele.t.pressureRms;} else {- m.airway.apply(st.artic);- ph = m.airway.phAreas;- or = m.airway.orAreas;- phLen = m.airway.phLen;- orLen = m.airway.orLen;+ const ar = m.areas(st.artic);+ ph = ar.phAreas;+ or = ar.orAreas;+ phLen = ar.phLen;+ orLen = ar.orLen;}const nPh = ph.length, nOr = or.length;const total = phLen + orLen;@@ -41,7 +41,7 @@ export function TubeView() {const velum = tele ? tele.t.velumPort : m.frame(st.artic).velumPort;const naX0 = padL + phLen * sx;const naY = axisY - h * 0.36;- const naLen = 11.4 * m.airway.body.scale;+ const naLen = 11.4 * m.bodyParams.scale;const nasalLit = Math.min(1, velum / 0.4);ctx.strokeStyle = `rgba(160,170,175,${0.25 + 0.5 * nasalLit})`;ctx.lineWidth = 1;diff --git a/src/ui/creatureLive.ts b/src/ui/creatureLive.tsindex e094991..3707443 100644--- a/src/ui/creatureLive.ts+++ b/src/ui/creatureLive.ts@@ -1,19 +1,19 @@import { useEffect, useState } from "react";import { engine } from "../audio/AudioEngine.ts";-import { CreatureVoice, type CreatureTelemetry } from "../engine/creatures/voice.ts";-import type { CreatureDef } from "../engine/creatures/types.ts";+import { creaturePreview, type CreatureTelemetry } from "../wasm/engine.ts";+import type { CreatureDef } from "../wasm/types.ts";const previews = new Map<string, CreatureTelemetry>();/*** A still frame of a creature's airway at the given settings, for drawing before audio starts:- * builds the simulation on the main thread (well under a millisecond) and reads its geometry.+ * the engine builds the simulation on the main thread (well under a millisecond) and reads its geometry.*/export function previewTelemetry(def: CreatureDef, params?: Record<string, number>): CreatureTelemetry {const key = def.id + JSON.stringify(params ?? {});let t = previews.get(key);if (!t) {- t = new CreatureVoice(def, 48000, params).telemetry();+ t = creaturePreview(def.id, params);previews.set(key, t);if (previews.size > 48) previews.delete(previews.keys().next().value!);}diff --git a/src/ui/render/anatomy.ts b/src/ui/render/anatomy.tsindex a36a53c..fbabba1 100644--- a/src/ui/render/anatomy.ts+++ b/src/ui/render/anatomy.ts@@ -5,9 +5,9 @@* the airway, airflow particles at local particle velocity u = U/A, turbulence at the active* noise source. Handles for direct manipulation.*/-import type { HumanArtic, HumanFrame } from "../../engine/anatomy/human.ts";-import type { Vec } from "../../engine/anatomy/geom.ts";-import { rotateAbout, dist, catmullRom } from "../../engine/anatomy/geom.ts";+import type { HumanArtic, HumanFrame } from "../../wasm/types.ts";+import type { Vec } from "./geom.ts";+import { rotateAbout, dist, catmullRom } from "./geom.ts";import type { TelemetryMessage } from "../../worklet/protocol.ts";import type { VoiceModel } from "../analysis.ts";import { C, hot, pressureLevel } from "../colors.ts";@@ -115,7 +115,7 @@ export class AnatomyRenderer {}handles(model: VoiceModel, f: HumanFrame, a: HumanArtic): Handle[] {- const t = model.airway.tract;+ const t = model.tract;const J = this.jawFn(model, a);const lips = { x: (f.upperLip[6].x + f.lowerLip[6].x) / 2 + 0.15, y: (f.upperLip[6].y + f.lowerLip[6].y) / 2 };return [@@ -129,7 +129,7 @@ export class AnatomyRenderer {}private jawFn(model: VoiceModel, a: HumanArtic): (x: number, y: number) => Vec {- const t = model.airway.tract;+ const t = model.tract;const k = t.scale;const condyle = t.P(-2.5, 10.5);const jawRef = t.P(6.95, 7.75);@@ -196,7 +196,7 @@ export class AnatomyRenderer {private drawTissue(model: VoiceModel, f: HumanFrame, a: HumanArtic): void {const c = this.tctx;- const t = model.airway.tract;+ const t = model.tract;const P = (x: number, y: number) => t.P(x, y);const J = this.jawFn(model, a);const k = t.scale;@@ -212,7 +212,7 @@ export class AnatomyRenderer {// ---- head silhouette (skin + subcutaneous fat)// facial profile in true body coordinates (the oral-region x compression of P() would// flatten the nose): subnasale → nose tip → nasion → forehead- const ph = model.airway.body.pharynx;+ const ph = model.bodyParams.pharynx;const B = (x: number, y: number): Vec => ({ x: x * k, y: (y < 7 ? 7 - (7 - y) * ph : y) * k });const neckFront = catmullRom([B(2.3, -4.6), B(2.38, -1.5), B(2.52, 0.4), B(3.0, 1.7), J(5.3, 3.0), J(7.25, 3.35), J(7.95, 4.6), J(7.55, 5.7)], 4);const face = catmullRom([ulOut[ulOut.length - 1], B(7.05, 10.6), B(7.75, 10.78), B(8.75, 11.05), B(9.25, 11.65), B(8.95, 12.6), B(8.35, 13.9), B(7.7, 15.0), B(7.95, 16.1), B(7.9, 18.1), B(6.9, 20.5)], 4);@@ -358,7 +358,7 @@ export class AnatomyRenderer {}private palatePoints(model: VoiceModel): Vec[] {- const t = model.airway.tract;+ const t = model.tract;const raw: [number, number][] = [[1.0, 9.6], [1.8, 9.92], [2.7, 10.18], [3.6, 10.3], [4.4, 10.25], [5.1, 10.05], [5.7, 9.72], [6.15, 9.36], [6.55, 9.15], [7.0, 9.6]];return raw.map(([x, y]) => t.P(x, y));}diff --git a/src/ui/render/geom.ts b/src/ui/render/geom.tsnew file mode 100644index 0000000..3e16cf4--- /dev/null+++ b/src/ui/render/geom.ts@@ -0,0 +1,165 @@+/** 2D geometry helpers for drawing (Vec points, curves, rotations). */++export interface Vec {+ x: number;+ y: number;+}++export const v = (x: number, y: number): Vec => ({ x, y });+export const add = (a: Vec, b: Vec): Vec => ({ x: a.x + b.x, y: a.y + b.y });+export const sub = (a: Vec, b: Vec): Vec => ({ x: a.x - b.x, y: a.y - b.y });+export const scale = (a: Vec, s: number): Vec => ({ x: a.x * s, y: a.y * s });+export const len = (a: Vec): number => Math.hypot(a.x, a.y);+export const dist = (a: Vec, b: Vec): number => Math.hypot(a.x - b.x, a.y - b.y);+export const norm = (a: Vec): Vec => {+ const l = Math.hypot(a.x, a.y) || 1;+ return { x: a.x / l, y: a.y / l };+};+export const lerpV = (a: Vec, b: Vec, t: number): Vec => ({ x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t });+export const polar = (c: Vec, r: number, ang: number): Vec => ({ x: c.x + r * Math.cos(ang), y: c.y + r * Math.sin(ang) });+export const rotateAbout = (p: Vec, c: Vec, ang: number): Vec => {+ const s = Math.sin(ang), co = Math.cos(ang);+ const dx = p.x - c.x, dy = p.y - c.y;+ return { x: c.x + dx * co - dy * s, y: c.y + dx * s + dy * co };+};++/** Polyline stored as flat arrays for fast intersection. */+export class Polyline {+ xs: number[] = [];+ ys: number[] = [];+ push(p: Vec): this {+ this.xs.push(p.x);+ this.ys.push(p.y);+ return this;+ }+ pushXY(x: number, y: number): this {+ this.xs.push(x);+ this.ys.push(y);+ return this;+ }+ append(pts: Vec[], skipFirst = false): this {+ for (let i = skipFirst ? 1 : 0; i < pts.length; i++) this.push(pts[i]);+ return this;+ }+ get length(): number {+ return this.xs.length;+ }+ point(i: number): Vec {+ return { x: this.xs[i], y: this.ys[i] };+ }+ toArray(): Vec[] {+ return this.xs.map((x, i) => ({ x, y: this.ys[i] }));+ }+ clear(): void {+ this.xs.length = 0;+ this.ys.length = 0;+ }+}++/**+ * All intersections of the ray o + t·d (t in [tMin, tMax]) with a polyline.+ * Writes parameters t into `out` and returns their count.+ */+export function rayPolyline(ox: number, oy: number, dx: number, dy: number, pl: Polyline, tMin: number, tMax: number, out: number[]): number {+ let n = 0;+ const xs = pl.xs, ys = pl.ys;+ for (let i = 0; i < xs.length - 1; i++) {+ const t = crossingT(ox, oy, dx, dy, xs[i], ys[i], xs[i + 1], ys[i + 1]);+ if (t >= tMin && t <= tMax && n < out.length) out[n++] = t;+ }+ return n;+}++/**+ * Where segment A→B crosses the line through o along d (as t along d), or NaN. A segment+ * crosses only if its ends lie on different sides of the line, a point on the line counting as+ * the positive side: a polyline passing through a vertex then crosses once, and one that only+ * touches the line at a vertex crosses twice at the same t or not at all (a half-open rule on+ * the segment parameter kept one crossing of such a touch, an unmatched entry or exit).+ */+function crossingT(ox: number, oy: number, dx: number, dy: number, ax: number, ay: number, bx: number, by: number): number {+ const sa = dx * (ay - oy) - dy * (ax - ox) >= 0;+ const sb = dx * (by - oy) - dy * (bx - ox) >= 0;+ if (sa === sb) return NaN;+ const ex = bx - ax, ey = by - ay;+ const den = dx * ey - dy * ex;+ if (Math.abs(den) < 1e-15) return NaN;+ return ((ax - ox) * ey - (ay - oy) * ex) / den;+}++/**+ * Like rayPolyline, also telling for each crossing whether the ray leaves the tissue (the+ * polyline's right-hand side, along its direction) for the air: `exit[i]` is 1 then, else 0.+ */+export function rayCrossings(ox: number, oy: number, dx: number, dy: number, pl: Polyline, tMin: number, tMax: number, outT: number[], exit: Uint8Array): number {+ let n = 0;+ const xs = pl.xs, ys = pl.ys;+ for (let i = 0; i < xs.length - 1; i++) {+ const t = crossingT(ox, oy, dx, dy, xs[i], ys[i], xs[i + 1], ys[i + 1]);+ if (t >= tMin && t <= tMax && n < outT.length) {+ outT[n] = t;+ // leaving the tissue (on the polyline's right) for the air: the ray turns left across it+ exit[n] = dx * (ys[i + 1] - ys[i]) - dy * (xs[i + 1] - xs[i]) < 0 ? 1 : 0;+ n++;+ }+ }+ return n;+}++/** Sample a cubic Bézier into `count` points (including both ends). */+export function bezier3(p0: Vec, p1: Vec, p2: Vec, p3: Vec, count: number): Vec[] {+ const pts: Vec[] = [];+ for (let i = 0; i < count; i++) {+ const t = i / (count - 1);+ const u = 1 - t;+ const a = u * u * u, b = 3 * u * u * t, c = 3 * u * t * t, d = t * t * t;+ pts.push({ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x, y: a * p0.y + b * p1.y + c * p2.y + d * p3.y });+ }+ return pts;+}++/** Sample a quadratic Bézier. */+export function bezier2(p0: Vec, p1: Vec, p2: Vec, count: number): Vec[] {+ const pts: Vec[] = [];+ for (let i = 0; i < count; i++) {+ const t = i / (count - 1);+ const u = 1 - t;+ pts.push({ x: u * u * p0.x + 2 * u * t * p1.x + t * t * p2.x, y: u * u * p0.y + 2 * u * t * p1.y + t * t * p2.y });+ }+ return pts;+}++/** Arc from angle a0 to a1 (radians, either direction), `count` points. */+export function arc(c: Vec, r: number, a0: number, a1: number, count: number): Vec[] {+ const pts: Vec[] = [];+ for (let i = 0; i < count; i++) pts.push(polar(c, r, a0 + ((a1 - a0) * i) / (count - 1)));+ return pts;+}++/** Catmull–Rom spline through points (centripetal-ish uniform), `per` samples per segment. */+export function catmullRom(pts: Vec[], per: number): Vec[] {+ if (pts.length < 3) return pts.slice();+ const out: Vec[] = [];+ for (let i = 0; i < pts.length - 1; i++) {+ const p0 = pts[Math.max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[Math.min(pts.length - 1, i + 2)];+ for (let k = 0; k < per; k++) {+ const t = k / per;+ const t2 = t * t, t3 = t2 * t;+ out.push({+ x: 0.5 * (2 * p1.x + (-p0.x + p2.x) * t + (2 * p0.x - 5 * p1.x + 4 * p2.x - p3.x) * t2 + (-p0.x + 3 * p1.x - 3 * p2.x + p3.x) * t3),+ y: 0.5 * (2 * p1.y + (-p0.y + p2.y) * t + (2 * p0.y - 5 * p1.y + 4 * p2.y - p3.y) * t2 + (-p0.y + 3 * p1.y - 3 * p2.y + p3.y) * t3),+ });+ }+ }+ out.push(pts[pts.length - 1]);+ return out;+}++/** Upper tangent point from external point p to circle (c, r): returns angle on the circle. */+export function tangentAngle(c: Vec, r: number, p: Vec, upper: boolean): number | null {+ const d = dist(c, p);+ if (d <= r * 1.0001) return null;+ const base = Math.atan2(p.y - c.y, p.x - c.x);+ const off = Math.acos(r / d);+ return upper ? base + off : base - off;+}diff --git a/src/ui/singing.ts b/src/ui/singing.tsindex e82b311..d577a4c 100644--- a/src/ui/singing.ts+++ b/src/ui/singing.ts@@ -9,11 +9,11 @@import { create } from "zustand";import { engine } from "../audio/AudioEngine.ts";import { g2p } from "./speech.ts";-import { lyricsToSyllables, type Syllable } from "../engine/phonetics/syllables.ts";-import { planSong, planNoteOn, planNoteOff, planMelisma } from "../engine/phonetics/sing.ts";-import { EXHALE_LABEL } from "../engine/phonetics/planner.ts";-import { DEMO_SONGS } from "../engine/phonetics/songs.ts";-import type { Gesture } from "../engine/control/score.ts";+import { lyricsToSyllables, type Syllable } from "../wasm/engine.ts";+import { planSong, planNoteOn, planNoteOff, planMelisma } from "../wasm/engine.ts";+import { EXHALE_LABEL } from "../wasm/engine.ts";+import { DEMO_SONGS } from "../wasm/engine.ts";+import type { Gesture } from "../wasm/types.ts";import type { BodyName } from "../worklet/protocol.ts";/** A note on the piano roll, on the voice clock (s); t1 is null while it is held. */@@ -51,14 +51,14 @@ interface SingState {export const useSing = create<SingState>((set, get) => ({lyrics: DEFAULT_LYRICS,- syllables: lyricsToSyllables(DEFAULT_LYRICS, g2p),+ syllables: lyricsToSyllables(DEFAULT_LYRICS),cursor: 0,vibrato: 35,demo: null,demoAt: -1,setLyrics: (text) => {stopDemo();- set({ lyrics: text, syllables: lyricsToSyllables(text, g2p), cursor: 0 });+ set({ lyrics: text, syllables: lyricsToSyllables(text), cursor: 0 });},setCursor: (i) => set({ cursor: Math.max(0, Math.min(i, Math.max(0, get().syllables.length - 1))) }),setVibrato: (cents) => set({ vibrato: cents }),@@ -71,7 +71,7 @@ export function ensureDictionary(): void {.load().then(() => {const s = useSing.getState();- const syllables = lyricsToSyllables(s.lyrics, g2p);+ const syllables = lyricsToSyllables(s.lyrics);useSing.setState({ syllables, cursor: Math.min(s.cursor, Math.max(0, syllables.length - 1)) });}).catch(() => {@@ -225,7 +225,7 @@ export async function playDemo(name: string, body: BodyName, ready?: () => Promi// letter-to-sound rules}if (token !== demoToken) return;- const syl = lyricsToSyllables(song.lyrics, g2p);+ const syl = lyricsToSyllables(song.lyrics);if (!syl.length) return;const shift = song.octave[body] * 12;const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));diff --git a/src/ui/speech.ts b/src/ui/speech.tsindex 7614adf..ffa0c5d 100644--- a/src/ui/speech.ts+++ b/src/ui/speech.ts@@ -1,9 +1,9 @@/** Main-thread speech planning: text/IPA → phrases → gestural plan → worklet. */-import { EnglishG2P, type Phrase } from "../engine/phonetics/english.ts";-import { tokenizeIpa } from "../engine/phonetics/ipa.ts";-import { planPhrases, type Plan, type Segment } from "../engine/phonetics/planner.ts";+import { EnglishG2P, type Phrase } from "../wasm/engine.ts";+import { tokenizeIpa } from "../wasm/engine.ts";+import { planPhrases, type Plan, type Segment } from "../wasm/engine.ts";import { engine } from "../audio/AudioEngine.ts";-import type { Gesture } from "../engine/control/score.ts";+import type { Gesture } from "../wasm/types.ts";export const g2p = new EnglishG2P();diff --git a/src/ui/store.ts b/src/ui/store.tsindex 4e82d3f..851b96e 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -1,11 +1,11 @@import { create } from "zustand";import { engine } from "../audio/AudioEngine.ts";-import { DEFAULT_SOURCE, type VoiceSource } from "../engine/voice/humanVoice.ts";-import { NEUTRAL, restTip, type HumanArtic } from "../engine/anatomy/human.ts";+import { DEFAULT_SOURCE, type VoiceSource } from "../wasm/engine.ts";+import { NEUTRAL, restTip, type HumanArtic } from "../wasm/engine.ts";import type { BodyName } from "../worklet/protocol.ts";-import { creatureById } from "../engine/creatures/index.ts";-import type { ParamDef } from "../engine/creatures/types.ts";-import { BEAT_PRESETS, BASS_NOTE, beatReady, parseBeat, type BeatStep } from "../engine/phonetics/beatbox.ts";+import { creatureById } from "../wasm/engine.ts";+import type { ParamDef } from "../wasm/types.ts";+import { BEAT_PRESETS, BASS_NOTE, beatReady, parseBeat, type BeatStep } from "../wasm/engine.ts";import { singNoteOn, singNoteOff, stopSinging, ensureDictionary } from "./singing.ts";import { connectMidi, disconnectMidi, type MidiStatus } from "./midi.ts";diff --git a/src/worklet/protocol.ts b/src/worklet/protocol.tsindex a962104..94dbbd9 100644--- a/src/worklet/protocol.ts+++ b/src/worklet/protocol.ts@@ -1,10 +1,10 @@/** Messages between the main thread and the CHIMERA AudioWorklet. */-import type { HumanArtic } from "../engine/anatomy/human.ts";-import type { VoiceSource, VoiceTelemetry } from "../engine/voice/humanVoice.ts";-import type { Segment, PlannedSegment } from "../engine/phonetics/planner.ts";-import type { Gesture } from "../engine/control/score.ts";-import type { CreatureTelemetry } from "../engine/creatures/voice.ts";-import type { BeatStep } from "../engine/phonetics/beatbox.ts";+import type { HumanArtic } from "../wasm/types.ts";+import type { VoiceSource, VoiceTelemetry } from "../wasm/types.ts";+import type { Segment, PlannedSegment } from "../wasm/types.ts";+import type { Gesture } from "../wasm/types.ts";+import type { CreatureTelemetry } from "../wasm/types.ts";+import type { BeatStep } from "../wasm/types.ts";export interface PhraseMsg {segments: Segment[];diff --git a/tests/harness.ts b/tests/harness.tsnew file mode 100644index 0000000..893908f--- /dev/null+++ b/tests/harness.ts@@ -0,0 +1,74 @@+/**+ * Test harness for the wasm engine in bun: loads the build (`bun run wasm`) for the main-thread+ * facade, and runs separate engine instances the way the AudioWorklet does.+ */+import { readFileSync } from "node:fs";+import { initChimera } from "../src/wasm/chimera.ts";+import { writeGestures, fromUtf8 } from "../src/wasm/wire.ts";+import type { Gesture } from "../src/wasm/types.ts";++export const WASM_PATH = new URL("../src/wasm/chimera.wasm", import.meta.url).pathname;+const bytes = readFileSync(WASM_PATH);+export const wasmModule = new WebAssembly.Module(bytes);++/** Load the engine for the main-thread facade (src/wasm/engine.ts can be imported after this). */+export function initEngine(): Promise<void> {+ return initChimera(bytes);+}++type Fn = (...a: number[]) => number;+type Exports = { memory: WebAssembly.Memory } & Record<string, Fn>;++/** A human voice through the engine's audio-thread ABI (its own instance, as in the worklet). */+export class WasmVoice {+ private readonly x: Exports;+ private readonly h: number;+ constructor(readonly fs = 48000) {+ this.x = new WebAssembly.Instance(wasmModule, {}).exports as unknown as Exports;+ this.h = this.x.engine_new(fs);+ }+ get clock(): number {+ return this.x.engine_clock(this.h);+ }+ schedule(gestures: readonly Gesture[], lead: number, replace = false): number {+ const n = writeGestures(this.x.memory.buffer, this.x.engine_records(this.h), gestures, 4000);+ return this.x.engine_schedule(this.h, n, lead, replace ? 1 : 0);+ }+ release(tag: number): void {+ this.x.engine_release(this.h, tag);+ }+ stop(): void {+ this.x.engine_stop_speech(this.h);+ }+ setGate(level: number): void {+ this.x.engine_set_gate(this.h, level);+ }+ /** Source values by name (crates/chimera-wasm engine_set_source order). */+ setSource(values: Record<string, number | boolean>): void {+ const keys = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];+ const v = new Float64Array(this.x.memory.buffer, this.x.engine_values(this.h), 32).fill(NaN);+ for (const [k, val] of Object.entries(values)) v[keys.indexOf(k)] = typeof val === "boolean" ? (val ? 1 : 0) : val;+ this.x.engine_set_source(this.h);+ }+ render(n: number): Float32Array {+ const out = new Float32Array(n);+ for (let i = 0; i < n; i += 128) {+ const m = Math.min(128, n - i);+ out.set(new Float32Array(this.x.memory.buffer, this.x.engine_render(this.h, m), m), i);+ }+ return out;+ }+ /** f0, voicing and the oral tube's areas now (resets the telemetry's RMS measurements). */+ state(): { f0: number; voicing: number; orAreas: Float64Array } {+ const p = this.x.engine_telemetry(this.h);+ const head = new Float64Array(this.x.memory.buffer, p, 16);+ const [nArtic, nPh, nOr] = [head[11], head[12], head[13]];+ const orAreas = new Float64Array(this.x.memory.buffer, p + 8 * (16 + nArtic + nPh), nOr).slice();+ return { f0: head[3], voicing: head[4], orAreas };+ }+ /** The gesture score (times on the voice clock). */+ score(): Gesture[] {+ this.x.engine_score_json(this.h);+ return JSON.parse(fromUtf8(new Uint8Array(this.x.memory.buffer, this.x.chimera_result_ptr(), this.x.chimera_result_len())));+ }+}diff --git a/tests/live-control.test.ts b/tests/live-control.test.tsindex b97029e..62bd24c 100644--- a/tests/live-control.test.ts+++ b/tests/live-control.test.ts@@ -1,76 +1,63 @@/**- * Ownership and ordering of live control: tagged releases never let a gesture rise again, the- * worklet applies score messages sent during a body change to the new voice, and MIDI notes- * held on several keyboards/channels end only when the last one lets go.+ * Ownership and ordering of live control: the worklet applies messages in the order they arrive,+ * to the voice they were meant for (score messages right after a body change play on the new+ * voice; a beat stop cancels a hit sent just before it), and MIDI notes held on several+ * keyboards/channels end only when the last one lets go. (Tagged releases: crates/chimera/tests/live_control.rs.)*/import { describe, expect, test } from "bun:test";-import { GestureScore, activation } from "../src/engine/control/score.ts";-import { planNoteOn } from "../src/engine/phonetics/sing.ts";-import type { Syllable } from "../src/engine/phonetics/syllables.ts";-import type { HumanVoice } from "../src/engine/voice/humanVoice.ts";--describe("tagged release", () => {- test("a note released early drops what has not begun and fades what has, never rising again", () => {- // /strɑ/ held, released 30 ms in: the vowel and its pitch have not begun yet- const syl: Syllable = { text: "stra", onset: [{ ipa: "s" }, { ipa: "t" }, { ipa: "ɹ" }], nucleus: { ipa: "ɑ", stress: 1 }, coda: [], wordEnd: true, phraseEnd: false };- const gs = planNoteOn(syl, 57, { body: "male", vibrato: 30, tag: 4 });- const score = new GestureScore();- score.addAll(gs.map((g) => ({ ...g, t0: g.t0 + 0.05, t1: g.t1 + 0.05 })));- const t = 0.08;- const before = new Map(score.activeAt(t).map((g) => [g, activation(g, t)]));- score.release(4, t);- score.release(5, t);- for (const g of score.activeAt(t)) expect(activation(g, t)).toBeCloseTo(before.get(g) ?? 0, 6); // continuous- // after the release, no released gesture's activation exceeds what it had at the release- for (let tt = t; tt < t + 0.5; tt += 0.002)- for (const g of score.activeAt(tt)) if (g.tag === 4 || g.tag === 5) expect(activation(g, tt)).toBeLessThanOrEqual((before.get(g) ?? 0) + 1e-9);- // the vowel (not begun at 80 ms) is gone, and everything is over soon after- expect(score.activeAt(0.3).length).toBe(0);- });-});+import { wasmModule } from "./harness.ts";+import { fromUtf8 } from "../src/wasm/wire.ts";describe("worklet ordering", () => {- test("a note scheduled right after a body change plays on the new voice", async () => {- let Proc: (new () => { port: { onmessage: ((e: { data: unknown }) => void) | null }; process: (i: unknown, o: Float32Array[][]) => boolean }) | null = null;+ test("a note scheduled right after a body change plays on the new voice; a stop cancels what came before it", async () => {+ type Proc = { port: { onmessage: ((e: { data: unknown }) => void) | null }; process: (i: unknown, o: Float32Array[][]) => boolean };+ let Ctor: (new (o: unknown) => Proc) | null = null;+ const posted: { type: string; body?: string; message?: string }[] = [];const g = globalThis as Record<string, unknown>;g.sampleRate = 48000;g.AudioWorkletProcessor = class {- port = { onmessage: null as unknown, postMessage: () => {} };+ port = { onmessage: null as unknown, postMessage: (m: { type: string }) => posted.push(m) };};- g.registerProcessor = (_name: string, ctor: typeof Proc) => (Proc = ctor);+ g.registerProcessor = (_name: string, ctor: typeof Ctor) => (Ctor = ctor);await import("../src/worklet/processor.ts");- const p = new Proc!();+ const p = new Ctor!({ processorOptions: { module: wasmModule } });const send = (data: unknown) => p.port.onmessage!({ data });+ const block = () => p.process([], [[new Float32Array(128)]]);+ // the processor's engine, for inspection+ const { x, h } = p as unknown as { x: Record<string, (...a: number[]) => number> & { memory: WebAssembly.Memory }; h: number };+ const scoreSize = () => {+ x.engine_score_json(h);+ return JSON.parse(fromUtf8(new Uint8Array(x.memory.buffer, x.chimera_result_ptr(), x.chimera_result_len()))).length;+ };+ const body = () => ["male", "female", "child"][x.engine_body(h)];+const breath = { t0: 0, t1: 1, rampIn: 0.04, rampOut: 0.05, strength: 1, targets: { breath: 1 }, label: "breath" };send({ type: "body", body: "female" });send({ type: "schedule", gestures: [breath], segments: [], end: 1, id: 1, replace: false, lead: 0.006 });- p.process([], [[new Float32Array(128)]]);- const voice = (p as unknown as { voice: HumanVoice }).voice;- expect(voice.airway.body.scale).toBeLessThan(1); // the new (female) voice- expect(voice.score.size).toBe(1); // holding the note+ block();+ expect(body()).toBe("female"); // the new voice+ expect(posted.filter((m) => m.type === "ready").at(-1)?.body).toBe("female");+ expect(scoreSize()).toBe(1); // holding the note- // a beat stop sent after a hit, during a body change, still cancels that hit+ // a beat stop sent after a hit, around a body change, still cancels that hitsend({ type: "beat", steps: [{ id: "B" }, null, null, null], bpm: 96, playing: true });- for (let i = 0; i < 20; i++) p.process([], [[new Float32Array(128)]]);+ for (let i = 0; i < 20; i++) block();send({ type: "body", body: "male" });send({ type: "beatHit", id: "B" });send({ type: "beat", playing: false });- p.process([], [[new Float32Array(128)]]);- const v2 = (p as unknown as { voice: HumanVoice }).voice;- expect(v2.airway.body.scale).toBe(1);- expect(v2.score.size).toBe(0);+ block();+ expect(body()).toBe("male");+ expect(scoreSize()).toBe(0);- // a backlog replays in order, one full-size schedule per block+ // three full-size schedules, then a stop: the stop comes after all threeconst big = Array.from({ length: 4000 }, (_, i) => ({ ...breath, t0: 1 + i * 1e-3, t1: 1.5 + i * 1e-3, label: `g${i}` }));send({ type: "body", body: "child" });for (let k = 0; k < 3; k++) send({ type: "schedule", gestures: big, segments: [], end: 1, id: 10 + k, replace: false });- send({ type: "stopSpeech" }); // must come after all three- const sizes: number[] = [];- for (let i = 0; i < 4; i++) {- p.process([], [[new Float32Array(128)]]);- sizes.push((p as unknown as { voice: HumanVoice }).voice.score.size);- }- expect(sizes).toEqual([4000, 8000, 12000, 0]);+ expect(scoreSize()).toBe(12000);+ send({ type: "stopSpeech" });+ block();+ expect(scoreSize()).toBe(0);+ expect(posted.filter((m) => m.type === "error")).toEqual([]);});});diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.tsindex 1625f91..9e77e24 100644--- a/tests/singing-live.test.ts+++ b/tests/singing-live.test.ts@@ -1,31 +1,32 @@/*** Sing mode's live path end to end, without a browser: the key handling in src/ui/singing.ts* talks to a stand-in for the audio engine that does what the worklet does with each message- * (schedule at clock + lead, release by tag, cancel), on a real offline voice.+ * (schedule at clock + lead, release by tag, cancel), on the real engine (the wasm build, in its+ * own instance as in the worklet).*/import { describe, expect, mock, test } from "bun:test";-import { HumanVoice } from "../src/engine/voice/humanVoice.ts";-import { midiToHz } from "../src/engine/phonetics/sing.ts";-import { activation, type Gesture } from "../src/engine/control/score.ts";+import { initEngine, WasmVoice } from "./harness.ts";+import type { Gesture } from "../src/wasm/types.ts";++await initEngine();+const { activation } = await import("../src/wasm/engine.ts");+const midiToHz = (m: number) => 440 * Math.pow(2, (m - 69) / 12);const FS = 48000;-let voice = new HumanVoice({ fsOut: FS });+let voice = new WasmVoice(FS);const fakeEngine = {latest: null,voiceClock: () => voice.clock,onPlanned: () => () => {},scheduleGestures: (gs: Gesture[], lead = 0.006) => {- const off = voice.clock + lead;- voice.schedule(gs.map((g) => ({ ...g, t0: g.t0 + off, t1: g.t1 + off })));+ voice.schedule(gs, lead);},schedule: (plan: { gestures: Gesture[] }) => {- voice.cancelScore();- const off = voice.clock + 0.03;- voice.schedule(plan.gestures.map((g) => ({ ...g, t0: g.t0 + off, t1: g.t1 + off })));+ voice.schedule(plan.gestures, 0.03, true);return 1;},release: (tag: number) => voice.release(tag),- stopSpeech: () => voice.cancelScore(),+ stopSpeech: () => voice.stop(),};let startAudio: () => void = () => {};const engineStub = new Proxy(@@ -38,23 +39,30 @@ const engineStub = new Proxy();mock.module("../src/audio/AudioEngine.ts", () => ({ engine: engineStub }));const { useSing, singNoteOn, singNoteOff, playDemo, stopSinging } = await import("../src/ui/singing.ts");-const gesturesOf = () => (voice.score as unknown as { gestures: Gesture[] }).gestures;+const gesturesOf = () => voice.score();+/** breath the score is giving now (strength-weighted activation of breath gestures) */+const breathNow = () => {+ const t = voice.clock;+ let breath = 0;+ for (const g of voice.score()) if (g.targets.breath !== undefined) breath += activation(g, t) * g.strength;+ return breath;+};/** Render `sec` seconds; per 2.7 ms block: f0, voicing, output RMS, narrowest oral area. */function run(sec: number) {const n = Math.round(sec * FS);- const out = new Float32Array(n);const f0: number[] = [], voicing: number[] = [], rms: number[] = [], minOral: number[] = [];for (let i = 0; i < n; i += 128) {const m = Math.min(128, n - i);- voice.render(out, i, m);+ const out = voice.render(m);let e = 0;- for (let j = i; j < i + m; j++) e += out[j] * out[j];+ for (let j = 0; j < m; j++) e += out[j] * out[j];rms.push(Math.sqrt(e / m));- f0.push(voice.glottis.f0Now);- voicing.push(voice.glottis.voicing);+ const st = voice.state();+ f0.push(st.f0);+ voicing.push(st.voicing);let mn = Infinity;- for (const a of voice.airway.orAreas) mn = Math.min(mn, a);+ for (const a of st.orAreas) mn = Math.min(mn, a);minOral.push(mn);}// the last 40 % of the span, where a note has settled@@ -66,7 +74,7 @@ const cents = (f: number, midi: number) => 1200 * Math.log2(f / midiToHz(midi));describe("Sing mode, live keys", () => {test("each key sings the next syllable at its pitch; legato, melisma and release to silence", () => {- voice = new HumanVoice({ fsOut: FS });+ voice = new WasmVoice(FS);useSing.getState().setVibrato(0);useSing.getState().setLyrics("la ma -");expect(useSing.getState().syllables.map((s) => s.text)).toEqual(["la", "ma", "~"]);@@ -115,14 +123,14 @@ describe("Sing mode, live keys", () => {test("a soft key breathes less than a hard one", () => {const level = (velocity: number) => {- voice = new HumanVoice({ fsOut: FS });+ voice = new WasmVoice(FS);useSing.getState().setLyrics("ah");run(0.05);singNoteOn(50, velocity, "male");const r = run(0.5);singNoteOff(50, "male");run(0.4);- return { p: voice.source.pressure, rms: median(r.late(r.rms)) };+ return { rms: median(r.late(r.rms)) };};const soft = level(30), hard = level(127);if (process.env.SING_VERBOSE) console.log(`hard vs soft key: ${(20 * Math.log10(hard.rms / soft.rms)).toFixed(1)} dB`);@@ -130,7 +138,7 @@ describe("Sing mode, live keys", () => {});test("a demo still waiting for audio or the dictionary is cancelled by a stop", async () => {- voice = new HumanVoice({ fsOut: FS });+ voice = new WasmVoice(FS);let scheduled = 0;const schedule = engineStub.schedule as typeof fakeEngine.schedule;engineStub.schedule = (plan: { gestures: Gesture[] }) => (scheduled++, schedule(plan));@@ -149,7 +157,7 @@ describe("Sing mode, live keys", () => {});test("a quick next note drops the last one's breath-out; leaving Sing cancels a pending ending", () => {- voice = new HumanVoice({ fsOut: FS });+ voice = new WasmVoice(FS);useSing.getState().setVibrato(0);useSing.getState().setLyrics("cat dog");run(0.05);@@ -167,13 +175,11 @@ describe("Sing mode, live keys", () => {stopSinging(); // ...and the mode changes at oncerun(0.06);// the cancelled ending's breath is gone (the note's own breath is at the end of its 70 ms fade)- let breath = 0;- for (const g of voice.score.activeAt(voice.clock)) if (g.targets.breath !== undefined) breath += activation(g, voice.clock) * g.strength;- expect(breath).toBeLessThan(0.01);+ expect(breathNow()).toBeLessThan(0.01);});test("overlapping endings all stay owned: a stop cancels every one", () => {- voice = new HumanVoice({ fsOut: FS });+ voice = new WasmVoice(FS);useSing.getState().setLyrics("cats dogs");run(0.05);singNoteOn(50, 96, "male");@@ -186,16 +192,14 @@ describe("Sing mode, live keys", () => {run(0.01);stopSinging();run(0.08);- let breath = 0;- for (const g of voice.score.activeAt(voice.clock)) if (g.targets.breath !== undefined) breath += activation(g, voice.clock) * g.strength;- expect(breath).toBeLessThan(0.01);+ expect(breathNow()).toBeLessThan(0.01);});});describe("keys pressed before the audio has started", () => {test("only the press still down sings, once, and not after the body changed", async () => {const { useStore } = await import("../src/ui/store.ts");- voice = new HumanVoice({ fsOut: FS });+ voice = new WasmVoice(FS);useStore.setState({ started: false, mode: "play" });useStore.getState().setMode("sing");useSing.getState().setLyrics("one two three");diff --git a/tools/golden/analysis.ts b/tools/golden/analysis.tsindex e04438d..f4ec0cb 100644--- a/tools/golden/analysis.ts+++ b/tools/golden/analysis.ts@@ -120,7 +120,7 @@ const peakCases = (() => {{ name: "smooth", freqs: arr(f), mag: arr(smooth), minFreq: 80 },{ name: "noisy", freqs: arr(f), mag: arr(noisy), minFreq: 200 },{ name: "plateau", freqs: arr(f), mag: arr(plateau), minFreq: 0 },- ].map((c) => ({ ...c, peaks: peaks(findPeaks(c.freqs, c.mag, c.minFreq)) }));+ ].map((c) => ({ ...c, peaks: peaks(findPeaks(c.freqs as number[], c.mag as number[], c.minFreq)) }));})();// ------------------------------------------------------------ signals