Skip to content

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

Rust

chimera CLI: renders, speech diagnostics and calibration in Rust

Jameson Hodge5db36063788f
diff --git a/Cargo.lock b/Cargo.lock
index 8c21cd2..be00fc7 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -24,6 +24,16 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "chimera-cli"
+version = "0.1.0"
+dependencies = [
+ "chimera",
+ "flate2",
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "chimera-wasm"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index fa6351c..f14137a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[workspace]
resolver = "3"
-members = ["crates/chimera", "crates/chimera-wasm"]
+members = ["crates/chimera", "crates/chimera-wasm", "crates/chimera-cli"]
[workspace.package]
version = "0.1.0"
diff --git a/crates/chimera-cli/Cargo.toml b/crates/chimera-cli/Cargo.toml
new file mode 100644
index 0000000..8bf7b18
--- /dev/null
+++ b/crates/chimera-cli/Cargo.toml
@@ -0,0 +1,16 @@
+[package]
+name = "chimera-cli"
+description = "CHIMERA command-line tools: offline renders to WAV, speech diagnostics, calibration"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+
+[[bin]]
+name = "chimera"
+path = "src/main.rs"
+
+[dependencies]
+chimera = { path = "../chimera" }
+flate2 = "1"
+serde = "1"
+serde_json = "1"
diff --git a/crates/chimera-cli/src/calibrate.rs b/crates/chimera-cli/src/calibrate.rs
new file mode 100644
index 0000000..2c6f24b
--- /dev/null
+++ b/crates/chimera-cli/src/calibrate.rs
@@ -0,0 +1,345 @@
+//! `chimera calibrate …`: ports of `tools/calibrate-vowels.ts` and `tools/calibrate-consonants.ts`.
+//! They regenerate the tables the engine embeds (`crates/chimera/src/phonetics/*.generated.json`),
+//! written as `JSON.stringify(table, null, 1)` wrote them.
+
+use crate::js::{Json, fixed, pad_end, pad_start};
+use crate::repo_path;
+use chimera::airway::frequency::{find_peaks, transfer_function};
+use chimera::anatomy::human::{
+ ArticKey, BODY_CHILD, BODY_FEMALE, BODY_MALE, HumanArtic, HumanBody, NEUTRAL, rest_tip,
+};
+use chimera::math::{js_max, js_min, js_round, ln, pow};
+use chimera::phonetics::inventory::consonants as inventory;
+use chimera::phonetics::planner::VowelTable;
+use chimera::phonetics::vowel_data::VOWELS;
+use chimera::util::optimize::{NelderMeadOpts, nelder_mead};
+use chimera::voice::human_airway::HumanAirway;
+
+const VOWEL_TABLE: &str = "crates/chimera/src/phonetics/vowelTargets.generated.json";
+const CONSONANT_TABLE: &str = "crates/chimera/src/phonetics/consonantTargets.generated.json";
+const BODIES: [(&str, HumanBody); 3] = [
+ ("male", BODY_MALE),
+ ("female", BODY_FEMALE),
+ ("child", BODY_CHILD),
+];
+
+/// Split `--out <file>` from the positional arguments.
+fn out_option(a: &[String], default: &str) -> Result<(Vec<String>, String), String> {
+ let mut rest = Vec::new();
+ let mut out = repo_path(default);
+ let mut it = a.iter();
+ while let Some(x) = it.next() {
+ if x == "--out" {
+ out = it.next().ok_or("--out needs a file")?.clone();
+ } else {
+ rest.push(x.clone());
+ }
+ }
+ Ok((rest, out))
+}
+
+fn round3(x: f64) -> f64 {
+ js_round(x * 1000.0) / 1000.0
+}
+
+/// tbX tbY jaw lipAp lipProt lipWidth root larynx curl
+const LO: [f64; 9] = [1.2, 5.0, 0.05, 0.12, 0.0, 0.0, -0.9, -1.3, 0.0];
+const HI: [f64; 9] = [4.6, 8.8, 2.3, 2.0, 1.4, 1.0, 0.9, 1.3, 1.0];
+
+fn to_artic(p: &[f64]) -> HumanArtic {
+ let (tb_x, tb_y, jaw, lip_ap, lip_prot, lip_width, root, larynx, curl) =
+ (p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[8]);
+ let tip = rest_tip(jaw, tb_x, tb_y);
+ // rhotic curl raises the tip toward the post-alveolar region
+ let tt_x = tip.x - 0.4 * curl;
+ let tt_y = tip.y + 2.0 * curl;
+ HumanArtic {
+ tb_x,
+ tb_y,
+ jaw,
+ lip_ap,
+ lip_prot,
+ lip_width,
+ root,
+ larynx,
+ tt_x,
+ tt_y,
+ tt_curl: curl,
+ ..NEUTRAL
+ }
+}
+
+/// Resonance peaks of the airway in posture `a` (frequency-domain model), and its narrowest area.
+fn formants(air: &mut HumanAirway, freqs: &[f64], a: &HumanArtic) -> (Vec<f64>, f64) {
+ air.apply(a, 0.0);
+ let el = air.net.linear_elements();
+ let h = transfer_function(&el, air.pharynx.first_node(), freqs, &[air.glottis_port]);
+ let pk: Vec<f64> = find_peaks(freqs, &h.mag, 150.0)
+ .iter()
+ .map(|p| p.freq)
+ .collect();
+ let mut min_area = f64::INFINITY;
+ for &x in air.ph_areas.iter().chain(air.or_areas.iter()) {
+ min_area = js_min(min_area, x);
+ }
+ (pk, min_area)
+}
+
+/// Articulatory vowel targets fitted to reference formants with the frequency-domain airway
+/// model. `calibrate vowels [male|female|child|all] [--out file]`
+pub fn vowels(a: &[String]) -> Result<(), String> {
+ let (rest, out) = out_option(a, VOWEL_TABLE)?;
+ let which = rest.first().map(String::as_str).unwrap_or("all");
+ let n = 700;
+ let freqs: Vec<f64> = (0..n)
+ .map(|i| 120.0 * pow(4600.0 / 120.0, i as f64 / (n - 1) as f64))
+ .collect();
+ let mut results = match std::fs::read_to_string(&out) {
+ Ok(text) => Json::parse(&text).map_err(|e| format!("{out}: {e}"))?,
+ Err(_) => Json::Obj(Vec::new()),
+ };
+
+ for (bname, body) in BODIES {
+ if which != "all" && which != bname {
+ continue;
+ }
+ let mut air = HumanAirway::new(96000.0, body);
+ let k = body.scale;
+ let mut table: Vec<(String, Json)> = Vec::new();
+ for vw in VOWELS {
+ let t = match bname {
+ "male" => vw.male,
+ "female" => vw.female,
+ _ => vw.child,
+ };
+ // initial guess from vowel-space position
+ let mut x0 = vec![
+ 3.5 - 1.3 * vw.back + 0.2 * vw.height * (1.0 - vw.back),
+ 8.0 - 2.0 * vw.height - 0.25 * vw.back,
+ 0.25 + 1.4 * vw.height,
+ if vw.round {
+ 0.35 + 0.6 * vw.height
+ } else {
+ 0.6 + 1.0 * vw.height
+ },
+ if vw.round { 0.9 } else { 0.1 },
+ if vw.round { 0.12 } else { 0.85 },
+ 0.4 * (1.0 - vw.back) - 0.5 * vw.height * vw.back,
+ 0.4 * (1.0 - vw.height) * (1.0 - vw.back) - if vw.round { 0.4 } else { 0.0 },
+ if vw.ipa == "ɝ" { 0.6 } else { 0.0 },
+ ];
+ if vw.ipa == "ɯ" {
+ x0 = vec![2.6, 7.35, 0.25, 0.5, 0.1, 0.65, 0.4, 0.2, 0.0];
+ }
+ let jaw_prior = 0.2 + 1.5 * vw.height;
+ let mut cost = |p: &[f64]| -> f64 {
+ let a = to_artic(p);
+ let (f, min_area) = formants(&mut air, &freqs, &a);
+ if f.len() < 3 {
+ return 50.0;
+ }
+ let mut c = 0.0;
+ let w = [1.0, 1.0, if vw.ipa == "ɝ" { 1.2 } else { 0.45 }];
+ for i in 0..3 {
+ c += w[i] * pow(ln(f[i] / t[i]), 2.0);
+ }
+ // physiology priors (soft)
+ let min_ok = 0.22 * k * k;
+ if min_area < min_ok {
+ c += 0.4 * pow((min_ok - min_area) / min_ok, 2.0);
+ }
+ c += 0.004 * pow(p[2] - jaw_prior, 2.0);
+ let open = vw.height > 0.6;
+ if vw.round {
+ let (w_max, p_min, ap_max) = (
+ if open { 0.45 } else { 0.3 },
+ if open { 0.35 } else { 0.6 },
+ 0.3 + 0.7 * vw.height,
+ );
+ c += 0.05 * pow(js_max(0.0, p[5] - w_max), 2.0)
+ + 0.05 * pow(js_max(0.0, p_min - p[4]), 2.0)
+ + 0.05 * pow(js_max(0.0, p[3] - ap_max), 2.0);
+ } else {
+ let ap_prior = 0.35 + 0.75 * p[2];
+ c += 0.05 * pow(js_max(0.0, 0.55 - p[5]), 2.0)
+ + 0.05 * pow(js_max(0.0, p[4] - 0.35), 2.0)
+ + 0.03 * pow(js_max(0.0, (p[3] - ap_prior).abs() - 0.35), 2.0);
+ }
+ c += 0.002 * p[6] * p[6] + 0.006 * p[7] * p[7];
+ // the tongue body near where the vowel's height and backness put it: many postures
+ // give the same formants, and without this the fit wandered (a schwa with the
+ // tongue as low as /ɑ/), making every transition through it needlessly long
+ c += 0.006 * (pow(p[0] - x0[0], 2.0) + pow(p[1] - x0[1], 2.0));
+ if vw.ipa != "ɝ" {
+ c += 0.5 * p[8] * p[8];
+ }
+ c
+ };
+ let opts = |step: [f64; 9], max_iter: usize| NelderMeadOpts {
+ lo: Some(LO.to_vec()),
+ hi: Some(HI.to_vec()),
+ step: Some(step.to_vec()),
+ max_iter: Some(max_iter),
+ tol: None,
+ };
+ let mut best = nelder_mead(
+ &mut cost,
+ &x0,
+ opts([0.4, 0.4, 0.3, 0.25, 0.3, 0.25, 0.3, 0.3, 0.2], 1800),
+ );
+ // restart from the best point to escape shallow minima
+ for _ in 0..2 {
+ let nb = nelder_mead(
+ &mut cost,
+ &best.x,
+ opts([0.2, 0.2, 0.15, 0.12, 0.15, 0.12, 0.15, 0.15, 0.1], 1000),
+ );
+ if nb.fx < best.fx {
+ best = nb;
+ }
+ }
+ let a = to_artic(&best.x);
+ let (f, _) = formants(&mut air, &freqs, &a);
+ let err: Vec<f64> = (0..3)
+ .map(|i| match f.get(i) {
+ Some(&fi) if fi != 0.0 && !fi.is_nan() => (100.0 * (fi - t[i])) / t[i],
+ _ => f64::NAN,
+ })
+ .collect();
+ let nums = |xs: &mut dyn Iterator<Item = f64>| Json::Arr(xs.map(Json::Num).collect());
+ let artic = [
+ ("tbX", a.tb_x),
+ ("tbY", a.tb_y),
+ ("jaw", a.jaw),
+ ("lipAp", a.lip_ap),
+ ("lipProt", a.lip_prot),
+ ("lipWidth", a.lip_width),
+ ("root", a.root),
+ ("larynx", a.larynx),
+ ("ttX", a.tt_x),
+ ("ttY", a.tt_y),
+ ("ttCurl", a.tt_curl),
+ ];
+ table.push((
+ vw.ipa.to_string(),
+ Json::Obj(vec![
+ (
+ "artic".into(),
+ Json::Obj(
+ artic
+ .iter()
+ .map(|(k, x)| (k.to_string(), Json::Num(round3(*x))))
+ .collect(),
+ ),
+ ),
+ (
+ "formants".into(),
+ nums(&mut f.iter().take(4).map(|&x| js_round(x))),
+ ),
+ ("target".into(), nums(&mut t.iter().map(|&x| js_round(x)))),
+ (
+ "err".into(),
+ nums(&mut err.iter().map(|&e| js_round(e * 10.0) / 10.0)),
+ ),
+ ]),
+ ));
+ println!(
+ "{} {} F={} T={} err%={} tb=({},{}) jaw={} lip={}/{}/{} root={} lx={} curl={}",
+ pad_end(bname, 6),
+ pad_end(vw.ipa, 2),
+ f.iter()
+ .take(3)
+ .map(|x| pad_start(&fixed(*x, 0), 5))
+ .collect::<String>(),
+ t.iter()
+ .map(|x| pad_start(&fixed(*x, 0), 5))
+ .collect::<String>(),
+ err.iter()
+ .map(|e| pad_start(&fixed(*e, 1), 6))
+ .collect::<String>(),
+ fixed(a.tb_x, 2),
+ fixed(a.tb_y, 2),
+ fixed(a.jaw, 2),
+ fixed(a.lip_ap, 2),
+ fixed(a.lip_prot, 2),
+ fixed(a.lip_width, 2),
+ fixed(a.root, 2),
+ fixed(a.larynx, 2),
+ fixed(a.tt_curl, 2)
+ );
+ }
+ results.set(bname, Json::Obj(table));
+ }
+ std::fs::write(&out, results.stringify(1)).map_err(|e| format!("{out}: {e}"))?;
+ println!("wrote {out}");
+ Ok(())
+}
+
+/// The main coordinate of each fricative set so the constriction area matches its target
+/// (adult-male target × body scale²) in an /a/-like context: bisection on the monotonic contact
+/// model. Reads the vowel table (its /ɑ/) from disk. `calibrate consonants [--out file]`
+pub fn consonants(a: &[String]) -> Result<(), String> {
+ let (_, out) = out_option(a, CONSONANT_TABLE)?;
+ let vpath = repo_path(VOWEL_TABLE);
+ let vtext = std::fs::read_to_string(&vpath).map_err(|e| format!("{vpath}: {e}"))?;
+ let vtable: VowelTable = serde_json::from_str(&vtext).map_err(|e| format!("{vpath}: {e}"))?;
+ let mut result: Vec<(String, Json)> = Vec::new();
+ for (name, body) in BODIES {
+ let mut air = HumanAirway::new(96000.0, body);
+ let mut ctx = vtable[name]["ɑ"].artic.apply_to(&NEUTRAL);
+ ctx.set(ArticKey::Jaw, 0.55);
+ let mut table: Vec<(String, Json)> = Vec::new();
+ for p in inventory() {
+ let (Some(area), Some(key)) = (p.area, p.cal_key) else {
+ continue;
+ };
+ if area == 0.0 || area.is_nan() {
+ continue;
+ }
+ let target = area * body.scale * body.scale;
+ let mut min_area = |v: f64| -> f64 {
+ let mut a = p.targets.apply_to(&ctx);
+ a.set(key, v);
+ air.apply(&a, 0.0);
+ let mut m = f64::INFINITY;
+ for &x in air.ph_min.iter().chain(air.or_min.iter()) {
+ if x < m {
+ m = x;
+ }
+ }
+ m
+ };
+ // search direction: area decreases as the coordinate moves toward closure
+ let base = p.targets.get(key).unwrap_or(f64::NAN);
+ let (mut lo, mut hi) = (base - 1.2, base + 1.2);
+ let decreasing = min_area(hi) < min_area(lo); // area falls as value rises?
+ for _ in 0..40 {
+ let mid = (lo + hi) / 2.0;
+ let area_mid = min_area(mid);
+ if (area_mid > target) == decreasing {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+ let v = (lo + hi) / 2.0;
+ let got = min_area(v);
+ table.push((
+ p.ipa.to_string(),
+ Json::Obj(vec![(key.name().to_string(), Json::Num(round3(v)))]),
+ ));
+ println!(
+ "{} {} {}={} area {} (target {})",
+ pad_end(name, 6),
+ pad_end(p.ipa, 3),
+ key.name(),
+ fixed(v, 3),
+ fixed(got, 3),
+ fixed(target, 3)
+ );
+ }
+ result.push((name.to_string(), Json::Obj(table)));
+ }
+ std::fs::write(&out, Json::Obj(result).stringify(1)).map_err(|e| format!("{out}: {e}"))?;
+ Ok(())
+}
diff --git a/crates/chimera-cli/src/diagnose.rs b/crates/chimera-cli/src/diagnose.rs
new file mode 100644
index 0000000..3dbfe99
--- /dev/null
+++ b/crates/chimera-cli/src/diagnose.rs
@@ -0,0 +1,379 @@
+//! `chimera diagnose [outdir]`: port of `tools/speech-diagnostics.ts`, the running-speech battery
+//! ("marbles in the mouth"). Renders sentences through the full pipeline and measures, against
+//! published norms:
+//! - nasal leakage: velopharyngeal port during vowels with no nasal neighbour (heard as nasal
+//! from ~0.01 cm² for high vowels, ~0.15 cm² for low; Bunton & Story 2011)
+//! - vowel undershoot: LPC F1/F2 at vowel midpoints vs the calibrated (Hillenbrand) targets
+//! - formant bandwidths at vowel midpoints (Klatt defaults B1 60, B2 90, B3 150 Hz)
+//! - spectral balance: octave-band long-term spectrum relative to 500 Hz
+//! - duration contrasts: stressed vs unstressed, phrase-final vs not
+//! - pitch: share of voiced time stuck at the baseline (snapping back between vowels)
+//!
+//! `DIAG_VERBOSE=1` also lists every measured vowel.
+
+use crate::js::{fixed, num, pad_end, pad_start};
+use crate::render::g2p;
+use crate::{Ctx, FS};
+use chimera::analysis::fft::{Fft, hann};
+use chimera::analysis::lpc::{FormantOpts, estimate_formants};
+use chimera::math::{hypot, js_max, js_min, js_round, ln, log2, log10};
+use chimera::phonetics::planner::{PhraseInput, PlanOptions, diphthong_parts, plan_phrases};
+use chimera::phonetics::vowel_data::VOWELS;
+use chimera::voice::human_voice::HumanVoice;
+use std::collections::HashMap;
+
+const SENTENCES: [&str; 5] = [
+ "The north wind and the sun were disputing which was the stronger.",
+ "We were away a year ago.",
+ "Should we chase those cowboys?",
+ "Can you hear me now?",
+ "She sells sea shells by the sea shore.",
+];
+const NASALS: [&str; 3] = ["m", "n", "ŋ"];
+
+fn diphthong_of(a: &str, b: &str) -> bool {
+ ["aɪ", "aʊ", "ɔɪ", "eɪ", "oʊ"]
+ .iter()
+ .any(|d| diphthong_parts(d).is_some_and(|(p0, p1)| p0 == a && p1 == b))
+}
+
+struct VowelStat {
+ ipa: String,
+ stressed: bool,
+ is_final: bool,
+ dur: f64,
+ f1: f64,
+ f2: f64,
+ t1: f64,
+ t2: f64,
+ bw: Vec<f64>,
+}
+
+fn sorted(xs: &[f64]) -> Vec<f64> {
+ let mut s = xs.to_vec();
+ s.sort_by(f64::total_cmp);
+ s
+}
+
+fn median(xs: &[f64]) -> f64 {
+ let s = sorted(xs);
+ s.get(s.len() / 2).copied().unwrap_or(f64::NAN)
+}
+
+fn mean(xs: &[f64]) -> f64 {
+ xs.iter().sum::<f64>() / js_max(1.0, xs.len() as f64)
+}
+
+/// LPC fails on short vowels that came out voiceless (aspiration): drop frames with no F1 below 1.2 kHz
+fn ok<'a>(vs: &[&'a VowelStat]) -> Vec<&'a VowelStat> {
+ vs.iter()
+ .copied()
+ .filter(|x| x.f1 < 1200.0 && x.f2 < 3200.0)
+ .collect()
+}
+
+fn pct(a: usize, b: usize) -> String {
+ format!("{} %", fixed((100.0 * a as f64) / js_max(1.0, b as f64), 1))
+}
+
+pub fn run(ctx: &Ctx, a: &[String]) -> Result<(), String> {
+ let out_dir = a.first().map(String::as_str);
+ let g = g2p()?;
+ let reference: HashMap<&str, [f64; 3]> = VOWELS.iter().map(|v| (v.ipa, v.male)).collect();
+
+ let mut vowels: Vec<VowelStat> = Vec::new();
+ let (mut oral_frames, mut leak1, mut leak5, mut leak15, mut max_oral_port) =
+ (0usize, 0usize, 0usize, 0usize, 0.0f64);
+ let (mut voiced_frames, mut at_base) = (0usize, 0usize);
+ let mut f0s: Vec<f64> = Vec::new();
+ let bands = [250.0, 500.0, 1000.0, 2000.0, 4000.0, 8000.0];
+ let mut band_e = [0.0f64; 6];
+ let fft = Fft::new(2048);
+ let win = hann(2048);
+
+ for (si, text) in SENTENCES.iter().enumerate() {
+ let mut v = HumanVoice::new(FS, chimera::anatomy::human::BODY_MALE, 2);
+ let phrases = g.to_phrases(text);
+ let inputs: Vec<PhraseInput> = phrases
+ .iter()
+ .map(|p| PhraseInput {
+ segments: p.segments.clone(),
+ intonation: Some(p.intonation),
+ pause: Some(p.pause),
+ })
+ .collect();
+ let plan = plan_phrases(
+ &inputs,
+ &PlanOptions {
+ body: "male".into(),
+ t0: 0.1,
+ f0: Some(110.0),
+ ..Default::default()
+ },
+ );
+ v.schedule(&plan.gestures);
+ let n = js_round(FS * (plan.end + 0.3)) as usize;
+ let mut out = vec![0f32; n];
+ let (mut port, mut f0t, mut voic) = (Vec::new(), Vec::new(), Vec::new());
+ for block in out.chunks_mut(128) {
+ v.render(block);
+ port.push(v.airway.frame.as_ref().map_or(0.0, |f| f.velum_port));
+ f0t.push(v.glottis.f0_now);
+ voic.push(v.glottis.voicing);
+ }
+ let frame_at = |t: f64| {
+ js_min(
+ (port.len() - 1) as f64,
+ js_max(0.0, js_round((t * FS) / 128.0)),
+ ) as usize
+ };
+ let segs = &plan.segments;
+ let sample = |i: i64| {
+ if i >= 0 && (i as usize) < out.len() {
+ out[i as usize] as f64
+ } else {
+ 0.0
+ }
+ };
+ for (k, s) in segs.iter().enumerate() {
+ if s.kind != "vowel" {
+ continue;
+ }
+ // the second half of a diphthong is a glide, not a vowel that should reach its target
+ let pv = if k > 0 { segs.get(k - 1) } else { None };
+ if let Some(pv) = pv
+ && pv.kind == "vowel"
+ && (pv.t1 - s.t0).abs() < 1e-6
+ && diphthong_of(&pv.ipa, &s.ipa)
+ {
+ continue;
+ }
+ let nasal_nb = pv.is_some_and(|p| NASALS.contains(&p.ipa.as_str()))
+ || segs
+ .get(k + 1)
+ .is_some_and(|p| NASALS.contains(&p.ipa.as_str()));
+ if !nasal_nb {
+ for f in frame_at(s.t0)..=frame_at(s.t1) {
+ oral_frames += 1;
+ if port[f] > 0.01 {
+ leak1 += 1;
+ }
+ if port[f] > 0.05 {
+ leak5 += 1;
+ }
+ if port[f] > 0.15 {
+ leak15 += 1;
+ }
+ max_oral_port = js_max(max_oral_port, port[f]);
+ }
+ }
+ // formants at the midpoint (first target of a diphthong at 30 %)
+ let parts = diphthong_parts(&s.ipa);
+ let tgt = parts.map_or(s.ipa.as_str(), |p| p.0);
+ let r = reference.get(tgt);
+ let tm = if parts.is_some() {
+ s.t0 + 0.3 * (s.t1 - s.t0)
+ } else {
+ (s.t0 + s.t1) / 2.0
+ };
+ let (dec, len) = (4i64, js_round(0.025 * FS) as i64);
+ let c = js_round(tm * FS) as i64;
+ let mut fr: Vec<f64> = Vec::new();
+ let mut i = c - len / 2;
+ while i < c + len / 2 {
+ let mut acc = 0.0;
+ for j in 0..dec {
+ acc += sample(i + j);
+ }
+ fr.push(acc / dec as f64);
+ i += dec;
+ }
+ let fm = estimate_formants(
+ &fr,
+ FS / dec as f64,
+ FormantOpts {
+ order: Some(14),
+ max_bw: Some(700.0),
+ ..Default::default()
+ },
+ );
+ if let Some(r) = r
+ && fm.len() >= 2
+ {
+ let next = segs[k + 1..].iter().find(|x| x.kind == "vowel");
+ vowels.push(VowelStat {
+ ipa: s.ipa.clone(),
+ stressed: s.stress == Some(1),
+ is_final: next.is_none_or(|nx| nx.t0 - s.t1 > 0.2),
+ dur: s.t1 - s.t0,
+ f1: fm[0].freq,
+ f2: fm[1].freq,
+ t1: r[0],
+ t2: r[1],
+ bw: fm.iter().take(3).map(|x| x.bw).collect(),
+ });
+ }
+ }
+ // pitch: voiced frames within 3 % of the 110 Hz baseline
+ for f in 0..f0t.len() {
+ if voic[f] > 0.5 {
+ voiced_frames += 1;
+ f0s.push(f0t[f]);
+ if (f0t[f] / 110.0 - 1.0).abs() < 0.03 {
+ at_base += 1;
+ }
+ }
+ }
+ // long-term spectrum over frames with signal
+ let pk = crate::peak(&out);
+ let mut i = 0;
+ while i + 2048 < n {
+ let mut e = 0.0;
+ for j in 0..2048 {
+ e += out[i + j] as f64 * out[i + j] as f64;
+ }
+ if !((e / 2048.0).sqrt() < pk * 0.01) {
+ let mut re = vec![0.0; 2048];
+ let mut im = vec![0.0; 2048];
+ for j in 0..2048 {
+ re[j] = out[i + j] as f64 * win[j];
+ }
+ fft.transform(&mut re, &mut im);
+ for k in 1..1024 {
+ let f = (k as f64 * FS) / 2048.0;
+ let p = re[k] * re[k] + im[k] * im[k];
+ for (bi, b) in bands.iter().enumerate() {
+ if f >= b / core::f64::consts::SQRT_2 && f < b * core::f64::consts::SQRT_2 {
+ band_e[bi] += p;
+ }
+ }
+ }
+ }
+ i += 1024;
+ }
+ if let Some(dir) = out_dir {
+ ctx.write_wav(&format!("{dir}/s{}.wav", si + 1), &out)?;
+ }
+ }
+
+ println!("== nasal leakage during vowels with no nasal neighbour");
+ println!(
+ " frames with port > 0.01 cm²: {} > 0.05: {} > 0.15: {} max {} cm² (norm: ~0 %)",
+ pct(leak1, oral_frames),
+ pct(leak5, oral_frames),
+ pct(leak15, oral_frames),
+ fixed(max_oral_port, 3)
+ );
+ println!("== vowel midpoints vs calibrated targets");
+ let err = |vs0: &[&VowelStat]| -> String {
+ let vs = ok(vs0);
+ let e1: Vec<f64> = vs.iter().map(|x| (x.f1 / x.t1 - 1.0).abs()).collect();
+ let e2: Vec<f64> = vs.iter().map(|x| (x.f2 / x.t2 - 1.0).abs()).collect();
+ format!(
+ "F1 {} % F2 {} % median error (n={}/{} measurable)",
+ fixed(100.0 * median(&e1), 0),
+ fixed(100.0 * median(&e2), 0),
+ vs.len(),
+ vs0.len()
+ )
+ };
+ // distance from schwa in (F1, log F2) relative to the target's
+ let sch = [500.0, 1500.0];
+ let reach = |vs: &[&VowelStat]| -> f64 {
+ let d: Vec<f64> = ok(vs)
+ .iter()
+ .filter(|x| hypot(x.t1 - sch[0], 1000.0 * ln(x.t2 / sch[1])) > 80.0)
+ .map(|x| {
+ hypot(x.f1 - sch[0], 1000.0 * ln(x.f2 / sch[1]))
+ / hypot(x.t1 - sch[0], 1000.0 * ln(x.t2 / sch[1]))
+ })
+ .collect();
+ median(&d)
+ };
+ let all: Vec<&VowelStat> = vowels.iter().collect();
+ let s_v: Vec<&VowelStat> = vowels.iter().filter(|x| x.stressed).collect();
+ let u_v: Vec<&VowelStat> = vowels.iter().filter(|x| !x.stressed).collect();
+ println!(
+ " stressed: {}; distance from schwa reached {} % (norm ≥ 90 %)",
+ err(&s_v),
+ fixed(100.0 * reach(&s_v), 0)
+ );
+ println!(
+ " unstressed: {}; distance from schwa reached {} % (norm ≥ 75 %)",
+ err(&u_v),
+ fixed(100.0 * reach(&u_v), 0)
+ );
+ if std::env::var_os("DIAG_VERBOSE").is_some_and(|v| !v.is_empty()) {
+ for x in &vowels {
+ println!(
+ " {} {} {} ms F1 {}/{} F2 {}/{} B1 {}",
+ if x.stressed { "S" } else { "u" },
+ pad_end(&x.ipa, 3),
+ pad_start(&fixed(1000.0 * x.dur, 0), 4),
+ pad_start(&fixed(x.f1, 0), 4),
+ num(x.t1),
+ pad_start(&fixed(x.f2, 0), 5),
+ num(x.t2),
+ fixed(x.bw[0], 0)
+ );
+ }
+ }
+ println!("== formant bandwidths at vowel midpoints (median)");
+ let bw = |i: usize| -> Vec<f64> {
+ all.iter()
+ .map(|x| x.bw.get(i).copied().unwrap_or(f64::NAN))
+ .collect()
+ };
+ let b3: Vec<f64> = bw(2).into_iter().filter(|x| x.is_finite()).collect();
+ println!(
+ " B1 {} Hz B2 {} Hz B3 {} Hz (Klatt defaults 60 / 90 / 150)",
+ fixed(median(&bw(0)), 0),
+ fixed(median(&bw(1)), 0),
+ fixed(median(&b3), 0)
+ );
+ println!("== long-term spectrum, octave bands re 500 Hz");
+ let ref500 = band_e[1];
+ let ltass = [-2, 0, -6, -11, -16, -20]; // approximate natural male speech (Byrne et al. 1994 LTASS, octave-averaged)
+ let cells: Vec<String> = bands
+ .iter()
+ .enumerate()
+ .map(|(i, &b)| {
+ let name = if b >= 1000.0 {
+ format!("{}k", num(b / 1000.0))
+ } else {
+ num(b)
+ };
+ format!(
+ "{name}: {} (≈{})",
+ fixed(10.0 * log10(band_e[i] / ref500), 1),
+ ltass[i]
+ )
+ })
+ .collect();
+ println!(" {}", cells.join(" "));
+ println!("== durations");
+ let durs = |vs: &[&VowelStat]| -> Vec<f64> { vs.iter().map(|x| x.dur).collect() };
+ let fin: Vec<&VowelStat> = vowels.iter().filter(|x| x.is_final).collect();
+ let non: Vec<&VowelStat> = vowels.iter().filter(|x| !x.is_final).collect();
+ println!(
+ " stressed {} ms vs unstressed {} ms (norm ≥ 2 ×); phrase-final {} ms vs non-final {} ms (norm: final ≈ 1.3–1.4 ×)",
+ fixed(1000.0 * mean(&durs(&s_v)), 0),
+ fixed(1000.0 * mean(&durs(&u_v)), 0),
+ fixed(1000.0 * mean(&durs(&fin)), 0),
+ fixed(1000.0 * mean(&durs(&non)), 0)
+ );
+ println!("== pitch");
+ let st = |a: f64, b: f64| 12.0 * log2(a / b);
+ let s = sorted(&f0s);
+ let q = |p: f64| {
+ s.get((s.len() as f64 * p).floor() as usize)
+ .copied()
+ .unwrap_or(f64::NAN)
+ };
+ println!(
+ " voiced time at the 110 Hz baseline (±3 %): {} range (5–95 %) {} semitones",
+ pct(at_base, voiced_frames),
+ fixed(st(q(0.95), q(0.05)), 1)
+ );
+ Ok(())
+}
diff --git a/crates/chimera-cli/src/js.rs b/crates/chimera-cli/src/js.rs
new file mode 100644
index 0000000..9c22fbe
--- /dev/null
+++ b/crates/chimera-cli/src/js.rs
@@ -0,0 +1,243 @@
+//! JavaScript formatting, so the printed summaries and the regenerated tables read exactly as the
+//! TypeScript tools wrote them: `Number.prototype.toFixed`, `String(number)`, `padStart`/`padEnd`
+//! and `JSON.stringify(value, null, 1)` over an insertion-ordered value.
+
+use serde::de::{Deserialize, Deserializer, MapAccess, SeqAccess, Visitor};
+
+/// `x.toFixed(d)`: the exact decimal value rounded half away from zero (JS picks the larger n on
+/// a tie), the sign printed whenever x < 0 (so not for −0).
+pub fn fixed(x: f64, d: usize) -> String {
+ if !x.is_finite() || x.abs() >= 1e21 {
+ return num(x);
+ }
+ let neg = x < 0.0;
+ // the exact binary value in decimal (a double has at most 1074 fractional digits)
+ let s = format!("{:.1100}", x.abs());
+ let (int, frac) = s.split_once('.').unwrap();
+ let mut digits: Vec<u8> = int.bytes().chain(frac.bytes().take(d)).collect();
+ if frac.as_bytes()[d] >= b'5' {
+ let mut i = digits.len();
+ loop {
+ if i == 0 {
+ digits.insert(0, b'1');
+ break;
+ }
+ i -= 1;
+ if digits[i] == b'9' {
+ digits[i] = b'0';
+ } else {
+ digits[i] += 1;
+ break;
+ }
+ }
+ }
+ let n_int = digits.len() - d;
+ let mut out = String::with_capacity(digits.len() + 2);
+ if neg {
+ out.push('-');
+ }
+ out.push_str(core::str::from_utf8(&digits[..n_int]).unwrap());
+ if d > 0 {
+ out.push('.');
+ out.push_str(core::str::from_utf8(&digits[n_int..]).unwrap());
+ }
+ out
+}
+
+/// `String(x)`: the shortest round-trip digits, in exponent form outside [1e-6, 1e21).
+pub fn num(x: f64) -> String {
+ if x.is_nan() {
+ return "NaN".into();
+ }
+ if x.is_infinite() {
+ return if x > 0.0 { "Infinity" } else { "-Infinity" }.into();
+ }
+ if x == 0.0 {
+ return "0".into();
+ }
+ let a = x.abs();
+ if (1e-6..1e21).contains(&a) {
+ return format!("{x}");
+ }
+ let s = format!("{x:e}");
+ match s.split_once('e') {
+ Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"),
+ _ => s,
+ }
+}
+
+/// `s.padStart(n)` (JS counts UTF-16 units; every symbol printed here is one unit).
+pub fn pad_start(s: &str, n: usize) -> String {
+ format!("{s:>n$}")
+}
+
+/// `s.padEnd(n)`.
+pub fn pad_end(s: &str, n: usize) -> String {
+ format!("{s:<n$}")
+}
+
+/// A JSON value that keeps object keys in insertion order, as JS objects do (for the string
+/// keys used here).
+#[derive(Clone, Debug, PartialEq)]
+pub enum Json {
+ Null,
+ Bool(bool),
+ Num(f64),
+ Str(String),
+ Arr(Vec<Json>),
+ Obj(Vec<(String, Json)>),
+}
+
+impl Json {
+ /// `obj[key] = v`: replace in place (the key keeps its position) or append.
+ pub fn set(&mut self, key: &str, v: Json) {
+ let Json::Obj(m) = self else {
+ panic!("not an object")
+ };
+ match m.iter_mut().find(|(k, _)| k == key) {
+ Some((_, slot)) => *slot = v,
+ None => m.push((key.to_string(), v)),
+ }
+ }
+
+ /// `JSON.stringify(self, null, indent)`.
+ pub fn stringify(&self, indent: usize) -> String {
+ let mut out = String::new();
+ self.write(&mut out, indent, 0);
+ out
+ }
+
+ fn write(&self, out: &mut String, indent: usize, depth: usize) {
+ let nl = |out: &mut String, d: usize| {
+ out.push('\n');
+ out.extend(core::iter::repeat_n(' ', indent * d));
+ };
+ match self {
+ Json::Null => out.push_str("null"),
+ Json::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
+ Json::Num(x) => out.push_str(&if x.is_finite() {
+ num(*x)
+ } else {
+ "null".into()
+ }),
+ Json::Str(s) => out.push_str(&serde_json::to_string(s).unwrap()),
+ Json::Arr(a) if a.is_empty() => out.push_str("[]"),
+ Json::Obj(m) if m.is_empty() => out.push_str("{}"),
+ Json::Arr(a) => {
+ out.push('[');
+ for (i, v) in a.iter().enumerate() {
+ if i > 0 {
+ out.push(',');
+ }
+ nl(out, depth + 1);
+ v.write(out, indent, depth + 1);
+ }
+ nl(out, depth);
+ out.push(']');
+ }
+ Json::Obj(m) => {
+ out.push('{');
+ for (i, (k, v)) in m.iter().enumerate() {
+ if i > 0 {
+ out.push(',');
+ }
+ nl(out, depth + 1);
+ out.push_str(&serde_json::to_string(k).unwrap());
+ out.push_str(": ");
+ v.write(out, indent, depth + 1);
+ }
+ nl(out, depth);
+ out.push('}');
+ }
+ }
+ }
+
+ pub fn parse(text: &str) -> serde_json::Result<Json> {
+ serde_json::from_str(text)
+ }
+}
+
+impl<'de> Deserialize<'de> for Json {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ struct V;
+ impl<'de> Visitor<'de> for V {
+ type Value = Json;
+ fn expecting(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
+ f.write_str("JSON")
+ }
+ fn visit_unit<E>(self) -> Result<Json, E> {
+ Ok(Json::Null)
+ }
+ fn visit_bool<E>(self, b: bool) -> Result<Json, E> {
+ Ok(Json::Bool(b))
+ }
+ fn visit_i64<E>(self, x: i64) -> Result<Json, E> {
+ Ok(Json::Num(x as f64))
+ }
+ fn visit_u64<E>(self, x: u64) -> Result<Json, E> {
+ Ok(Json::Num(x as f64))
+ }
+ fn visit_f64<E>(self, x: f64) -> Result<Json, E> {
+ Ok(Json::Num(x))
+ }
+ fn visit_str<E>(self, s: &str) -> Result<Json, E> {
+ Ok(Json::Str(s.to_string()))
+ }
+ fn visit_seq<A: SeqAccess<'de>>(self, mut a: A) -> Result<Json, A::Error> {
+ let mut v = Vec::new();
+ while let Some(x) = a.next_element()? {
+ v.push(x);
+ }
+ Ok(Json::Arr(v))
+ }
+ fn visit_map<A: MapAccess<'de>>(self, mut a: A) -> Result<Json, A::Error> {
+ let mut m: Vec<(String, Json)> = Vec::new();
+ while let Some((k, v)) = a.next_entry::<String, Json>()? {
+ // a repeated key keeps its first position and takes the last value (JSON.parse)
+ match m.iter_mut().find(|(k0, _)| *k0 == k) {
+ Some((_, slot)) => *slot = v,
+ None => m.push((k, v)),
+ }
+ }
+ Ok(Json::Obj(m))
+ }
+ }
+ d.deserialize_any(V)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn to_fixed_matches_js() {
+ assert_eq!(fixed(0.125, 2), "0.13");
+ assert_eq!(fixed(1.005, 2), "1.00"); // 1.005 is just below in binary
+ assert_eq!(fixed(-0.04, 1), "-0.0");
+ assert_eq!(fixed(-0.0, 1), "0.0");
+ assert_eq!(fixed(9.96, 1), "10.0");
+ assert_eq!(fixed(2.5, 0), "3");
+ assert_eq!(fixed(f64::NAN, 1), "NaN");
+ assert_eq!(fixed(123.456, 0), "123");
+ }
+
+ #[test]
+ fn number_strings_match_js() {
+ assert_eq!(num(3.0), "3");
+ assert_eq!(num(-0.0), "0");
+ assert_eq!(num(0.1), "0.1");
+ assert_eq!(num(1e-7), "1e-7");
+ assert_eq!(num(1e21), "1e+21");
+ assert_eq!(num(96000.0), "96000");
+ }
+
+ #[test]
+ fn stringify_keeps_order_and_js_layout() {
+ let j = Json::parse(r#"{"b":{"x":[1,2.5,-0]},"a":[],"c":{}}"#).unwrap();
+ assert_eq!(
+ j.stringify(1),
+ "{\n \"b\": {\n \"x\": [\n 1,\n 2.5,\n 0\n ]\n },\n \"a\": [],\n \"c\": {}\n}"
+ );
+ }
+}
diff --git a/crates/chimera-cli/src/main.rs b/crates/chimera-cli/src/main.rs
new file mode 100644
index 0000000..56fe9d3
--- /dev/null
+++ b/crates/chimera-cli/src/main.rs
@@ -0,0 +1,113 @@
+//! `chimera`: offline renders to WAV, speech diagnostics and table calibration over the CHIMERA
+//! engine. Ports of the TypeScript tools (`tools/render-*.ts`, `speech-diagnostics.ts`,
+//! `calibrate-*.ts`) with their arguments, defaults and printed summaries. Spectrograms of the
+//! WAVs: `bun tools/spectrogram.ts in.wav out.png [title] [maxFreq] [windowMs]`.
+
+mod calibrate;
+mod diagnose;
+mod js;
+mod render;
+mod wav;
+
+use chimera::anatomy::human::{BODY_CHILD, BODY_FEMALE, BODY_MALE, HumanBody};
+use std::process::ExitCode;
+
+const USAGE: &str = "\
+usage: chimera <command> [args] [--float]
+
+ render speech <out> [\"ipa / ipa\"] [male|female|child]
+ render text <out> [\"English text.\"] [male|female|child]
+ render song [outdir] [male|female|child]
+ render beatbox [outdir] [preset name] [male|female|child]
+ render creature [creatureId] [outdir]
+ render vowels [male|female|child] [out]
+ diagnose [outdir]
+ calibrate vowels [male|female|child|all] [--out file]
+ calibrate consonants [--out file]
+
+Output names are stems (<out>.wav). --float writes 32-bit float WAVs instead of 16-bit PCM.
+Calibration writes the tables the engine embeds, in crates/chimera/src/phonetics/.";
+
+/// The output rate of every render.
+pub const FS: f64 = 48000.0;
+
+/// The repository root (data files and the generated tables are found from here).
+pub fn repo_path(rel: &str) -> String {
+ format!("{}/../../{rel}", env!("CARGO_MANIFEST_DIR"))
+}
+
+/// Options shared by every command.
+pub struct Ctx {
+ /// write 32-bit float WAVs
+ pub float: bool,
+}
+
+impl Ctx {
+ pub fn write_wav(&self, path: &str, x: &[f32]) -> Result<(), String> {
+ wav::write(path, x, FS as u32, self.float).map_err(|e| format!("{path}: {e}"))
+ }
+}
+
+/// The body for a name (`male`, `female`, `child`).
+pub fn body(name: &str) -> Result<HumanBody, String> {
+ match name {
+ "male" => Ok(BODY_MALE),
+ "female" => Ok(BODY_FEMALE),
+ "child" => Ok(BODY_CHILD),
+ _ => Err(format!("unknown body {name:?}; have male, female, child")),
+ }
+}
+
+/// `<out>.wav` for an output stem (a trailing `.wav` is accepted too).
+pub fn wav_name(stem: &str) -> String {
+ format!("{}.wav", stem.strip_suffix(".wav").unwrap_or(stem))
+}
+
+pub fn peak(x: &[f32]) -> f64 {
+ x.iter()
+ .fold(0.0f64, |p, &v| chimera::math::js_max(p, (v as f64).abs()))
+}
+
+/// Positional argument `i`, or a default.
+pub fn arg<'a>(a: &'a [String], i: usize, default: &'a str) -> &'a str {
+ a.get(i).map(String::as_str).unwrap_or(default)
+}
+
+fn run(args: Vec<String>) -> Result<(), String> {
+ let float = args.iter().any(|a| a == "--float");
+ let args: Vec<String> = args.into_iter().filter(|a| a != "--float").collect();
+ let ctx = Ctx { float };
+ let cmd: Vec<&str> = args.iter().take(2).map(String::as_str).collect();
+ match cmd.as_slice() {
+ ["render", kind, ..] => {
+ let rest = &args[2..];
+ match *kind {
+ "speech" => render::speech(&ctx, rest),
+ "text" => render::text(&ctx, rest),
+ "song" => render::song(&ctx, rest),
+ "beatbox" => render::beatbox(&ctx, rest),
+ "creature" => render::creature(&ctx, rest),
+ "vowels" => render::vowels(&ctx, rest),
+ _ => Err(format!("unknown render kind {kind:?}\n\n{USAGE}")),
+ }
+ }
+ ["diagnose", ..] => diagnose::run(&ctx, &args[1..]),
+ ["calibrate", "vowels", ..] => calibrate::vowels(&args[2..]),
+ ["calibrate", "consonants", ..] => calibrate::consonants(&args[2..]),
+ ["help" | "--help" | "-h", ..] => {
+ println!("{USAGE}");
+ Ok(())
+ }
+ _ => Err(USAGE.to_string()),
+ }
+}
+
+fn main() -> ExitCode {
+ match run(std::env::args().skip(1).collect()) {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(e) => {
+ eprintln!("{e}");
+ ExitCode::FAILURE
+ }
+ }
+}
diff --git a/crates/chimera-cli/src/render.rs b/crates/chimera-cli/src/render.rs
new file mode 100644
index 0000000..73f4ef1
--- /dev/null
+++ b/crates/chimera-cli/src/render.rs
@@ -0,0 +1,631 @@
+//! `chimera render …`: ports of `tools/render-{speech,text,song,beatbox,creature,vowels}.ts`.
+
+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;
+use chimera::creatures::voice::CreatureVoice;
+use chimera::creatures::{CREATURES, creature_by_id};
+use chimera::math::{js_max, js_min, js_round, log10};
+use chimera::phonetics::beatbox::{BEAT_PRESETS, BEAT_SOUNDS, BeatStep, beat_ready, parse_beat};
+use chimera::phonetics::english::EnglishG2P;
+use chimera::phonetics::ipa::tokenize_ipa;
+use chimera::phonetics::planner::{
+ PhraseInput, PlanOptions, plan_phrases, plan_utterance, vowel_table,
+};
+use chimera::phonetics::sing::{
+ LegatoFrom, NoteOnOptions, SongOptions, SungNote, midi_to_hz, plan_note_off, plan_note_on,
+ plan_song,
+};
+use chimera::phonetics::songs::DEMO_SONGS;
+use chimera::phonetics::syllables::lyrics_to_syllables;
+use chimera::phonetics::{Intonation, Syllable};
+use chimera::voice::human_voice::{HumanVoice, SourcePatch};
+use std::io::Read;
+use std::time::Instant;
+
+/// Render `out.len()` samples in 128-sample blocks, as the tools did.
+fn render_blocks(v: &mut HumanVoice, out: &mut [f32]) {
+ for block in out.chunks_mut(128) {
+ v.render(block);
+ }
+}
+
+/// The CMU dictionary (`public/data/cmudict.txt.gz`) loaded into a G2P.
+pub fn g2p() -> Result<EnglishG2P, String> {
+ let path = repo_path("public/data/cmudict.txt.gz");
+ let gz = std::fs::read(&path).map_err(|e| format!("{path}: {e}"))?;
+ let mut text = String::new();
+ flate2::read::GzDecoder::new(&gz[..])
+ .read_to_string(&mut text)
+ .map_err(|e| format!("{path}: {e}"))?;
+ let mut g = EnglishG2P::new();
+ g.load_dict(&text);
+ Ok(g)
+}
+
+/// `name.toLowerCase().replace(/[^a-z]+/g, "-")`
+fn slug(name: &str) -> String {
+ let mut out = String::new();
+ let mut run = false;
+ for c in name.to_lowercase().chars() {
+ if c.is_ascii_lowercase() {
+ out.push(c);
+ run = false;
+ } else if !run {
+ out.push('-');
+ run = true;
+ }
+ }
+ out
+}
+
+fn ms_since(t: Instant) -> f64 {
+ t.elapsed().as_secs_f64() * 1000.0
+}
+
+/// Mark list `ipa@t` as render-speech printed it.
+fn mark_line(marks: &[(f64, String)]) -> String {
+ marks
+ .iter()
+ .map(|(t, l)| format!("{l}@{}", fixed(*t, 3)))
+ .collect::<Vec<_>>()
+ .join(" ")
+}
+
+/// IPA utterances through the planner. `render speech <out> ["ˈɑpɑ / ˈɑbɑ"] [body]`
+pub fn speech(ctx: &Ctx, a: &[String]) -> Result<(), String> {
+ let name = arg(a, 0, "out/speech");
+ let text = arg(a, 1, "ˈɑpɑ");
+ let body_name = arg(a, 2, "male");
+ let b = body(body_name)?;
+ let f0 = match body_name {
+ "female" => 200.0,
+ "child" => 250.0,
+ _ => 110.0,
+ };
+ let mut voice = HumanVoice::new(FS, b, 2);
+ voice.set_source(&SourcePatch::f0(f0));
+ let mut marks: Vec<(f64, String)> = Vec::new();
+ let mut t0 = 0.05;
+ for u in text.split('/').map(str::trim).filter(|u| !u.is_empty()) {
+ let segs = tokenize_ipa(u);
+ let plan = plan_utterance(
+ &segs,
+ &PlanOptions {
+ body: body_name.into(),
+ t0,
+ f0: Some(f0),
+ ..Default::default()
+ },
+ );
+ voice.schedule(&plan.gestures);
+ for s in &plan.segments {
+ marks.push((s.t0, s.ipa.clone()));
+ }
+ t0 = plan.end + 0.35;
+ }
+ let total = js_round(FS * (t0 + 0.2)) as usize;
+ let mut out = vec![0f32; total];
+ render_blocks(&mut voice, &mut out);
+ let file = wav_name(name);
+ ctx.write_wav(&file, &out)?;
+ println!(
+ "wrote {file} {} s peak {}",
+ fixed(total as f64 / FS, 2),
+ fixed(peak(&out), 3)
+ );
+ println!("{}", mark_line(&marks));
+ Ok(())
+}
+
+/// English text through G2P and the phrase planner. `render text <out> ["Text."] [body]`
+pub fn text(ctx: &Ctx, a: &[String]) -> Result<(), String> {
+ let name = arg(a, 0, "out/text");
+ let text = arg(a, 1, "Hello world.");
+ let body_name = arg(a, 2, "male");
+ let b = body(body_name)?;
+ let f0 = match body_name {
+ "female" => 205.0,
+ "child" => 250.0,
+ _ => 112.0,
+ };
+ let g = g2p()?;
+ let phrases = g.to_phrases(text);
+ let shown: Vec<String> = phrases
+ .iter()
+ .map(|p| {
+ let s: String = p
+ .segments
+ .iter()
+ .map(|s| format!("{}{}", if s.stress == Some(1) { "ˈ" } else { "" }, s.ipa))
+ .collect();
+ s + if p.intonation == Intonation::Question {
+ "?"
+ } else {
+ ""
+ }
+ })
+ .collect();
+ println!("{}", shown.join(" | "));
+ let mut voice = HumanVoice::new(FS, b, 2);
+ voice.set_source(&SourcePatch::f0(f0));
+ let inputs: Vec<PhraseInput> = phrases
+ .iter()
+ .map(|p| PhraseInput {
+ segments: p.segments.clone(),
+ intonation: Some(p.intonation),
+ pause: Some(p.pause),
+ })
+ .collect();
+ let plan = plan_phrases(
+ &inputs,
+ &PlanOptions {
+ body: body_name.into(),
+ t0: 0.05,
+ f0: Some(f0),
+ ..Default::default()
+ },
+ );
+ voice.schedule(&plan.gestures);
+ let total = js_round(FS * (plan.end + 0.3)) as usize;
+ let mut out = vec![0f32; total];
+ let t = Instant::now();
+ render_blocks(&mut voice, &mut out);
+ let ms = ms_since(t);
+ let file = wav_name(name);
+ ctx.write_wav(&file, &out)?;
+ println!(
+ "wrote {file} {} s, rendered in {} ms",
+ fixed(total as f64 / FS, 2),
+ fixed(ms, 0)
+ );
+ Ok(())
+}
+
+/// The demo songs, and a live-style key sequence. `render song [outdir] [body]`
+pub fn song(ctx: &Ctx, a: &[String]) -> Result<(), String> {
+ let out_dir = arg(a, 0, "out/song");
+ let body_name = arg(a, 1, "male");
+ let b = body(body_name)?;
+ let g = g2p()?;
+ let syl_text = |syl: &[Syllable]| {
+ syl.iter()
+ .map(|s| s.text.as_str())
+ .collect::<Vec<_>>()
+ .join(" ")
+ };
+
+ for song in DEMO_SONGS {
+ let syl = lyrics_to_syllables(song.lyrics, &g);
+ let octave = match body_name {
+ "female" => song.octave.female,
+ "child" => song.octave.child,
+ _ => song.octave.male,
+ };
+ let shift = octave * 12.0;
+ let notes: Vec<SungNote> = song
+ .notes
+ .iter()
+ .enumerate()
+ .map(|(i, n)| SungNote {
+ midi: n[0] + shift,
+ beats: n[1],
+ syl: syl[i % syl.len()].clone(),
+ })
+ .collect();
+ let mut v = HumanVoice::new(FS, b, 2);
+ v.set_source(&SourcePatch {
+ f0: Some(midi_to_hz(notes[0].midi)),
+ voiced: Some(true),
+ pressure: Some(9.0),
+ tension: Some(0.55),
+ ..Default::default()
+ });
+ let plan = plan_song(
+ &notes,
+ &SongOptions {
+ body: body_name.into(),
+ bpm: song.bpm,
+ t0: 0.3,
+ vibrato: 35.0,
+ },
+ );
+ v.schedule(&plan.gestures);
+ let n = js_round(FS * (plan.end + 0.4)) as usize;
+ let mut out = vec![0f32; n];
+ render_blocks(&mut v, &mut out);
+ ctx.write_wav(
+ &format!("{out_dir}/{}-{body_name}.wav", slug(song.name)),
+ &out,
+ )?;
+ println!(
+ "{}: {} s, peak {}, syllables {}",
+ song.name,
+ fixed(n as f64 / FS, 1),
+ fixed(peak(&out), 3),
+ syl_text(&syl)
+ );
+ }
+
+ // live-style: key presses with gaps and one legato pair, as the keyboard would send them
+ let syl = lyrics_to_syllables("hello there my friend", &g);
+ let mut v = HumanVoice::new(FS, b, 2);
+ v.set_source(&SourcePatch {
+ f0: Some(130.0),
+ voiced: Some(true),
+ pressure: Some(9.0),
+ ..Default::default()
+ });
+ let keys: [(f64, f64, f64); 4] = [
+ (0.2, 0.55, 57.0),
+ (0.6, 1.0, 59.0),
+ (1.1, 1.8, 62.0),
+ (1.75, 2.6, 60.0),
+ ]; // (down, up, midi)
+ let n = js_round(FS * 3.0) as usize;
+ let mut out = vec![0f32; n];
+ let mut tag = 2.0;
+ struct Held {
+ syl: Syllable,
+ midi: f64,
+ tag: f64,
+ }
+ let mut held: Option<Held> = None;
+ // (t, on, midi, key index), sorted by time (stable, as Array.sort)
+ let mut events: Vec<(f64, bool, f64, usize)> = keys
+ .iter()
+ .enumerate()
+ .flat_map(|(i, &(d, u, m))| [(d, true, m, i), (u, false, m, i)])
+ .collect();
+ events.sort_by(|x, y| x.0.total_cmp(&y.0));
+ let mut e = 0;
+ for block in out.chunks_mut(128) {
+ let now = v.clock;
+ while e < events.len() && events[e].0 <= now {
+ let (_, on, m, i) = events[e];
+ e += 1;
+ let shift = |gs: Vec<Gesture>| -> Vec<Gesture> {
+ gs.into_iter()
+ .map(|g| Gesture {
+ t0: g.t0 + now + 0.006,
+ t1: g.t1 + now + 0.006,
+ ..g
+ })
+ .collect()
+ };
+ if on {
+ let s = &syl[i];
+ if let Some(h) = &held {
+ v.release(h.tag);
+ v.release(h.tag + 1.0);
+ }
+ let legato_from = held.as_ref().map(|h| LegatoFrom {
+ syl: h.syl.clone(),
+ midi: h.midi,
+ });
+ let gs = shift(plan_note_on(
+ s,
+ m,
+ &NoteOnOptions {
+ body: body_name.into(),
+ vibrato: 35.0,
+ tag,
+ legato_from,
+ },
+ ));
+ v.schedule(&gs);
+ held = Some(Held {
+ syl: s.clone(),
+ midi: m,
+ tag,
+ });
+ tag += 2.0;
+ } 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));
+ v.schedule(&gs);
+ }
+ }
+ v.render(block);
+ }
+ ctx.write_wav(&format!("{out_dir}/live-{body_name}.wav"), &out)?;
+ println!("live: syllables {}", syl_text(&syl));
+ Ok(())
+}
+
+/// The beatbox kit, each sound alone, and a preset pattern through the sequencer.
+/// `render beatbox [outdir] [preset name] [body]`
+pub fn beatbox(ctx: &Ctx, a: &[String]) -> Result<(), String> {
+ let out_dir = arg(a, 0, "out/beatbox");
+ let preset_name = arg(a, 1, "Boots and cats");
+ let body_name = arg(a, 2, "male");
+ 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_source(&SourcePatch {
+ f0: Some(100.0),
+ voiced: Some(true),
+ pressure: Some(8.0),
+ ..Default::default()
+ });
+ v.set_gate(0.0);
+ v
+ };
+ let at = |t: f64| js_round(t * FS) as usize;
+
+ // ---- each sound alone
+ let mut player = BeatPlayer::new();
+ player.body = BodyName::parse(body_name);
+ 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];
+ for (idx, s) in BEAT_SOUNDS.iter().enumerate() {
+ let mut v = voice();
+ let hit = 0.25;
+ let mut gs = Vec::new();
+ player.gestures(&BeatStep::new(s.id), hit, 0.15, &mut gs);
+ v.schedule(&gs);
+ let mut out = vec![0f32; n];
+ render_blocks(&mut v, &mut out);
+ let abs = |i: usize| (out[i] as f64).abs();
+ // the event: its peak within [hit − 30 ms, hit + 80 ms]; onset = first sample from
+ // hit − 40 ms that reaches a quarter of that peak
+ let mut pk = 0.0;
+ for i in at(hit - 0.03)..at(hit + 0.08) {
+ pk = js_max(pk, abs(i));
+ }
+ let mut on = at(hit);
+ for i in at(hit - 0.04)..at(hit + 0.08) {
+ if abs(i) > 0.25 * pk {
+ on = i;
+ break;
+ }
+ }
+ // energy before the hit (set-up noise) relative to the hit
+ let mut pre = 0.0;
+ for i in at(hit - 0.15)..at(hit - 0.04) {
+ pre = js_max(pre, abs(i));
+ }
+ // what follows: level 60–150 ms after the hit (unwanted voicing shows up here)
+ let mut tail = 0.0;
+ for i in at(hit + 0.06)..at(hit + 0.15) {
+ tail = js_max(tail, abs(i));
+ }
+ rows.push(format!(
+ "{} {} onset {} ms peak {} set-up {} dB tail {} dB lead-in {} ms",
+ pad_end(s.id, 4),
+ pad_end(s.name, 13),
+ pad_start(&fixed((on as f64 / FS - hit) * 1000.0, 1), 6),
+ 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),
+ ));
+ strip[idx * n..(idx + 1) * n].copy_from_slice(&out);
+ let file: String =
+ s.id.chars()
+ .map(|c| if c.is_ascii_alphabetic() { c } else { '_' })
+ .collect();
+ ctx.write_wav(&format!("{out_dir}/{file}.wav"), &out)?;
+ }
+ println!("{}", rows.join("\n"));
+ ctx.write_wav(&format!("{out_dir}/kit.wav"), &strip)?;
+
+ // ---- a pattern, two bars, through the sequencer exactly as the worklet ran it
+ let preset = BEAT_PRESETS
+ .iter()
+ .find(|p| p.name.to_lowercase() == preset_name.to_lowercase())
+ .unwrap_or(&BEAT_PRESETS[0]);
+ let mut v = voice();
+ let mut seq = BeatPlayer::new();
+ seq.body = BodyName::parse(body_name);
+ seq.set_steps(&parse_beat(preset.text));
+ seq.set_tempo(preset.bpm, preset.swing);
+ seq.start(v.clock);
+ let bars = 2.0;
+ let total = js_round(
+ FS * (BeatPlayer::HORIZON + bars * seq.steps().len() as f64 * seq.step_dur() + 0.3),
+ ) as usize;
+ let mut out = vec![0f32; total];
+ for block in out.chunks_mut(128) {
+ let clock = v.clock;
+ seq.tick(clock, &mut |gs: &[Gesture]| v.schedule(gs));
+ v.render(block);
+ }
+ let file = format!("{out_dir}/{}.wav", slug(preset.name));
+ ctx.write_wav(&file, &out)?;
+ println!(
+ "pattern \"{}\": {} s, peak {} -> {file}",
+ preset.name,
+ fixed(total as f64 / FS, 2),
+ fixed(peak(&out), 3)
+ );
+ Ok(())
+}
+
+/// A creature's sustained note and calls; level, stability and pitch.
+/// `render creature [creatureId] [outdir]`
+pub fn creature(ctx: &Ctx, a: &[String]) -> Result<(), String> {
+ let id = arg(a, 0, "songbird");
+ let out_dir = arg(a, 1, "out/creatures");
+ let def = creature_by_id(id).ok_or_else(|| {
+ format!(
+ "unknown creature {id}; have {}",
+ CREATURES
+ .iter()
+ .map(|c| c.id)
+ .collect::<Vec<_>>()
+ .join(", ")
+ )
+ })?;
+ let mut v = CreatureVoice::new(def, FS, &[]);
+ let mut out: Vec<f32> = Vec::new();
+ let t = Instant::now();
+ let render_for =
+ |v: &mut CreatureVoice, out: &mut Vec<f32>, sec: f64| -> std::ops::Range<usize> {
+ let n = js_round(sec * FS) as usize;
+ let start = out.len();
+ out.resize(start + n, 0.0);
+ for block in out[start..].chunks_mut(128) {
+ v.render(block);
+ }
+ start..start + n
+ };
+ // sustained note at the default pitch
+ let pitch_param = def.params.iter().find(|p| p.role == Some(ParamRole::Pitch));
+ let voices = def.param_index("voices");
+ if let Some(k) = voices {
+ v.set_params(&[(k, 0.0)]); // single voice for the pitch check
+ }
+ v.set_gate(1.0);
+ let sus = render_for(&mut v, &mut out, 1.2);
+ v.set_gate(0.0);
+ render_for(&mut v, &mut out, 0.4);
+ if let Some(k) = voices {
+ v.set_params(&[(k, 0.5)]);
+ }
+ let mut pitch_report = String::new();
+ if let Some(p) = pitch_param {
+ let s = sus.start + js_round(0.6 * FS) as usize;
+ let frame: Vec<f64> = out[s..s + 4096].iter().map(|&x| x as f64).collect();
+ let est = yin_pitch(
+ &frame,
+ FS,
+ YinOpts {
+ min_f0: Some(js_max(20.0, p.min * 0.5)),
+ max_f0: Some(js_min(12000.0, p.max * 2.0)),
+ ..Default::default()
+ },
+ );
+ pitch_report = format!(
+ "target {} Hz, measured {} Hz (aperiodicity {})",
+ num(p.default),
+ fixed(est.f0, 1),
+ fixed(est.aperiodicity, 2)
+ );
+ }
+ for call in &def.calls {
+ v.play_call_id(call.id, None, 1.0);
+ let dur = call.keys[call.keys.len() - 1].t + 0.5;
+ render_for(&mut v, &mut out, dur);
+ }
+ let ms = ms_since(t);
+ let total = out.len() as f64;
+ let bad = out.iter().filter(|x| !x.is_finite()).count();
+ let file = format!("{out_dir}/{id}.wav");
+ ctx.write_wav(&file, &out)?;
+ println!(
+ "{}: {} s in {} ms ({}% RT, internal {} Hz) peak {} non-finite {bad}",
+ def.name,
+ fixed(total / FS, 1),
+ fixed(ms, 0),
+ fixed(ms / 1000.0 / (total / FS) * 100.0, 1),
+ num(v.fs),
+ fixed(peak(&out), 3)
+ );
+ println!(" {pitch_report}");
+ Ok(())
+}
+
+/// The calibrated vowels through the real-time voice; LPC formants and YIN f0 from the audio.
+/// `render vowels [body] [out]`
+pub fn vowels(ctx: &Ctx, a: &[String]) -> Result<(), String> {
+ let body_name = arg(a, 0, "male");
+ let b = body(body_name)?;
+ let default_out = format!("out/vowels-{body_name}");
+ let name = arg(a, 1, &default_out);
+ let f0 = match body_name {
+ "female" => 205.0,
+ "child" => 260.0,
+ _ => 110.0,
+ };
+ let mut voice = HumanVoice::new(FS, b, 2);
+ voice.set_source(&SourcePatch::f0(f0));
+ let list = ["i", "e", "ɛ", "æ", "ɑ", "ɔ", "o", "u", "ʌ", "ɝ"];
+ let seg = 0.6;
+ let mut out = vec![0f32; js_round(FS * seg * list.len() as f64) as usize];
+ let table = &vowel_table()[body_name];
+ let t = Instant::now();
+ let block = 128;
+ let mut pos = 0;
+ 'vowels: for ipa in list {
+ voice.set_articulation(&table[ipa].artic, Some(true));
+ let n = js_round(FS * seg) as usize;
+ let mut i = 0;
+ while i < n {
+ let local = i as f64 / FS;
+ voice.set_gate(if local < seg - 0.12 { 1.0 } else { 0.0 });
+ let len = block.min(out.len() - pos);
+ voice.render(&mut out[pos..pos + len]);
+ pos += block;
+ if pos >= out.len() {
+ break 'vowels;
+ }
+ i += block;
+ }
+ }
+ let ms = ms_since(t);
+ let secs = out.len() as f64 / FS;
+ println!(
+ "{body_name}: rendered {} s in {} ms → {}% of real time; peak {}",
+ fixed(secs, 1),
+ fixed(ms, 0),
+ fixed(ms / 1000.0 / secs * 100.0, 1),
+ fixed(peak(&out), 3)
+ );
+ for (k, ipa) in list.iter().enumerate() {
+ let c = js_round(FS * (k as f64 * seg + 0.3)) as usize;
+ let frame = &out[c..c + 1536];
+ let ds: Vec<f64> = (0..384)
+ .map(|i| {
+ (frame[4 * i] as f64
+ + frame[4 * i + 1] as f64
+ + frame[4 * i + 2] as f64
+ + frame[4 * i + 3] as f64)
+ / 4.0
+ })
+ .collect();
+ let fm = estimate_formants(
+ &ds,
+ FS / 4.0,
+ FormantOpts {
+ order: Some(12),
+ ..Default::default()
+ },
+ );
+ let y: Vec<f64> = out[c..c + 2400].iter().map(|&x| x as f64).collect();
+ let est = yin_pitch(
+ &y,
+ FS,
+ YinOpts {
+ min_f0: Some(60.0),
+ ..Default::default()
+ },
+ );
+ let reference = &table[*ipa].formants;
+ let lpc: String = fm
+ .iter()
+ .take(3)
+ .map(|f| pad_start(&fixed(f.freq, 0), 5))
+ .collect();
+ let model: String = reference
+ .iter()
+ .take(3)
+ .map(|f| pad_start(&num(*f), 5))
+ .collect();
+ println!(
+ " {} f0={} LPC {lpc} model {model}",
+ pad_end(ipa, 2),
+ fixed(est.f0, 1)
+ );
+ }
+ ctx.write_wav(&wav_name(name), &out)?;
+ Ok(())
+}
diff --git a/crates/chimera-cli/src/wav.rs b/crates/chimera-cli/src/wav.rs
new file mode 100644
index 0000000..be2fc06
--- /dev/null
+++ b/crates/chimera-cli/src/wav.rs
@@ -0,0 +1,42 @@
+//! Mono WAV output, as `tools/lib/wav.ts` wrote it: 16-bit PCM, non-finite samples as 0, clamped
+//! to [−1, 1], `Math.round(v · 32767)`. `--float` writes 32-bit IEEE float instead (the engine's
+//! samples exactly, for comparisons).
+
+use chimera::math::js_round;
+use std::path::Path;
+
+pub fn write(path: &str, x: &[f32], sample_rate: u32, float: bool) -> std::io::Result<()> {
+ let (format, bytes_per_sample): (u16, u32) = if float { (3, 4) } else { (1, 2) };
+ let data_bytes = x.len() as u32 * bytes_per_sample;
+ let mut b = Vec::with_capacity(44 + data_bytes as usize);
+ b.extend_from_slice(b"RIFF");
+ b.extend_from_slice(&(36 + data_bytes).to_le_bytes());
+ b.extend_from_slice(b"WAVEfmt ");
+ b.extend_from_slice(&16u32.to_le_bytes());
+ b.extend_from_slice(&format.to_le_bytes());
+ b.extend_from_slice(&1u16.to_le_bytes());
+ b.extend_from_slice(&sample_rate.to_le_bytes());
+ b.extend_from_slice(&(sample_rate * bytes_per_sample).to_le_bytes());
+ b.extend_from_slice(&(bytes_per_sample as u16).to_le_bytes());
+ b.extend_from_slice(&(bytes_per_sample as u16 * 8).to_le_bytes());
+ b.extend_from_slice(b"data");
+ b.extend_from_slice(&data_bytes.to_le_bytes());
+ for &s in x {
+ if float {
+ b.extend_from_slice(&s.to_le_bytes());
+ } else {
+ let mut v = s as f64;
+ if !v.is_finite() {
+ v = 0.0;
+ }
+ v = v.clamp(-1.0, 1.0);
+ b.extend_from_slice(&(js_round(v * 32767.0) as i16).to_le_bytes());
+ }
+ }
+ if let Some(dir) = Path::new(path).parent()
+ && !dir.as_os_str().is_empty()
+ {
+ std::fs::create_dir_all(dir)?;
+ }
+ std::fs::write(path, b)
+}
diff --git a/crates/chimera-cli/tests/cli.rs b/crates/chimera-cli/tests/cli.rs
new file mode 100644
index 0000000..25def9a
--- /dev/null
+++ b/crates/chimera-cli/tests/cli.rs
@@ -0,0 +1,153 @@
+//! The `chimera` binary end to end: a render writes a sound of the planned length, and the
+//! calibrations reproduce the tables the engine embeds.
+
+use chimera::math::js_round;
+use chimera::phonetics::ipa::tokenize_ipa;
+use chimera::phonetics::planner::{PlanOptions, plan_utterance};
+use std::process::Command;
+
+const PHONETICS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../chimera/src/phonetics");
+
+fn chimera(args: &[&str]) -> String {
+ let out = Command::new(env!("CARGO_BIN_EXE_chimera"))
+ .args(args)
+ .output()
+ .expect("run chimera");
+ assert!(
+ out.status.success(),
+ "chimera {args:?} failed:\n{}",
+ String::from_utf8_lossy(&out.stderr)
+ );
+ String::from_utf8(out.stdout).unwrap()
+}
+
+fn tmp(name: &str) -> String {
+ format!("{}/{name}", env!("CARGO_TARGET_TMPDIR"))
+}
+
+#[test]
+fn render_speech_writes_a_sounding_wav_of_the_planned_length() {
+ let stem = tmp("hello");
+ let stdout = chimera(&["render", "speech", &stem, "ˈhɛloʊ"]);
+ assert!(
+ stdout.starts_with(&format!("wrote {stem}.wav 1.10 s peak ")),
+ "{stdout}"
+ );
+
+ let b = std::fs::read(format!("{stem}.wav")).unwrap();
+ assert_eq!(&b[0..4], b"RIFF");
+ assert_eq!(&b[8..16], b"WAVEfmt ");
+ let u16_at = |i: usize| u16::from_le_bytes([b[i], b[i + 1]]);
+ let u32_at = |i: usize| u32::from_le_bytes([b[i], b[i + 1], b[i + 2], b[i + 3]]);
+ assert_eq!(
+ (u16_at(20), u16_at(22), u32_at(24), u16_at(34)),
+ (1, 1, 48000, 16),
+ "16-bit PCM mono 48 kHz"
+ );
+ let samples: Vec<i16> = b[44..]
+ .chunks_exact(2)
+ .map(|c| i16::from_le_bytes([c[0], c[1]]))
+ .collect();
+ assert_eq!(u32_at(40) as usize, samples.len() * 2);
+
+ // the tool renders until 0.35 s + 0.2 s after the plan's end (TS wrote 52 692 samples)
+ let plan = plan_utterance(
+ &tokenize_ipa("ˈhɛloʊ"),
+ &PlanOptions {
+ body: "male".into(),
+ t0: 0.05,
+ f0: Some(110.0),
+ ..Default::default()
+ },
+ );
+ let expected = js_round(48000.0 * (plan.end + 0.35 + 0.2)) as usize;
+ assert_eq!(samples.len(), expected);
+ assert_eq!(samples.len(), 52692);
+
+ let peak = samples.iter().map(|s| s.unsigned_abs()).max().unwrap();
+ assert!(peak > 3000, "peak {peak}");
+ let loud = samples.iter().filter(|s| s.unsigned_abs() > 300).count();
+ assert!(
+ loud > samples.len() / 10,
+ "only {loud} of {} samples above −40 dB",
+ samples.len()
+ );
+}
+
+#[test]
+fn calibrate_consonants_reproduces_the_committed_table() {
+ let out = tmp("consonantTargets.json");
+ chimera(&["calibrate", "consonants", "--out", &out]);
+ let got = std::fs::read_to_string(&out).unwrap();
+ let want =
+ std::fs::read_to_string(format!("{PHONETICS}/consonantTargets.generated.json")).unwrap();
+ assert!(
+ got == want,
+ "calibrate consonants differs from the committed table"
+ );
+}
+
+/// About 100 s in release. Not byte-identical: the Nelder–Mead fit runs 1 800 + 2 × 1 000
+/// iterations on a flat minimum, which amplifies last-ulp differences between V8's libm and Rust's
+/// (in the airway geometry and the transfer function) into ~1e-4 changes of the fitted posture.
+/// Three entries round the other way at the third decimal: male /ə/ root, child /u/ lipAp (the TS
+/// tool gives the committed values), and female /a/ (the TS tool at the port's base commit does
+/// not reproduce its committed values either; Rust gives what TS gives today). Everything else,
+/// layout and key order included, is identical.
+#[test]
+#[ignore = "slow (~100 s): cargo test -p chimera-cli --release -- --ignored"]
+fn calibrate_vowels_reproduces_the_committed_table() {
+ let out = tmp("vowelTargets.json");
+ let _ = std::fs::remove_file(&out);
+ chimera(&["calibrate", "vowels", "all", "--out", &out]);
+ let got = std::fs::read_to_string(&out).unwrap();
+ let want = std::fs::read_to_string(format!("{PHONETICS}/vowelTargets.generated.json")).unwrap();
+ let (g, w): (Vec<&str>, Vec<&str>) = (got.lines().collect(), want.lines().collect());
+ assert_eq!(g.len(), w.len(), "line count");
+ let mut differing = Vec::new();
+ for (i, (a, b)) in g.iter().zip(&w).enumerate() {
+ if a == b {
+ continue;
+ }
+ // only a posture value may differ, and only in the last digit or two
+ let split = |l: &str| -> (String, f64) {
+ let (k, v) = l
+ .trim()
+ .trim_end_matches(',')
+ .split_once(": ")
+ .unwrap_or_else(|| panic!("line {}: {a:?} vs {b:?}", i + 1));
+ (
+ k.to_string(),
+ v.parse()
+ .unwrap_or_else(|_| panic!("line {}: {a:?} vs {b:?}", i + 1)),
+ )
+ };
+ let ((ka, va), (kb, vb)) = (split(a), split(b));
+ assert_eq!(ka, kb, "line {}", i + 1);
+ assert!(
+ [
+ "\"tbX\"",
+ "\"tbY\"",
+ "\"jaw\"",
+ "\"lipAp\"",
+ "\"lipProt\"",
+ "\"lipWidth\"",
+ "\"root\"",
+ "\"larynx\"",
+ "\"ttX\"",
+ "\"ttY\"",
+ "\"ttCurl\""
+ ]
+ .contains(&ka.as_str()),
+ "line {}: {a:?} vs {b:?}",
+ i + 1
+ );
+ assert!((va - vb).abs() <= 0.0025, "line {}: {a:?} vs {b:?}", i + 1);
+ differing.push(i + 1);
+ }
+ assert!(
+ differing.len() <= 8,
+ "{} posture values differ (lines {differing:?})",
+ differing.len()
+ );
+}
diff --git a/tools/spectrogram.ts b/tools/spectrogram.ts
new file mode 100644
index 0000000..bb4ec40
--- /dev/null
+++ b/tools/spectrogram.ts
@@ -0,0 +1,20 @@
+/**
+ * Spectrogram PNG of a WAV (the renders of `chimera render …`; the first channel).
+ * Usage: bun tools/spectrogram.ts in.wav out.png [title] [maxFreq Hz, default 8000] [windowMs, default 5]
+ */
+import { readWav } from "./lib/wav.ts";
+import { renderSpectrogram } from "./lib/spectrogram.ts";
+
+const [input, output, title, maxFreq, windowMs] = process.argv.slice(2);
+if (!input || !output) {
+ console.error("usage: bun tools/spectrogram.ts in.wav out.png [title] [maxFreq] [windowMs]");
+ process.exit(1);
+}
+const { sampleRate, channels } = readWav(input);
+const name = input.split("/").pop() ?? input;
+renderSpectrogram(output, channels[0], sampleRate, {
+ title: (title ?? name).replace(/[^\x20-\x7e]/g, "?"),
+ maxFreq: maxFreq ? Number(maxFreq) : 8000,
+ windowMs: windowMs ? Number(windowMs) : 5,
+});
+console.log(`wrote ${output} ${(channels[0].length / sampleRate).toFixed(2)} s`);