Skip to content

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

Rust

Ramp the lung pressure across each control block, and add a Bright control

Jameson Hodge4980e3bf4531
diff --git a/crates/chimera-wasm/src/lib.rs b/crates/chimera-wasm/src/lib.rs
index 58709db..b087e7b 100644
--- a/crates/chimera-wasm/src/lib.rs
+++ b/crates/chimera-wasm/src/lib.rs
@@ -235,7 +235,7 @@ pub unsafe extern "C" fn engine_set_artic(h: *mut Handle, tip_free: u32) {
}
/// Source values in the value area, in this order (NaN: unchanged): f0, glide, pressure,
-/// breathiness, tension, fry, roughness, vibratoDepth, vibratoRate, drift, voiced (0/1).
+/// breathiness, tension, fry, roughness, vibratoDepth, vibratoRate, drift, voiced (0/1), brightness.
///
/// # Safety
/// `h` must be a live handle.
@@ -255,6 +255,7 @@ pub unsafe extern "C" fn engine_set_source(h: *mut Handle) {
vibrato_rate: opt(v[8]),
drift: opt(v[9]),
voiced: opt(v[10]).map(|x| x != 0.0),
+ brightness: opt(v[11]),
};
h.engine.set_source(&p);
}
diff --git a/crates/chimera/src/voice/human_voice.rs b/crates/chimera/src/voice/human_voice.rs
index 7962ce5..ea8be62 100644
--- a/crates/chimera/src/voice/human_voice.rs
+++ b/crates/chimera/src/voice/human_voice.rs
@@ -35,9 +35,18 @@ pub struct VoiceSource {
pub drift: f64,
/// false → whisper (no fold vibration)
pub voiced: bool,
+ /// 0 dark … 1 bright: how abruptly the folds close, at any tension. The default (0.25) leaves
+ /// it to tension; it sits low because a spoken or sung voice already closes nearly as softly as
+ /// the model can, so there is little room to darken and a lot to brighten.
+ #[serde(default = "default_brightness")]
+ pub brightness: f64,
}
-pub const DEFAULT_SOURCE: VoiceSource = VoiceSource { f0: 110.0, glide: 0.06, pressure: 8.0, breathiness: 0.15, tension: 0.5, fry: 0.0, roughness: 0.1, vibrato_depth: 0.0, vibrato_rate: 6.0, drift: 5.0, voiced: true };
+fn default_brightness() -> f64 {
+ DEFAULT_SOURCE.brightness
+}
+
+pub const DEFAULT_SOURCE: VoiceSource = VoiceSource { f0: 110.0, glide: 0.06, pressure: 8.0, breathiness: 0.15, tension: 0.5, fry: 0.0, roughness: 0.1, vibrato_depth: 0.0, vibrato_rate: 6.0, drift: 5.0, voiced: true, brightness: 0.25 };
/// `Partial<VoiceSource>`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
@@ -65,6 +74,8 @@ pub struct SourcePatch {
pub drift: Option<f64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub voiced: Option<bool>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub brightness: Option<f64>,
}
impl SourcePatch {
@@ -76,13 +87,13 @@ impl SourcePatch {
macro_rules! set {
($($f:ident),*) => { $( if let Some(x) = self.$f { s.$f = x; } )* };
}
- set!(f0, glide, pressure, breathiness, tension, fry, roughness, vibrato_depth, vibrato_rate, drift, voiced);
+ set!(f0, glide, pressure, breathiness, tension, fry, roughness, vibrato_depth, vibrato_rate, drift, voiced, brightness);
}
pub fn merge(&mut self, o: &SourcePatch) {
macro_rules! set {
($($f:ident),*) => { $( if o.$f.is_some() { self.$f = o.$f; } )* };
}
- set!(f0, glide, pressure, breathiness, tension, fry, roughness, vibrato_depth, vibrato_rate, drift, voiced);
+ set!(f0, glide, pressure, breathiness, tension, fry, roughness, vibrato_depth, vibrato_rate, drift, voiced, brightness);
}
pub fn from_source(s: &VoiceSource) -> Self {
SourcePatch {
@@ -97,6 +108,7 @@ impl SourcePatch {
vibrato_rate: Some(s.vibrato_rate),
drift: Some(s.drift),
voiced: Some(s.voiced),
+ brightness: Some(s.brightness),
}
}
}
@@ -150,6 +162,9 @@ pub struct HumanVoice {
/// time left (s) during which a release of the gate follows the score's own breath ramp
score_breath_hold: f64,
p_lung: f64,
+ /// lung pressure applied this sample, ramped toward `p_lung` across the control block
+ p_lung_now: f64,
+ p_lung_step: f64,
f0: f64,
pub output_gain: f64,
dc_x: f64,
@@ -205,6 +220,8 @@ impl HumanVoice {
gate_target: 0.0,
score_breath_hold: 0.0,
p_lung: 0.0,
+ p_lung_now: 0.0,
+ p_lung_step: 0.0,
f0: DEFAULT_SOURCE.f0,
output_gain: 5.5e-7,
dc_x: 0.0,
@@ -304,9 +321,13 @@ impl HumanVoice {
// The folds close along their length and depth over a return phase, not all at once, so
// a sung or spoken voice closes softly (0.22 at tension 0.55): an abrupt closure put
// 3-8 dB too much energy above 2 kHz. Pressing harder than that brings the abrupt closure
- // back, up to 0.95 at full tension, so a pressed voice still has its edge.
- g.closure_sharpness = 0.4 * s.tension + 1.375 * js_max(0.0, s.tension - 0.6);
- g.skew = 0.56 + 0.16 * s.tension;
+ // back, up to 0.95 at full tension, so a pressed voice still has its edge. Brightness moves
+ // the closure from there, and shortens or lengthens the closing phase: 0 closes as softly as
+ // the model allows, 1 about as abruptly as a pressed voice.
+ let bright = s.brightness - DEFAULT_SOURCE.brightness;
+ let by_tension = 0.4 * s.tension + 1.375 * js_max(0.0, s.tension - 0.6);
+ g.closure_sharpness = clamp(by_tension + 0.8 * bright, 0.0, 1.0);
+ g.skew = 0.56 + 0.16 * s.tension + 0.2 * bright;
g.fry = s.fry;
// Jitter of a healthy, trained voice at the default roughness (0.1): about 0.45 %, well
// under the clinical threshold (MDVP: 1.04 %).
@@ -337,7 +358,8 @@ impl HumanVoice {
}
self.ctrl_counter -= 1;
let net = &mut self.airway.net;
- net.set_fixed_pressure(lungs, self.p_lung);
+ self.p_lung_now += self.p_lung_step;
+ net.set_fixed_pressure(lungs, self.p_lung_now);
let a = self.glottis.next(net.p[sub_node] - net.p[supra]);
net.set_port_area(gp, a);
let y = net.step();
@@ -469,6 +491,7 @@ impl HumanVoice {
};
self.gate += (gate_goal - self.gate) * (1.0 - exp(-dt / tau));
self.p_lung = self.source.pressure * CM_H2O * self.gate;
+ self.p_lung_step = (self.p_lung - self.p_lung_now) / self.ctrl_every as f64;
// vocal effort follows the pressure actually applied: a harder breath (a louder sung note)
// gives wider, sharper-closing pulses, as in real phonation, not just more flow
self.glottis.params.effort = clamp(((self.source.pressure * self.gate).abs() - 3.0) / 10.0, 0.0, 1.0);
diff --git a/crates/chimera/tests/consonant_artifacts.rs b/crates/chimera/tests/consonant_artifacts.rs
new file mode 100644
index 0000000..d1d00fe
--- /dev/null
+++ b/crates/chimera/tests/consonant_artifacts.rs
@@ -0,0 +1,111 @@
+//! Artifacts a listener reported in running speech (2026-11-07): a tinny ring as sounds fade, and
+//! a pop on the /p/ of "sharp" in "A cold paper walks under the sharp tree." (still open)
+use chimera::anatomy::human::{BODY_FEMALE, BODY_MALE, HumanBody};
+use chimera::phonetics::Plan;
+use chimera::phonetics::english::EnglishG2P;
+use chimera::phonetics::ipa::tokenize_ipa;
+use chimera::phonetics::planner::{PhraseInput, PlanOptions, plan_phrases, plan_utterance};
+use chimera::voice::human_voice::{HumanVoice, SourcePatch};
+
+const FS: f64 = 48000.0;
+/// Output samples per control update (`HumanVoice` updates its controls every 64 output samples).
+const BLOCK: usize = 64;
+const VOICES: [(HumanBody, &str, f64); 2] = [(BODY_MALE, "male", 112.0), (BODY_FEMALE, "female", 205.0)];
+
+fn render(plan: Plan, body: HumanBody, f0: f64) -> (Plan, Vec<f32>) {
+ let mut v = HumanVoice::new(FS, body, 2);
+ v.set_source(&SourcePatch::f0(f0));
+ v.schedule(&plan.gestures);
+ let mut out = vec![0.0f32; (FS * (plan.end + 0.3)).round() as usize];
+ for chunk in out.chunks_mut(128) {
+ v.render(chunk);
+ }
+ (plan, out)
+}
+
+fn options(body: &str, f0: f64) -> PlanOptions {
+ PlanOptions { body: body.into(), t0: 0.05, f0: Some(f0), ..Default::default() }
+}
+
+fn idx(t: f64) -> usize {
+ (t * FS).round() as usize
+}
+
+/// Share of the energy in `x[a..b]` that repeats exactly every control block: K·Σavg² / Σx² over
+/// K block-aligned frames, frame means removed. Noise gives about 1/K; a pure buzz gives 1.
+fn block_periodic_share(x: &[f32], a: usize, b: usize) -> f64 {
+ let a = a.div_ceil(BLOCK) * BLOCK;
+ let k = (b.min(x.len()) - a) / BLOCK;
+ let mut avg = [0.0f64; BLOCK];
+ let mut total = 0.0;
+ for f in 0..k {
+ let fr = &x[a + f * BLOCK..a + (f + 1) * BLOCK];
+ let m = fr.iter().map(|v| *v as f64).sum::<f64>() / BLOCK as f64;
+ for (i, v) in fr.iter().enumerate() {
+ let d = *v as f64 - m;
+ avg[i] += d / k as f64;
+ total += d * d;
+ }
+ }
+ let mean = avg.iter().sum::<f64>() / BLOCK as f64;
+ k as f64 * avg.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / total
+}
+
+fn peak(x: &[f32], a: usize, b: usize) -> f64 {
+ x[a.min(x.len())..b.min(x.len())].iter().fold(0.0f64, |m, v| m.max(v.abs() as f64))
+}
+
+#[test]
+fn fading_sounds_do_not_buzz_at_the_control_rate() {
+ // The lung pressure used to step once per control block, so as a word's breath ran down after
+ // its last vowel, the tail was about a fifth block-periodic: a 750 Hz buzz with overtones.
+ for (body, name, f0) in VOICES {
+ for w in ["tɹˈʌk", "ʃˈit", "pˈʊʃəz", "ʃˈɑɹptɹˈi"] {
+ let (plan, out) = render(plan_utterance(&tokenize_ipa(w), &options(name, f0)), body, f0);
+ let last_vowel = plan.segments.iter().rev().find(|s| s.kind == "vowel").unwrap();
+ let (a, b) = (idx(last_vowel.t1), idx(plan.end + 0.25));
+ let share = block_periodic_share(&out, a, b);
+ println!("{w} ({name}): {:.1} % of the tail is block-periodic", 100.0 * share);
+ assert!(share < 0.05, "{w} ({name}): {:.0} % of the tail repeats every control block", 100.0 * share);
+ }
+ }
+}
+
+#[test]
+#[ignore = "target for the pronunciation batch: run with --ignored to measure it"]
+fn the_p_of_sharp_does_not_pop() {
+ // "sharp tree": the lips close for /p/, then the tongue seals for /t/ while still moving and
+ // squeezes the air shut in between to about 11x the lungs' pressure (88 cmH2O, male voice).
+ // The /p/ releases 7 dB above the loudest vowel of the sentence; the p's of "paper" sit at
+ // -6 and -7 dB. With the moving-wall volume source off, the pressure never passes the lungs'.
+ // Absorbing a sealed pocket's wall motion halves the pop but breaks
+ // `airway_adversarial::sealed_cavity_compression_follows_the_linearised_adiabatic_law`.
+ let mut g = EnglishG2P::new();
+ g.load_dict("a\tAH0\ncold\tK OW1 L D\npaper\tP EY1 P ER0\nwalks\tW AO1 K S\nunder\tAH1 N D ER0\nthe\tDH AH0\nsharp\tSH AA1 R P\ntree\tT R IY1\n");
+ let inputs: Vec<PhraseInput> = g
+ .to_phrases("A cold paper walks under the sharp tree.")
+ .into_iter()
+ .map(|p| PhraseInput { segments: p.segments, intonation: Some(p.intonation), pause: Some(p.pause) })
+ .collect();
+ for (body, name, f0) in VOICES {
+ let plan = plan_phrases(&inputs, &options(name, f0));
+ let mut v = HumanVoice::new(FS, body, 2);
+ v.set_source(&SourcePatch::f0(f0));
+ v.schedule(&plan.gestures);
+ let (o0, on) = (v.airway.oral.first_node(), v.airway.oral.n);
+ let mut out = vec![0.0f32; (FS * (plan.end + 0.3)).round() as usize];
+ let mut most = 0.0f64;
+ for c in out.chunks_mut(BLOCK) {
+ v.render(c);
+ most = (o0..o0 + on).fold(most, |m, k| m.max(v.airway.net.p[k]));
+ }
+ let lungs = v.source.pressure * 980.665;
+ println!("{name}: oral pressure peaks at {:.1}x the lungs'", most / lungs);
+ let vowel_peak = plan.segments.iter().filter(|s| s.kind == "vowel").map(|s| peak(&out, idx(s.t0), idx(s.t1))).fold(0.0, f64::max);
+ let p = plan.segments.iter().filter(|s| s.ipa == "p").last().unwrap();
+ let db = 20.0 * (peak(&out, idx(p.t1 - 0.005), idx(p.t1 + 0.03)) / vowel_peak).log10();
+ println!("{name}: the /p/ of sharp releases at {db:+.1} dB re the loudest vowel");
+ assert!(most < 2.0 * lungs, "{name}: oral pressure reached {:.1}x the lungs'", most / lungs);
+ assert!(db < -3.0, "{name}: the /p/ of sharp releases at {db:+.1} dB re the loudest vowel");
+ }
+}
diff --git a/crates/chimera/tests/golden/beatbox-bar.f32 b/crates/chimera/tests/golden/beatbox-bar.f32
index adec999..dd6583a 100644
Binary files a/crates/chimera/tests/golden/beatbox-bar.f32 and b/crates/chimera/tests/golden/beatbox-bar.f32 differ
diff --git a/crates/chimera/tests/golden/voice-artic-sweep.f32 b/crates/chimera/tests/golden/voice-artic-sweep.f32
index 54f13e9..726717c 100644
Binary files a/crates/chimera/tests/golden/voice-artic-sweep.f32 and b/crates/chimera/tests/golden/voice-artic-sweep.f32 differ
diff --git a/crates/chimera/tests/golden/voice-release-cancel.f32 b/crates/chimera/tests/golden/voice-release-cancel.f32
index e91cf0b..b4412f7 100644
Binary files a/crates/chimera/tests/golden/voice-release-cancel.f32 and b/crates/chimera/tests/golden/voice-release-cancel.f32 differ
diff --git a/crates/chimera/tests/golden/voice-speech-child.f32 b/crates/chimera/tests/golden/voice-speech-child.f32
index 228e5c9..94d58e7 100644
Binary files a/crates/chimera/tests/golden/voice-speech-child.f32 and b/crates/chimera/tests/golden/voice-speech-child.f32 differ
diff --git a/crates/chimera/tests/golden/voice-speech-female-96k.f32 b/crates/chimera/tests/golden/voice-speech-female-96k.f32
index 1717101..4afb11d 100644
Binary files a/crates/chimera/tests/golden/voice-speech-female-96k.f32 and b/crates/chimera/tests/golden/voice-speech-female-96k.f32 differ
diff --git a/crates/chimera/tests/golden/voice-speech-male.f32 b/crates/chimera/tests/golden/voice-speech-male.f32
index 238932e..5c8040b 100644
Binary files a/crates/chimera/tests/golden/voice-speech-male.f32 and b/crates/chimera/tests/golden/voice-speech-male.f32 differ
diff --git a/crates/chimera/tests/golden/voice-sustain-male.f32 b/crates/chimera/tests/golden/voice-sustain-male.f32
index b5cb24b..41b43f8 100644
Binary files a/crates/chimera/tests/golden/voice-sustain-male.f32 and b/crates/chimera/tests/golden/voice-sustain-male.f32 differ
diff --git a/crates/chimera/tests/voice_source.rs b/crates/chimera/tests/voice_source.rs
index 6260286..ba2e79a 100644
--- a/crates/chimera/tests/voice_source.rs
+++ b/crates/chimera/tests/voice_source.rs
@@ -20,3 +20,33 @@ fn a_pressed_voice_still_closes_abruptly() {
last = s;
}
}
+
+#[test]
+fn brightness_tilts_the_voice_and_its_default_changes_nothing() {
+ // the Bright control: at its default the closure is what tension alone gives; turned up, the
+ // folds close more abruptly and the voice carries more high-frequency energy
+ let mut v = HumanVoice::with_defaults(48000.0);
+ v.set_source(&SourcePatch { tension: Some(0.55), ..Default::default() });
+ let default = v.glottis.params.closure_sharpness;
+ assert!((default - 0.22).abs() < 1e-12, "{default}");
+ let mut tilt = |b: f64| {
+ let mut v = HumanVoice::with_defaults(48000.0);
+ v.set_source(&SourcePatch { tension: Some(0.55), brightness: Some(b), ..Default::default() });
+ v.set_gate(1.0);
+ let mut out = vec![0.0f32; 48000];
+ for c in out.chunks_mut(128) {
+ v.render(c);
+ }
+ // mean squared first difference over mean square: rises with the share of high frequencies
+ let x = &out[24000..];
+ let d: f64 = x.windows(2).map(|w| ((w[1] - w[0]) as f64).powi(2)).sum();
+ let e: f64 = x.iter().map(|s| (*s as f64).powi(2)).sum();
+ (v.glottis.params.closure_sharpness, 10.0 * (d / e).log10())
+ };
+ let (dark, mid, bright) = (tilt(0.0), tilt(0.25), tilt(1.0));
+ assert_eq!(mid.0, default);
+ assert!(dark.0 < mid.0 && mid.0 < bright.0);
+ println!("high-frequency share (dB): dark {:.1}, default {:.1}, bright {:.1}", dark.1, mid.1, bright.1);
+ // little room to darken (the default closure is already soft), a lot to brighten
+ assert!(dark.1 < mid.1 && mid.1 < bright.1 - 3.0, "{dark:?} {mid:?} {bright:?}");
+}
diff --git a/src/ui/components/SingPanel.tsx b/src/ui/components/SingPanel.tsx
index 6783b68..ff6a92d 100644
--- a/src/ui/components/SingPanel.tsx
+++ b/src/ui/components/SingPanel.tsx
@@ -102,6 +102,10 @@ function SongControls() {
{ label: "Ring", value: epilarynx, min: 0, max: 1, onChange: (v) => setArtic({ epilarynx: v }), format: (v) => ({ value: String(Math.round(v * 100)), unit: "%" }) },
],
},
+ {
+ name: "Tone",
+ encoders: [{ label: "Bright", value: source.brightness, min: 0, max: 1, onChange: (v) => setSource({ brightness: v }), format: (v) => ({ value: String(Math.round(v * 100)), unit: "%" }) }],
+ },
]}
/>
);
diff --git a/src/ui/components/VoiceControls.tsx b/src/ui/components/VoiceControls.tsx
index 30ac66f..b294e2e 100644
--- a/src/ui/components/VoiceControls.tsx
+++ b/src/ui/components/VoiceControls.tsx
@@ -34,12 +34,16 @@ export function VoiceControls() {
{
name: "Tone",
encoders: [
+ { label: "Bright", value: s.brightness, min: 0, max: 1, onChange: (v) => setSource({ brightness: v }), format: pct },
{ label: "Breathy", value: s.breathiness, min: 0, max: 1, onChange: (v) => setSource({ breathiness: v }), format: pct },
{ label: "Rough", value: s.roughness, min: 0, max: 1, onChange: (v) => setSource({ roughness: v }), format: pct },
{ label: "Fry", value: s.fry, min: 0, max: 1, onChange: (v) => setSource({ fry: v }), format: pct },
- { label: "Glide", value: s.glide, min: 0.005, max: 0.6, log: true, onChange: (v) => setSource({ glide: v }), format: (v) => ({ value: (v * 1000).toFixed(0), unit: "ms" }) },
],
},
+ {
+ name: "Pitch",
+ encoders: [{ label: "Glide", value: s.glide, min: 0.005, max: 0.6, log: true, onChange: (v) => setSource({ glide: v }), format: (v) => ({ value: (v * 1000).toFixed(0), unit: "ms" }) }],
+ },
{
name: "Mouth",
encoders: [
diff --git a/src/wasm/types.ts b/src/wasm/types.ts
index e5f352a..3e27fc8 100644
--- a/src/wasm/types.ts
+++ b/src/wasm/types.ts
@@ -121,6 +121,8 @@ export interface VoiceSource {
vibratoRate: number;
drift: number;
voiced: boolean;
+ /** 0 dark … 1 bright (default 0.25: as tension sets it) */
+ brightness: number;
}
export interface VoiceTelemetry {
diff --git a/src/worklet/processor.ts b/src/worklet/processor.ts
index 632ebf0..bf473b4 100644
--- a/src/worklet/processor.ts
+++ b/src/worklet/processor.ts
@@ -22,7 +22,7 @@ type Fn = (...a: number[]) => number;
type Exports = { memory: WebAssembly.Memory } & Record<string, Fn>;
const ARTIC_KEYS = CONTROL_KEYS.slice(0, 17);
-const SOURCE_KEYS = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];
+const SOURCE_KEYS = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced", "brightness"];
/** scalars at the head of the human telemetry block (crates/chimera-wasm/src/lib.rs) */
const TELE_HEADER = 16;
/** gestures taken from one schedule message */
diff --git a/tests/harness.ts b/tests/harness.ts
index 893908f..29d1d6b 100644
--- a/tests/harness.ts
+++ b/tests/harness.ts
@@ -45,7 +45,7 @@ export class WasmVoice {
}
/** Source values by name (crates/chimera-wasm engine_set_source order). */
setSource(values: Record<string, number | boolean>): void {
- const keys = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];
+ const keys = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced", "brightness"];
const v = new Float64Array(this.x.memory.buffer, this.x.engine_values(this.h), 32).fill(NaN);
for (const [k, val] of Object.entries(values)) v[keys.indexOf(k)] = typeof val === "boolean" ? (val ? 1 : 0) : val;
this.x.engine_set_source(this.h);
diff --git a/tests/wasm-engine.test.ts b/tests/wasm-engine.test.ts
index a06b933..21b9022 100644
--- a/tests/wasm-engine.test.ts
+++ b/tests/wasm-engine.test.ts
@@ -10,7 +10,7 @@ import type { Gesture } from "../src/wasm/types.ts";
const ROOT = new URL("..", import.meta.url).pathname;
const WASM = `${ROOT}target/wasm32-unknown-unknown/release/chimera_wasm.wasm`;
-const SOURCE_KEYS = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced"];
+const SOURCE_KEYS = ["f0", "glide", "pressure", "breathiness", "tension", "fry", "roughness", "vibratoDepth", "vibratoRate", "drift", "voiced", "brightness"];
interface Exports {
memory: WebAssembly.Memory;