Skip to content

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

Rust

Engine facade groundwork: JSON call API, telemetry block, wasm loading before the UI

Jameson Hodgea662a371a7cb
diff --git a/.gitignore b/.gitignore
index 98b10cb..7f61610 100644
--- a/.gitignore
+++ b/.gitignore
@@ -4,3 +4,4 @@ out
*.wav
.DS_Store
target/
+src/wasm/chimera.wasm
diff --git a/Cargo.lock b/Cargo.lock
index ec4277a..48052e3 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -16,6 +16,7 @@ name = "chimera-wasm"
version = "0.1.0"
dependencies = [
"chimera",
+ "serde",
"serde_json",
]
diff --git a/crates/chimera-wasm/Cargo.toml b/crates/chimera-wasm/Cargo.toml
index a8883d4..4d4e41f 100644
--- a/crates/chimera-wasm/Cargo.toml
+++ b/crates/chimera-wasm/Cargo.toml
@@ -11,4 +11,5 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
chimera = { path = "../chimera" }
+serde = "1"
serde_json = { version = "1", features = ["float_roundtrip"] }
diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rs
new file mode 100644
index 0000000..c7e4a2f
--- /dev/null
+++ b/crates/chimera-wasm/src/api.rs
@@ -0,0 +1,113 @@
+//! The main thread's JSON calls: `chimera_call` takes `{"fn": name, ...args}` as UTF-8 JSON in a
+//! buffer from `chimera_alloc`, and leaves the JSON result (or `{"error": message}`) in a buffer
+//! read with `chimera_result_ptr`/`chimera_result_len`, valid until the next call. Nothing here
+//! runs on the audio thread: these calls allocate.
+
+use chimera::anatomy::human::{BodyName, HumanArtic, HumanFrame};
+use chimera::voice::human_airway::HumanAirway;
+use serde_json::{Value, json};
+use std::cell::RefCell;
+
+struct Model {
+ body: BodyName,
+ fs: f64,
+ airway: HumanAirway,
+}
+
+#[derive(Default)]
+struct State {
+ result: Vec<u8>,
+ models: Vec<Model>,
+}
+
+thread_local! {
+ static STATE: RefCell<State> = RefCell::new(State::default());
+}
+
+type Res = Result<Value, String>;
+
+fn arg<T: serde::de::DeserializeOwned>(req: &Value, key: &str) -> Result<T, String> {
+ serde_json::from_value(req.get(key).cloned().unwrap_or(Value::Null)).map_err(|e| format!("{key}: {e}"))
+}
+
+fn model<'a>(st: &'a mut State, req: &Value) -> Result<&'a mut Model, String> {
+ let id: usize = arg(req, "model")?;
+ st.models.get_mut(id).ok_or_else(|| format!("no model {id}"))
+}
+
+fn dispatch(st: &mut State, req: &Value) -> Res {
+ let name = req.get("fn").and_then(Value::as_str).ok_or("missing fn")?;
+ match name {
+ "version" => Ok(json!({ "layout": crate::LAYOUT_VERSION, "crate": env!("CARGO_PKG_VERSION") })),
+ // ---------------------------------------------------------------- the anatomy model
+ "model" => {
+ // the main-thread mirror of the worklet's airway: same topology and node counts
+ let body = BodyName::parse(&arg::<String>(req, "body")?);
+ let fs: f64 = arg(req, "sampleRate")?;
+ let m = if fs > 60000.0 { 1.0 } else { 2.0 };
+ let id = match st.models.iter().position(|x| x.body == body && x.fs == fs * m) {
+ Some(i) => i,
+ None => {
+ st.models.push(Model { body, fs: fs * m, airway: HumanAirway::new(fs * m, body.body()) });
+ st.models.len() - 1
+ }
+ };
+ let a = &st.models[id].airway;
+ Ok(json!({
+ "model": id,
+ "body": a.body,
+ "nPh": a.n_ph,
+ "nOr": a.n_or,
+ "pharynxBranches": { "base": a.pharynx.branch_base, "n": a.pharynx.n },
+ "oralBranches": { "base": a.oral.branch_base, "n": a.oral.n },
+ "glottisPort": a.glottis_port,
+ }))
+ }
+ "frame" => {
+ let a: HumanArtic = arg(req, "artic")?;
+ let m = model(st, req)?;
+ let f: HumanFrame = m.airway.tract.compute_new(&a);
+ serde_json::to_value(&f).map_err(|e| e.to_string())
+ }
+ "apply" => {
+ let a: HumanArtic = arg(req, "artic")?;
+ let m = model(st, req)?;
+ m.airway.apply(&a, 0.0);
+ let air = &m.airway;
+ Ok(json!({ "phAreas": air.ph_areas, "orAreas": air.or_areas, "phLen": air.ph_len, "orLen": air.or_len }))
+ }
+ _ => Err(format!("unknown fn {name}")),
+ }
+}
+
+/// Run one JSON call (see the module docs). Returns 0 on success, 1 if the result is an error.
+///
+/// # Safety
+/// `ptr..ptr+len` must be readable (a buffer from `chimera_alloc`).
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn chimera_call(ptr: *const u8, len: usize) -> u32 {
+ let bytes = unsafe { core::slice::from_raw_parts(ptr, len) };
+ STATE.with(|s| {
+ let mut st = s.borrow_mut();
+ let out = match serde_json::from_slice::<Value>(bytes) {
+ Err(e) => Err(format!("bad request: {e}")),
+ Ok(req) => dispatch(&mut st, &req),
+ };
+ let (code, v) = match out {
+ Ok(v) => (0, v),
+ Err(e) => (1, json!({ "error": e })),
+ };
+ st.result = serde_json::to_vec(&v).unwrap_or_else(|_| b"{\"error\":\"unserialisable result\"}".to_vec());
+ code
+ })
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn chimera_result_ptr() -> *const u8 {
+ STATE.with(|s| s.borrow().result.as_ptr())
+}
+
+#[unsafe(no_mangle)]
+pub extern "C" fn chimera_result_len() -> usize {
+ STATE.with(|s| s.borrow().result.len())
+}
diff --git a/crates/chimera-wasm/src/lib.rs b/crates/chimera-wasm/src/lib.rs
index d48771d..9666a4a 100644
--- a/crates/chimera-wasm/src/lib.rs
+++ b/crates/chimera-wasm/src/lib.rs
@@ -23,6 +23,8 @@
//! | 241 | 24 × u8 | label, UTF-8, cut at a character boundary |
//! | 265 | 7 × u8 | padding |
+pub mod api;
+
use chimera::anatomy::human::{ArticPatch, BodyName, N_ARTIC};
use chimera::control::score::{Gesture, Label, N_CONTROL, Targets};
use chimera::engine::{Engine, MAX_SCHEDULE};
@@ -112,6 +114,10 @@ pub struct Handle {
/// N_ARTIC values (NaN: absent) for `engine_set_artic`; also source values for `engine_set_source`
values: Vec<f64>,
tele: VoiceTelemetry,
+ /// the flat telemetry block (see `engine_telemetry`)
+ tele_block: Vec<f64>,
+ /// active gesture labels: up to 4 × (length byte + 24 bytes)
+ tele_labels: Vec<u8>,
}
fn bodies(i: u32) -> BodyName {
@@ -131,6 +137,8 @@ pub extern "C" fn engine_new(sample_rate: f64) -> *mut Handle {
gestures: Vec::with_capacity(MAX_SCHEDULE),
values: vec![f64::NAN; 32],
tele: VoiceTelemetry::default(),
+ tele_block: Vec::with_capacity(TELE_HEADER + 1024),
+ tele_labels: vec![0u8; 4 * 25],
});
// size every telemetry buffer once, so later snapshots reuse them
h.engine.telemetry(&mut h.tele);
@@ -331,3 +339,46 @@ pub extern "C" fn chimera_probe(f: u32, x: f64, y: f64) -> f64 {
_ => f64::NAN,
}
}
+
+/// Scalars at the head of the telemetry block, in order: phLen, orLen, velumPort, f0, voicing,
+/// pLung, outRms, noiseLevel, noiseNode, gate, clock, then the array lengths nArtic, nPh, nOr,
+/// nScope, nActive. The arrays follow: artic, phAreas, orAreas, pressureRms (nPh+nOr),
+/// flow (nPh+nOr), glottalArea (nScope), glottalFlow (nScope).
+pub const TELE_HEADER: usize = 16;
+
+/// Take a human-voice telemetry snapshot (resets its interval measurements: RMS levels) into the
+/// flat f64 block whose address it returns; active gesture labels go to `engine_tele_labels`.
+///
+/// # Safety
+/// `h` must be a live handle.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn engine_telemetry(h: *mut Handle) -> *const f64 {
+ let h = handle!(h);
+ h.engine.telemetry(&mut h.tele);
+ let t = &h.tele;
+ let b = &mut h.tele_block;
+ b.clear();
+ let n_ph = t.ph_areas.len();
+ let n_or = t.or_areas.len();
+ b.extend_from_slice(&[t.ph_len, t.or_len, t.velum_port, t.f0, t.voicing, t.p_lung, t.out_rms, t.noise_level, t.noise_node as f64, t.gate, t.clock]);
+ b.extend_from_slice(&[t.artic.len() as f64, n_ph as f64, n_or as f64, t.glottal_area.len() as f64, t.active.len() as f64]);
+ debug_assert_eq!(b.len(), TELE_HEADER);
+ for arr in [&t.artic, &t.ph_areas, &t.or_areas, &t.pressure_rms, &t.flow, &t.glottal_area, &t.glottal_flow] {
+ b.extend(arr.iter().map(|x| *x as f64));
+ }
+ for (i, l) in t.active.iter().enumerate() {
+ let bytes = l.as_bytes();
+ h.tele_labels[i * 25] = bytes.len() as u8;
+ h.tele_labels[i * 25 + 1..i * 25 + 1 + bytes.len()].copy_from_slice(bytes);
+ }
+ b.as_ptr()
+}
+
+/// The active-label area of the last telemetry snapshot: up to 4 × (length byte, 24 bytes).
+///
+/// # Safety
+/// `h` must be a live handle.
+#[unsafe(no_mangle)]
+pub unsafe extern "C" fn engine_tele_labels(h: *mut Handle) -> *const u8 {
+ handle!(h).tele_labels.as_ptr()
+}
diff --git a/package.json b/package.json
index 5248275..cc4212c 100644
--- a/package.json
+++ b/package.json
@@ -4,11 +4,12 @@
"version": "0.1.0",
"type": "module",
"scripts": {
- "dev": "vite --host 127.0.0.1",
- "build": "tsc --noEmit && vite build",
+ "dev": "bun run wasm && vite --host 127.0.0.1",
+ "build": "bun run wasm && tsc --noEmit && vite build",
"preview": "vite preview --host 127.0.0.1",
- "test": "bun test tests",
- "typecheck": "tsc --noEmit"
+ "test": "bun run wasm && cargo test --workspace && bun test tests",
+ "typecheck": "tsc --noEmit",
+ "wasm": "cargo build -p chimera-wasm --release --target wasm32-unknown-unknown && cp target/wasm32-unknown-unknown/release/chimera_wasm.wasm src/wasm/chimera.wasm"
},
"dependencies": {
"react": "19.3.1",
diff --git a/src/main.tsx b/src/main.tsx
index d55e15e..efb26a3 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -1,14 +1,31 @@
-import { StrictMode } from "react";
-import { createRoot } from "react-dom/client";
-import { App } from "./ui/App.tsx";
+/**
+ * Entry: load the engine (wasm) first — UI modules call into it as they load (Sing mode builds
+ * its syllables at import time) — then import and render the app. A failed load can be retried.
+ */
import "./ui/styles.css";
-import { engine } from "./audio/AudioEngine.ts";
+import { initChimera } from "./wasm/chimera.ts";
-// console/debug handle (used by the browser smoke test)
-(window as unknown as { __chimeraEngine: typeof engine }).__chimeraEngine = engine;
+const root = document.getElementById("root")!;
-createRoot(document.getElementById("root")!).render(
- <StrictMode>
- <App />
- </StrictMode>,
-);
+async function boot(): Promise<void> {
+ try {
+ await initChimera();
+ } catch (err) {
+ root.replaceChildren();
+ const box = document.createElement("div");
+ box.className = "boot-error";
+ const msg = document.createElement("p");
+ msg.textContent = `The voice engine could not load: ${err instanceof Error ? err.message : String(err)}`;
+ const retry = document.createElement("button");
+ retry.className = "primary";
+ retry.textContent = "Try again";
+ retry.onclick = () => void boot();
+ box.append(msg, retry);
+ root.append(box);
+ return;
+ }
+ const { mount } = await import("./ui/mount.tsx");
+ mount(root);
+}
+
+void boot();
diff --git a/src/ui/creatureVisuals.ts b/src/ui/creatureVisuals.ts
new file mode 100644
index 0000000..24477b3
--- /dev/null
+++ b/src/ui/creatureVisuals.ts
@@ -0,0 +1,73 @@
+/**
+ * How each creature is drawn (UI-only data, keyed by creature id; the engine defines the creature
+ * itself): body outline, tissue shapes, airway centrelines per tube, and source glyphs.
+ */
+export interface CreatureVisual {
+ /** body outline in drawing units (≈ cm; y up) */
+ silhouette: [number, number][];
+ /** extra shapes drawn in tissue tones (shade 0 black … 1 white) */
+ parts?: { shade: number; pts: [number, number][]; stroke?: boolean }[];
+ /** airway centrelines per tube name (tube nodes are distributed along the path); inView: false
+ * keeps the label out of the cross-section (it still names the tube's lane) */
+ tubes: { tube: string; path: [number, number][]; label?: string; inView?: boolean }[];
+ /** how much wider than life to draw the airway (narrow tubes stay legible) */
+ tubeScale?: number;
+ /** drawing extents */
+ view: { x0: number; x1: number; y0: number; y1: number };
+ /** sound sources to draw, keyed into the creature's source state */
+ sources?: { key: string; at: [number, number]; label: string }[];
+}
+
+export const CREATURE_VISUALS: Record<string, CreatureVisual> = {
+ "songbird": {
+ view: { x0: -4, x1: 14, y0: -6, y1: 8 },
+ silhouette: [[-3.2, -1.2], [-1.6, -3.4], [1.6, -4.6], [5.2, -4.4], [7.8, -2.6], [9.0, -0.4], [9.6, 1.8], [10.4, 2.4], [12.8, 2.6], [10.6, 3.0], [9.8, 3.6], [9.2, 4.6], [7.6, 5.2], [6.0, 4.6], [4.2, 2.8], [2.0, 2.0], [-0.2, 1.6], [-3.6, 1.4], [-3.4, 0.2]],
+ parts: [{ shade: 0.2, pts: [[8.6, 4.0], [8.95, 4.3], [9.2, 4.0], [8.95, 3.7]] }],
+ tubes: [
+ { tube: "bronchusL", path: [[3.4, -1.9], [4.4, -1.4]], label: "Left bronchus", inView: false },
+ { tube: "bronchusR", path: [[3.4, -0.9], [4.4, -1.2]], label: "Right bronchus", inView: false },
+ { tube: "trachea", path: [[4.4, -1.3], [5.6, -0.4], [6.8, 0.8], [7.8, 1.9], [8.6, 2.5]], label: "Trachea" },
+ { tube: "beak", path: [[9.4, 2.75], [10.6, 2.75], [12.4, 2.7]], label: "Beak" },
+ ],
+ tubeScale: 1.6,
+ sources: [{ key: "left", at: [4.2, -1.6], label: "Left voice" }, { key: "right", at: [4.2, -1.0], label: "Right voice" }],
+ },
+ "seal": {
+ view: { x0: -60, x1: 60, y0: -30, y1: 30 },
+ silhouette: [[-58, -2], [-50, -8], [-30, -14], [-5, -16], [20, -14], [38, -10], [48, -6], [55, -3], [58, 1], [56, 5], [50, 8], [42, 10], [30, 11], [10, 13], [-15, 13], [-35, 10], [-50, 6], [-56, 3], [-62, 8], [-64, 4], [-60, 0], [-64, -4], [-62, -8]],
+ parts: [{ shade: 0.15, pts: [[47, 4], [48.5, 5], [50, 4], [48.5, 3]] }],
+ tubes: [
+ { tube: "trachea", path: [[8, -4], [20, -3], [30, -2]], label: "Trachea" },
+ { tube: "pharynx", path: [[30, -2], [38, 0], [44, 1.5]], label: "Pharynx" },
+ { tube: "oral", path: [[44, 1.5], [50, 0.5], [57, -0.5]], label: "Mouth" },
+ ],
+ tubeScale: 1.3,
+ sources: [{ key: "glottis", at: [30, -2], label: "Larynx" }],
+ },
+ "alligator": {
+ view: { x0: -120, x1: 120, y0: -40, y1: 40 },
+ silhouette: [[-118, 2], [-90, -4], [-60, -8], [-30, -14], [0, -16], [30, -14], [50, -10], [70, -8], [95, -5], [114, -3], [118, 0], [115, 3], [98, 5], [75, 7], [52, 9], [40, 12], [20, 14], [-10, 14], [-40, 11], [-70, 7], [-100, 4]],
+ parts: [{ shade: 0.15, pts: [[54, 9], [56, 11], [58, 9], [56, 8]] }],
+ tubes: [
+ { tube: "trachea", path: [[0, -6], [18, -5], [36, -4]], label: "Trachea" },
+ { tube: "pharynx", path: [[36, -4], [46, -2], [54, 0]], label: "Pharynx" },
+ { tube: "oral", path: [[54, 0], [80, -1], [112, -1]], label: "Mouth" },
+ { tube: "nasal", path: [[54, 2], [80, 4], [113, 2]], label: "Nostrils" },
+ ],
+ tubeScale: 1.05,
+ sources: [{ key: "glottis", at: [36, -4], label: "Larynx" }],
+ },
+ "elephant": {
+ view: { x0: -170, x1: 170, y0: -170, y1: 130 },
+ silhouette: [[-160, 20], [-150, 70], [-110, 105], [-40, 118], [30, 115], [70, 100], [95, 112], [120, 108], [140, 85], [148, 55], [146, 25], [140, 5], [132, -20], [128, -60], [122, -110], [118, -150], [108, -152], [112, -100], [110, -50], [104, -20], [96, -5], [80, 0], [70, -10], [66, -90], [40, -95], [44, -30], [-90, -30], [-95, -95], [-125, -95], [-122, -10], [-150, -5]],
+ parts: [{ shade: 0.15, pts: [[118, 62], [122, 66], [126, 62], [122, 58]] }, { shade: 0.62, pts: [[70, 100], [40, 60], [55, 25], [85, 40], [95, 80]] }],
+ tubes: [
+ { tube: "trachea", path: [[40, 20], [70, 30], [95, 38]], label: "Trachea" },
+ { tube: "pharynx", path: [[95, 38], [112, 50], [124, 58]], label: "Pharynx" },
+ { tube: "oral", path: [[124, 58], [130, 42], [134, 30]], label: "Mouth" },
+ { tube: "trunk", path: [[136, 70], [142, 40], [136, 0], [128, -50], [120, -100], [113, -148]], label: "Trunk" },
+ ],
+ tubeScale: 3,
+ sources: [{ key: "glottis", at: [95, 38], label: "Vocal folds" }, { key: "lips", at: [136, 70], label: "Trunk valve" }],
+ },
+};
diff --git a/src/ui/mount.tsx b/src/ui/mount.tsx
new file mode 100644
index 0000000..d4727ab
--- /dev/null
+++ b/src/ui/mount.tsx
@@ -0,0 +1,15 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { App } from "./App.tsx";
+import { engine } from "../audio/AudioEngine.ts";
+
+export function mount(root: HTMLElement): void {
+ // console/debug handle (used by the browser smoke test)
+ (window as unknown as { __chimeraEngine: typeof engine }).__chimeraEngine = engine;
+ root.replaceChildren();
+ createRoot(root).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+ );
+}
diff --git a/src/ui/styles.css b/src/ui/styles.css
index 74a69f1..d305738 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -1316,3 +1316,14 @@ button.midi.on .midi-status {
animation: none;
}
}
+
+/* the engine failed to load */
+.boot-error {
+ max-width: 34rem;
+ margin: 18vh auto;
+ padding: 0 16px;
+ display: grid;
+ gap: 1rem;
+ justify-items: start;
+ color: var(--text);
+}
diff --git a/src/wasm/chimera.ts b/src/wasm/chimera.ts
new file mode 100644
index 0000000..a8acd11
--- /dev/null
+++ b/src/wasm/chimera.ts
@@ -0,0 +1,72 @@
+/**
+ * The CHIMERA engine (Rust, compiled to wasm) on the main thread: one compiled module, shared
+ * with the AudioWorklet (which instantiates its own copy), and a synchronous JSON call interface
+ * for everything that is not real time (planning, G2P, geometry, catalogues).
+ * `initChimera()` must resolve before anything calls into the engine (main.tsx awaits it).
+ */
+type Fn = (...a: number[]) => number;
+export interface ChimeraExports {
+ memory: WebAssembly.Memory;
+ chimera_alloc: Fn;
+ chimera_free: Fn;
+ chimera_call: Fn;
+ chimera_result_ptr: Fn;
+ chimera_result_len: Fn;
+ [name: string]: Fn | WebAssembly.Memory;
+}
+
+let module: WebAssembly.Module | null = null;
+let exports: ChimeraExports | null = null;
+let loading: Promise<void> | null = null;
+
+/** Compile and instantiate the engine (once). `source`: the wasm bytes or a URL (default: the bundled build). */
+export function initChimera(source?: BufferSource | string): Promise<void> {
+ if (loading) return loading;
+ loading = (async () => {
+ let mod: WebAssembly.Module;
+ if (source && typeof source !== "string") mod = await WebAssembly.compile(source);
+ else {
+ const url = source ?? (await import("./chimera.wasm?url")).default;
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`engine: ${url}: HTTP ${res.status}`);
+ mod = await WebAssembly.compile(await res.arrayBuffer());
+ }
+ if (WebAssembly.Module.imports(mod).length) throw new Error("engine: the wasm module must not have imports");
+ exports = (await WebAssembly.instantiate(mod, {})).exports as unknown as ChimeraExports;
+ module = mod;
+ })();
+ loading.catch(() => (loading = null)); // a failed load may be retried
+ return loading;
+}
+
+export function chimeraReady(): boolean {
+ return exports !== null;
+}
+
+/** The compiled module, for the AudioWorklet's own instance. */
+export function chimeraModule(): WebAssembly.Module {
+ if (!module) throw new Error("engine not loaded (await initChimera())");
+ return module;
+}
+
+function x(): ChimeraExports {
+ if (!exports) throw new Error("engine not loaded (await initChimera())");
+ return exports;
+}
+
+const enc = new TextEncoder();
+const dec = new TextDecoder();
+
+/** Call the engine's JSON interface (crates/chimera-wasm/src/api.rs); throws on an engine error. */
+export function call<T>(fn: string, args: Record<string, unknown> = {}): T {
+ const e = x();
+ const bytes = enc.encode(JSON.stringify({ fn, ...args }));
+ const p = e.chimera_alloc(bytes.length);
+ new Uint8Array(e.memory.buffer, p, bytes.length).set(bytes);
+ const status = e.chimera_call(p, bytes.length);
+ e.chimera_free(p, bytes.length);
+ const out = dec.decode(new Uint8Array(e.memory.buffer, e.chimera_result_ptr(), e.chimera_result_len()));
+ const v = JSON.parse(out);
+ if (status !== 0) throw new Error(`engine ${fn}: ${v.error}`);
+ return v as T;
+}
diff --git a/src/wasm/wasm.d.ts b/src/wasm/wasm.d.ts
new file mode 100644
index 0000000..ef3343b
--- /dev/null
+++ b/src/wasm/wasm.d.ts
@@ -0,0 +1,4 @@
+declare module "*.wasm?url" {
+ const url: string;
+ export default url;
+}