the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Review fixes: the page owns its models; keys release what they pressed
Jameson Hodge30d9d54e4d27
diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rsindex 7fb53b5..3b46e72 100644--- a/crates/chimera-wasm/src/api.rs+++ b/crates/chimera-wasm/src/api.rs@@ -17,10 +17,6 @@ use chimera::voice::human_airway::HumanAirway;use serde_json::{Value, json};use std::cell::RefCell;-/// Models kept at once. A body is continuous, so the page can ask for any number of them; it-/// keeps fewer of its own (`useModel.ts`), so a model it still holds is never dropped here.-const MAX_MODELS: usize = 16;-struct Model {id: usize,body: BodyMix,@@ -31,7 +27,8 @@ struct Model {#[derive(Default)]struct State {result: Vec<u8>,- /// oldest first+ /// the page's models; a body is continuous, so the page drops the ones it no longer keeps+ /// (`dropModel`, from `useModel.ts`)models: Vec<Model>,next_model: usize,/// the page's English G2P (one dictionary, loaded once)@@ -71,9 +68,6 @@ fn dispatch(st: &mut State, req: &Value) -> Res {let i = match st.models.iter().position(|x| x.body == body && x.fs == fs * m) {Some(i) => i,None => {- if st.models.len() >= MAX_MODELS {- st.models.remove(0);- }st.models.push(Model { id: st.next_model, body, fs: fs * m, airway: HumanAirway::new(fs * m, body.body()) });st.next_model += 1;st.models.len() - 1@@ -90,6 +84,11 @@ fn dispatch(st: &mut State, req: &Value) -> Res {"glottisPort": a.glottis_port,}))}+ "dropModel" => {+ let id: usize = arg(req, "model")?;+ st.models.retain(|m| m.id != id);+ Ok(Value::Null)+ }"restTip" => to_json(&chimera::anatomy::human::rest_tip(arg(req, "jaw")?, arg(req, "tbX")?, arg(req, "tbY")?)),"frame" => {let a: HumanArtic = arg(req, "artic")?;diff --git a/src/ui/analysis.ts b/src/ui/analysis.tsindex f158d5a..0d3d3f8 100644--- a/src/ui/analysis.ts+++ b/src/ui/analysis.ts@@ -3,7 +3,7 @@* 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 { airwayModel, airwayFrame, airwayAreas, airwayTransfer, TractMap, NEUTRAL, ARTIC_KEYS, VOWELS, VOWEL_TARGETS, type AirwayModel, type HumanArtic, type HumanBody, type HumanFrame } from "../wasm/engine.ts";+import { airwayModel, dropAirwayModel, airwayFrame, airwayAreas, airwayTransfer, TractMap, NEUTRAL, ARTIC_KEYS, VOWELS, VOWEL_TARGETS, type AirwayModel, type HumanArtic, type HumanBody, type HumanFrame } from "../wasm/engine.ts";import { bodyWeights, type BodyMix } from "./body.ts";export interface VowelPoint {@@ -59,6 +59,11 @@ export class VoiceModel {});}+ /** Free the engine's model; this VoiceModel must not be used afterwards. */+ dispose(): void {+ dropAirwayModel(this.model);+ }+static articFromArray(arr: ArrayLike<number>): HumanArtic {const a = { ...NEUTRAL };ARTIC_KEYS.forEach((k, i) => (a[k] = arr[i]));diff --git a/src/ui/components/Keys.tsx b/src/ui/components/Keys.tsxindex 60de822..bd77f5d 100644--- a/src/ui/components/Keys.tsx+++ b/src/ui/components/Keys.tsx@@ -19,7 +19,8 @@ export function Keys() {const base = BASE(body) + octave.current * 12;useEffect(() => {- const down = new Set<string>();+ /** pressed key → the note it played (released as that note, whatever the body or octave now) */+ const down = new Map<string, number>();const onDown = (e: KeyboardEvent) => {if (e.repeat || e.metaKey || e.ctrlKey || e.altKey) return;const target = e.target as HTMLElement;@@ -30,19 +31,21 @@ export function Keys() {if (k === "z") octave.current = Math.max(-2, octave.current - 1);if (k === "x") octave.current = Math.min(2, octave.current + 1);if (!(k in KEYMAP) || down.has(k)) return;- down.add(k);+ const midi = BASE(useStore.getState().body) + octave.current * 12 + KEYMAP[k];+ down.set(k, midi);void start();- noteOn(BASE(useStore.getState().body) + octave.current * 12 + KEYMAP[k]);+ noteOn(midi);e.preventDefault();};const onUp = (e: KeyboardEvent) => {const k = e.key.toLowerCase();- if (!down.has(k)) return;+ const midi = down.get(k);+ if (midi === undefined) return;down.delete(k);- noteOff(BASE(useStore.getState().body) + octave.current * 12 + KEYMAP[k]);+ noteOff(midi);};const onBlur = () => {- for (const k of down) noteOff(BASE(useStore.getState().body) + octave.current * 12 + KEYMAP[k]);+ for (const midi of down.values()) noteOff(midi);down.clear();};window.addEventListener("keydown", onDown);diff --git a/src/ui/useModel.ts b/src/ui/useModel.tsindex 0980a23..b3bbacf 100644--- a/src/ui/useModel.ts+++ b/src/ui/useModel.ts@@ -6,8 +6,8 @@ import { bodyKey, type BodyMix } from "./body.ts";/*** Shared main-thread acoustic models, most recent last (rebuilt on body / sample-rate change).- * A body is continuous, so only the last few are kept: fewer than the engine's own model cache- * (MAX_MODELS in crates/chimera-wasm/src/api.rs), so every model kept here is still alive there.+ * A body is continuous, so only the last few are kept; an evicted one is freed in the engine too+ * (components read the current body's model on every render, so none holds an evicted one).*/const cache = new Map<string, VoiceModel>();const KEEP = 8;@@ -18,7 +18,11 @@ export function getModel(body: BodyMix, sampleRate: number): VoiceModel {if (m) cache.delete(key);else m = new VoiceModel(body, sampleRate);cache.set(key, m);- if (cache.size > KEEP) cache.delete(cache.keys().next().value!);+ if (cache.size > KEEP) {+ const [oldest, old] = cache.entries().next().value!;+ cache.delete(oldest);+ old.dispose();+ }return m;}diff --git a/src/wasm/engine.ts b/src/wasm/engine.tsindex 9bdfebb..e2ceaf8 100644--- a/src/wasm/engine.ts+++ b/src/wasm/engine.ts@@ -226,6 +226,11 @@ export function airwayModel(body: BodyMix, sampleRate: number): AirwayModel {return call("model", { body, sampleRate });}+/** Free a model (its id is invalid afterwards). */+export function dropAirwayModel(m: AirwayModel): void {+ call("dropModel", { model: m.model });+}+export function airwayFrame(m: AirwayModel, artic: HumanArtic): HumanFrame {return call("frame", { model: m.model, artic });}