the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Continuous body: blend male, female and child (issue #4)
Jameson Hodge657af3d34a6d
diff --git a/DESIGN.md b/DESIGN.mdindex e3e254e..d3cec96 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -136,6 +136,9 @@ branching (nasal tract, sinuses, piriform fossae, two bronchi, vocal sacs, OEC).* Calibration: optimise vowel targets against reference formants (Hillenbrand 1995 malemeans, plus cardinal vowels for non-English) with the chain-matrix model. Female/childvia anatomical scaling (shorter pharynx proportion), not formant warping.+* The body is continuous (`BodyMix`: a female axis and a child axis): anatomy, calibrated+ phoneme targets and default pitch blend the three calibrated bodies by weight. A body+ change rebuilds the airway (its node counts follow the tract length).* Other mammals/reptiles: same topology, species parameters (snout length, palateshape, larynx position/descent, nasal length, lip shape, trunk = long nasal tube,vocal sac = Helmholtz side branch). Birds: separate topology (syrinx/trachea/OEC/beak,diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rsindex 73f4ef1..234fbb8 100644--- a/crates/chimera-cli/src/render.rs+++ b/crates/chimera-cli/src/render.rs@@ -4,7 +4,6 @@ use crate::js::{fixed, num, pad_end, pad_start};use crate::{Ctx, FS, arg, body, peak, repo_path, wav_name};use chimera::analysis::lpc::{FormantOpts, estimate_formants};use chimera::analysis::pitch::{YinOpts, yin_pitch};-use chimera::anatomy::human::BodyName;use chimera::control::beat_player::BeatPlayer;use chimera::control::score::Gesture;use chimera::creatures::types::ParamRole;@@ -328,7 +327,7 @@ pub fn song(ctx: &Ctx, a: &[String]) -> Result<(), String> {} else if let Some(h) = held.take_if(|h| h.midi == m) {v.release(h.tag);v.release(h.tag + 1.0);- let gs = shift(plan_note_off(&h.syl, h.midi, body_name));+ let gs = shift(plan_note_off(&h.syl, h.midi, body_name.into()));v.schedule(&gs);}}@@ -348,7 +347,7 @@ pub fn beatbox(ctx: &Ctx, a: &[String]) -> Result<(), String> {let b = body(body_name)?;let voice = || {let mut v = HumanVoice::new(FS, b, 2);- v.set_articulation(&beat_ready(body_name), None);+ v.set_articulation(&beat_ready(body_name.into()), None);v.set_source(&SourcePatch {f0: Some(100.0),voiced: Some(true),@@ -362,7 +361,7 @@ pub fn beatbox(ctx: &Ctx, a: &[String]) -> Result<(), String> {// ---- each sound alonelet mut player = BeatPlayer::new();- player.body = BodyName::parse(body_name);+ player.body = body_name.into();let mut rows: Vec<String> = Vec::new();let n = js_round(FS * 0.5) as usize;let mut strip = vec![0f32; js_round(FS * 0.5 * BEAT_SOUNDS.len() as f64) as usize];@@ -406,7 +405,7 @@ pub fn beatbox(ctx: &Ctx, a: &[String]) -> Result<(), String> {fixed(pk, 3),fixed(20.0 * log10(js_max(1e-6, pre) / pk), 1),fixed(20.0 * log10(js_max(1e-6, tail) / pk), 1),- fixed(BeatPlayer::lead_in(s.id, body_name) * 1000.0, 0),+ fixed(BeatPlayer::lead_in(s.id, body_name.into()) * 1000.0, 0),));strip[idx * n..(idx + 1) * n].copy_from_slice(&out);let file: String =@@ -425,7 +424,7 @@ pub fn beatbox(ctx: &Ctx, a: &[String]) -> Result<(), String> {.unwrap_or(&BEAT_PRESETS[0]);let mut v = voice();let mut seq = BeatPlayer::new();- seq.body = BodyName::parse(body_name);+ seq.body = body_name.into();seq.set_steps(&parse_beat(preset.text));seq.set_tempo(preset.bpm, preset.swing);seq.start(v.clock);diff --git a/crates/chimera-wasm/examples/render_scenarios.rs b/crates/chimera-wasm/examples/render_scenarios.rsindex f4e37df..56a16c1 100644--- a/crates/chimera-wasm/examples/render_scenarios.rs+++ b/crates/chimera-wasm/examples/render_scenarios.rs@@ -25,13 +25,13 @@ fn render(s: &Value) -> Vec<f32> {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,+ let (female, child) = match s["body"].as_str().unwrap() {+ "female" => (1.0, 0.0),+ "child" => (0.0, 1.0),+ _ => (0.0, 0.0),};- if body != 0 {- engine_set_body(h, body);+ if (female, child) != (0.0, 0.0) {+ engine_set_body(h, female, child);}let mut ops: Vec<&Value> = s["ops"].as_array().unwrap().iter().collect();ops.sort_by_key(|o| o["at"].as_u64().unwrap());diff --git a/crates/chimera-wasm/src/api.rs b/crates/chimera-wasm/src/api.rsindex 082f678..7fb53b5 100644--- a/crates/chimera-wasm/src/api.rs+++ b/crates/chimera-wasm/src/api.rs@@ -4,7 +4,7 @@//! runs on the audio thread: these calls allocate.use chimera::airway::frequency::{find_peaks, transfer_function};-use chimera::anatomy::human::{BodyName, HumanArtic, HumanFrame};+use chimera::anatomy::human::{BodyMix, HumanArtic, HumanFrame};use chimera::control::beat_player::BeatPlayer;use chimera::creatures::voice::CreatureVoice;use chimera::math;@@ -17,8 +17,13 @@ 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 {- body: BodyName,+ id: usize,+ body: BodyMix,fs: f64,airway: HumanAirway,}@@ -26,7 +31,9 @@ struct Model {#[derive(Default)]struct State {result: Vec<u8>,+ /// oldest firstmodels: Vec<Model>,+ next_model: usize,/// the page's English G2P (one dictionary, loaded once)g2p: EnglishG2P,}@@ -47,7 +54,7 @@ fn to_json<T: serde::Serialize>(v: &T) -> Res {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}"))+ st.models.iter_mut().find(|m| m.id == id).ok_or_else(|| format!("no model {id}"))}fn dispatch(st: &mut State, req: &Value) -> Res {@@ -58,17 +65,21 @@ fn dispatch(st: &mut State, req: &Value) -> Res {// ---------------------------------------------------------------- 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 body: BodyMix = arg(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) {+ let i = 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()) });+ 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}};- let a = &st.models[id].airway;+ let (id, a) = (st.models[i].id, &st.models[i].airway);Ok(json!({"model": id,"body": a.body,@@ -131,13 +142,13 @@ fn dispatch(st: &mut State, req: &Value) -> Res {"planPhrases" => to_json(&planner::plan_phrases(&arg::<Vec<PhraseInput>>(req, "phrases")?, &arg::<PlanOptions>(req, "options")?)),"planSong" => to_json(&sing::plan_song(&arg::<Vec<SungNote>>(req, "notes")?, &arg::<SongOptions>(req, "options")?)),"planNoteOn" => to_json(&sing::plan_note_on(&arg::<Syllable>(req, "syl")?, arg(req, "midi")?, &arg::<NoteOnOptions>(req, "options")?)),- "planNoteOff" => to_json(&sing::plan_note_off(&arg::<Syllable>(req, "syl")?, arg(req, "midi")?, &arg::<String>(req, "body")?)),+ "planNoteOff" => to_json(&sing::plan_note_off(&arg::<Syllable>(req, "syl")?, arg(req, "midi")?, arg::<BodyMix>(req, "body")?)),"planMelisma" => to_json(&sing::plan_melisma(arg(req, "midi")?, &arg::<MelismaOptions>(req, "options")?)),// ---------------------------------------------------------------- beatbox"parseBeat" => to_json(&beatbox::parse_beat(&arg::<String>(req, "text")?)),"formatBeat" => Ok(Value::String(beatbox::format_beat(&arg::<Vec<Option<BeatStep>>>(req, "steps")?))),- "beatReady" => to_json(&beatbox::beat_ready(&arg::<String>(req, "body")?)),- "leadIn" => Ok(json!(BeatPlayer::lead_in(&arg::<String>(req, "id")?, &arg::<String>(req, "body")?))),+ "beatReady" => to_json(&beatbox::beat_ready(arg::<BodyMix>(req, "body")?)),+ "leadIn" => Ok(json!(BeatPlayer::lead_in(&arg::<String>(req, "id")?, arg::<BodyMix>(req, "body")?))),_ => Err(format!("unknown fn {name}")),}}diff --git a/crates/chimera-wasm/src/lib.rs b/crates/chimera-wasm/src/lib.rsindex fbc9027..58709db 100644--- a/crates/chimera-wasm/src/lib.rs+++ b/crates/chimera-wasm/src/lib.rs@@ -34,7 +34,7 @@pub mod api;-use chimera::anatomy::human::{ArticPatch, BodyName, N_ARTIC};+use chimera::anatomy::human::{ArticPatch, BodyMix, N_ARTIC};use chimera::control::score::{Gesture, Label, N_CONTROL, Targets};use chimera::engine::{Engine, MAX_SCHEDULE};use chimera::phonetics::beatbox::BeatStep;@@ -134,14 +134,6 @@ pub struct Handle {ctele_block: Vec<f64>,}-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 {@@ -274,15 +266,15 @@ 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`.+/// Switch body: `female` 0 (male) … 1 (female), `child` 0 (adult) … 1 (child); see `BodyMix`.+/// 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) {+pub unsafe extern "C" fn engine_set_body(h: *mut Handle, female: f64, child: f64) {let h = handle!(h);- h.engine.set_body(bodies(body));+ h.engine.set_body(BodyMix::new(female, child));h.engine.telemetry(&mut h.tele); // resize the telemetry buffers for the new voice}@@ -324,12 +316,15 @@ pub unsafe extern "C" fn engine_n_or(h: *mut Handle) -> 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,- }+pub unsafe extern "C" fn engine_body_female(h: *mut Handle) -> f64 {+ handle!(h).engine.info().body.female+}++/// # Safety+/// `h` must be a live handle.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn engine_body_child(h: *mut Handle) -> f64 {+ handle!(h).engine.info().body.child}/// Evaluate one of the engine's math functions (diagnostics: native and wasm must agree bit fordiff --git a/crates/chimera/src/anatomy/human.rs b/crates/chimera/src/anatomy/human.rsindex 9f97920..62b48d5 100644--- a/crates/chimera/src/anatomy/human.rs+++ b/crates/chimera/src/anatomy/human.rs@@ -215,6 +215,24 @@ impl ArticPatch {pub fn is_empty(&self) -> bool {self.values.iter().all(|x| x.is_none())}+ /// Each key's weighted mean over the parts that have it (parts weighing 0 or less are left+ /// out). Allocates nothing.+ pub fn blend(parts: &[(f64, ArticPatch)]) -> ArticPatch {+ let mut out = ArticPatch::default();+ for i in 0..N_ARTIC {+ let (mut sum, mut wsum) = (0.0, 0.0);+ for (w, p) in parts {+ if let (true, Some(x)) = (*w > 0.0, p.values[i]) {+ sum += w * x;+ wsum += w;+ }+ }+ if wsum > 0.0 {+ out.values[i] = Some(sum / wsum);+ }+ }+ out+ }}impl Serialize for ArticPatch {@@ -293,6 +311,112 @@ impl BodyName {}}+/// A body anywhere between the three calibrated ones: `female` runs from the adult male (0) to+/// the adult female (1), `child` from adult (0) to child (1). The child has no female axis, so+/// the weights are male (1−c)(1−f), female (1−c)·f, child c. Everything body-dependent (the+/// anatomy, the calibrated phoneme targets, the default pitch) blends with these weights; at a+/// preset it is exactly that preset.+///+/// Deserializes from a preset name (`"female"`) or `{ "female": f, "child": c }`.+#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]+pub struct BodyMix {+ pub female: f64,+ pub child: f64,+}++impl BodyMix {+ pub const MALE: BodyMix = BodyMix { female: 0.0, child: 0.0 };+ pub const FEMALE: BodyMix = BodyMix { female: 1.0, child: 0.0 };+ pub const CHILD: BodyMix = BodyMix { female: 0.0, child: 1.0 };++ /// Clamped to 0..1 (non-finite values count as 0).+ pub fn new(female: f64, child: f64) -> BodyMix {+ let c = |x: f64| if x.is_finite() { clamp(x, 0.0, 1.0) } else { 0.0 };+ BodyMix { female: c(female), child: c(child) }+ }++ /// Weights of male, female and child (they sum to 1).+ pub fn weights(self) -> [(BodyName, f64); 3] {+ let BodyMix { female: f, child: c } = BodyMix::new(self.female, self.child);+ [(BodyName::Male, (1.0 - c) * (1.0 - f)), (BodyName::Female, (1.0 - c) * f), (BodyName::Child, c)]+ }++ /// The preset this is exactly, if any.+ pub fn preset(self) -> Option<BodyName> {+ self.weights().iter().find(|(_, w)| *w == 1.0).map(|(b, _)| *b)+ }++ /// The preset with the largest weight.+ pub fn nearest(self) -> BodyName {+ let w = self.weights();+ let mut best = w[0];+ for x in &w[1..] {+ if x.1 > best.1 {+ best = *x;+ }+ }+ best.0+ }++ /// `f` of each preset, blended by weight (exactly `f(preset)` at a preset).+ pub fn blend(self, f: impl Fn(BodyName) -> f64) -> f64 {+ if let Some(b) = self.preset() {+ return f(b);+ }+ self.weights().iter().fold(0.0, |acc, (b, w)| acc + w * f(*b))+ }++ /// The blended anatomy (named after the nearest preset).+ pub fn body(self) -> HumanBody {+ if let Some(b) = self.preset() {+ return b.body();+ }+ HumanBody {+ name: self.nearest().body().name,+ scale: self.blend(|b| b.body().scale),+ pharynx: self.blend(|b| b.body().pharynx),+ tongue_radius: self.blend(|b| b.body().tongue_radius),+ lip_width: self.blend(|b| b.body().lip_width),+ }+ }+}++impl From<BodyName> for BodyMix {+ fn from(b: BodyName) -> BodyMix {+ match b {+ BodyName::Male => BodyMix::MALE,+ BodyName::Female => BodyMix::FEMALE,+ BodyName::Child => BodyMix::CHILD,+ }+ }+}++impl From<&str> for BodyMix {+ fn from(s: &str) -> BodyMix {+ BodyName::parse(s).into()+ }+}++impl<'de> Deserialize<'de> for BodyMix {+ fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ #[derive(Deserialize)]+ #[serde(untagged)]+ enum Wire {+ Name(String),+ Mix {+ #[serde(default)]+ female: f64,+ #[serde(default)]+ child: f64,+ },+ }+ Ok(match Wire::deserialize(d)? {+ Wire::Name(s) => BodyMix::from(s.as_str()),+ Wire::Mix { female, child } => BodyMix::new(female, child),+ })+ }+}+/// Neutral (schwa-like) articulation for the male template, unscaled coordinates.pub const NEUTRAL: HumanArtic = HumanArtic {jaw: 0.6,diff --git a/crates/chimera/src/control/beat_player.rs b/crates/chimera/src/control/beat_player.rsindex 85265de..3f9893e 100644--- a/crates/chimera/src/control/beat_player.rs+++ b/crates/chimera/src/control/beat_player.rs@@ -10,7 +10,7 @@//! phoneme tables are not parsed on the audio thread.use super::score::Gesture;-use crate::anatomy::human::BodyName;+use crate::anatomy::human::BodyMix;use crate::math::{js_max, js_min, midi_to_hz};use crate::phonetics::beatbox::{BASS_NOTE, BeatBuild, BeatStep, MAX_SOUND_GESTURES, beat_sound};@@ -24,7 +24,7 @@ pub struct BeatPlayer {/// 0..0.6: off-beat sixteenths are delayed by swing × half a steppub swing: f64,pub playing: bool,- pub body: BodyName,+ pub body: BodyMix,anchor_time: f64,anchor_step: i64,next: i64,@@ -55,7 +55,7 @@ impl BeatPlayer {bpm: 96.0,swing: 0.0,playing: false,- body: BodyName::Male,+ body: BodyMix::MALE,anchor_time: 0.0,anchor_step: 0,next: 0,@@ -196,7 +196,7 @@ impl BeatPlayer {pub fn gestures(&self, cell: &BeatStep, hit: f64, len: f64, out: &mut Vec<Gesture>) {let Some(s) = beat_sound(cell.id.as_str()) else { return };let start = out.len();- (s.build)(self.body.as_str(), &BeatBuild { f0: midi_to_hz(cell.note.unwrap_or(BASS_NOTE)), len, accent: cell.accent.unwrap_or(1.0) }, out);+ (s.build)(self.body, &BeatBuild { f0: midi_to_hz(cell.note.unwrap_or(BASS_NOTE)), len, accent: cell.accent.unwrap_or(1.0) }, out);let off = hit - s.latency;for g in out[start..].iter_mut() {g.t0 += off;@@ -206,7 +206,7 @@ impl BeatPlayer {/// Set-up time a sound needs before its hit (s): when a pad press can sound at the earliest./// `scratch` is cleared and used to build the sound (no allocation when it has room).- pub fn lead_in_with(id: &str, body: &str, scratch: &mut Vec<Gesture>) -> f64 {+ pub fn lead_in_with(id: &str, body: BodyMix, scratch: &mut Vec<Gesture>) -> f64 {let Some(s) = beat_sound(id) else { return 0.0 };scratch.clear();(s.build)(body, &BeatBuild { f0: 100.0, len: 0.15, accent: 1.0 }, scratch);@@ -218,7 +218,7 @@ impl BeatPlayer {}/// [`Self::lead_in_with`] on a fresh buffer (allocates; for the UI and tests).- pub fn lead_in(id: &str, body: &str) -> f64 {+ pub fn lead_in(id: &str, body: BodyMix) -> f64 {Self::lead_in_with(id, body, &mut Vec::with_capacity(MAX_SOUND_GESTURES))}}diff --git a/crates/chimera/src/engine.rs b/crates/chimera/src/engine.rsindex e976d5a..2cfd051 100644--- a/crates/chimera/src/engine.rs+++ b/crates/chimera/src/engine.rs@@ -9,7 +9,7 @@//! - 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::anatomy::human::{ArticPatch, BodyMix, BodyName};use crate::control::beat_player::BeatPlayer;use crate::control::score::{Gesture, GestureScore};use crate::creatures::types::CreatureDef;@@ -22,26 +22,31 @@ 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 {+/// Default pitch per body (Hz): the presets', blended geometrically in between.+pub fn default_f0(body: impl Into<BodyMix>) -> f64 {+ let body = body.into();+ let f = |b: BodyName| match b {BodyName::Male => 110.0,BodyName::Female => 205.0,BodyName::Child => 260.0,+ };+ match body.preset() {+ Some(b) => f(b),+ None => crate::math::exp(body.blend(|b| crate::math::ln(f(b)))),}}/// Identity of the voice the engine is playing (the browser's "ready" message).-#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[derive(Clone, Copy, Debug, PartialEq)]pub struct VoiceInfo {- pub body: BodyName,+ pub body: BodyMix,pub n_ph: usize,pub n_or: usize,}pub struct Engine {pub sample_rate: f64,- body: BodyName,+ body: BodyMix,voice: HumanVoice,/// the performer's breath (the voice's own gate also follows the score)gate_level: f64,@@ -56,11 +61,11 @@ pub struct Engine {impl Engine {pub fn new(sample_rate: f64) -> Engine {crate::init();- let body = BodyName::Male;+ let body = BodyMix::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(), creature: None }}- fn make_voice(fs: f64, body: BodyName) -> HumanVoice {+ fn make_voice(fs: f64, body: BodyMix) -> 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@@ -80,7 +85,9 @@ impl Engine {/// 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 {+ pub fn set_body(&mut self, body: impl Into<BodyMix>) -> VoiceInfo {+ let body: BodyMix = body.into();+ let body = BodyMix::new(body.female, body.child);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);@@ -261,7 +268,7 @@ impl Engine {/// Play one beatbox sound as soon as the mouth can make it.pub fn beat_hit(&mut self, step: &BeatStep) {self.scratch.clear();- let hit = self.voice.clock + BeatPlayer::lead_in_with(step.id.as_str(), self.body.as_str(), &mut self.scratch);+ let hit = self.voice.clock + BeatPlayer::lead_in_with(step.id.as_str(), self.body, &mut self.scratch);self.scratch.clear();self.beat.gestures(step, hit, 0.18, &mut self.scratch);debug_assert!(self.scratch.len() <= MAX_SOUND_GESTURES);diff --git a/crates/chimera/src/phonetics/beatbox.rs b/crates/chimera/src/phonetics/beatbox.rsindex 82e7860..072174b 100644--- a/crates/chimera/src/phonetics/beatbox.rs+++ b/crates/chimera/src/phonetics/beatbox.rs@@ -17,7 +17,7 @@use super::inventory::phoneme;use super::planner::{oral_gestures_into, vowel_artic};-use crate::anatomy::human::{ArticKey, ArticPatch};+use crate::anatomy::human::{ArticKey, ArticPatch, BodyMix};use crate::control::score::{ControlKey, Gesture, Label, Targets};use crate::math::{js_max, js_min};use serde::{Deserialize, Serialize};@@ -28,7 +28,7 @@ pub fn init() {}/// A beatboxer's ready posture: jaw nearly closed, lips just apart, tongue relaxed.-pub fn beat_ready(body: &str) -> ArticPatch {+pub fn beat_ready(body: BodyMix) -> ArticPatch {// with the jaw nearly closed the tongue rests a little higher than in a spoken schwa; the// velar hits need it there: from lower, the release peels open and loses its punchlet schwa = vowel_artic("ə", body).unwrap_or_default();@@ -69,7 +69,7 @@ pub struct BeatBuild {}/// Builds a sound's gestures (acoustic hit at t = 0), appending them to `out`.-pub type BuildFn = fn(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>);+pub type BuildFn = fn(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>);/// The most gestures any sound builds (a `Vec` with this much room never reallocates).pub const MAX_SOUND_GESTURES: usize = 16;@@ -92,7 +92,7 @@ pub struct BeatSound {impl BeatSound {/// `build` into a new `Vec` (allocates; for tools and tests).- pub fn build_vec(&self, body: &str, o: &BeatBuild) -> Vec<Gesture> {+ pub fn build_vec(&self, body: BodyMix, o: &BeatBuild) -> Vec<Gesture> {let mut out = Vec::with_capacity(MAX_SOUND_GESTURES);(self.build)(body, o, &mut out);out@@ -107,7 +107,7 @@ impl core::fmt::Debug for BeatSound {/// The consonant's oral gestures with `extra` targets over its own; returns where they start in `out`.#[allow(clippy::too_many_arguments)]-fn oral(body: &str, ipa: &str, a: f64, b: f64, speed: f64, label: &str, extra: &[(ArticKey, f64)], out: &mut Vec<Gesture>) -> usize {+fn oral(body: BodyMix, ipa: &str, a: f64, b: f64, speed: f64, label: &str, extra: &[(ArticKey, f64)], out: &mut Vec<Gesture>) -> usize {let start = out.len();let Some(d) = phoneme(ipa, body) else { return start };let mut tg = d.targets;@@ -170,13 +170,13 @@ fn blow(t0: f64, t1: f64, level: f64, abduction: f64, label: &str, tail: f64, ouuse ArticKey::{Jaw, LipAp, TbY};-fn kick(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn kick(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let s = oral(body, "p", -0.075, 0.0, 2.0, "B", &[(Jaw, 0.3)], out);snap(&mut out[s..], 3.5, 0.01);ejective(-0.075, o.accent, "B", out);}-fn hat(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn hat(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let s = oral(body, "t", -0.05, 0.0, 2.0, "t", &[(Jaw, 0.3)], out);snap(&mut out[s..], 3.5, 0.01);let s = oral(body, "s", 0.012, 0.03, 1.6, "t", &[], out);@@ -184,7 +184,7 @@ fn hat(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {blow(-0.03, 0.026, 1.25 * o.accent, 0.36, "t", 0.02, out);}-fn open_hat(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn open_hat(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let end = js_max(0.09, js_min(0.26, o.len * 1.6));let s = oral(body, "t", -0.05, 0.0, 2.0, "tss", &[(Jaw, 0.3)], out);snap(&mut out[s..], 3.5, 0.01);@@ -193,7 +193,7 @@ fn open_hat(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {blow(-0.03, end, 1.2 * o.accent, 0.4, "tss", 0.09, out);}-fn snare(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn snare(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let s = oral(body, "p", -0.06, 0.0, 2.0, "Pf", &[], out);snap(&mut out[s..], 3.5, 0.01);let s = oral(body, "f", 0.018, 0.08, 1.6, "Pf", &[], out);@@ -201,13 +201,13 @@ fn snare(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {blow(-0.045, 0.075, 1.7 * o.accent, 0.45, "Pf", 0.04, out);}-fn rimshot(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn rimshot(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let s = oral(body, "k", -0.08, 0.0, 2.0, "K", &[(Jaw, 0.35)], out);snap(&mut out[s..], 4.0, 0.008);ejective(-0.08, o.accent, "K", out);}-fn inward_snare(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn inward_snare(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let s = oral(body, "k", -0.06, 0.0, 2.0, "^K", &[(Jaw, 0.35)], out);snap(&mut out[s..], 4.0, 0.008);let s = oral(body, "x", 0.012, 0.085, 1.4, "^K", &[(TbY, 7.35)], out);@@ -217,7 +217,7 @@ fn inward_snare(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {out.push(g(-0.035, 0.085, 0.015, 0.05, 2.0, tg(&[(ControlKey::BREATH, -1.7 * o.accent)]), "^K", None));}-fn tongue_click(body: &str, _o: &BeatBuild, out: &mut Vec<Gesture>) {+fn tongue_click(body: BodyMix, _o: &BeatBuild, out: &mut Vec<Gesture>) {// the tip seals without the alveolar's fronted tongue body (that would close the pocket)let s = oral(body, "t", -0.12, 0.0, 2.0, "!", &[], out);snap(&mut out[s..], 3.5, 0.01);@@ -234,7 +234,7 @@ fn tongue_click(body: &str, _o: &BeatBuild, out: &mut Vec<Gesture>) {out.push(g(-0.03, 0.006, 0.04, 0.03, 40.0, tg(&[(a(ArticKey::Dorsum), 1.0)]), "!", Some(2.0)));}-fn lip_pop(body: &str, _o: &BeatBuild, out: &mut Vec<Gesture>) {+fn lip_pop(body: BodyMix, _o: &BeatBuild, out: &mut Vec<Gesture>) {// a light seal (pressing the lips squeezes the pocket before the suction starts)let s = oral(body, "p", -0.12, 0.0, 2.0, "P!", &[(LipAp, -0.08)], out);snap(&mut out[s..], 5.0, 0.006);@@ -243,7 +243,7 @@ fn lip_pop(body: &str, _o: &BeatBuild, out: &mut Vec<Gesture>) {out.push(g(-0.07, 0.004, 0.04, 0.05, 40.0, tg(&[(a(Jaw), 1.6), (a(ArticKey::Dorsum), 1.0)]), "P!", Some(2.0)));}-fn crash(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn crash(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let end = js_max(0.14, js_min(0.34, o.len * 2.0));// the "ch": the back of the tongue lingers by the velum after the burst ([x]) while the// blade rises into the long rounded [ʃ]@@ -256,7 +256,7 @@ fn crash(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {blow(-0.035, end, 1.75 * o.accent, 0.45, "kch", 0.14, out);}-fn hum(body: &str, o: &BeatBuild, out: &mut Vec<Gesture>) {+fn hum(body: BodyMix, o: &BeatBuild, out: &mut Vec<Gesture>) {let end = js_max(0.06, o.len * 0.92);// lips shut before the voice starts, so the note begins as a hum rather than a vowel;// the folds stay apart (breathing) while the velum drops into the sealed mouth, so thediff --git a/crates/chimera/src/phonetics/inventory.rs b/crates/chimera/src/phonetics/inventory.rsindex 4aab866..b7d92d0 100644--- a/crates/chimera/src/phonetics/inventory.rs+++ b/crates/chimera/src/phonetics/inventory.rs@@ -6,7 +6,7 @@//! Real time: [`phoneme`] returns a `Copy` definition (targets inline, strings static) and//! allocates nothing once [`init`] has parsed the tables.-use crate::anatomy::human::{ArticKey, ArticPatch};+use crate::anatomy::human::{ArticKey, ArticPatch, BodyMix, BodyName};use serde::{Deserialize, Serialize};use std::collections::BTreeMap;use std::sync::LazyLock;@@ -241,18 +241,25 @@ fn by_ipa(ipa: &str) -> Option<&'static PhonemeDef> {BASE.iter().rev().find(|p| p.ipa == ipa)}-/// Phoneme definition with calibrated targets for a body (falls back to defaults).-/// Allocates nothing (the definition is `Copy`).-pub fn phoneme(ipa: &str, body: &str) -> Option<PhonemeDef> {+/// Phoneme definition with calibrated targets for a body (falls back to defaults); between+/// presets the calibrated targets blend by the body's weights. Allocates nothing (the definition+/// is `Copy`).+pub fn phoneme(ipa: &str, body: BodyMix) -> Option<PhonemeDef> {let p = by_ipa(ipa)?;- match CAL.get(body).and_then(|b| b.get(ipa)) {+ let of = |b: BodyName| match CAL.get(b.as_str()).and_then(|t| t.get(ipa)) {Some(cal) => {- let mut out = *p;- out.targets.merge(cal);- Some(out)+ let mut t = p.targets;+ t.merge(cal);+ t}- None => Some(*p),- }+ None => p.targets,+ };+ let mut out = *p;+ out.targets = match body.preset() {+ Some(b) => of(b),+ None => ArticPatch::blend(&body.weights().map(|(b, w)| (w, of(b)))),+ };+ Some(out)}pub fn consonants() -> &'static [PhonemeDef] {diff --git a/crates/chimera/src/phonetics/planner.rs b/crates/chimera/src/phonetics/planner.rsindex ac3c3dd..4e43c3e 100644--- a/crates/chimera/src/phonetics/planner.rs+++ b/crates/chimera/src/phonetics/planner.rs@@ -8,7 +8,7 @@use super::durations::{SegInfo, klatt_durations};use super::inventory::{Glottal, Manner, PhonemeDef, Voicing, phoneme};use super::{Intonation, Plan, PlannedSegment, Segment};-use crate::anatomy::human::{ArticKey, ArticPatch};+use crate::anatomy::human::{ArticKey, ArticPatch, BodyMix, BodyName};use crate::control::score::{ControlKey, Gesture, Targets};use crate::math::{js_max, js_round};use serde::{Deserialize, Serialize};@@ -61,13 +61,30 @@ pub fn diphthong_parts(ipa: &str) -> Option<(&'static str, &'static str)> {}}-pub fn is_vowel(ipa: &str, body: &str) -> bool {- vowel_table().get(body).is_some_and(|t| t.contains_key(ipa)) || expand(ipa).is_some()+pub fn is_vowel(ipa: &str, body: BodyMix) -> bool {+ let t = vowel_table();+ body.weights().iter().any(|(b, w)| *w > 0.0 && t.get(b.as_str()).is_some_and(|t| t.contains_key(ipa))) || expand(ipa).is_some()+}++/// The calibrated articulation of a vowel for a body: between presets, the presets' calibrated+/// articulations blended by the body's weights.+pub fn vowel_artic(ipa: &str, body: BodyMix) -> Option<ArticPatch> {+ if let Some(b) = body.preset() {+ return preset_vowel_artic(ipa, b);+ }+ let w = body.weights();+ let mut parts = [(0.0, ArticPatch::default()); 3];+ for (i, (b, wi)) in w.iter().enumerate() {+ if *wi > 0.0 {+ parts[i] = (*wi, preset_vowel_artic(ipa, *b)?);+ }+ }+ Some(ArticPatch::blend(&parts))}-pub fn vowel_artic(ipa: &str, body: &str) -> Option<ArticPatch> {+fn preset_vowel_artic(ipa: &str, body: BodyName) -> Option<ArticPatch> {let t = vowel_table();- let v = t.get(body).and_then(|b| b.get(ipa)).or_else(|| t.get("male").and_then(|m| m.get(ipa)))?;+ let v = t.get(body.as_str()).and_then(|b| b.get(ipa)).or_else(|| t.get("male").and_then(|m| m.get(ipa)))?;let mut out = ArticPatch::default();for k in VOWEL_KEYS {if let Some(x) = v.artic.get(k) {@@ -96,7 +113,7 @@ pub fn init() {#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct PlanOptions {- pub body: String,+ pub body: BodyMix,/// voice-clock start time (s)pub t0: f64,/// speaking-rate multiplier (>1 = faster)@@ -156,7 +173,7 @@ struct Span {pub fn plan_utterance(input: &[Segment], o: &PlanOptions) -> Plan {let rate = o.rate.unwrap_or(1.0);- let body = o.body.as_str();+ let body = o.body;// durations by the Klatt rules, on whole segments (diphthongs before they are split)let durs = klatt_durations(input, |s| {if is_vowel(&s.ipa, body) {diff --git a/crates/chimera/src/phonetics/sing.rs b/crates/chimera/src/phonetics/sing.rsindex e02c740..0f9dec6 100644--- a/crates/chimera/src/phonetics/sing.rs+++ b/crates/chimera/src/phonetics/sing.rs@@ -12,6 +12,7 @@//! These planners allocate (they run off the audio thread).use super::inventory::phoneme;+use crate::anatomy::human::BodyMix;use super::planner::{PlanOptions, diphthong_parts, plan_utterance};use super::{Intonation, Plan, PlannedSegment, Segment, Syllable};use crate::control::score::{ControlKey, Gesture, Targets};@@ -22,11 +23,11 @@ use serde::{Deserialize, Serialize};pub use crate::math::midi_to_hz;/// sung consonants are a little shorter than spoken ones-fn cdur(ipa: &str, body: &str, k: f64) -> f64 {+fn cdur(ipa: &str, body: BodyMix, k: f64) -> f64 {phoneme(ipa, body).map_or(0.07, |d| d.dur) * k}-fn consonants(segs: &[Segment], body: &str, k: f64) -> Vec<Segment> {+fn consonants(segs: &[Segment], body: BodyMix, k: f64) -> Vec<Segment> {segs.iter().map(|c| Segment { ipa: c.ipa.clone(), dur: Some(cdur(&c.ipa, body, k)), ..Default::default() }).collect()}@@ -52,7 +53,7 @@ pub struct SungNote {#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SongOptions {- pub body: String,+ pub body: BodyMix,pub bpm: f64,/// plan time of the first note's beat (its onset consonants come before)pub t0: f64,@@ -84,12 +85,12 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {}let mut segs: Vec<Segment> = Vec::new();let mut vowel_spans: Vec<(f64, f64)> = Vec::new();- let onset_of = |k: usize| if melisma(¬es[k].syl) { Vec::new() } else { consonants(¬es[k].syl.onset, &o.body, 0.8) };+ let onset_of = |k: usize| if melisma(¬es[k].syl) { Vec::new() } else { consonants(¬es[k].syl.onset, o.body, 0.8) };for k in i..=j {let n = ¬es[k];let hz = midi_to_hz(n.midi);let next_melisma = k < j && melisma(¬es[k + 1].syl);- let coda = if next_melisma { Vec::new() } else { consonants(&last_of_chain(notes, k).coda, &o.body, 0.8) };+ let coda = if next_melisma { Vec::new() } else { consonants(&last_of_chain(notes, k).coda, o.body, 0.8) };let onset = onset_of(k);// vowel from this note's beat to the next note's onset (less this note's coda);// the phrase's last vowel leaves a short breath before the next phrase@@ -112,7 +113,7 @@ pub fn plan_song(notes: &[SungNote], o: &SongOptions) -> Plan {}if !segs.is_empty() {// the planner lays segments out from t0 + 0.06: start so the first vowel lands on its beat- let plan = plan_utterance(&segs, &PlanOptions { body: o.body.clone(), t0: times[i] - total(&onset_of(i)) - 0.06, f0: Some(midi_to_hz(notes[i].midi)), intonation: Some(Intonation::Flat), ..Default::default() });+ let plan = plan_utterance(&segs, &PlanOptions { body: o.body, t0: times[i] - total(&onset_of(i)) - 0.06, f0: Some(midi_to_hz(notes[i].midi)), intonation: Some(Intonation::Flat), ..Default::default() });gestures.extend_from_slice(&plan.gestures);segments.extend(plan.segments);for (a, b) in vowel_spans {@@ -152,7 +153,7 @@ pub struct LegatoFrom {#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct NoteOnOptions {- pub body: String,+ pub body: BodyMix,pub vibrato: f64,pub tag: f64,#[serde(default, skip_serializing_if = "Option::is_none")]@@ -166,12 +167,12 @@ pub fn plan_note_on(syl: &Syllable, midi: f64, o: &NoteOnOptions) -> Vec<Gesturelet hz = midi_to_hz(midi);let mut segs: Vec<Segment> = Vec::new();if let Some(l) = &o.legato_from {- segs.extend(tail(&l.syl, &o.body, midi_to_hz(l.midi)));+ segs.extend(tail(&l.syl, o.body, midi_to_hz(l.midi)));}- segs.extend(consonants(&syl.onset, &o.body, 0.7));+ segs.extend(consonants(&syl.onset, o.body, 0.7));let parts = diphthong_parts(&syl.nucleus.ipa);segs.push(Segment { ipa: parts.map_or(syl.nucleus.ipa.clone(), |p| p.0.to_string()), dur: Some(HOLD), f0: Some(hz), stress: Some(1), word_end: None });- let plan = plan_utterance(&segs, &PlanOptions { body: o.body.clone(), t0: LIVE_T0, f0: Some(hz), intonation: Some(Intonation::Flat), open_end: Some(true), ..Default::default() });+ let plan = plan_utterance(&segs, &PlanOptions { body: o.body, t0: LIVE_T0, f0: Some(hz), intonation: Some(Intonation::Flat), open_end: Some(true), ..Default::default() });let vowel = &plan.segments[plan.segments.len() - 1];let mut out: Vec<Gesture> = plan.gestures.iter().map(|g| g.tag(if g.targets.has(ControlKey::F0) { o.tag + 1.0 } else { o.tag })).collect();out.push(vibrato_gesture(vowel.t0, vowel.t1, o.vibrato, Some(o.tag + 1.0)));@@ -195,17 +196,17 @@ pub fn plan_melisma(midi: f64, o: &MelismaOptions) -> Vec<Gesture> {}/// Key released: the diphthong's glide and the coda (release the note's tags first).-pub fn plan_note_off(syl: &Syllable, midi: f64, body: &str) -> Vec<Gesture> {+pub fn plan_note_off(syl: &Syllable, midi: f64, body: BodyMix) -> Vec<Gesture> {let hz = midi_to_hz(midi);let segs = tail(syl, body, hz);if segs.is_empty() {return Vec::new();}- plan_utterance(&segs, &PlanOptions { body: body.to_string(), t0: LIVE_T0, f0: Some(hz), intonation: Some(Intonation::Flat), ..Default::default() }).gestures+ plan_utterance(&segs, &PlanOptions { body, t0: LIVE_T0, f0: Some(hz), intonation: Some(Intonation::Flat), ..Default::default() }).gestures}/// What follows a held vowel: the diphthong's glide (at the note's pitch) and the coda.-fn tail(syl: &Syllable, body: &str, hz: f64) -> Vec<Segment> {+fn tail(syl: &Syllable, body: BodyMix, hz: f64) -> Vec<Segment> {let parts = diphthong_parts(&syl.nucleus.ipa);let mut out: Vec<Segment> = Vec::new();if let Some((_, b)) = parts {diff --git a/crates/chimera/src/phonetics/syllables.rs b/crates/chimera/src/phonetics/syllables.rsindex 231d7c7..40fc7ed 100644--- a/crates/chimera/src/phonetics/syllables.rs+++ b/crates/chimera/src/phonetics/syllables.rs@@ -4,6 +4,7 @@//! Typed hyphens force syllable breaks; a lone "-" (or "~") holds the previous vowel onto the//! next note (melisma), as in vocaloid editors.+use crate::anatomy::human::BodyMix;use super::english::js_is_space;use super::planner::is_vowel;use super::{Segment, Syllable};@@ -30,7 +31,7 @@ pub struct SyllableParts {/// Split one word's segments into onset / nucleus / coda syllables.pub fn syllabify_segments(segs: &[Segment]) -> Vec<SyllableParts> {- let vi: Vec<usize> = segs.iter().enumerate().filter(|(_, s)| is_vowel(&s.ipa, "male")).map(|(i, _)| i).collect();+ let vi: Vec<usize> = segs.iter().enumerate().filter(|(_, s)| is_vowel(&s.ipa, BodyMix::MALE)).map(|(i, _)| i).collect();if vi.is_empty() {return Vec::new();}diff --git a/crates/chimera/src/voice/human_voice.rs b/crates/chimera/src/voice/human_voice.rsindex f052485..911a1b6 100644--- a/crates/chimera/src/voice/human_voice.rs+++ b/crates/chimera/src/voice/human_voice.rs@@ -238,7 +238,15 @@ impl HumanVoice {v.airway.apply(&x, 0.0);v.airway.net.snap_to_targets();// smaller bodies radiate more high-frequency (derivative) energy at their higher f0- v.output_gain *= if v.airway.body.scale < 0.95 { 0.55 } else { 1.0 };+ // (a ramp from the adult female's scale up to the adult male's, so blended bodies have no step)+ let sc = v.airway.body.scale;+ v.output_gain *= if sc >= 1.0 {+ 1.0+ } else if sc <= 0.9 {+ 0.55+ } else {+ 0.55 + 0.45 * (sc - 0.9) / 0.1+ };v.apply_source();v}diff --git a/crates/chimera/tests/beat_alloc.rs b/crates/chimera/tests/beat_alloc.rsindex 2dd5f61..3b591c5 100644--- a/crates/chimera/tests/beat_alloc.rs+++ b/crates/chimera/tests/beat_alloc.rs@@ -56,7 +56,7 @@ fn the_beat_player_does_not_allocate() {p.set_steps(&other);}if b == 1300 {- p.body = chimera::anatomy::human::BodyName::Child;+ p.body = chimera::anatomy::human::BodyName::Child.into();p.rebase(-clock);clock = 0.0;p.rewind(clock);@@ -66,7 +66,7 @@ fn the_beat_player_does_not_allocate() {clock += 128.0 / 48000.0;}for s in &BEAT_SOUNDS {- let lead = BeatPlayer::lead_in_with(s.id, "female", &mut scratch);+ let lead = BeatPlayer::lead_in_with(s.id, "female".into(), &mut scratch);scratch.clear();p.gestures(&BeatStep { note: Some(45.0), accent: Some(1.2), ..BeatStep::new(s.id) }, clock + lead, 0.18, &mut scratch);assert!(!scratch.is_empty() && scratch.len() <= MAX_SOUND_GESTURES);diff --git a/crates/chimera/tests/beatbox.rs b/crates/chimera/tests/beatbox.rsindex 094982b..de7fc28 100644--- a/crates/chimera/tests/beatbox.rs+++ b/crates/chimera/tests/beatbox.rs@@ -55,12 +55,12 @@ fn format_and_parse_round_trip_every_preset() {fn every_sound_builds_gestures_that_start_before_and_end_after_its_hit() {for s in &BEAT_SOUNDS {for body in ["male", "female", "child"] {- let gs = s.build_vec(body, &BeatBuild { f0: 82.0, len: 0.15, accent: 1.0 });+ let gs = s.build_vec(body.into(), &BeatBuild { f0: 82.0, len: 0.15, accent: 1.0 });assert!(!gs.is_empty());assert!(gs.iter().map(|g| g.t0 - g.ramp_in).fold(f64::INFINITY, f64::min) < 0.0);assert!(gs.iter().map(|g| g.t1 + g.ramp_out).fold(f64::NEG_INFINITY, f64::max) > 0.0);// everything a sound needs fits inside the sequencer's look-ahead- assert!(BeatPlayer::lead_in(s.id, body) < BeatPlayer::HORIZON, "{} {body}", s.id);+ assert!(BeatPlayer::lead_in(s.id, body.into()) < BeatPlayer::HORIZON, "{} {body}", s.id);}}}diff --git a/crates/chimera/tests/body_mix.rs b/crates/chimera/tests/body_mix.rsnew file mode 100644index 0000000..66e4573--- /dev/null+++ b/crates/chimera/tests/body_mix.rs@@ -0,0 +1,84 @@+//! The continuous body: presets are exact, blends land between them (anatomy, calibrated+//! targets, formants, pitch), and a blended voice plays.+use chimera::airway::frequency::{find_peaks, transfer_function};+use chimera::anatomy::human::{BODY_CHILD, BODY_FEMALE, BODY_MALE, BodyMix, BodyName, HumanArtic, NEUTRAL};+use chimera::engine::{Engine, default_f0};+use chimera::phonetics::inventory::phoneme;+use chimera::phonetics::planner::{PlanOptions, vowel_artic};+use chimera::voice::human_airway::HumanAirway;++fn between(x: f64, a: f64, b: f64) -> bool {+ x >= a.min(b) - 1e-12 && x <= a.max(b) + 1e-12+}++#[test]+fn presets_are_exact_and_weights_sum_to_one() {+ for (name, mix, body) in [(BodyName::Male, BodyMix::MALE, BODY_MALE), (BodyName::Female, BodyMix::FEMALE, BODY_FEMALE), (BodyName::Child, BodyMix::CHILD, BODY_CHILD)] {+ assert_eq!(mix.preset(), Some(name));+ assert_eq!(mix.body(), body);+ assert_eq!(BodyMix::from(name.as_str()), mix);+ assert_eq!(vowel_artic("i", mix), vowel_artic("i", name.into()));+ }+ // a child has no female axis+ assert_eq!(BodyMix::new(0.7, 1.0).preset(), Some(BodyName::Child));+ for f in [0.0, 0.3, 1.0] {+ for c in [0.0, 0.5, 0.9] {+ let w: f64 = BodyMix::new(f, c).weights().iter().map(|x| x.1).sum();+ assert!((w - 1.0).abs() < 1e-12);+ }+ }+ assert_eq!(BodyMix::new(f64::NAN, 3.0), BodyMix { female: 0.0, child: 1.0 });+}++#[test]+fn deserializes_from_a_name_or_a_mix() {+ let o: PlanOptions = serde_json::from_str(r#"{"body":"female","t0":0}"#).unwrap();+ assert_eq!(o.body, BodyMix::FEMALE);+ let o: PlanOptions = serde_json::from_str(r#"{"body":{"female":0.25,"child":0.5},"t0":0}"#).unwrap();+ assert_eq!(o.body, BodyMix { female: 0.25, child: 0.5 });+}++#[test]+fn blends_land_between_the_presets() {+ let mid = BodyMix::new(0.5, 0.0);+ assert!((mid.body().scale - 0.95).abs() < 1e-12);+ assert!(default_f0(mid) > 110.0 && default_f0(mid) < 205.0);+ // calibrated targets: each key between the two presets'+ for v in ["i", "a", "u"] {+ let (m, f, x) = (vowel_artic(v, BodyMix::MALE).unwrap(), vowel_artic(v, BodyMix::FEMALE).unwrap(), vowel_artic(v, mid).unwrap());+ for (k, xv) in x.iter() {+ assert!(between(xv, m.get(k).unwrap(), f.get(k).unwrap()), "{v} {k:?}");+ }+ }+ let (m, c, x) = (phoneme("s", BodyMix::MALE).unwrap(), phoneme("s", BodyMix::CHILD).unwrap(), phoneme("s", BodyMix::new(0.0, 0.5)).unwrap());+ for (k, xv) in x.targets.iter() {+ assert!(between(xv, m.targets.get(k).unwrap(), c.targets.get(k).unwrap()), "s {k:?}");+ }+ // the formants of /a/ for a body half way to a child sit between the adult male's and the child's+ let f = |b: BodyMix| {+ let a: HumanArtic = vowel_artic("a", b).unwrap().apply_to(&NEUTRAL);+ let mut w = HumanAirway::new(96000.0, b.body());+ w.apply(&a, 0.0);+ let el = w.net.linear_elements();+ let freqs: Vec<f64> = (0..360).map(|i| 60.0 * (8000.0f64 / 60.0).powf(i as f64 / 359.0)).collect();+ let h = transfer_function(&el, w.pharynx.first_node(), &freqs, &[w.glottis_port]);+ find_peaks(&freqs, &h.mag, 150.0).iter().map(|p| p.freq).take(2).collect::<Vec<_>>()+ };+ let (fm, fc, fx) = (f(BodyMix::MALE), f(BodyMix::CHILD), f(BodyMix::new(0.0, 0.5)));+ for i in 0..2 {+ assert!(fx[i] > fm[i] && fx[i] < fc[i], "F{}: male {} half {} child {}", i + 1, fm[i], fx[i], fc[i]);+ }+}++#[test]+fn a_blended_voice_plays() {+ let mut e = Engine::new(48000.0);+ let info = e.set_body(BodyMix::new(0.4, 0.3));+ assert_eq!(info.body, BodyMix::new(0.4, 0.3));+ e.set_gate(1.0);+ let mut out = vec![0.0f32; 24000];+ e.render(&mut out);+ let peak = out.iter().fold(0.0f32, |m, x| m.max(x.abs()));+ assert!(out.iter().all(|x| x.is_finite()));+ assert!(peak > 1e-3, "peak {peak}");+}diff --git a/crates/chimera/tests/engine.rs b/crates/chimera/tests/engine.rsindex 50a1aeb..4f29221 100644--- a/crates/chimera/tests/engine.rs+++ b/crates/chimera/tests/engine.rs@@ -16,7 +16,7 @@ fn engine_plays_the_beatbox_bar_like_the_typescript_worklet() {let reference = load_f32("beatbox-bar");let mut e = Engine::new(num(&a["fs"]));e.set_source(&SourcePatch::f0(num(&a["f0"])));- e.set_artic(&beat_ready("male"), None);+ e.set_artic(&beat_ready("male".into()), None);e.set_beat_steps(&parse_beat(a["text"].as_str().unwrap()));e.set_beat_tempo(Some(num(&a["bpm"])), Some(num(&a["swing"])));e.set_beat_playing(true);diff --git a/crates/chimera/tests/geometry_continuity.rs b/crates/chimera/tests/geometry_continuity.rsindex 95ac0f1..1ace2ea 100644--- a/crates/chimera/tests/geometry_continuity.rs+++ b/crates/chimera/tests/geometry_continuity.rs@@ -122,7 +122,7 @@ fn no_area_jumps_anywhere_in_the_articulators_speech_ranges() {for (body_name, body) in BODIES {let mut areas = Areas::new(body);for vw in ["i", "ɑ", "u", "ə"] {- let v = vowel_artic(vw, body_name).unwrap();+ let v = vowel_artic(vw, body_name.into()).unwrap();let tip = rest_tip(v.get(ArticKey::Jaw).unwrap_or(NEUTRAL.jaw), v.get(ArticKey::TbX).unwrap(), v.get(ArticKey::TbY).unwrap());let mut base = v.apply_to(&NEUTRAL);base.tt_x = tip.x;diff --git a/crates/chimera/tests/golden_planning.rs b/crates/chimera/tests/golden_planning.rsindex 98b61ff..825d669 100644--- a/crates/chimera/tests/golden_planning.rs+++ b/crates/chimera/tests/golden_planning.rs@@ -3,7 +3,7 @@//! the same keys everywhere, strings and labels exact, `speed`/`releaseHold`/`tag` exact, other//! numbers to 1e-9 relative (absolute floor 1e-9).mod common;-use chimera::anatomy::human::{BODY_MALE, BodyName};+use chimera::anatomy::human::BODY_MALE;use chimera::control::beat_player::BeatPlayer;use chimera::control::score::Gesture;use chimera::phonetics::Segment;@@ -142,7 +142,7 @@ fn live_notes_match_typescript() {legato += o.legato_from.is_some() as usize;plan_note_on(&de(&n["syl"]), midi, &o)}- "off" => plan_note_off(&de(&n["syl"]), midi, n["body"].as_str().unwrap()),+ "off" => plan_note_off(&de(&n["syl"]), midi, n["body"].as_str().unwrap().into()),"melisma" => plan_melisma(midi, &de::<MelismaOptions>(&n["opts"])),k => panic!("{k}"),};@@ -168,15 +168,15 @@ fn beat_sounds_match_typescript() {let body = b["body"].as_str().unwrap();let o: BeatBuild = de(&b["o"]);let mut out = Vec::new();- (s.build)(body, &o, &mut out);+ (s.build)(body.into(), &o, &mut out);cmp(&format!("sound {} {body} {}", s.id, b["o"]), &b["gestures"], &val(&out), &mut st);}for body in ["male", "female", "child"] {- cmp(&format!("leadIn {} {body}", s.id), &want["leadIn"][body], &json!(BeatPlayer::lead_in(s.id, body)), &mut st);+ cmp(&format!("leadIn {} {body}", s.id), &want["leadIn"][body], &json!(BeatPlayer::lead_in(s.id, body.into())), &mut st);}}for body in ["male", "female", "child"] {- cmp(&format!("ready {body}"), &f["ready"][body], &val(&beat_ready(body)), &mut st);+ cmp(&format!("ready {body}"), &f["ready"][body], &val(&beat_ready(body.into())), &mut st);}report("sounds", &st);}@@ -207,7 +207,7 @@ fn run_player(ops: &[Value]) -> Vec<Value> {"tempo" => p.set_tempo(num(&o["bpm"]), num(&o["swing"])),"start" => p.start(num(&o["clock"])),"stop" => p.stop(),- "body" => p.body = BodyName::parse(o["body"].as_str().unwrap()),+ "body" => p.body = o["body"].as_str().unwrap().into(),"rebase" => p.rebase(num(&o["delta"])),"rewind" => p.rewind(num(&o["clock"])),"stepAt" => out.push(json!(nums(&o["clocks"]).iter().map(|c| p.step_at(*c)).collect::<Vec<_>>())),@@ -257,7 +257,7 @@ fn beatbox_bar_audio_matches_typescript() {chimera::phonetics::beatbox::init();let mut v = HumanVoice::new(fs, BODY_MALE, 2);v.set_source(&SourcePatch::f0(num(&a["f0"])));- v.set_articulation(&beat_ready("male"), None);+ v.set_articulation(&beat_ready("male".into()), None);let mut p = BeatPlayer::new();p.set_steps(&parse_beat(a["text"].as_str().unwrap()));p.set_tempo(num(&a["bpm"]), num(&a["swing"]));diff --git a/src/audio/AudioEngine.ts b/src/audio/AudioEngine.tsindex fdee95e..0090867 100644--- a/src/audio/AudioEngine.ts+++ b/src/audio/AudioEngine.ts@@ -4,7 +4,8 @@*/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 { ToWorklet, FromWorklet, TelemetryMessage, PlannedMessage, CreatureTelemetryMessage } from "../worklet/protocol.ts";+import type { BodyMix } from "../wasm/types.ts";import type { HumanArtic } from "../wasm/types.ts";import type { VoiceSource } from "../wasm/types.ts";@@ -209,7 +210,7 @@ export class AudioEngine {if (this.master && this.ctx) this.master.gain.setTargetAtTime(v, this.ctx.currentTime, 0.02);}- setBody(body: BodyName): void {+ setBody(body: BodyMix): void {this.send({ type: "body", body });}diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex a2385aa..3669bf0 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -19,8 +19,8 @@ import { SingRight, singInfo } from "./components/SingPanel.tsx";import { playDemo, DEMO_SONGS } from "./singing.ts";import type { Mode } from "./store.ts";import type { BodyName } from "../worklet/protocol.ts";--const BODY_NAME: Record<BodyName, string> = { male: "Adult male", female: "Adult female", child: "Child" };+import { BodyPad } from "./components/BodyPad.tsx";+import { bodyLabel, presetOf, PRESETS } from "./body.ts";function TopBar() {const started = useStore((s) => s.started);@@ -56,16 +56,19 @@ function TopBar() {]}/>{mode !== "bestiary" && (- <Segmented<BodyName>- label="Body"- value={body}- onChange={setBody}- options={[- { value: "male", label: "Male" },- { value: "female", label: "Female" },- { value: "child", label: "Child" },- ]}- />+ <div className="body-control">+ <Segmented<BodyName>+ label="Body"+ value={presetOf(body)}+ onChange={(b) => setBody(PRESETS[b])}+ options={[+ { value: "male", label: "Male" },+ { value: "female", label: "Female" },+ { value: "child", label: "Child" },+ ]}+ />+ <BodyPad />+ </div>)}<div className="topbar-right"><label className="volume">@@ -150,7 +153,7 @@ function LeftScreen() {className="left"focustitle={bestiary ? "Creature" : "Vocal tract"}- sub={bestiary ? "Airway / live" : `${BODY_NAME[body]} / midsagittal`}+ sub={bestiary ? "Airway / live" : `${bodyLabel(body)} / midsagittal`}label={bestiary ? "Live creature airway" : "Live vocal tract"}tools={<ViewToggles />}>diff --git a/src/ui/analysis.ts b/src/ui/analysis.tsindex 4e55cdb..f158d5a 100644--- a/src/ui/analysis.ts+++ b/src/ui/analysis.ts@@ -3,10 +3,8 @@* 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, 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 };+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 { bodyWeights, type BodyMix } from "./body.ts";export interface VowelPoint {ipa: string;@@ -17,8 +15,8 @@ export interface VowelPoint {}export class VoiceModel {- readonly body: BodyName;- /** the body's dimensions */+ readonly body: BodyMix;+ /** the body's dimensions (blended, as the engine builds it) */readonly bodyParams: HumanBody;/** template ↔ body coordinates */readonly tract: TractMap;@@ -31,21 +29,34 @@ export class VoiceModel {private tfKey = "";private tf: { freqs: number[]; db: number[]; formants: number[] } | null = null;- constructor(body: BodyName, sampleRate: number) {+ constructor(body: BodyMix, sampleRate: number) {this.body = body;- this.bodyParams = BODIES[body];- this.tract = new TractMap(this.bodyParams);this.model = airwayModel(body, sampleRate);+ this.bodyParams = this.model.body;+ this.tract = new TractMap(this.bodyParams);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,- F1: table[v.ipa].formants[0],- F2: table[v.ipa].formants[1],- artic: table[v.ipa].artic,- }));+ // calibrated vowels of the presets, blended by the body's weights (as the engine plans them;+ // the formants are a blend too, close to what this body produces)+ const parts = bodyWeights(body)+ .filter(([, w]) => w > 0)+ .map(([n, w]) => ({ w, table: VOWEL_TARGETS[n] ?? {} }));+ this.vowels = VOWELS.filter((v) => parts.every((p) => p.table[v.ipa])).map((v) => {+ const at = (f: (t: (typeof parts)[number]["table"][string]) => number | undefined) => {+ let acc = 0, ws = 0;+ for (const p of parts) {+ const x = f(p.table[v.ipa]);+ if (x !== undefined) (acc += p.w * x), (ws += p.w);+ }+ return ws > 0 ? acc / ws : undefined;+ };+ const artic: Partial<HumanArtic> = {};+ for (const k of ARTIC_KEYS) {+ const x = at((t) => t.artic[k]);+ if (x !== undefined) artic[k] = x;+ }+ return { ipa: v.ipa, example: v.example, F1: at((t) => t.formants[0])!, F2: at((t) => t.formants[1])!, artic };+ });}static articFromArray(arr: ArrayLike<number>): HumanArtic {diff --git a/src/ui/body.ts b/src/ui/body.tsnew file mode 100644index 0000000..6ad0a5a--- /dev/null+++ b/src/ui/body.ts@@ -0,0 +1,64 @@+/**+ * The continuous body (see `BodyMix` in the engine): the page's twin of its weights, so the UI can+ * blend the few per-body things it keeps itself (default pitch, vowel chart, keyboard range).+ */+import type { BodyMix } from "../wasm/types.ts";+import type { BodyName } from "../worklet/protocol.ts";++export type { BodyMix };++export const PRESETS: Record<BodyName, BodyMix> = {+ male: { female: 0, child: 0 },+ female: { female: 1, child: 0 },+ child: { female: 0, child: 1 },+};++export const PRESET_LABEL: Record<BodyName, string> = { male: "Adult male", female: "Adult female", child: "Child" };++const clamp01 = (x: number) => (Number.isFinite(x) ? Math.min(1, Math.max(0, x)) : 0);++/** Weights of male, female and child (as the engine computes them; they sum to 1). */+export function bodyWeights(b: BodyMix): [BodyName, number][] {+ const f = clamp01(b.female), c = clamp01(b.child);+ return [+ ["male", (1 - c) * (1 - f)],+ ["female", (1 - c) * f],+ ["child", c],+ ];+}++/** The preset this body is exactly, or null. */+export function presetOf(b: BodyMix): BodyName | null {+ return bodyWeights(b).find(([, w]) => w === 1)?.[0] ?? null;+}++/** The preset with the largest weight (for things that stay per preset, like the keyboard's octave). */+export function nearestBody(b: BodyMix): BodyName {+ return bodyWeights(b).reduce((best, x) => (x[1] > best[1] ? x : best))[0];+}++export function sameBody(a: BodyMix | null | undefined, b: BodyMix | null | undefined): boolean {+ return !!a && !!b && a.female === b.female && a.child === b.child;+}++export const bodyKey = (b: BodyMix) => `${b.female},${b.child}`;++/** A per-preset quantity blended by the body's weights (geometrically: pitches, frequencies). */+export function blendLog(b: BodyMix, of: Record<BodyName, number>): number {+ const p = presetOf(b);+ if (p) return of[p];+ return Math.exp(bodyWeights(b).reduce((s, [n, w]) => s + w * Math.log(of[n]), 0));+}++/** Default pitch: the presets' (as the engine's `default_f0`), blended geometrically in between. */+export const defaultF0 = (b: BodyMix) => blendLog(b, { male: 110, female: 205, child: 260 });++/** "Adult female", or the blend's shares: "Male 40 · Female 30 · Child 30 %". */+export function bodyLabel(b: BodyMix): string {+ const p = presetOf(b);+ if (p) return PRESET_LABEL[p];+ const parts = bodyWeights(b)+ .filter(([, w]) => w > 0.005)+ .map(([n, w]) => `${n[0].toUpperCase()}${n.slice(1)} ${Math.round(w * 100)}`);+ return `${parts.join(" · ")} %`;+}diff --git a/src/ui/components/AnatomyView.tsx b/src/ui/components/AnatomyView.tsxindex 4a34262..b214384 100644--- a/src/ui/components/AnatomyView.tsx+++ b/src/ui/components/AnatomyView.tsx@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from "react";import { AnatomyRenderer, type HandleId, type Slot } from "../render/anatomy.ts";import { Glow } from "../render/vector.ts";import { engine } from "../../audio/AudioEngine.ts";+import { sameBody } from "../body.ts";import { useStore } from "../store.ts";import { VoiceModel } from "../analysis.ts";import { useModel } from "../useModel.ts";@@ -86,7 +87,7 @@ export function AnatomyView(props: { slots?: SlotsFn; info?: InfoFn; showFormantlast = now;if (Math.min(2, window.devicePixelRatio || 1) !== dpr) fit();const st = useStore.getState();- const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;const m = model.current;if (m && w > 0 && h > 0) {@@ -117,7 +118,7 @@ export function AnatomyView(props: { slots?: SlotsFn; info?: InfoFn; showFormantconst rect = canvasRef.current!.getBoundingClientRect();const p = r.toBody(e.clientX - rect.left, e.clientY - rect.top);const st = useStore.getState();- const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;const f = m.frame(a);let best: HandleId | null = null;diff --git a/src/ui/components/BodyPad.tsx b/src/ui/components/BodyPad.tsxnew file mode 100644index 0000000..0f86707--- /dev/null+++ b/src/ui/components/BodyPad.tsx@@ -0,0 +1,100 @@+import { useRef } from "react";+import { useStore } from "../store.ts";+import { bodyLabel, PRESETS, sameBody, type BodyMix } from "../body.ts";++const W = 64, H = 32, P = 4;+const STEP = 0.05;+const q = (x: number) => Math.min(1, Math.max(0, Math.round(x / STEP) * STEP));++/** Pad position (0..1 across, 0..1 down) of a body: male top left, female top right, child below. */+function toUV(b: BodyMix): [number, number] {+ return [0.5 + (b.female - 0.5) * (1 - b.child), b.child];+}++/** The body at a pad position (clamped into the triangle; at the child corner `female` is kept). */+function fromUV(u: number, v: number, prev: BodyMix): BodyMix {+ const child = q(v);+ const female = child < 1 ? q(0.5 + (u - 0.5) / (1 - Math.min(v, 0.999))) : prev.female;+ return { female, child };+}++const X = (u: number) => P + u * (W - 2 * P);+const Y = (v: number) => P + v * (H - 2 * P);++/**+ * The body as a point in a triangle of the three calibrated bodies (a grid of 5 % steps). Dragging+ * shows the body at once and rebuilds the voice on release (a new airway, as a preset switch+ * does); the arrow keys move it a step at a time (left/right toward male/female, down toward child).+ */+export function BodyPad() {+ const body = useStore((s) => s.body);+ const previewBody = useStore((s) => s.previewBody);+ const setBody = useStore((s) => s.setBody);+ const drag = useRef<{ id: number; at: BodyMix } | null>(null);++ const at = (e: React.PointerEvent): BodyMix => {+ const r = (e.currentTarget as Element).getBoundingClientRect();+ const u = ((e.clientX - r.left) / r.width) * (W / (W - 2 * P)) - P / (W - 2 * P);+ const v = ((e.clientY - r.top) / r.height) * (H / (H - 2 * P)) - P / (H - 2 * P);+ return fromUV(Math.min(1, Math.max(0, u)), Math.min(1, Math.max(0, v)), drag.current?.at ?? useStore.getState().body);+ };+ const move = (b: BodyMix) => {+ if (!drag.current || sameBody(b, drag.current.at)) return;+ drag.current.at = b;+ previewBody(b);+ };+ const end = () => {+ const d = drag.current;+ drag.current = null;+ if (d) setBody(d.at);+ };++ const [u, v] = toUV(body);+ const grid: string[] = [];+ for (const k of [0.25, 0.5, 0.75]) {+ grid.push(`M${X(0.5 - 0.5 * (1 - k))} ${Y(k)}H${X(0.5 + 0.5 * (1 - k))}`); // equal age+ grid.push(`M${X(k)} ${Y(0)}L${X(0.5)} ${Y(1)}`); // equal male/female share+ }+ return (+ <div+ className="body-pad"+ role="slider"+ tabIndex={0}+ aria-label="Body between male, female and child"+ aria-valuetext={bodyLabel(body)}+ aria-valuenow={Math.round(body.child * 100)}+ aria-valuemin={0}+ aria-valuemax={100}+ title={`${bodyLabel(body)} — drag between male, female and child; arrow keys step`}+ onPointerDown={(e) => {+ if (e.button !== 0) return;+ (e.currentTarget as Element).setPointerCapture(e.pointerId);+ drag.current = { id: e.pointerId, at: useStore.getState().body };+ move(at(e));+ }}+ onPointerMove={(e) => drag.current?.id === e.pointerId && move(at(e))}+ onPointerUp={end}+ onPointerCancel={end}+ onLostPointerCapture={end}+ onKeyDown={(e) => {+ const b = useStore.getState().body;+ const next =+ e.key === "ArrowLeft" ? { ...b, female: q(b.female - STEP) }+ : e.key === "ArrowRight" ? { ...b, female: q(b.female + STEP) }+ : e.key === "ArrowUp" ? { ...b, child: q(b.child - STEP) }+ : e.key === "ArrowDown" ? { ...b, child: q(b.child + STEP) }+ : e.key === "Home" ? PRESETS.male+ : null;+ if (!next) return;+ e.preventDefault();+ if (!sameBody(next, b)) setBody(next);+ }}+ >+ <svg viewBox={`0 0 ${W} ${H}`} width={W} height={H} aria-hidden="true">+ <path d={grid.join("")} className="body-grid" />+ <path d={`M${X(0)} ${Y(0)}H${X(1)}L${X(0.5)} ${Y(1)}Z`} className="body-frame" />+ <circle cx={X(u)} cy={Y(v)} r={3} className="body-dot" />+ </svg>+ </div>+ );+}diff --git a/src/ui/components/Controls.tsx b/src/ui/components/Controls.tsxindex 12ea36b..e290932 100644--- a/src/ui/components/Controls.tsx+++ b/src/ui/components/Controls.tsx@@ -44,7 +44,7 @@ export function Toggle(props: { label: string; checked: boolean; onChange: (v: b);}-export function Segmented<T extends string>(props: { value: T; options: { value: T; label: string }[]; onChange: (v: T) => void; label: string }) {+export function Segmented<T extends string>(props: { value: T | null; options: { value: T; label: string }[]; onChange: (v: T) => void; label: string }) {return (<div className="segmented" role="radiogroup" aria-label={props.label}>{props.options.map((o) => (diff --git a/src/ui/components/Keys.tsx b/src/ui/components/Keys.tsxindex 7f7ddec..60de822 100644--- a/src/ui/components/Keys.tsx+++ b/src/ui/components/Keys.tsx@@ -1,10 +1,13 @@import { useEffect, useRef } from "react";import { useStore } from "../store.ts";import { midiSupported } from "../midi.ts";+import { nearestBody, type BodyMix } from "../body.ts";/** Computer-keyboard layout: two rows like a piano (A W S E D F T G Y H U J K O L P ;). */const KEYMAP: Record<string, number> = { a: 0, w: 1, s: 2, e: 3, d: 4, f: 5, t: 6, g: 7, y: 8, h: 9, u: 10, j: 11, k: 12, o: 13, l: 14, p: 15, ";": 16 };-const BASE: Record<string, number> = { male: 48, female: 57, child: 60 };+const BASES: Record<string, number> = { male: 48, female: 57, child: 60 };+/** the lowest key, from the nearest preset body (so the keys stay on whole octaves of C/A) */+const BASE = (b: BodyMix) => BASES[nearestBody(b)];export function Keys() {const body = useStore((s) => s.body);@@ -13,7 +16,7 @@ export function Keys() {const noteOff = useStore((s) => s.noteOff);const start = useStore((s) => s.start);const octave = useRef(0);- const base = BASE[body] + octave.current * 12;+ const base = BASE(body) + octave.current * 12;useEffect(() => {const down = new Set<string>();@@ -29,17 +32,17 @@ export function Keys() {if (!(k in KEYMAP) || down.has(k)) return;down.add(k);void start();- noteOn(BASE[useStore.getState().body] + octave.current * 12 + KEYMAP[k]);+ noteOn(BASE(useStore.getState().body) + octave.current * 12 + KEYMAP[k]);e.preventDefault();};const onUp = (e: KeyboardEvent) => {const k = e.key.toLowerCase();if (!down.has(k)) return;down.delete(k);- noteOff(BASE[useStore.getState().body] + octave.current * 12 + KEYMAP[k]);+ noteOff(BASE(useStore.getState().body) + octave.current * 12 + KEYMAP[k]);};const onBlur = () => {- for (const k of down) noteOff(BASE[useStore.getState().body] + octave.current * 12 + KEYMAP[k]);+ for (const k of down) noteOff(BASE(useStore.getState().body) + octave.current * 12 + KEYMAP[k]);down.clear();};window.addEventListener("keydown", onDown);diff --git a/src/ui/components/PianoRoll.tsx b/src/ui/components/PianoRoll.tsxindex 95e95ba..37d7716 100644--- a/src/ui/components/PianoRoll.tsx+++ b/src/ui/components/PianoRoll.tsx@@ -5,6 +5,7 @@ import { useStore } from "../store.ts";import { roll, tickSinging } from "../singing.ts";import { V } from "../colors.ts";import { beam, beamPts, label, seg, type Pt } from "../render/vector.ts";+import { nearestBody } from "../body.ts";/** pixels per second of voice time */const SPEED = 96;@@ -48,7 +49,7 @@ export function PianoRoll() {lo = Math.min(lo, n.midi);hi = Math.max(hi, n.midi);}- const want = lo <= hi ? (lo + hi) / 2 : (KEY_CENTRE[body] ?? 60);+ const want = lo <= hi ? (lo + hi) / 2 : KEY_CENTRE[nearestBody(body)];if (!Number.isFinite(s.centre)) s.centre = want;s.centre += (want - s.centre) * (1 - Math.exp(-dt / 0.6));const bottom = s.centre - SPAN / 2;diff --git a/src/ui/components/SpectrumView.tsx b/src/ui/components/SpectrumView.tsxindex 16324b2..6a846be 100644--- a/src/ui/components/SpectrumView.tsx+++ b/src/ui/components/SpectrumView.tsx@@ -1,6 +1,7 @@import { useRef } from "react";import { usePhosphor } from "../usePhosphor.ts";import { engine } from "../../audio/AudioEngine.ts";+import { sameBody } from "../body.ts";import { useStore } from "../store.ts";import { useModel } from "../useModel.ts";import { VoiceModel } from "../analysis.ts";@@ -27,7 +28,7 @@ export function SpectrumView(props: { ring?: boolean }) {const left = 36, right = w - 14, top = 22, bot = h - 22;const fx = (f: number) => left + ((Math.log(f) - Math.log(FMIN)) / (Math.log(FMAX) - Math.log(FMIN))) * (right - left);const dbY = (db: number) => top + (Math.min(0, Math.max(-RANGE, db)) / -RANGE) * (bot - top);- const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;const f0 = tele && tele.t.voicing > 0.3 ? tele.t.f0 : 0;for (const f of [100, 200, 500, 1000, 2000, 5000]) {diff --git a/src/ui/components/Stroboscope.tsx b/src/ui/components/Stroboscope.tsxindex f1dfa99..c85165c 100644--- a/src/ui/components/Stroboscope.tsx+++ b/src/ui/components/Stroboscope.tsx@@ -1,6 +1,7 @@import { useRef } from "react";import { usePhosphor } from "../usePhosphor.ts";import { engine } from "../../audio/AudioEngine.ts";+import { sameBody } from "../body.ts";import { useStore } from "../store.ts";import { V } from "../colors.ts";import { beam, beamPts, label, ring, seg, type Pt } from "../render/vector.ts";@@ -13,7 +14,7 @@ export function Stroboscope() {const phase = useRef(0);const ref = usePhosphor(({ ctx, w, h, dt }) => {const st = useStore.getState();- const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;const area = tele?.t.glottalArea;const flow = tele?.t.glottalFlow;const n = area?.length ?? 0;diff --git a/src/ui/components/TubeView.tsx b/src/ui/components/TubeView.tsxindex 199385d..2421529 100644--- a/src/ui/components/TubeView.tsx+++ b/src/ui/components/TubeView.tsx@@ -1,5 +1,6 @@import { usePhosphor } from "../usePhosphor.ts";import { engine } from "../../audio/AudioEngine.ts";+import { sameBody } from "../body.ts";import { useStore } from "../store.ts";import { useModel } from "../useModel.ts";import { VoiceModel } from "../analysis.ts";@@ -16,7 +17,7 @@ export function TubeView() {const st = useStore.getState();const m = model.current;if (!m) return;- const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;let ph: ArrayLike<number>, or: ArrayLike<number>, phLen: number, orLen: number;let rms: ArrayLike<number> | null = null;if (tele) {diff --git a/src/ui/components/VowelMap.tsx b/src/ui/components/VowelMap.tsxindex 1b3247d..63b9d3b 100644--- a/src/ui/components/VowelMap.tsx+++ b/src/ui/components/VowelMap.tsx@@ -2,6 +2,7 @@ import { useRef } from "react";import { usePhosphor } from "../usePhosphor.ts";import { engine } from "../../audio/AudioEngine.ts";import { useStore } from "../store.ts";+import { blendLog, sameBody, type BodyMix } from "../body.ts";import { useModel } from "../useModel.ts";import { VoiceModel } from "../analysis.ts";import { V } from "../colors.ts";@@ -18,7 +19,8 @@ export function VowelMap() {const dragging = useRef(false);const range = () => {const b = useStore.getState().body;- return b === "male" ? { f1: [230, 950], f2: [700, 2700] } : b === "female" ? { f1: [280, 1150], f2: [800, 3200] } : { f1: [300, 1250], f2: [900, 3500] };+ const at = (male: number, female: number, child: number) => blendLog(b, { male, female, child });+ return { f1: [at(230, 280, 300), at(950, 1150, 1250)], f2: [at(700, 800, 900), at(2700, 3200, 3500)] };};const toXY = (F1: number, F2: number, w: number, h: number) => {const r = range();@@ -37,7 +39,7 @@ export function VowelMap() {return { F1, F2 };};/** recent (F1, F2) of the live tract, so the trail survives resizes and fades out */- const trail = useRef<{ F1: number; F2: number; t: number; body: string }[]>([]);+ const trail = useRef<{ F1: number; F2: number; t: number; body: BodyMix }[]>([]);const ref = usePhosphor(({ ctx, w, h }) => {const m = model.current;if (!m) return;@@ -45,7 +47,7 @@ export function VowelMap() {// vowel trapezoid guide, like a border on a mapconst corners = [toXY(300, 2500, w, h), toXY(320, 850, w, h), toXY(720, 1050, w, h), toXY(780, 1650, w, h)];beamPts(ctx, corners.map((p) => [p.x, p.y] as Pt), V.blueDim, 1, { close: true, alpha: 0.9 });- const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;+ const tele = engine.latest && sameBody(engine.latest.body, st.body) ? engine.latest : null;const a = tele ? VoiceModel.articFromArray(tele.t.artic) : st.artic;const fm = m.transfer(a).formants;const live = fm.length >= 2 ? toXY(fm[0], fm[1], w, h) : null;@@ -58,7 +60,7 @@ export function VowelMap() {if (live) {// where the tongue has been: a trail of the last 1.5 s, fading with ageconst now = performance.now();- const tr = (trail.current = trail.current.filter((p) => p.body === st.body && now - p.t < 1500));+ const tr = (trail.current = trail.current.filter((p) => sameBody(p.body, st.body) && now - p.t < 1500));const last = tr[tr.length - 1];if (!last || Math.abs(Math.log(last.F1 / fm[0])) + Math.abs(Math.log(last.F2 / fm[1])) > 0.004) tr.push({ F1: fm[0], F2: fm[1], t: now, body: st.body });for (let i = 1; i < tr.length; i++) {diff --git a/src/ui/singing.ts b/src/ui/singing.tsindex 4ee3e43..e1d8ff3 100644--- a/src/ui/singing.ts+++ b/src/ui/singing.ts@@ -14,7 +14,7 @@ import { planSong, planNoteOn, planNoteOff, planMelisma } from "../wasm/engine.timport { 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";+import { nearestBody, type BodyMix } from "./body.ts";/** A note on the piano roll, on the voice clock (s); t1 is null while it is held. */export interface RollNote {@@ -124,7 +124,7 @@ function parentOf(syls: Syllable[], i: number): Syllable {return AH;}-function startNote(syl: Syllable, midi: number, velocity: number, body: BodyName, text: string): void {+function startNote(syl: Syllable, midi: number, velocity: number, body: BodyMix, text: string): void {const t = now();const tag = nextTag;nextTag += 2;@@ -155,7 +155,7 @@ function glide(midi: number, text: string): void {s.note = addNote(midi, t, text);}-export function singNoteOn(midi: number, velocity: number, body: BodyName): void {+export function singNoteOn(midi: number, velocity: number, body: BodyMix): void {stopDemo();keys = keys.filter((k) => k !== midi).concat(midi);const st = useSing.getState();@@ -168,7 +168,7 @@ export function singNoteOn(midi: number, velocity: number, body: BodyName): voiduseSing.setState({ cursor: (i + 1) % syls.length });}-export function singNoteOff(midi: number, body: BodyName): void {+export function singNoteOff(midi: number, body: BodyMix): void {keys = keys.filter((k) => k !== midi);const s = sounding;if (!s || s.midi !== midi) return;@@ -218,7 +218,7 @@ engine.onPlanned((m) => {});/** Sing a demo song (after `ready`, e.g. audio startup, resolves; unless stopped meanwhile). */-export async function playDemo(name: string, body: BodyName, ready?: () => Promise<void>): Promise<void> {+export async function playDemo(name: string, body: BodyMix, ready?: () => Promise<void>): Promise<void> {const song = DEMO_SONGS.find((s) => s.name === name);if (!song) return;stopSinging();@@ -232,7 +232,7 @@ export async function playDemo(name: string, body: BodyName, ready?: () => Promiif (token !== demoToken) return;const syl = lyricsToSyllables(song.lyrics);if (!syl.length) return;- const shift = song.octave[body] * 12;+ const shift = song.octave[nearestBody(body)] * 12;const notes = song.notes.map((n, i) => ({ midi: n[0] + shift, beats: n[1], syl: syl[i % syl.length] }));const t0 = 0.35;const plan = planSong(notes, { body, bpm: song.bpm, t0, vibrato: useSing.getState().vibrato });diff --git a/src/ui/speech.ts b/src/ui/speech.tsindex ffa0c5d..87d78bb 100644--- a/src/ui/speech.ts+++ b/src/ui/speech.ts@@ -1,4 +1,5 @@/** Main-thread speech planning: text/IPA → phrases → gestural plan → worklet. */+import type { BodyMix } from "../wasm/types.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";@@ -45,7 +46,7 @@ export function transcribe(phrases: { segments: Segment[]; intonation?: string }return phrases.map((p) => p.segments.map((s) => (s.stress === 1 ? "ˈ" : s.stress === 2 ? "ˌ" : "") + s.ipa + (s.wordEnd ? " " : "")).join("").trim() + (p.intonation === "question" ? "?" : "")).join(" | ");}-export function speakPhrases(phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[], o: { body: string; rate: number; f0: number }): SpokenPlan {+export function speakPhrases(phrases: { segments: Segment[]; intonation?: "statement" | "question" | "flat"; pause?: number }[], o: { body: BodyMix; rate: number; f0: number }): SpokenPlan {const plan = planPhrases(phrases, { body: o.body, t0: 0, rate: o.rate, f0: o.f0 });const id = engine.schedule({ gestures: plan.gestures.map((g: Gesture) => ({ ...g, targets: { ...g.targets } })), segments: plan.segments, end: plan.end });current = { plan, offset: null, id, transcription: transcribe(phrases) };@@ -53,7 +54,7 @@ export function speakPhrases(phrases: { segments: Segment[]; intonation?: "statereturn current;}-export async function speakText(text: string, o: { ipa: boolean; body: string; rate: number; f0: number }): Promise<SpokenPlan | null> {+export async function speakText(text: string, o: { ipa: boolean; body: BodyMix; rate: number; f0: number }): Promise<SpokenPlan | null> {if (!text.trim()) return null;let phrases: Phrase[];if (o.ipa) phrases = ipaToPhrases(text);diff --git a/src/ui/store.ts b/src/ui/store.tsindex 851b96e..ebe79d6 100644--- a/src/ui/store.ts+++ b/src/ui/store.ts@@ -2,15 +2,13 @@ import { create } from "zustand";import { engine } from "../audio/AudioEngine.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 { defaultF0, PRESETS, sameBody, type BodyMix } from "./body.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";-export const DEFAULT_F0: Record<BodyName, number> = { male: 110, female: 205, child: 260 };-export type Mode = "play" | "speak" | "sing" | "bestiary" | "beatbox";export interface BeatState {@@ -33,7 +31,8 @@ interface State {started: boolean;starting: boolean;startError: string | null;- body: BodyName;+ /** the body shown; while the body pad is dragged it runs ahead of the voice (see previewBody) */+ body: BodyMix;source: VoiceSource;artic: HumanArtic;tipFree: boolean;@@ -67,7 +66,10 @@ interface State {beatHit: (id: string) => void;setMic: (on: boolean) => void;start: () => Promise<void>;- setBody: (b: BodyName) => void;+ /** switch the voice to this body (rebuilds its airway) */+ setBody: (b: BodyMix) => void;+ /** show this body without rebuilding the voice yet (a drag in progress; setBody commits it) */+ previewBody: (b: BodyMix) => void;setSource: (v: Partial<VoiceSource>) => void;setArtic: (v: Partial<HumanArtic>, tipFree?: boolean) => void;setVolume: (v: number) => void;@@ -116,7 +118,7 @@ export const useStore = create<State>((set, get) => ({started: false,starting: false,startError: null,- body: "male",+ body: PRESETS.male,source: { ...DEFAULT_SOURCE },artic: (() => {const tip = restTip(NEUTRAL.jaw, NEUTRAL.tbX, NEUTRAL.tbY);@@ -240,7 +242,7 @@ export const useStore = create<State>((set, get) => ({// anything set before audio existed was not delivered: send the whole state nowconst s = get();engine.setVolume(s.volume);- if (s.body !== "male") engine.setBody(s.body);+ if (!sameBody(s.body, PRESETS.male)) engine.setBody(s.body);engine.setSource(s.source);engine.setArtic(s.artic, s.tipFree);if (s.mode === "bestiary") engine.setCreature(s.creature, s.cparams[s.creature]);@@ -262,10 +264,11 @@ export const useStore = create<State>((set, get) => ({session++;// the new voice starts without the old one's score: a sung note would hangif (get().mode === "sing") stopSinging();- const f0 = DEFAULT_F0[b];+ const f0 = defaultF0(b);set((s) => ({ body: b, source: { ...s.source, f0 } }));engine.setBody(b);},+ previewBody: (b) => set({ body: b }),setSource: (v) => {set((s) => ({ source: { ...s.source, ...v } }));engine.setSource(v);diff --git a/src/ui/styles.css b/src/ui/styles.cssindex 67c7c3e..7212af5 100644--- a/src/ui/styles.css+++ b/src/ui/styles.css@@ -1163,11 +1163,19 @@ body {/* ---------- top bar */.topbar {- gap: 18px 24px;+ gap: 18px 16px;padding: 4px 2px;min-height: 40px;}+.topbar-right {+ gap: 14px;+}++.volume input {+ width: 90px;+}+.brand {gap: 18px;align-items: baseline;@@ -1219,6 +1227,50 @@ body {text-shadow: var(--glow-blue);}+/* the body: preset chips and the triangle between them */+.body-control {+ display: flex;+ align-items: center;+ gap: 8px;+}++.body-pad {+ display: block;+ cursor: crosshair;+ touch-action: none;+ outline: none;+ line-height: 0;+}++.body-pad svg {+ overflow: visible;+}++.body-pad .body-grid {+ fill: none;+ stroke: var(--blue-dim);+ stroke-width: 0.6;+ opacity: 0.7;+}++.body-pad .body-frame {+ fill: none;+ stroke: var(--blue-mid);+ stroke-width: 1;+ stroke-linejoin: round;+}++.body-pad:hover .body-frame,+.body-pad:focus-visible .body-frame {+ stroke: var(--blue);+ filter: drop-shadow(0 0 2px rgba(79, 182, 242, 0.6));+}++.body-pad .body-dot {+ fill: var(--blue);+ filter: drop-shadow(0 0 3px rgba(79, 182, 242, 0.9));+}+.volume,.load {font-size: 10px;diff --git a/src/ui/useModel.ts b/src/ui/useModel.tsindex c2b1da3..0980a23 100644--- a/src/ui/useModel.ts+++ b/src/ui/useModel.ts@@ -2,17 +2,23 @@ import { useEffect, useRef } from "react";import { VoiceModel } from "./analysis.ts";import { useStore } from "./store.ts";import { engine } from "../audio/AudioEngine.ts";+import { bodyKey, type BodyMix } from "./body.ts";-/** Shared main-thread acoustic model for the current body (rebuilt on body / sample-rate change). */+/**+ * 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.+ */const cache = new Map<string, VoiceModel>();+const KEEP = 8;-export function getModel(body: string, sampleRate: number): VoiceModel {- const key = `${body}@${sampleRate}`;+export function getModel(body: BodyMix, sampleRate: number): VoiceModel {+ const key = `${bodyKey(body)}@${sampleRate}`;let m = cache.get(key);- if (!m) {- m = new VoiceModel(body as "male" | "female" | "child", sampleRate);- cache.set(key, m);- }+ 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!);return m;}diff --git a/src/wasm/engine.ts b/src/wasm/engine.tsindex 9b80257..9bdfebb 100644--- a/src/wasm/engine.ts+++ b/src/wasm/engine.ts@@ -7,7 +7,7 @@import { call } from "./chimera.ts";import { CREATURE_VISUALS } from "../ui/creatureVisuals.ts";import type {- ArticKey, ArticSpec, BeatPreset, BeatSound, BeatStep, CreatureDef, CreatureTelemetry, DemoSong, Gesture, HumanArtic, HumanBody,+ ArticKey, ArticSpec, BeatPreset, BodyMix, BeatSound, BeatStep, CreatureDef, CreatureTelemetry, DemoSong, Gesture, HumanArtic, HumanBody,HumanFrame, Phrase, Plan, Segment, SungNote, Syllable, VoiceSource, VowelRef,} from "./types.ts";@@ -120,7 +120,7 @@ export function lyricsToSyllables(text: string): Syllable[] {// ------------------------------------------------------------------ planningexport interface PlanOptions {- body: string;+ body: BodyMix;/** voice-clock start time (s) */t0: number;/** speaking-rate multiplier (>1 = faster) */@@ -142,11 +142,11 @@ export function planPhrases(phrases: { segments: Segment[]; intonation?: "statemreturn call("planPhrases", { phrases: phrases.map((p) => ({ segments: p.segments, intonation: p.intonation, pause: p.pause })), options });}-export function planSong(notes: SungNote[], options: { body: string; bpm: number; t0: number; vibrato: number }): Plan {+export function planSong(notes: SungNote[], options: { body: BodyMix; bpm: number; t0: number; vibrato: number }): Plan {return call("planSong", { notes, options });}-export function planNoteOn(syl: Syllable, midi: number, options: { body: string; vibrato: number; tag: number; legatoFrom?: { syl: Syllable; midi: number } }): Gesture[] {+export function planNoteOn(syl: Syllable, midi: number, options: { body: BodyMix; vibrato: number; tag: number; legatoFrom?: { syl: Syllable; midi: number } }): Gesture[] {return call("planNoteOn", { syl, midi, options });}@@ -154,7 +154,7 @@ export function planMelisma(midi: number, options: { vibrato: number; tag: numbereturn call("planMelisma", { midi, options });}-export function planNoteOff(syl: Syllable, midi: number, body: string): Gesture[] {+export function planNoteOff(syl: Syllable, midi: number, body: BodyMix): Gesture[] {return call("planNoteOff", { syl, midi, body });}@@ -177,7 +177,7 @@ export function formatBeat(steps: readonly (BeatStep | null)[]): string {}/** A beatboxer's ready posture for this body. */-export function beatReady(body: string): Partial<HumanArtic> {+export function beatReady(body: BodyMix): Partial<HumanArtic> {return call("beatReady", { body });}@@ -222,7 +222,7 @@ export interface AirwayModel {glottisPort: number;}-export function airwayModel(body: string, sampleRate: number): AirwayModel {+export function airwayModel(body: BodyMix, sampleRate: number): AirwayModel {return call("model", { body, sampleRate });}diff --git a/src/wasm/types.ts b/src/wasm/types.tsindex 728ce6e..e5f352a 100644--- a/src/wasm/types.ts+++ b/src/wasm/types.ts@@ -44,6 +44,15 @@ export interface HumanArtic {dorsum: number;}+/**+ * A body between the three calibrated ones (mirrors the engine's BodyMix): `female` from the adult+ * male (0) to the adult female (1), `child` from adult (0) to child (1).+ */+export interface BodyMix {+ female: number;+ child: number;+}+export interface HumanBody {name: string;/** overall size scale (1 = adult male) */diff --git a/src/worklet/processor.ts b/src/worklet/processor.tsindex 40be255..632ebf0 100644--- a/src/worklet/processor.ts+++ b/src/worklet/processor.ts@@ -7,8 +7,8 @@* reports once; the main thread may build a new node, which restarts playback state.*/import { writeGestures, writeSteps, fromUtf8, utf8, CONTROL_KEYS } from "../wasm/wire.ts";-import type { ToWorklet, FromWorklet, BodyName, TelemetryMessage } from "./protocol.ts";-import type { CreatureTelemetry } from "../wasm/types.ts";+import type { ToWorklet, FromWorklet, TelemetryMessage } from "./protocol.ts";+import type { BodyMix, CreatureTelemetry } from "../wasm/types.ts";// Minimal AudioWorkletGlobalScope typingsdeclare const sampleRate: number;@@ -21,7 +21,6 @@ declare class AudioWorkletProcessor {type Fn = (...a: number[]) => number;type Exports = { memory: WebAssembly.Memory } & Record<string, Fn>;-const BODIES: BodyName[] = ["male", "female", "child"];const ARTIC_KEYS = CONTROL_KEYS.slice(0, 17);const SOURCE_KEYS = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];/** scalars at the head of the human telemetry block (crates/chimera-wasm/src/lib.rs) */@@ -76,9 +75,13 @@ class ChimeraProcessor extends AudioWorkletProcessor {return this.x.memory.buffer;}+ private body(): BodyMix {+ return { female: this.x.engine_body_female(this.h), child: this.x.engine_body_child(this.h) };+ }+private postReady(): void {const x = this.x, h = this.h;- this.post({ type: "ready", sampleRate, body: BODIES[x.engine_body(h)], nPh: x.engine_n_ph(h), nOr: x.engine_n_or(h), creature: this.creature?.id ?? "human" });+ this.post({ type: "ready", sampleRate, body: this.body(), nPh: x.engine_n_ph(h), nOr: x.engine_n_or(h), creature: this.creature?.id ?? "human" });}/** A JSON call on this instance's engine (non-real-time: creature switches). */@@ -103,7 +106,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {const x = this.x, h = this.h;switch (m.type) {case "body":- x.engine_set_body(h, Math.max(0, BODIES.indexOf(m.body)));+ x.engine_set_body(h, m.body.female, m.body.child);this.postReady();break;case "artic": {@@ -223,7 +226,7 @@ class ChimeraProcessor extends AudioWorkletProcessor {type: "telemetry",t: { artic, phAreas, orAreas, phLen, orLen, pressureRms, flow, velumPort, glottalArea, glottalFlow, f0, voicing, pLung, outRms, noiseLevel, noiseNode, gate, clock, active },load: this.load,- body: BODIES[x.engine_body(h)],+ body: this.body(),nPh,nOr,beatStep: x.engine_beat_step(h),diff --git a/src/worklet/protocol.ts b/src/worklet/protocol.tsindex 94dbbd9..757dc56 100644--- a/src/worklet/protocol.ts+++ b/src/worklet/protocol.ts@@ -4,7 +4,7 @@ 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";+import type { BeatStep, BodyMix } from "../wasm/types.ts";export interface PhraseMsg {segments: Segment[];@@ -15,7 +15,7 @@ export interface PhraseMsg {export type BodyName = "male" | "female" | "child";export type ToWorklet =- | { type: "body"; body: BodyName }+ | { type: "body"; body: BodyMix }| { type: "artic"; values: Partial<HumanArtic>; tipFree?: boolean }| { type: "source"; values: Partial<VoiceSource> }| { type: "gate"; level: number }@@ -40,7 +40,7 @@ export interface TelemetryMessage {t: VoiceTelemetry;/** fraction of the render-quantum budget used by the engine (smoothed) */load: number;- body: BodyName;+ body: BodyMix;nPh: number;nOr: number;/** beatbox step under the playhead (−1 when the sequencer is stopped) */@@ -62,7 +62,7 @@ export interface CreatureTelemetryMessage {}export type FromWorklet =- | { type: "ready"; sampleRate: number; body: BodyName; nPh: number; nOr: number; creature: string }+ | { type: "ready"; sampleRate: number; body: BodyMix; nPh: number; nOr: number; creature: string }| TelemetryMessage| CreatureTelemetryMessage| PlannedMessagediff --git a/tests/live-control.test.ts b/tests/live-control.test.tsindex 62bd24c..8b5ea07 100644--- a/tests/live-control.test.ts+++ b/tests/live-control.test.ts@@ -12,7 +12,7 @@ describe("worklet ordering", () => {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 posted: { type: string; body?: unknown; message?: string }[] = [];const g = globalThis as Record<string, unknown>;g.sampleRate = 48000;g.AudioWorkletProcessor = class {@@ -29,29 +29,30 @@ describe("worklet ordering", () => {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 body = () => ({ female: x.engine_body_female(h), child: x.engine_body_child(h) });+ const FEMALE = { female: 1, child: 0 }, MALE = { female: 0, child: 0 }, CHILD = { female: 0, child: 1 };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: "body", body: FEMALE });send({ type: "schedule", gestures: [breath], segments: [], end: 1, id: 1, replace: false, lead: 0.006 });block();- expect(body()).toBe("female"); // the new voice- expect(posted.filter((m) => m.type === "ready").at(-1)?.body).toBe("female");+ expect(body()).toEqual(FEMALE); // the new voice+ expect(posted.filter((m) => m.type === "ready").at(-1)?.body).toEqual(FEMALE);expect(scoreSize()).toBe(1); // holding the note// 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++) block();- send({ type: "body", body: "male" });+ send({ type: "body", body: MALE });send({ type: "beatHit", id: "B" });send({ type: "beat", playing: false });block();- expect(body()).toBe("male");+ expect(body()).toEqual(MALE);expect(scoreSize()).toBe(0);// 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" });+ 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 });expect(scoreSize()).toBe(12000);send({ type: "stopSpeech" });diff --git a/tests/singing-live.test.ts b/tests/singing-live.test.tsindex 9e77e24..f6ed440 100644--- a/tests/singing-live.test.ts+++ b/tests/singing-live.test.ts@@ -7,6 +7,7 @@import { describe, expect, mock, test } from "bun:test";import { initEngine, WasmVoice } from "./harness.ts";import type { Gesture } from "../src/wasm/types.ts";+const MALE = { female: 0, child: 0 };await initEngine();const { activation } = await import("../src/wasm/engine.ts");@@ -81,26 +82,26 @@ describe("Sing mode, live keys", () => {run(0.1);// first key: /la/ on A2- singNoteOn(45, 96, "male");+ singNoteOn(45, 96, MALE);expect(useSing.getState().cursor).toBe(1);const a = run(0.5);expect(Math.abs(cents(median(a.late(a.f0)), 45))).toBeLessThan(30);expect(Math.min(...a.late(a.voicing))).toBeGreaterThan(0.5);// second key pressed while the first is down: legato into /ma/ on C3 (the lips close once)- singNoteOn(48, 96, "male");+ singNoteOn(48, 96, MALE);const b = run(0.5);expect(Math.abs(cents(median(b.late(b.f0)), 48))).toBeLessThan(30);expect(Math.min(...b.minOral)).toBeLessThan(0.05); // the /m/ closureexpect(Math.min(...b.late(b.minOral))).toBeGreaterThan(0.2); // open again on the vowel// releasing the first key (no longer sounding) changes nothing- singNoteOff(45, "male");+ singNoteOff(45, MALE);const c = run(0.2);expect(Math.min(...c.voicing)).toBeGreaterThan(0.5);// melisma: the vowel carries on to E3 without a consonant- singNoteOn(52, 96, "male");+ singNoteOn(52, 96, MALE);expect(useSing.getState().cursor).toBe(0); // wrapped roundconst d = run(0.5);expect(Math.abs(cents(median(d.late(d.f0)), 52))).toBeLessThan(30);@@ -108,13 +109,13 @@ describe("Sing mode, live keys", () => {expect(Math.min(...d.voicing)).toBeGreaterThan(0.5);// releasing E3 while C3 is still down glides back to C3 on the same vowel- singNoteOff(52, "male");+ singNoteOff(52, MALE);const e = run(0.4);expect(Math.abs(cents(median(e.late(e.f0)), 48))).toBeLessThan(30);expect(Math.min(...e.voicing)).toBeGreaterThan(0.5);// last key up: the note ends and the voice falls silent- singNoteOff(48, "male");+ singNoteOff(48, MALE);const f = run(0.6);let peak = 0;for (const r of [...a.rms, ...b.rms]) peak = Math.max(peak, r);@@ -126,9 +127,9 @@ describe("Sing mode, live keys", () => {voice = new WasmVoice(FS);useSing.getState().setLyrics("ah");run(0.05);- singNoteOn(50, velocity, "male");+ singNoteOn(50, velocity, MALE);const r = run(0.5);- singNoteOff(50, "male");+ singNoteOff(50, MALE);run(0.4);return { rms: median(r.late(r.rms)) };};@@ -143,13 +144,13 @@ describe("Sing mode, live keys", () => {const schedule = engineStub.schedule as typeof fakeEngine.schedule;engineStub.schedule = (plan: { gestures: Gesture[] }) => (scheduled++, schedule(plan));let go!: () => void;- const waiting = playDemo("Made of air", "male", () => new Promise<void>((r) => (go = r)));+ const waiting = playDemo("Made of air", MALE, () => new Promise<void>((r) => (go = r)));stopSinging(); // e.g. the mode changed while audio was startinggo();await waiting;expect(scheduled).toBe(0);expect(useSing.getState().demo).toBeNull();- await playDemo("Made of air", "male", () => Promise.resolve());+ await playDemo("Made of air", MALE, () => Promise.resolve());expect(scheduled).toBe(1);expect(useSing.getState().demo).toBe("Made of air");stopSinging();@@ -161,16 +162,16 @@ describe("Sing mode, live keys", () => {useSing.getState().setVibrato(0);useSing.getState().setLyrics("cat dog");run(0.05);- singNoteOn(50, 96, "male");+ singNoteOn(50, 96, MALE);run(0.4);- singNoteOff(50, "male"); // "cat": its /t/ and the breath-out are scheduled+ singNoteOff(50, MALE); // "cat": its /t/ and the breath-out are scheduledexpect(gesturesOf().some((g) => g.label === "exhale")).toBe(true);run(0.02);- singNoteOn(52, 96, "male"); // "dog" straight after+ singNoteOn(52, 96, MALE); // "dog" straight afterexpect(gesturesOf().some((g) => g.label === "exhale")).toBe(false);const d = run(0.4);expect(Math.min(...d.late(d.voicing))).toBeGreaterThan(0.5);- singNoteOff(52, "male"); // "dog": its /g/ ending is scheduled...+ singNoteOff(52, MALE); // "dog": its /g/ ending is scheduled...run(0.01);stopSinging(); // ...and the mode changes at oncerun(0.06);@@ -182,13 +183,13 @@ describe("Sing mode, live keys", () => {voice = new WasmVoice(FS);useSing.getState().setLyrics("cats dogs");run(0.05);- singNoteOn(50, 96, "male");+ singNoteOn(50, 96, MALE);run(0.3);- singNoteOff(50, "male"); // "cats": /ts/ and breath-out+ singNoteOff(50, MALE); // "cats": /ts/ and breath-outrun(0.01);- singNoteOn(52, 96, "male");+ singNoteOn(52, 96, MALE);run(0.03);- singNoteOff(52, "male"); // "dogs" released quickly, while the /ts/ is still going+ singNoteOff(52, MALE); // "dogs" released quickly, while the /ts/ is still goingrun(0.01);stopSinging();run(0.08);@@ -224,7 +225,7 @@ describe("keys pressed before the audio has started", () => {scheduled = 0;const before = useSing.getState().cursor;useStore.getState().noteOn(52);- useStore.getState().setBody("female");+ useStore.getState().setBody({ female: 1, child: 0 });startAudio();await new Promise((r) => setTimeout(r, 0));await new Promise((r) => setTimeout(r, 0));diff --git a/tests/wasm-engine.test.ts b/tests/wasm-engine.test.tsindex 71bff13..a06b933 100644--- a/tests/wasm-engine.test.ts+++ b/tests/wasm-engine.test.ts@@ -29,8 +29,8 @@ 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 [female, child] = { male: [0, 0], female: [1, 0], child: [0, 1] }[s.body] ?? [0, 0];+ if (female || child) fn("engine_set_body")(h, female, child);const out = new Float32Array(s.samples);const ops = [...s.ops].sort((a, b) => a.at - b.at);let i = 0, oi = 0;