the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Rust engine: Engine (human path), wasm C ABI, native = wasm bit for bit, exact float parsing
Jameson Hodgedde6a27fc737
diff --git a/Cargo.lock b/Cargo.lockindex a3e4eef..ec4277a 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -11,6 +11,14 @@ dependencies = ["serde_json",]+[[package]]+name = "chimera-wasm"+version = "0.1.0"+dependencies = [+ "chimera",+ "serde_json",+]+[[package]]name = "itoa"version = "1.0.18"diff --git a/Cargo.toml b/Cargo.tomlindex 20f305f..fa6351c 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[workspace]resolver = "3"-members = ["crates/chimera"]+members = ["crates/chimera", "crates/chimera-wasm"][workspace.package]version = "0.1.0"diff --git a/crates/chimera-wasm/Cargo.toml b/crates/chimera-wasm/Cargo.tomlnew file mode 100644index 0000000..a8883d4--- /dev/null+++ b/crates/chimera-wasm/Cargo.toml@@ -0,0 +1,14 @@+[package]+name = "chimera-wasm"+description = "C-ABI wasm bindings of the CHIMERA engine for the browser (AudioWorklet and main thread)"+version.workspace = true+edition.workspace = true+license.workspace = true+publish = false++[lib]+crate-type = ["cdylib", "rlib"]++[dependencies]+chimera = { path = "../chimera" }+serde_json = { version = "1", features = ["float_roundtrip"] }diff --git a/crates/chimera-wasm/examples/probe.rs b/crates/chimera-wasm/examples/probe.rsnew file mode 100644index 0000000..20aa78c--- /dev/null+++ b/crates/chimera-wasm/examples/probe.rs@@ -0,0 +1,12 @@+//! Print chimera_probe(f, x, y) as hex bits for the (f, x, y) triples read from stdin (hex bits).+use std::io::BufRead;+fn main() {+ for line in std::io::stdin().lock().lines() {+ let line = line.unwrap();+ let mut it = line.split_whitespace();+ let f: u32 = it.next().unwrap().parse().unwrap();+ let x = f64::from_bits(u64::from_str_radix(it.next().unwrap(), 16).unwrap());+ let y = f64::from_bits(u64::from_str_radix(it.next().unwrap(), 16).unwrap());+ println!("{:016x}", chimera_wasm::chimera_probe(f, x, y).to_bits());+ }+}diff --git a/crates/chimera-wasm/examples/render_scenarios.rs b/crates/chimera-wasm/examples/render_scenarios.rsnew file mode 100644index 0000000..f4e37df--- /dev/null+++ b/crates/chimera-wasm/examples/render_scenarios.rs@@ -0,0 +1,94 @@+//! Render the voice scenarios of crates/chimera/tests/golden/voice.json natively, through the+//! same C ABI the browser uses, into target/native-render/<name>.f32. The wasm test+//! (tests/wasm-engine.test.ts) renders them through the wasm build and requires identical bytes.+use chimera::control::score::Gesture;+use chimera_wasm::*;+use serde_json::Value;++fn main() {+ let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../..");+ let scenarios: Value = serde_json::from_str(&std::fs::read_to_string(format!("{root}/crates/chimera/tests/golden/voice.json")).unwrap()).unwrap();+ let out_dir = format!("{root}/target/native-render");+ std::fs::create_dir_all(&out_dir).unwrap();+ for s in scenarios.as_array().unwrap() {+ let name = s["name"].as_str().unwrap();+ let out = render(s);+ let bytes: Vec<u8> = out.iter().flat_map(|x| x.to_le_bytes()).collect();+ std::fs::write(format!("{out_dir}/{name}.f32"), bytes).unwrap();+ println!("{name}: {} samples", out.len());+ }+}++/// The scenario's operations through the engine ABI, one 128-frame quantum at a time.+fn render(s: &Value) -> Vec<f32> {+ let fs = s["fsOut"].as_f64().unwrap();+ let n = s["samples"].as_u64().unwrap() as usize;+ let h = engine_new(fs);+ unsafe {+ let body = match s["body"].as_str().unwrap() {+ "female" => 1,+ "child" => 2,+ _ => 0,+ };+ if body != 0 {+ engine_set_body(h, body);+ }+ let mut ops: Vec<&Value> = s["ops"].as_array().unwrap().iter().collect();+ ops.sort_by_key(|o| o["at"].as_u64().unwrap());+ let mut out = Vec::with_capacity(n);+ let mut oi = 0;+ while out.len() < n {+ while oi < ops.len() && ops[oi]["at"].as_u64().unwrap() as usize <= out.len() {+ apply(h, ops[oi]);+ oi += 1;+ }+ let next = if oi < ops.len() { ops[oi]["at"].as_u64().unwrap() as usize } else { usize::MAX };+ let m = 128.min(n - out.len()).min(next.max(out.len() + 1) - out.len());+ let p = engine_render(h, m);+ out.extend_from_slice(std::slice::from_raw_parts(p, m));+ }+ engine_free(h);+ out+ }+}++unsafe fn apply(h: *mut Handle, o: &Value) {+ unsafe {+ let vals = std::slice::from_raw_parts_mut(engine_values(h), 32);+ match o["op"].as_str().unwrap() {+ "gate" => engine_set_gate(h, o["level"].as_f64().unwrap()),+ "artic" => {+ vals.fill(f64::NAN);+ for (k, v) in o["values"].as_object().unwrap() {+ let i = chimera::anatomy::human::ArticKey::from_name(k).unwrap().index();+ vals[i] = v.as_f64().unwrap();+ }+ engine_set_artic(h, match o["tipFree"].as_bool() {+ Some(false) => 0,+ Some(true) => 1,+ None => 2,+ });+ }+ "source" => {+ vals.fill(f64::NAN);+ let names = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];+ for (k, v) in o["values"].as_object().unwrap() {+ let i = names.iter().position(|n| n == k).unwrap();+ vals[i] = v.as_f64().unwrap_or_else(|| if v.as_bool().unwrap() { 1.0 } else { 0.0 });+ }+ engine_set_source(h);+ }+ "schedule" => {+ let gs: Vec<Gesture> = serde_json::from_value(o["gestures"].clone()).unwrap();+ let rec = std::slice::from_raw_parts_mut(engine_records(h), gs.len() * GESTURE_RECORD);+ for (i, g) in gs.iter().enumerate() {+ write_gesture(g, &mut rec[i * GESTURE_RECORD..(i + 1) * GESTURE_RECORD]);+ }+ engine_schedule(h, gs.len(), o["offset"].as_f64().unwrap(), 0);+ }+ "release" => engine_release(h, o["tag"].as_f64().unwrap()),+ "cancel" => engine_stop_speech(h),+ op => panic!("{op}"),+ }+ }+}diff --git a/crates/chimera-wasm/src/lib.rs b/crates/chimera-wasm/src/lib.rsnew file mode 100644index 0000000..d48771d--- /dev/null+++ b/crates/chimera-wasm/src/lib.rs@@ -0,0 +1,333 @@+//! C-ABI bindings of the CHIMERA engine for the browser. No wasm-bindgen and no imports: the+//! AudioWorkletGlobalScope has no TextEncoder/TextDecoder or fetch, so everything crosses as+//! numbers and pointers into this module's linear memory.+//!+//! Ownership: every object is a handle (`*mut T` from `Box::into_raw`) freed by its `*_free`.+//! Buffers an object owns (output, gesture scratch, telemetry arrays) keep their address for the+//! object's lifetime; JavaScript must still re-create its typed-array views whenever+//! `memory.buffer` changes (memory growth detaches them), and copy telemetry before the next call.+//!+//! # Gesture records (layout version 1, [`GESTURE_RECORD`] = 272 bytes, little-endian)+//! | offset | type | field |+//! |-------:|-------------|-------|+//! | 0 | f64 | t0 |+//! | 8 | f64 | t1 |+//! | 16 | f64 | rampIn |+//! | 24 | f64 | rampOut |+//! | 32 | f64 | strength |+//! | 40 | f64 | speed (NaN: absent) |+//! | 48 | f64 | releaseHold (NaN: absent) |+//! | 56 | f64 | tag (NaN: absent) |+//! | 64 | 22 × f64 | targets in ControlKey order: the 17 articulators (ArticKey order), then abduction, closure, breath, f0, vibrato (NaN: absent) |+//! | 240 | u8 | label length in bytes (255: no label) |+//! | 241 | 24 × u8 | label, UTF-8, cut at a character boundary |+//! | 265 | 7 × u8 | padding |++use chimera::anatomy::human::{ArticPatch, BodyName, N_ARTIC};+use chimera::control::score::{Gesture, Label, N_CONTROL, Targets};+use chimera::engine::{Engine, MAX_SCHEDULE};+use chimera::voice::human_voice::{SourcePatch, VoiceTelemetry};++pub const GESTURE_RECORD: usize = 272;+pub const LAYOUT_VERSION: u32 = 1;+/// Largest `engine_render` request (frames).+pub const MAX_RENDER: usize = 4096;++#[unsafe(no_mangle)]+pub extern "C" fn chimera_layout_version() -> u32 {+ LAYOUT_VERSION+}++#[unsafe(no_mangle)]+pub extern "C" fn chimera_gesture_record_size() -> u32 {+ GESTURE_RECORD as u32+}++// ------------------------------------------------------------------ memory for JS-owned buffers++/// Allocate `n` bytes (8-aligned) for JavaScript; free with `chimera_free(ptr, n)`.+#[unsafe(no_mangle)]+pub extern "C" fn chimera_alloc(n: usize) -> *mut u8 {+ let v: Vec<u64> = vec![0; n.div_ceil(8).max(1)];+ Box::into_raw(v.into_boxed_slice()) as *mut u8+}++/// # Safety+/// `p` and `n` must come from one `chimera_alloc` call.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn chimera_free(p: *mut u8, n: usize) {+ if p.is_null() {+ return;+ }+ let words = n.div_ceil(8).max(1);+ drop(unsafe { Box::from_raw(core::ptr::slice_from_raw_parts_mut(p as *mut u64, words)) });+}++// ------------------------------------------------------------------ gesture records++fn opt(x: f64) -> Option<f64> {+ if x.is_nan() { None } else { Some(x) }+}++/// Decode one record (see the module docs).+pub fn read_gesture(b: &[u8]) -> Gesture {+ let f = |i: usize| f64::from_le_bytes(b[i * 8..i * 8 + 8].try_into().unwrap());+ let mut targets = Targets::default();+ for k in 0..N_CONTROL {+ targets.0[k] = f(8 + k);+ }+ let len = b[240];+ let label = if len == 255 { None } else { Some(Label::from_bytes(&b[241..241 + (len as usize).min(Label::CAP)])) };+ Gesture { t0: f(0), t1: f(1), ramp_in: f(2), ramp_out: f(3), strength: f(4), speed: opt(f(5)), release_hold: opt(f(6)), tag: opt(f(7)), targets, label }+}++/// Encode one record (the inverse of [`read_gesture`]).+pub fn write_gesture(g: &Gesture, b: &mut [u8]) {+ let mut put = |i: usize, x: f64| b[i * 8..i * 8 + 8].copy_from_slice(&x.to_le_bytes());+ for (i, x) in [g.t0, g.t1, g.ramp_in, g.ramp_out, g.strength, g.speed.unwrap_or(f64::NAN), g.release_hold.unwrap_or(f64::NAN), g.tag.unwrap_or(f64::NAN)].into_iter().enumerate() {+ put(i, x);+ }+ for k in 0..N_CONTROL {+ put(8 + k, g.targets.0[k]);+ }+ match &g.label {+ None => b[240] = 255,+ Some(l) => {+ let bytes = l.as_bytes();+ b[240] = bytes.len() as u8;+ b[241..241 + bytes.len()].copy_from_slice(bytes);+ }+ }+}++// ------------------------------------------------------------------ the engine (audio thread)++/// An engine and the buffers JavaScript reads and writes.+pub struct Handle {+ engine: Engine,+ out: Vec<f32>,+ /// MAX_SCHEDULE gesture records written by JS before `engine_schedule`+ records: Vec<u8>,+ gestures: Vec<Gesture>,+ /// N_ARTIC values (NaN: absent) for `engine_set_artic`; also source values for `engine_set_source`+ values: Vec<f64>,+ tele: VoiceTelemetry,+}++fn bodies(i: u32) -> BodyName {+ match i {+ 1 => BodyName::Female,+ 2 => BodyName::Child,+ _ => BodyName::Male,+ }+}++#[unsafe(no_mangle)]+pub extern "C" fn engine_new(sample_rate: f64) -> *mut Handle {+ let mut h = Box::new(Handle {+ engine: Engine::new(sample_rate),+ out: vec![0.0; MAX_RENDER],+ records: vec![0u8; MAX_SCHEDULE * GESTURE_RECORD],+ gestures: Vec::with_capacity(MAX_SCHEDULE),+ values: vec![f64::NAN; 32],+ tele: VoiceTelemetry::default(),+ });+ // size every telemetry buffer once, so later snapshots reuse them+ h.engine.telemetry(&mut h.tele);+ Box::into_raw(h)+}++/// # Safety+/// `h` must come from `engine_new` and not be used afterwards.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_free(h: *mut Handle) {+ if !h.is_null() {+ drop(unsafe { Box::from_raw(h) });+ }+}++macro_rules! handle {+ ($h:expr) => {+ unsafe { &mut *$h }+ };+}++/// Render `n` (≤ MAX_RENDER) frames; returns the output buffer's address.+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_render(h: *mut Handle, n: usize) -> *const f32 {+ let h = handle!(h);+ let n = n.min(MAX_RENDER);+ h.engine.render(&mut h.out[..n]);+ h.out.as_ptr()+}++/// The record area JavaScript fills before `engine_schedule` (MAX_SCHEDULE records).+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_records(h: *mut Handle) -> *mut u8 {+ handle!(h).records.as_mut_ptr()+}++/// Schedule `count` records from the record area, times relative to now + `lead`. Returns the+/// offset added (the plan's time 0 on the voice clock).+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_schedule(h: *mut Handle, count: usize, lead: f64, replace: u32) -> f64 {+ let h = handle!(h);+ let count = count.min(MAX_SCHEDULE);+ h.gestures.clear();+ for i in 0..count {+ h.gestures.push(read_gesture(&h.records[i * GESTURE_RECORD..(i + 1) * GESTURE_RECORD]));+ }+ h.engine.schedule(&h.gestures, lead, replace != 0)+}++/// A scratch array of 32 f64 for value-carrying calls (artic patches, source patches).+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_values(h: *mut Handle) -> *mut f64 {+ handle!(h).values.as_mut_ptr()+}++/// Apply the articulation in the value area (N_ARTIC values in ArticKey order, NaN: unchanged).+/// `tip_free`: 0 false, 1 true, anything else unchanged.+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_set_artic(h: *mut Handle, tip_free: u32) {+ let h = handle!(h);+ let mut p = ArticPatch::default();+ for k in 0..N_ARTIC {+ p.values[k] = opt(h.values[k]);+ }+ let tf = match tip_free {+ 0 => Some(false),+ 1 => Some(true),+ _ => None,+ };+ h.engine.set_artic(&p, tf);+}++/// Source values in the value area, in this order (NaN: unchanged): f0, glide, pressure,+/// breathiness, tension, fry, roughness, vibratoDepth, vibratoRate, drift, voiced (0/1).+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_set_source(h: *mut Handle) {+ let h = handle!(h);+ let v = &h.values;+ let p = SourcePatch {+ f0: opt(v[0]),+ glide: opt(v[1]),+ pressure: opt(v[2]),+ breathiness: opt(v[3]),+ tension: opt(v[4]),+ fry: opt(v[5]),+ roughness: opt(v[6]),+ vibrato_depth: opt(v[7]),+ vibrato_rate: opt(v[8]),+ drift: opt(v[9]),+ voiced: opt(v[10]).map(|x| x != 0.0),+ };+ h.engine.set_source(&p);+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_set_gate(h: *mut Handle, level: f64) {+ handle!(h).engine.set_gate(level);+}++/// Switch body (0 male, 1 female, 2 child). Allocates. The new voice's node counts can be read+/// with `engine_n_ph`/`engine_n_or`.+///+/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_set_body(h: *mut Handle, body: u32) {+ let h = handle!(h);+ h.engine.set_body(bodies(body));+ h.engine.telemetry(&mut h.tele); // resize the telemetry buffers for the new voice+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_stop_speech(h: *mut Handle) {+ handle!(h).engine.stop_speech();+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_release(h: *mut Handle, tag: f64) {+ handle!(h).engine.release(tag);+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_clock(h: *mut Handle) -> f64 {+ handle!(h).engine.clock()+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_n_ph(h: *mut Handle) -> u32 {+ handle!(h).engine.info().n_ph as u32+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_n_or(h: *mut Handle) -> u32 {+ handle!(h).engine.info().n_or as u32+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_body(h: *mut Handle) -> u32 {+ match handle!(h).engine.info().body {+ BodyName::Male => 0,+ BodyName::Female => 1,+ BodyName::Child => 2,+ }+}++/// Evaluate one of the engine's math functions (diagnostics: native and wasm must agree bit for+/// bit). 0 sin 1 cos 2 tan 3 exp 4 ln 5 log10 6 log2 7 pow 8 tanh 9 atan2 10 acos 11 cbrt 12 hypot 13 sqrt.+#[unsafe(no_mangle)]+pub extern "C" fn chimera_probe(f: u32, x: f64, y: f64) -> f64 {+ use chimera::math as m;+ match f {+ 0 => m::sin(x),+ 1 => m::cos(x),+ 2 => m::tan(x),+ 3 => m::exp(x),+ 4 => m::ln(x),+ 5 => m::log10(x),+ 6 => m::log2(x),+ 7 => m::pow(x, y),+ 8 => m::tanh(x),+ 9 => m::atan2(x, y),+ 10 => m::acos(x),+ 11 => m::cbrt(x),+ 12 => m::hypot(x, y),+ 13 => m::sqrt(x),+ _ => f64::NAN,+ }+}diff --git a/crates/chimera/Cargo.toml b/crates/chimera/Cargo.tomlindex 9e1088b..cf48630 100644--- a/crates/chimera/Cargo.toml+++ b/crates/chimera/Cargo.toml@@ -8,4 +8,4 @@ license.workspace = true[dependencies]libm = "=0.2.16"serde = { version = "1", features = ["derive"] }-serde_json = "1"+serde_json = { version = "1", features = ["float_roundtrip"] }diff --git a/crates/chimera/examples/bench.rs b/crates/chimera/examples/bench.rsnew file mode 100644index 0000000..0518b2f--- /dev/null+++ b/crates/chimera/examples/bench.rs@@ -0,0 +1,33 @@+//! Real-time factor of the voices (single core): `cargo run --release -p chimera --example bench`.+use chimera::anatomy::human::BODY_MALE;+use chimera::control::score::Gesture;+use chimera::voice::human_voice::{HumanVoice, SourcePatch};+use std::time::Instant;++fn main() {+ let root = concat!(env!("CARGO_MANIFEST_DIR"));+ let v: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(format!("{root}/tests/golden/voice.json")).unwrap()).unwrap();+ let s = v.as_array().unwrap().iter().find(|s| s["name"] == "speech-male").unwrap();+ let gs: Vec<Gesture> = serde_json::from_value(s["ops"][0]["gestures"].clone()).unwrap();+ for os in [2usize, 1] {+ let fs = 48000.0;+ let mut voice = HumanVoice::new(fs, BODY_MALE, os);+ voice.set_source(&SourcePatch::f0(110.0));+ let mut g2 = gs.clone();+ for g in g2.iter_mut() {+ g.t0 += 0.03;+ g.t1 += 0.03;+ }+ voice.schedule(&g2);+ voice.set_gate(1.0);+ let secs = 4.0;+ let n = (fs * secs) as usize;+ let mut out = vec![0.0f32; 128];+ let t0 = Instant::now();+ for _ in 0..n / 128 {+ voice.render(&mut out);+ }+ let dt = t0.elapsed().as_secs_f64();+ println!("human male os={os}: {:.1}% of one core in real time ({:.2} ms per 128-sample block)", 100.0 * dt / secs, 1000.0 * dt / (n / 128) as f64);+ }+}diff --git a/crates/chimera/examples/bench_parts.rs b/crates/chimera/examples/bench_parts.rsnew file mode 100644index 0000000..d26a779--- /dev/null+++ b/crates/chimera/examples/bench_parts.rs@@ -0,0 +1,27 @@+//! Where a human voice's time goes: geometry (per control step) vs the FDTD step (per sample).+use chimera::anatomy::human::{BODY_MALE, NEUTRAL};+use chimera::voice::human_airway::HumanAirway;+use std::time::Instant;+fn main() {+ let fs = 96000.0;+ let mut air = HumanAirway::new(fs, BODY_MALE);+ let mut a = NEUTRAL;+ let n_ctrl = 750 * 4; // 4 s of control steps at 96 kHz / 128+ let t0 = Instant::now();+ for i in 0..n_ctrl {+ a.tb_x = 2.9 + 0.5 * ((i as f64) * 0.01).sin();+ air.apply(&a, 128.0 / fs);+ air.net.begin_block(128);+ }+ let geo = t0.elapsed().as_secs_f64();+ let net = &mut air.net;+ let n = (fs * 4.0) as usize;+ let t0 = Instant::now();+ let mut acc = 0.0;+ for _ in 0..n {+ net.set_fixed_pressure(0, 8000.0);+ acc += net.step();+ }+ let step = t0.elapsed().as_secs_f64();+ println!("per 4 s of audio: geometry {:.1} ms ({:.1}%), FDTD steps {:.1} ms ({:.1}%) [{acc:e}] nodes {} branches {}", geo * 1e3, geo / 4.0 * 100.0, step * 1e3, step / 4.0 * 100.0, net.n_nodes, net.n_branches);+}diff --git a/crates/chimera/src/airway/network.rs b/crates/chimera/src/airway/network.rsindex 718d46a..a7fcd78 100644--- a/crates/chimera/src/airway/network.rs+++ b/crates/chimera/src/airway/network.rs@@ -254,6 +254,11 @@ pub struct AirwayNetwork {dx_step: Vec<f64>,vol: Vec<f64>,inv_a: Vec<f64>,+ /// per-sample half-section terms of each node, shared by its branches (same operations, in+ /// the same order, as computing them per branch): Δ/A, and S·Δ·√A/A²·visc factor+ half_l: Vec<f64>,+ half_r: Vec<f64>,+ sqrt_a: Vec<f64>,flow_sum: Vec<f64>,/// external volume-velocity injection per node for the next step (cleared after use)pub ext_flow: Vec<f64>,@@ -363,6 +368,9 @@ impl AirwayNetwork {dx_step: Vec::new(),vol: Vec::new(),inv_a: Vec::new(),+ half_l: Vec::new(),+ half_r: Vec::new(),+ sqrt_a: Vec::new(),flow_sum: Vec::new(),ext_flow: Vec::new(),fixed: Vec::new(),@@ -493,6 +501,9 @@ impl AirwayNetwork {self.dx_step = zf(n);self.vol = zf(n);self.inv_a = zf(n);+ self.half_l = zf(n);+ self.half_r = zf(n);+ self.sqrt_a = zf(n);self.flow_sum = zf(n);self.ext_flow = zf(n);self.fixed = vec![false; n];@@ -539,6 +550,9 @@ impl AirwayNetwork {for &k in &self.pending_fixed {self.fixed[k] = true;}+ // the step's branch loop indexes nodes without bounds checks: every endpoint must exist+ assert!(self.b_a.iter().chain(&self.b_b).all(|&k| k < n), "branch endpoint out of range");+ assert!(self.rad_nodes.iter().all(|&k| k < n), "radiator node out of range");self.u = zf(b);self.mom = zf(b);self.l_prev = zf(b);@@ -792,8 +806,13 @@ impl AirwayNetwork {amin[k] = amk;dx[k] += self.dx_step[k];let d = dx[k];- self.inv_a[k] = 1.0 / (if a > 1e-6 { a } else { 1e-6 });+ let ia = 1.0 / (if a > 1e-6 { a } else { 1e-6 });+ self.inv_a[k] = ia;self.inv_amin[k] = 1.0 / (if amk > 1e-6 { amk } else { 1e-6 });+ let sa = sqrt(a);+ self.sqrt_a[k] = sa;+ self.half_l[k] = d * ia;+ self.half_r[k] = self.wall_perim[k] * d * sa * ia * ia * self.visc_f[k];let v = (if a > min_a { a } else { min_a }) * d;if vol_on {let raw = -(v - self.vol[k]) * inv_t;@@ -852,110 +871,138 @@ impl AirwayNetwork {let half_rho = 0.5 * RHO;let enable_energy_safe = self.energy_safe;let symmetric = self.symmetric_kinetic;- for j in 0..nb {- let a = self.b_a[j];- let b = self.b_b[j];- let l: f64;- let r: f64;- let mut kf: f64;- let mut kb: f64;- let a_eff: f64;- if self.b_kind[j] == KIND_SERIES {- let aa = self.area[a];- let ab = self.area[b];- let ma = self.amin[a];- let mb = self.amin[b];- a_eff = if ma < mb { ma } else { mb };- if (if aa < ab { aa } else { ab }) < closed || a_eff < closed {- self.u[j] = 0.0;- self.mom[j] = 0.0;- self.branch_area[j] = a_eff;- continue;- }- let ia = self.inv_a[a];- let ib = self.inv_a[b];- let dxa = self.dx[a];- let dxb = self.dx[b];- l = half_rho * (dxa * ia + dxb * ib);- // viscous: R = S·l/A² · sqrt(ρμω/2) with S = perimeter of each half-section- r = 0.5 * visc * (self.wall_perim[a] * dxa * sqrt(aa) * ia * ia * self.visc_f[a] + self.wall_perim[b] * dxb * sqrt(ab) * ib * ib * self.visc_f[b]);- // Borda–Carnot: the jet leaving the narrowest point of the upstream node expands into- // the downstream node (sub-section minima make short constrictions lossy as they should be)- let ima = self.inv_amin[a];- let imb = self.inv_amin[b];- let ef = ima - ib; // a→b- let eb = imb - ia; // b→a- kf = if ef > 0.0 { half_rho * ef * ef } else { 0.0 };- kb = if eb > 0.0 { half_rho * eb * eb } else { 0.0 };- // small contraction (vena contracta) loss entering a narrower node- let cf = imb - ia;- let cb = ima - ib;- if cf > 0.0 {- kf += 0.1 * half_rho * cf * cf;- }- if cb > 0.0 {- kb += 0.1 * half_rho * cb * cb;+ {+ // indices were validated in finalize(): every b_a/b_b < n_nodes, and the per-branch+ // arrays all have n_branches entries+ let area = &self.area[..n];+ let amin = &self.amin[..n];+ let inv_a = &self.inv_a[..n];+ let inv_amin = &self.inv_amin[..n];+ let half_l = &self.half_l[..n];+ let half_r = &self.half_r[..n];+ let is_j = &self.is_junction[..n];+ let p = &self.p[..n];+ let flow_sum = &mut self.flow_sum[..n];+ let inv_lsum = &mut self.inv_lsum[..n];+ let (b_a, b_b, b_kind) = (&self.b_a[..nb], &self.b_b[..nb], &self.b_kind[..nb]);+ let (u_arr, mom, l_prev, psrc) = (&mut self.u[..nb], &mut self.mom[..nb], &mut self.l_prev[..nb], &self.psrc[..nb]);+ let branch_area = &mut self.branch_area[..nb];+ let port_area = &mut self.port_area[..nb];+ let (port_area_step, port_len, port_half, port_slit, port_extra_r, port_kin, port_kex) = (&self.port_area_step[..nb], &self.port_len[..nb], &self.port_half[..nb], &self.port_slit[..nb], &self.port_extra_r[..nb], &self.port_kin[..nb], &self.port_kex[..nb]);+ macro_rules! node {+ ($v:expr, $i:expr) => {+ // SAFETY: $i is a branch endpoint (< n, checked in finalize) and $v has n entries+ unsafe { *$v.get_unchecked($i) }+ };+ }+ for j in 0..nb {+ let a = b_a[j];+ let b = b_b[j];+ let l: f64;+ let r: f64;+ let mut kf: f64;+ let mut kb: f64;+ let a_eff: f64;+ if b_kind[j] == KIND_SERIES {+ let aa = node!(area, a);+ let ab = node!(area, b);+ let ma = node!(amin, a);+ let mb = node!(amin, b);+ a_eff = if ma < mb { ma } else { mb };+ if (if aa < ab { aa } else { ab }) < closed || a_eff < closed {+ u_arr[j] = 0.0;+ mom[j] = 0.0;+ branch_area[j] = a_eff;+ continue;+ }+ let ia = node!(inv_a, a);+ let ib = node!(inv_a, b);+ l = half_rho * (node!(half_l, a) + node!(half_l, b));+ // viscous: R = S·l/A² · sqrt(ρμω/2) with S = perimeter of each half-section+ r = 0.5 * visc * (node!(half_r, a) + node!(half_r, b));+ // Borda–Carnot: the jet leaving the narrowest point of the upstream node expands into+ // the downstream node (sub-section minima make short constrictions lossy as they should be)+ let ima = node!(inv_amin, a);+ let imb = node!(inv_amin, b);+ let ef = ima - ib; // a→b+ let eb = imb - ia; // b→a+ kf = if ef > 0.0 { half_rho * ef * ef } else { 0.0 };+ kb = if eb > 0.0 { half_rho * eb * eb } else { 0.0 };+ // small contraction (vena contracta) loss entering a narrower node+ let cf = imb - ia;+ let cb = ima - ib;+ if cf > 0.0 {+ kf += 0.1 * half_rho * cf * cf;+ }+ if cb > 0.0 {+ kb += 0.1 * half_rho * cb * cb;+ }+ } else {+ port_area[j] += port_area_step[j];+ let mut ap = port_area[j];+ if ap < 0.0 {+ port_area[j] = 0.0;+ ap = 0.0;+ }+ a_eff = ap;+ if ap < closed {+ u_arr[j] = 0.0;+ mom[j] = 0.0;+ branch_area[j] = ap;+ continue;+ }+ let ip = 1.0 / ap;+ let len = port_len[j];+ let mut ll = RHO * len * ip;+ if port_half[j] {+ ll += half_rho * (node!(half_l, a) + node!(half_l, b));+ }+ l = ll;+ let w = port_slit[j];+ let mut rr = if w > 0.0 { (12.0 * MU * len * w * w) * ip * ip * ip } else { visc * 2.0 * sqrt(PI) * len * sqrt(ap) * ip * ip };+ rr += port_extra_r[j];+ r = rr;+ // kinetic: entrance (contraction) + exit (jet expansion into the downstream node)+ let ex_f = ip - node!(inv_a, b); // flow a→b exits into b+ let ex_b = ip - node!(inv_a, a); // flow b→a exits into a+ let kin = port_kin[j] * half_rho * ip * ip;+ kf = kin + port_kex[j] * half_rho * (if ex_f > 0.0 { ex_f * ex_f } else { 0.0 });+ kb = kin + port_kex[j] * half_rho * (if ex_b > 0.0 { ex_b * ex_b } else { 0.0 });}- } else {- self.port_area[j] += self.port_area_step[j];- let mut ap = self.port_area[j];- if ap < 0.0 {- self.port_area[j] = 0.0;- ap = 0.0;+ branch_area[j] = a_eff;+ // energy-safe momentum transfer when the inertance changes: closing (L↑) conserves+ // momentum (flow drops), opening (L↓) conserves flow — never injects kinetic energy+ if symmetric {+ let km = if kf > kb { kf } else { kb };+ kf = km;+ kb = km;}- a_eff = ap;- if ap < closed {- self.u[j] = 0.0;- self.mom[j] = 0.0;- self.branch_area[j] = ap;- continue;+ let lp = l_prev[j];+ let m0 = if enable_energy_safe && l < lp { l * u_arr[j] } else { mom[j] };+ let c = node!(p, a) - node!(p, b) + psrc[j] + m0 * inv_t;+ let bq = l * inv_t + r;+ let u = if c >= 0.0 {+ if kf > 0.0 { (2.0 * c) / (bq + sqrt(bq * bq + 4.0 * kf * c)) } else { c / bq }+ } else if kb > 0.0 {+ (2.0 * c) / (bq + sqrt(bq * bq - 4.0 * kb * c))+ } else {+ c / bq+ };+ u_arr[j] = u;+ mom[j] = l * u;+ l_prev[j] = l;+ // SAFETY: as above (endpoints < n)+ unsafe {+ *flow_sum.get_unchecked_mut(a) -= u;+ *flow_sum.get_unchecked_mut(b) += u;}- let ip = 1.0 / ap;- let len = self.port_len[j];- let mut ll = RHO * len * ip;- if self.port_half[j] {- ll += half_rho * (self.dx[a] * self.inv_a[a] + self.dx[b] * self.inv_a[b]);+ if node!(is_j, a) | node!(is_j, b) {+ let il = 1.0 / l;+ unsafe {+ *inv_lsum.get_unchecked_mut(a) += il;+ *inv_lsum.get_unchecked_mut(b) += il;+ }}- l = ll;- let w = self.port_slit[j];- let mut rr = if w > 0.0 { (12.0 * MU * len * w * w) * ip * ip * ip } else { visc * 2.0 * sqrt(PI) * len * sqrt(ap) * ip * ip };- rr += self.port_extra_r[j];- r = rr;- // kinetic: entrance (contraction) + exit (jet expansion into the downstream node)- let ex_f = ip - self.inv_a[b]; // flow a→b exits into b- let ex_b = ip - self.inv_a[a]; // flow b→a exits into a- let kin = self.port_kin[j] * half_rho * ip * ip;- kf = kin + self.port_kex[j] * half_rho * (if ex_f > 0.0 { ex_f * ex_f } else { 0.0 });- kb = kin + self.port_kex[j] * half_rho * (if ex_b > 0.0 { ex_b * ex_b } else { 0.0 });- }- self.branch_area[j] = a_eff;- // energy-safe momentum transfer when the inertance changes: closing (L↑) conserves- // momentum (flow drops), opening (L↓) conserves flow — never injects kinetic energy- if symmetric {- let km = if kf > kb { kf } else { kb };- kf = km;- kb = km;- }- let lp = self.l_prev[j];- let m0 = if enable_energy_safe && l < lp { l * self.u[j] } else { self.mom[j] };- let c = self.p[a] - self.p[b] + self.psrc[j] + m0 * inv_t;- let bq = l * inv_t + r;- let u = if c >= 0.0 {- if kf > 0.0 { (2.0 * c) / (bq + sqrt(bq * bq + 4.0 * kf * c)) } else { c / bq }- } else if kb > 0.0 {- (2.0 * c) / (bq + sqrt(bq * bq - 4.0 * kb * c))- } else {- c / bq- };- self.u[j] = u;- self.mom[j] = l * u;- self.l_prev[j] = l;- self.flow_sum[a] -= u;- self.flow_sum[b] += u;- if self.is_junction[a] | self.is_junction[b] {- let il = 1.0 / l;- self.inv_lsum[a] += il;- self.inv_lsum[b] += il;}}@@ -970,8 +1017,8 @@ impl AirwayNetwork {let v = ((m * inv_t - 0.5 * r) * self.wall_v[k] + self.p[k] - self.wall_k[k] * self.wall_y[k]) / (m * inv_t + 0.5 * r);self.wall_v[k] = v;self.wall_y[k] += t * v;- let a = if self.area[k] > min_a { self.area[k] } else { min_a };- let uw = self.wall_perim[k] * sqrt(a) * self.dx[k] * v;+ let sa = if self.area[k] > min_a { self.sqrt_a[k] } else { sqrt(min_a) };+ let uw = self.wall_perim[k] * sa * self.dx[k] * v;self.wall_u[k] = uw;self.flow_sum[k] -= uw;wall_rad_sum += uw * self.wall_rad[k];diff --git a/crates/chimera/src/engine.rs b/crates/chimera/src/engine.rsnew file mode 100644index 0000000..b53ad6d--- /dev/null+++ b/crates/chimera/src/engine.rs@@ -0,0 +1,162 @@+//! The instrument: one human voice (any body), the creatures, and the beatbox sequencer, driven by+//! commands. This is what the browser's AudioWorklet runs and what a DAW wraps as a source module.+//!+//! Contract (see docs/rust-engine.md):+//! - Commands take effect at once, between `render` calls. A host that needs sample accuracy+//! splits its block at the event.+//! - `render` advances in 128-sample sub-blocks on an absolute sample count. The sequencer ticks at+//! each sub-block boundary, so the output does not depend on the host's block size.+//! - Rendering, gestures, releases, artic/source/gate changes and beat edits allocate nothing once+//! warm. A body or creature switch builds a new airway network (it allocates).++use crate::anatomy::human::{ArticPatch, BodyName};+use crate::control::score::{Gesture, GestureScore};+use crate::voice::human_voice::{HumanVoice, SourcePatch, VoiceTelemetry};++/// Samples per sub-block: the browser's render quantum, kept for every host.+pub const SUB_BLOCK: usize = 128;+/// Gestures taken from one schedule command (as the TypeScript worklet did).+pub const MAX_SCHEDULE: usize = 4000;++/// Default pitch per body (Hz).+pub fn default_f0(body: BodyName) -> f64 {+ match body {+ BodyName::Male => 110.0,+ BodyName::Female => 205.0,+ BodyName::Child => 260.0,+ }+}++/// Identity of the voice the engine is playing (the browser's "ready" message).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct VoiceInfo {+ pub body: BodyName,+ pub n_ph: usize,+ pub n_or: usize,+}++pub struct Engine {+ pub sample_rate: f64,+ body: BodyName,+ voice: HumanVoice,+ /// the performer's breath (the voice's own gate also follows the score)+ gate_level: f64,+ /// samples rendered so far (sub-block phase)+ pos: u64,+ scratch: Vec<Gesture>,+}++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) }+ }++ fn make_voice(fs: f64, body: BodyName) -> HumanVoice {+ let mut v = HumanVoice::new(fs, body.body(), if fs > 60000.0 { 1 } else { 2 });+ v.set_source(&SourcePatch::f0(default_f0(body)));+ v+ }++ pub fn info(&self) -> VoiceInfo {+ VoiceInfo { body: self.body, n_ph: self.voice.airway.n_ph, n_or: self.voice.airway.n_or }+ }++ pub fn voice(&self) -> &HumanVoice {+ &self.voice+ }++ pub fn voice_mut(&mut self) -> &mut HumanVoice {+ &mut self.voice+ }++ /// Switch the human body. The performer's settings carry over: source (pitch reset to the+ /// new body's default), posture, breath. Allocates (a new airway network).+ pub fn set_body(&mut self, body: BodyName) -> VoiceInfo {+ let prev = core::mem::replace(&mut self.voice, Self::make_voice(self.sample_rate, body));+ self.body = body;+ let mut src = SourcePatch::from_source(&prev.source);+ src.f0 = Some(default_f0(body));+ self.voice.set_source(&src);+ let mut target = ArticPatch::default();+ for (k, x) in prev.artic.target.to_array().iter().enumerate() {+ target.values[k] = Some(*x);+ }+ self.voice.set_articulation(&target, Some(prev.artic.tip_free));+ // the performer's breath, not the voice's (which includes breath from the score)+ self.voice.set_gate(self.gate_level);+ self.info()+ }++ pub fn set_artic(&mut self, values: &ArticPatch, tip_free: Option<bool>) {+ self.voice.set_articulation(values, tip_free);+ }++ pub fn set_source(&mut self, values: &SourcePatch) {+ self.voice.set_source(values);+ }++ pub fn set_gate(&mut self, level: f64) {+ self.gate_level = level;+ self.voice.set_gate(level);+ }++ /// Schedule gestures planned with times relative to "now": they are shifted onto the voice+ /// clock by `clock + lead`. Returns that offset (the plan's time 0 on the voice clock).+ pub fn schedule(&mut self, gestures: &[Gesture], lead: f64, replace: bool) -> f64 {+ let off = self.voice.clock + lead;+ self.scratch.clear();+ for g in gestures.iter().take(MAX_SCHEDULE) {+ let mut g = *g;+ g.t0 += off;+ g.t1 += off;+ self.scratch.push(g);+ }+ if replace {+ self.voice.cancel_score();+ }+ self.voice.schedule(&self.scratch);+ off+ }++ pub fn stop_speech(&mut self) {+ self.voice.cancel_score();+ }++ /// End the open-ended gestures with this tag now (a sung note released).+ pub fn release(&mut self, tag: f64) {+ self.voice.release(tag);+ }++ pub fn score(&self) -> &GestureScore {+ &self.voice.score+ }++ /// The voice clock (s): the time base of scheduled gestures.+ pub fn clock(&self) -> f64 {+ self.voice.clock+ }++ /// Render `out.len()` samples.+ pub fn render(&mut self, out: &mut [f32]) {+ let mut i = 0;+ while i < out.len() {+ let phase = (self.pos % SUB_BLOCK as u64) as usize;+ if phase == 0 {+ self.sub_block_start();+ }+ let n = (SUB_BLOCK - phase).min(out.len() - i);+ self.voice.render(&mut out[i..i + n]);+ i += n;+ self.pos += n as u64;+ }+ }++ /// Per-sub-block bookkeeping (the sequencer's tick).+ fn sub_block_start(&mut self) {}++ pub fn telemetry(&mut self, out: &mut VoiceTelemetry) {+ self.voice.telemetry(out);+ }+}diff --git a/crates/chimera/src/lib.rs b/crates/chimera/src/lib.rsindex 67bd07e..b8fd9c0 100644--- a/crates/chimera/src/lib.rs+++ b/crates/chimera/src/lib.rs@@ -46,4 +46,11 @@ pub mod util {}pub mod creatures;+pub mod engine;pub mod phonetics;++/// Parse every embedded data table now (an `Engine` does this when it is created), so nothing+/// initialises lazily on an audio thread later.+pub fn init() {+ phonetics::planner::vowel_table();+}diff --git a/crates/chimera/tests/common/mod.rs b/crates/chimera/tests/common/mod.rsindex 970ef5d..beb96fc 100644--- a/crates/chimera/tests/common/mod.rs+++ b/crates/chimera/tests/common/mod.rs@@ -61,10 +61,10 @@ pub fn save_json(name: &str, v: &Value) {println!("blessed {path}");}-/// Renders must agree sample for sample (to ~1e-6 of peak) until a discrete decision can go the-/// other way on a last-ulp difference (V8's libm and Rust's differ there; e.g. which of two-/// near-equal sections is the narrowest, so where the frication noise is injected). After that-/// the loudness envelope must still agree to 0.05 dB in every 10 ms window.+/// For renders that may legitimately part after a discrete decision goes the other way on a+/// last-ulp difference (V8's libm and Rust's differ in the last bit of some functions; chaotic or+/// self-oscillating sources can amplify that): the loudness envelope must still agree to 0.05 dB+/// in every 10 ms window. Renders expected to agree throughout assert `first_diverge.is_none()`.pub fn assert_close(name: &str, d: &AudioDiff) {assert!(d.env_db < 0.05, "{name}: RMS envelope differs by {:.3} dB (max sample error {:.2e} of peak, first at {:?})", d.env_db, d.max_err, d.first_diverge);}diff --git a/crates/chimera/tests/golden_voice.rs b/crates/chimera/tests/golden_voice.rsindex 227b35c..ba5390d 100644--- a/crates/chimera/tests/golden_voice.rs+++ b/crates/chimera/tests/golden_voice.rs@@ -62,7 +62,8 @@ fn voice_matches_typescript() {}let d = compare_audio(&reference, &got, 1e-6, 480);println!("{name:>20}: peak {:.3} max err {:.2e} first >1e-6 at {:?} env {:.4} dB", d.peak, d.max_err, d.first_diverge, d.env_db);- assert_close(name, &d);+ // the human voice is linear enough (and the port literal enough) to agree throughout+ assert!(d.first_diverge.is_none(), "{name}: renders diverge from sample {:?} (max error {:.2e} of peak)", d.first_diverge, d.max_err);for block in [1usize, 77, 4096] {assert_eq!(run(s, block), got, "{name}: block size {block} changed the output");}diff --git a/src/wasm/types.ts b/src/wasm/types.tsnew file mode 100644index 0000000..6d2f1e6--- /dev/null+++ b/src/wasm/types.ts@@ -0,0 +1,20 @@+/** Engine types as the UI sees them (the JSON shapes of the Rust engine's serde types). */+export type ArticKey = "jaw" | "tbX" | "tbY" | "ttX" | "ttY" | "ttCurl" | "root" | "lipAp" | "lipProt" | "lipWidth" | "labiodental" | "velum" | "larynx" | "epilarynx" | "ventricular" | "lateral" | "dorsum";+export type SourceKey = "abduction" | "closure" | "breath" | "f0" | "vibrato";+export type ControlKey = ArticKey | SourceKey;++export interface Gesture {+ t0: number;+ t1: number;+ rampIn: number;+ rampOut: number;+ strength: number;+ targets: Partial<Record<ControlKey, number>>;+ /** articulator speed multiplier while active and during `releaseHold` seconds after t1 */+ speed?: number;+ releaseHold?: number;+ /** label for visualisation (phoneme / gesture name) */+ label?: string;+ /** open-ended gestures (a sung note held until its key is released) end via release(tag) */+ tag?: number;+}diff --git a/src/wasm/wire.ts b/src/wasm/wire.tsnew file mode 100644index 0000000..47613bc--- /dev/null+++ b/src/wasm/wire.ts@@ -0,0 +1,76 @@+/**+ * The engine's binary gesture records (layout version 1, crates/chimera-wasm/src/lib.rs): how+ * gestures cross into the wasm engine on the audio thread, where JSON and TextEncoder are out of+ * reach. 272 little-endian bytes per gesture; NaN marks an absent value.+ */+import type { Gesture } from "./types.ts";++export const LAYOUT_VERSION = 1;+export const GESTURE_RECORD = 272;++/** Control keys in the engine's order: the 17 articulators, then the source channels. */+export const CONTROL_KEYS = [+ "jaw", "tbX", "tbY", "ttX", "ttY", "ttCurl", "root", "lipAp", "lipProt", "lipWidth", "labiodental", "velum", "larynx", "epilarynx", "ventricular", "lateral", "dorsum",+ "abduction", "closure", "breath", "f0", "vibrato",+] as const;+const KEY_INDEX: Record<string, number> = Object.fromEntries(CONTROL_KEYS.map((k, i) => [k, i]));+const LABEL_CAP = 24;++/** UTF-8 encode (no TextEncoder in the AudioWorkletGlobalScope). */+export function utf8(s: string): number[] {+ const out: number[] = [];+ for (const ch of s) {+ const c = ch.codePointAt(0)!;+ if (c < 0x80) out.push(c);+ else if (c < 0x800) out.push(0xc0 | (c >> 6), 0x80 | (c & 63));+ else if (c < 0x10000) out.push(0xe0 | (c >> 12), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));+ else out.push(0xf0 | (c >> 18), 0x80 | ((c >> 12) & 63), 0x80 | ((c >> 6) & 63), 0x80 | (c & 63));+ }+ return out;+}++/** UTF-8 decode (no TextDecoder in the AudioWorkletGlobalScope). */+export function fromUtf8(b: Uint8Array): string {+ let s = "";+ for (let i = 0; i < b.length; ) {+ const c = b[i];+ let cp: number;+ if (c < 0x80) (cp = c), (i += 1);+ else if (c < 0xe0) (cp = ((c & 31) << 6) | (b[i + 1] & 63)), (i += 2);+ else if (c < 0xf0) (cp = ((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63)), (i += 3);+ else (cp = ((c & 7) << 18) | ((b[i + 1] & 63) << 12) | ((b[i + 2] & 63) << 6) | (b[i + 3] & 63)), (i += 4);+ s += String.fromCodePoint(cp);+ }+ return s;+}++/** Write gestures as records at byte offset `at` of `buf` (as many as fit in `max`). Returns the count written. */+export function writeGestures(buf: ArrayBuffer, at: number, gestures: readonly Gesture[], max: number): number {+ const n = Math.min(gestures.length, max);+ const dv = new DataView(buf, at, n * GESTURE_RECORD);+ const bytes = new Uint8Array(buf, at, n * GESTURE_RECORD);+ for (let i = 0; i < n; i++) {+ const g = gestures[i];+ const o = i * GESTURE_RECORD;+ const head = [g.t0, g.t1, g.rampIn, g.rampOut, g.strength, g.speed ?? NaN, g.releaseHold ?? NaN, g.tag ?? NaN];+ for (let j = 0; j < 8; j++) dv.setFloat64(o + j * 8, head[j], true);+ for (let k = 0; k < CONTROL_KEYS.length; k++) dv.setFloat64(o + 64 + k * 8, NaN, true);+ for (const [key, value] of Object.entries(g.targets)) {+ const k = KEY_INDEX[key];+ if (k !== undefined && value !== undefined) dv.setFloat64(o + 64 + k * 8, value, true);+ }+ if (g.label === undefined) bytes[o + 240] = 255;+ else {+ let b = utf8(g.label);+ if (b.length > LABEL_CAP) {+ // cut at a character boundary (continuation bytes are 10xxxxxx)+ let n = LABEL_CAP;+ while (n > 0 && (b[n] & 0xc0) === 0x80) n--;+ b = b.slice(0, n);+ }+ bytes[o + 240] = b.length;+ bytes.set(b, o + 241);+ }+ }+ return n;+}diff --git a/tests/wasm-engine.test.ts b/tests/wasm-engine.test.tsnew file mode 100644index 0000000..71bff13--- /dev/null+++ b/tests/wasm-engine.test.ts@@ -0,0 +1,92 @@+/**+ * The wasm build of the Rust engine: no imports, and the same samples as the native build (bit+ * for bit) on the voice scenarios, driven through the gesture-record codec the worklet uses.+ * Needs `bun run wasm` (the wasm build) and cargo (it renders the native reference).+ */+import { describe, expect, test } from "bun:test";+import { readFileSync, existsSync } from "node:fs";+import { writeGestures, CONTROL_KEYS, GESTURE_RECORD } from "../src/wasm/wire.ts";+import type { Gesture } from "../src/wasm/types.ts";++const ROOT = new URL("..", import.meta.url).pathname;+const WASM = `${ROOT}target/wasm32-unknown-unknown/release/chimera_wasm.wasm`;+const SOURCE_KEYS = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];++interface Exports {+ memory: WebAssembly.Memory;+ [k: string]: unknown;+}++function instance(): Exports {+ const mod = new WebAssembly.Module(readFileSync(WASM));+ expect(WebAssembly.Module.imports(mod)).toEqual([]);+ return new WebAssembly.Instance(mod, {}).exports as unknown as Exports;+}++type Op = { at: number; op: string; [k: string]: unknown };+type F = (...a: number[]) => number;++function render(x: Exports, s: { body: string; fsOut: number; samples: number; ops: Op[] }): Float32Array {+ const fn = (name: string) => x[name] as F;+ const h = fn("engine_new")(s.fsOut);+ const body = { male: 0, female: 1, child: 2 }[s.body] ?? 0;+ if (body) fn("engine_set_body")(h, body);+ const out = new Float32Array(s.samples);+ const ops = [...s.ops].sort((a, b) => a.at - b.at);+ let i = 0, oi = 0;+ while (i < s.samples) {+ while (oi < ops.length && ops[oi].at <= i) {+ const o = ops[oi++];+ const vals = () => new Float64Array(x.memory.buffer, fn("engine_values")(h), 32).fill(NaN);+ if (o.op === "gate") fn("engine_set_gate")(h, o.level as number);+ else if (o.op === "artic") {+ const v = vals();+ for (const [k, val] of Object.entries(o.values as object)) v[CONTROL_KEYS.indexOf(k as never)] = val as number;+ fn("engine_set_artic")(h, o.tipFree === undefined ? 2 : o.tipFree ? 1 : 0);+ } else if (o.op === "source") {+ const v = vals();+ for (const [k, val] of Object.entries(o.values as object)) v[SOURCE_KEYS.indexOf(k)] = typeof val === "boolean" ? (val ? 1 : 0) : val;+ fn("engine_set_source")(h);+ } else if (o.op === "schedule") {+ const gs = o.gestures as Gesture[];+ const n = writeGestures(x.memory.buffer, fn("engine_records")(h), gs, 4000);+ fn("engine_schedule")(h, n, o.offset as number, 0);+ } else if (o.op === "release") fn("engine_release")(h, o.tag as number);+ else fn("engine_stop_speech")(h);+ }+ const next = oi < ops.length ? Math.max(i + 1, ops[oi].at) : Infinity;+ const m = Math.min(128, s.samples - i, next - i);+ const p = fn("engine_render")(h, m);+ out.set(new Float32Array(x.memory.buffer, p, m), i);+ i += m;+ }+ fn("engine_free")(h);+ return out;+}++describe("wasm engine", () => {+ test.skipIf(!existsSync(WASM))("renders the voice scenarios bit-identically to the native build", () => {+ const proc = Bun.spawnSync(["cargo", "run", "-q", "--release", "-p", "chimera-wasm", "--example", "render_scenarios"], { cwd: ROOT });+ expect(proc.exitCode).toBe(0);+ const scenarios = JSON.parse(readFileSync(`${ROOT}crates/chimera/tests/golden/voice.json`, "utf8"));+ const x = instance();+ for (const s of scenarios) {+ const wasm = render(x, s);+ const native = new Float32Array(readFileSync(`${ROOT}target/native-render/${s.name}.f32`).buffer.slice(0));+ expect(wasm.length).toBe(native.length);+ let diff = 0, first = -1, maxd = 0;+ for (let i = 0; i < wasm.length; i++)+ if (Object.is(wasm[i], native[i]) === false) {+ diff++;+ if (first < 0) first = i;+ maxd = Math.max(maxd, Math.abs(wasm[i] - native[i]));+ }+ if (diff) console.log(`${s.name}: first difference at ${first} (${(first / s.fsOut).toFixed(4)} s): wasm ${wasm[first]} native ${native[first]}; max |Δ| ${maxd}`);+ expect(`${s.name}: ${diff} samples differ`).toBe(`${s.name}: 0 samples differ`);+ }+ }, 120000);+ test("gesture records are 272 bytes", () => {+ expect(GESTURE_RECORD).toBe(272);+ expect(CONTROL_KEYS.length).toBe(22);+ });+});diff --git a/tools/bench-wasm.ts b/tools/bench-wasm.tsnew file mode 100644index 0000000..c1256bc--- /dev/null+++ b/tools/bench-wasm.ts@@ -0,0 +1,33 @@+/**+ * Real-time factor of the human voice: the wasm build (as the AudioWorklet runs it) next to the+ * TypeScript engine, on the same speech. Usage: bun tools/bench-wasm.ts (after `bun run wasm`).+ */+import { readFileSync, existsSync } from "node:fs";+import { writeGestures } from "../src/wasm/wire.ts";++const ROOT = new URL("..", import.meta.url).pathname;+const scenario = JSON.parse(readFileSync(`${ROOT}crates/chimera/tests/golden/voice.json`, "utf8")).find((s: { name: string }) => s.name === "speech-male");+const gestures = scenario.ops[0].gestures;+const FS = 48000, SECS = 4, BLOCKS = (FS * SECS) / 128;++const x = new WebAssembly.Instance(new WebAssembly.Module(readFileSync(`${ROOT}target/wasm32-unknown-unknown/release/chimera_wasm.wasm`)), {}).exports as Record<string, (...a: number[]) => number> & { memory: WebAssembly.Memory };+const h = x.engine_new(FS);+writeGestures(x.memory.buffer, x.engine_records(h), gestures, 4000);+x.engine_schedule(h, gestures.length, 0.03, 0);+x.engine_set_gate(h, 1);+let t0 = performance.now();+for (let i = 0; i < BLOCKS; i++) x.engine_render(h, 128);+const wasm = (performance.now() - t0) / 1000;+console.log(`wasm human male os=2: ${((100 * wasm) / SECS).toFixed(1)}% of one core`);++if (existsSync(`${ROOT}src/engine/voice/humanVoice.ts`)) {+ const { HumanVoice } = await import(`${ROOT}src/engine/voice/humanVoice.ts`);+ const v = new HumanVoice({ fsOut: FS });+ v.schedule(gestures.map((g: { t0: number; t1: number }) => ({ ...g, t0: g.t0 + 0.03, t1: g.t1 + 0.03 })));+ v.setGate(1);+ const out = new Float32Array(128);+ t0 = performance.now();+ for (let i = 0; i < BLOCKS; i++) v.render(out, 0, 128);+ const ts = (performance.now() - t0) / 1000;+ console.log(`TS human male os=2: ${((100 * ts) / SECS).toFixed(1)}% of one core (wasm is ${(ts / wasm).toFixed(2)}× faster)`);+}