the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Review fixes: no unsafe in the FDTD step, creature telemetry layout, warm buffers
Jameson Hodged819611f5ac8
diff --git a/Cargo.lock b/Cargo.lockindex 8c21cd2..2b6a6d4 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -42,6 +42,12 @@ dependencies = ["cfg-if",]+[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"+[[package]]name = "flate2"version = "1.1.10"@@ -53,6 +59,28 @@ dependencies = ["zlib-rs",]+[[package]]+name = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown",+]+[[package]]name = "itoa"version = "1.0.18"@@ -135,6 +163,8 @@ version = "1.0.154"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"dependencies = [+ "foldhash",+ "indexmap","itoa","memchr","serde",diff --git a/crates/chimera-wasm/Cargo.toml b/crates/chimera-wasm/Cargo.tomlindex 4d4e41f..3c0ff1e 100644--- a/crates/chimera-wasm/Cargo.toml+++ b/crates/chimera-wasm/Cargo.toml@@ -12,4 +12,4 @@ crate-type = ["cdylib", "rlib"][dependencies]chimera = { path = "../chimera" }serde = "1"-serde_json = { version = "1", features = ["float_roundtrip"] }+serde_json = { version = "1", features = ["float_roundtrip", "preserve_order"] }diff --git a/crates/chimera-wasm/src/lib.rs b/crates/chimera-wasm/src/lib.rsindex de7da84..fbc9027 100644--- a/crates/chimera-wasm/src/lib.rs+++ b/crates/chimera-wasm/src/lib.rs@@ -486,8 +486,10 @@ pub unsafe extern "C" fn engine_set_creature(h: *mut Handle, ptr: *const u8, len}}h.engine.set_creature(Some(def), &initial);- let c = h.engine.creature().unwrap();- let t = c.new_telemetry();+ // a filled snapshot (taken now, while switching allocates anyway) gives the layout the+ // worklet decodes and the block's capacity; `new_telemetry` alone only reserves room+ let mut t = h.engine.creature().unwrap().new_telemetry();+ h.engine.creature_telemetry(&mut t);let info = serde_json::json!({"id": def.id,"params": def.params.iter().map(|p| p.key).collect::<Vec<_>>(),diff --git a/crates/chimera-wasm/tests/realtime.rs b/crates/chimera-wasm/tests/realtime.rsnew file mode 100644index 0000000..b5aeb43--- /dev/null+++ b/crates/chimera-wasm/tests/realtime.rs@@ -0,0 +1,107 @@+//! The audio-thread ABI allocates nothing once an engine exists: from idle into the first labelled+//! speech gestures, telemetry snapshots, the sequencer and pad hits, releases and parameter+//! changes; and, after a creature switch (which may allocate), the creature's rendering,+//! telemetry, params and calls. Driven through the same C ABI the worklet uses.+use chimera::phonetics::ipa::tokenize_ipa;+use chimera::phonetics::planner::{PlanOptions, plan_utterance};+use chimera_wasm::*;+use std::alloc::{GlobalAlloc, Layout, System};+use std::cell::Cell;++struct Counting;+thread_local! {+ static ALLOCS: Cell<usize> = const { Cell::new(0) };+}+unsafe impl GlobalAlloc for Counting {+ unsafe fn alloc(&self, l: Layout) -> *mut u8 {+ ALLOCS.with(|n| n.set(n.get() + 1));+ unsafe { System.alloc(l) }+ }+ unsafe fn dealloc(&self, p: *mut u8, l: Layout) {+ unsafe { System.dealloc(p, l) }+ }+ unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {+ ALLOCS.with(|c| c.set(c.get() + 1));+ unsafe { System.realloc(p, l, n) }+ }+}+#[global_allocator]+static A: Counting = Counting;+fn allocs() -> usize {+ ALLOCS.with(|n| n.get())+}++fn write_step(rec: &mut [u8], id: &str) {+ rec[0] = id.len() as u8;+ rec[1..1 + id.len()].copy_from_slice(id.as_bytes());+ rec[32..40].copy_from_slice(&f64::NAN.to_le_bytes());+ rec[40..48].copy_from_slice(&f64::NAN.to_le_bytes());+}++#[test]+fn the_audio_thread_abi_does_not_allocate() {+ let h = engine_new(48000.0);+ // planned off the audio thread+ let plan = plan_utterance(&tokenize_ipa("ˈhɛloʊ ˈwɝld ʃi sɛlz"), &PlanOptions { body: "male".into(), t0: 0.0, f0: Some(110.0), ..Default::default() });+ let creature_req = br#"{"id":"elephant","params":{"pitch":20}}"#.to_vec();+ unsafe {+ let render = |blocks: usize| {+ for b in 0..blocks {+ engine_render(h, 128);+ if b % 6 == 0 {+ engine_telemetry(h);+ engine_beat_step(h);+ }+ }+ };+ render(40); // idle for a while: nothing labelled has been seen yet+ let before = allocs();+ let rec = std::slice::from_raw_parts_mut(engine_records(h), plan.gestures.len() * GESTURE_RECORD);+ for (i, g) in plan.gestures.iter().enumerate() {+ write_gesture(g, &mut rec[i * GESTURE_RECORD..(i + 1) * GESTURE_RECORD]);+ }+ engine_schedule(h, plan.gestures.len(), 0.03, 1);+ render(400); // speech: labelled gestures in every telemetry snapshot+ let vals = std::slice::from_raw_parts_mut(engine_values(h), 32);+ vals.fill(f64::NAN);+ vals[0] = 0.8; // jaw+ engine_set_artic(h, 2);+ vals.fill(f64::NAN);+ vals[0] = 140.0; // f0+ engine_set_source(h);+ engine_set_gate(h, 1.0);+ let steps = std::slice::from_raw_parts_mut(engine_records(h), 4 * STEP_RECORD);+ for (i, id) in ["B", "t", "Pf", "t"].iter().enumerate() {+ write_step(&mut steps[i * STEP_RECORD..(i + 1) * STEP_RECORD], id);+ }+ engine_set_beat(h, 1, 4, 120.0, 0.1, 1);+ render(300);+ write_step(&mut steps[..STEP_RECORD], "K");+ engine_beat_hit(h);+ engine_release(h, 7.0);+ render(100);+ engine_set_beat(h, 0, 0, f64::NAN, f64::NAN, 0);+ engine_stop_speech(h);+ render(50);+ assert_eq!(allocs() - before, 0, "the human voice's audio path allocated");++ // a creature switch allocates; what follows must not+ assert_eq!(engine_set_creature(h, creature_req.as_ptr(), creature_req.len()), 0);+ let before = allocs();+ for b in 0..600 {+ engine_render(h, 128);+ if b % 6 == 0 {+ assert!(!engine_creature_telemetry(h).is_null());+ }+ match b {+ 50 => engine_play_call(h, 0, f64::NAN, f64::NAN),+ 200 => engine_creature_param(h, 0, 30.0),+ 300 => engine_play_call(h, 1, 25.0, 0.8),+ 400 => engine_stop_call(h),+ _ => {}+ }+ }+ assert_eq!(allocs() - before, 0, "the creature's audio path allocated");+ engine_free(h);+ }+}diff --git a/crates/chimera/src/airway/network.rs b/crates/chimera/src/airway/network.rsindex a7fcd78..455989e 100644--- a/crates/chimera/src/airway/network.rs+++ b/crates/chimera/src/airway/network.rs@@ -550,9 +550,6 @@ 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);@@ -872,8 +869,8 @@ impl AirwayNetwork {let enable_energy_safe = self.energy_safe;let symmetric = self.symmetric_kinetic;{- // indices were validated in finalize(): every b_a/b_b < n_nodes, and the per-branch- // arrays all have n_branches entries+ // the arrays the branch loop reads, borrowed once (checked indexing costs nothing+ // measurable here, against get_unchecked)let area = &self.area[..n];let amin = &self.amin[..n];let inv_a = &self.inv_a[..n];@@ -889,12 +886,6 @@ impl AirwayNetwork {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];@@ -904,10 +895,10 @@ impl AirwayNetwork {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);+ let aa = area[a];+ let ab = area[b];+ let ma = amin[a];+ let mb = 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;@@ -915,15 +906,15 @@ impl AirwayNetwork {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));+ let ia = inv_a[a];+ let ib = inv_a[b];+ l = half_rho * (half_l[a] + 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));+ r = 0.5 * visc * (half_r[a] + 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 ima = inv_amin[a];+ let imb = inv_amin[b];let ef = ima - ib; // a→blet eb = imb - ia; // b→akf = if ef > 0.0 { half_rho * ef * ef } else { 0.0 };@@ -955,7 +946,7 @@ impl AirwayNetwork {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));+ ll += half_rho * (half_l[a] + half_l[b]);}l = ll;let w = port_slit[j];@@ -963,8 +954,8 @@ impl AirwayNetwork {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 ex_f = ip - inv_a[b]; // flow a→b exits into b+ let ex_b = ip - inv_a[a]; // flow b→a exits into alet 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 });@@ -979,7 +970,7 @@ impl AirwayNetwork {}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 c = p[a] - 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 }@@ -991,17 +982,12 @@ impl AirwayNetwork {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;- }- if node!(is_j, a) | node!(is_j, b) {+ flow_sum[a] -= u;+ flow_sum[b] += u;+ if is_j[a] | is_j[b] {let il = 1.0 / l;- unsafe {- *inv_lsum.get_unchecked_mut(a) += il;- *inv_lsum.get_unchecked_mut(b) += il;- }+ inv_lsum[a] += il;+ inv_lsum[b] += il;}}}diff --git a/crates/chimera/src/anatomy/human.rs b/crates/chimera/src/anatomy/human.rsindex c25663e..9f97920 100644--- a/crates/chimera/src/anatomy/human.rs+++ b/crates/chimera/src/anatomy/human.rs@@ -425,6 +425,62 @@ struct Scratch {outline: Polyline,}+/// Room reserved in every point buffer: the outlines' lengths vary with the posture (how much of+/// the pharyngeal wall and tongue root they take), and reserving the most they can hold up front+/// keeps a voice from allocating the first time it meets a new posture.+const POINTS: usize = 256;++impl Scratch {+ fn new() -> Scratch {+ let pts = || Vec::with_capacity(POINTS);+ let line = || Polyline::with_capacity(POINTS);+ Scratch {+ tmp: vec![0.0; MAX_CROSS],+ cross_t: vec![0.0; MAX_CROSS],+ cross_exit: vec![false; MAX_CROSS],+ vel: pts(),+ vel_oral: pts(),+ vel_nasal: pts(),+ outer: line(),+ inner: line(),+ upper_lip_in: pts(),+ lower_lip_in: pts(),+ lip_out: pts(),+ root: pts(),+ arc_pts: pts(),+ blade: pts(),+ under: pts(),+ back: pts(),+ roof: line(),+ cum: Vec::with_capacity(POINTS),+ tip_pts: pts(),+ outline: line(),+ }+ }+}++impl HumanFrame {+ /// A frame with room for any posture's outlines (see [`HumanVocalTract::compute`]).+ pub fn with_capacity() -> HumanFrame {+ let pts = || Vec::with_capacity(POINTS);+ HumanFrame {+ outer: pts(),+ inner: pts(),+ tongue: pts(),+ velum: pts(),+ upper_lip: pts(),+ lower_lip: pts(),+ upper_teeth: pts(),+ lower_teeth: pts(),+ jaw_bone: pts(),+ epiglottis: pts(),+ nasal_cavity: pts(),+ grid: Vec::with_capacity(64),+ ..Default::default()+ }+ }+}+#[derive(Clone, Debug)]pub struct HumanVocalTract {pub body: HumanBody,@@ -459,7 +515,7 @@ impl HumanVocalTract {polar_c: v(0.0, 0.0),polar_c2: v(0.0, 0.0),nasal_cavity: Vec::new(),- sc: Scratch { tmp: vec![0.0; MAX_CROSS], cross_t: vec![0.0; MAX_CROSS], cross_exit: vec![false; MAX_CROSS], ..Default::default() },+ sc: Scratch::new(),contact_tip: 1.0,contact_body: 1.0,contact_tip_n: v(0.0, -1.0),diff --git a/crates/chimera/src/voice/human_airway.rs b/crates/chimera/src/voice/human_airway.rsindex 0671efb..0b3fbc9 100644--- a/crates/chimera/src/voice/human_airway.rs+++ b/crates/chimera/src/voice/human_airway.rs@@ -149,7 +149,7 @@ impl HumanAirway {base: None,base_dt: 0.0,noise_list: Vec::with_capacity(8),- scratch_frame: HumanFrame::default(),+ scratch_frame: HumanFrame::with_capacity(),}}diff --git a/crates/chimera/src/voice/human_voice.rs b/crates/chimera/src/voice/human_voice.rsindex 57cabb0..f052485 100644--- a/crates/chimera/src/voice/human_voice.rs+++ b/crates/chimera/src/voice/human_voice.rs@@ -560,6 +560,8 @@ impl HumanVoice {out.gate = self.gate;out.clock = self.clock;out.active.clear();+ // room for every label it can hold, so the first labelled gesture does not allocate+ out.active.reserve(4);for g in self.score.active_at(self.clock) {if out.active.len() == 4 {break;diff --git a/crates/chimera/tests/golden_planning.rs b/crates/chimera/tests/golden_planning.rsindex 39bfff8..98b61ff 100644--- a/crates/chimera/tests/golden_planning.rs+++ b/crates/chimera/tests/golden_planning.rs@@ -29,8 +29,11 @@ struct Stats {fn cmp(path: &str, want: &Value, got: &Value, st: &mut Stats) {match (want, got) {(Value::Object(a), Value::Object(b)) => {- let ka: Vec<&String> = a.keys().collect();- let kb: Vec<&String> = b.keys().collect();+ // the same keys (in any order: JSON objects are maps)+ let mut ka: Vec<&String> = a.keys().collect();+ let mut kb: Vec<&String> = b.keys().collect();+ ka.sort();+ kb.sort();assert_eq!(ka, kb, "{path}: keys differ");for (k, va) in a {let p = format!("{path}.{k}");diff --git a/tests/creature-abi.test.ts b/tests/creature-abi.test.tsnew file mode 100644index 0000000..94d8a04--- /dev/null+++ b/tests/creature-abi.test.ts@@ -0,0 +1,56 @@+/**+ * Creatures through the worklet: after a switch, the telemetry the processor decodes has the+ * creature's real layout (every tube's nodes, every source, every param), matching what the+ * engine reports for the same creature on the main thread.+ */+import { describe, expect, test } from "bun:test";+import { initEngine, wasmModule } from "./harness.ts";++await initEngine();+const { CREATURES, creaturePreview } = await import("../src/wasm/engine.ts");++describe("creature telemetry through the worklet", () => {+ test("every creature's tubes, sources and params arrive with their real sizes", 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; t?: unknown; message?: string }[] = [];+ const g = globalThis as Record<string, unknown>;+ g.sampleRate = 48000;+ g.AudioWorkletProcessor = class {+ port = { onmessage: null as unknown, postMessage: (m: { type: string }) => posted.push(m) };+ };+ g.registerProcessor = (_name: string, ctor: typeof Ctor) => (Ctor = ctor);+ await import("../src/worklet/processor.ts?creature-abi");+ const p = new Ctor!({ processorOptions: { module: wasmModule } });+ const send = (data: unknown) => p.port.onmessage!({ data });+ expect(CREATURES.length).toBeGreaterThan(0);+ for (const def of CREATURES) {+ send({ type: "creature", id: def.id });+ send({ type: "gate", level: 1 });+ send({ type: "call", id: def.calls[0].id });+ posted.length = 0;+ for (let i = 0; i < 24; i++) p.process([], [[new Float32Array(128)]]);+ const tele = posted.filter((m) => m.type === "ctelemetry").map((m) => m.t as import("../src/wasm/types.ts").CreatureTelemetry);+ expect(tele.length).toBeGreaterThan(0);+ const t = tele.at(-1)!;+ const ref = creaturePreview(def.id);+ expect(t.id).toBe(def.id);+ expect(Object.keys(t.params)).toEqual(def.params.map((q) => q.key));+ expect(Object.keys(t.source)).toEqual(Object.keys(ref.source));+ expect(Object.keys(t.tubes)).toEqual(Object.keys(ref.tubes));+ for (const [name, tube] of Object.entries(ref.tubes)) {+ expect(t.tubes[name].areas.length).toBe(tube.areas.length);+ expect(t.tubes[name].rms.length).toBe(tube.areas.length);+ expect(tube.areas.length).toBeGreaterThan(0);+ for (const a of t.tubes[name].areas) expect(Number.isFinite(a)).toBe(true);+ }+ expect(t.call).toBe(def.calls[0].id);+ expect(t.outRms).toBeGreaterThan(0);+ }+ send({ type: "creature", id: "human" });+ posted.length = 0;+ for (let i = 0; i < 6; i++) p.process([], [[new Float32Array(128)]]);+ expect(posted.some((m) => m.type === "telemetry")).toBe(true);+ expect(posted.filter((m) => m.type === "error")).toEqual([]);+ });+});