Skip to content

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

Rust

Denormals: each decayed state is zeroed at control rate (in wasm a block took 4x as long after a nasal) (#88)

osoe780f7dd1159
diff --git a/crates/chimera/src/airway/network.rs b/crates/chimera/src/airway/network.rs
index 455989e..e8cc693 100644
--- a/crates/chimera/src/airway/network.rs
+++ b/crates/chimera/src/airway/network.rs
@@ -160,6 +160,20 @@ pub struct LinearElements {
pub rad_area: Vec<f64>,
}
+/// Below this a state is nothing (the network's own silence is 1e-9): see `flush_tiny`.
+pub const TINY: f64 = 1e-30;
+#[inline]
+pub fn tiny(x: &mut f64) {
+ if x.abs() < TINY {
+ *x = 0.0;
+ }
+}
+/// A number too small to be held at full precision, which a processor computes with slowly.
+#[inline]
+pub fn is_denormal(x: f64) -> bool {
+ x != 0.0 && x.abs() < f64::MIN_POSITIVE
+}
+
/// A turbulence noise source request (control rate).
#[derive(Clone, Copy, Debug)]
pub struct NoiseSpec {
@@ -720,6 +734,50 @@ impl AirwayNetwork {
self.port_area_step[j] = (self.port_area_target[j] - self.port_area[j]) * inv;
}
}
+ self.flush_tiny();
+ }
+
+ /// How many of the states `flush_tiny` looks after are denormal (for tests: none should be).
+ pub fn denormal_states(&self) -> usize {
+ let per_node = [&self.p, &self.wall_v, &self.wall_y, &self.vol_src1, &self.vol_src2];
+ let per_branch = [&self.u, &self.mom, &self.rad_ul, &self.rad_u];
+ let arrays = per_node.iter().chain(per_branch.iter()).map(|a| a.iter().filter(|x| is_denormal(**x)).count()).sum::<usize>();
+ let noise = self.noise.iter().map(|s| [s.hp, s.lp1, s.lp2, s.level].iter().filter(|x| is_denormal(**x)).count()).sum::<usize>();
+ arrays + noise + is_denormal(self.rad_prev_total) as usize
+ }
+
+ /// Zero whatever has decayed to nothing, each on its own. The flush above waits for the whole
+ /// network to fall silent, but one part can die away while another sounds: a nasal tract shut
+ /// off by the velum, a sealed cell, the wall-movement source once the mouth has stopped moving.
+ /// Their states then shrink into the denormal range and stay there (a one-pole decay rounds a
+ /// small enough denormal back to itself), and arithmetic on denormals is several times slower:
+ /// measured, a block took four times as long after the velum had been lowered and raised.
+ /// WebAssembly has no flush-to-zero mode, so it is done here, once a control block.
+ fn flush_tiny(&mut self) {
+ for k in 0..self.n_nodes {
+ if !self.fixed[k] {
+ tiny(&mut self.p[k]);
+ }
+ tiny(&mut self.wall_v[k]);
+ tiny(&mut self.wall_y[k]);
+ tiny(&mut self.vol_src1[k]);
+ tiny(&mut self.vol_src2[k]);
+ }
+ for j in 0..self.n_branches {
+ tiny(&mut self.u[j]);
+ tiny(&mut self.mom[j]);
+ }
+ for r in 0..self.rad_ul.len() {
+ tiny(&mut self.rad_ul[r]);
+ tiny(&mut self.rad_u[r]);
+ }
+ tiny(&mut self.rad_prev_total);
+ for s in self.noise.iter_mut() {
+ tiny(&mut s.hp);
+ tiny(&mut s.lp1);
+ tiny(&mut s.lp2);
+ tiny(&mut s.level);
+ }
}
/// Replace the set of turbulence noise sources (called at control rate). Filter states of
diff --git a/crates/chimera/src/control/articulators.rs b/crates/chimera/src/control/articulators.rs
index 8a41a99..e4356cc 100644
--- a/crates/chimera/src/control/articulators.rs
+++ b/crates/chimera/src/control/articulators.rs
@@ -143,7 +143,15 @@ impl ArticulatorBank {
let x = self.x.get(k);
let acc = w * w * (tgt - x) - 2.0 * w * self.v[i];
self.v[i] += acc * dt;
- self.x.set(k, x + self.v[i] * dt);
+ let mut nx = x + self.v[i] * dt;
+ // an articulator sent to zero (the velum raised, the tongue's sides back up) arrives
+ // asymptotically, which in floating point means among the denormals, for good
+ // (see `AirwayNetwork::flush_tiny`): once it is there to all purposes, it is there
+ if tgt == 0.0 {
+ crate::airway::network::tiny(&mut nx);
+ }
+ crate::airway::network::tiny(&mut self.v[i]);
+ self.x.set(k, nx);
}
}
}
diff --git a/crates/chimera/src/engine.rs b/crates/chimera/src/engine.rs
index a703c88..2d26ed7 100644
--- a/crates/chimera/src/engine.rs
+++ b/crates/chimera/src/engine.rs
@@ -203,6 +203,12 @@ impl Engine {
&self.voice.score
}
+ /// How many of the human voice's decaying states are denormal numbers (for tests: none should
+ /// be; see `AirwayNetwork::flush_tiny`).
+ pub fn denormal_states(&self) -> usize {
+ self.voice.denormal_states()
+ }
+
/// The voice clock (s): the time base of scheduled gestures.
pub fn clock(&self) -> f64 {
self.voice.clock
diff --git a/crates/chimera/src/sources/glottis.rs b/crates/chimera/src/sources/glottis.rs
index 83ce8e5..dbf19cb 100644
--- a/crates/chimera/src/sources/glottis.rs
+++ b/crates/chimera/src/sources/glottis.rs
@@ -226,6 +226,23 @@ impl ParametricGlottis {
pub fn cycle_phase(&self) -> f64 {
self.phase
}
+
+ /// How many of the smoothed values are denormal (for tests: none should be).
+ pub fn denormal_states(&self) -> usize {
+ [self.dp_sm, self.voicing_sm, self.amp_sm, self.closure_sm, self.static_sm].iter().filter(|x| crate::airway::network::is_denormal(**x)).count()
+ }
+
+ /// Zero the smoothed values that have decayed to nothing (see `AirwayNetwork::flush_tiny`):
+ /// with the breath off or the folds apart each of them heads for zero and would otherwise
+ /// stall among the denormals. Called at control rate.
+ pub fn flush_tiny(&mut self) {
+ use crate::airway::network::tiny;
+ tiny(&mut self.dp_sm);
+ tiny(&mut self.voicing_sm);
+ tiny(&mut self.amp_sm);
+ tiny(&mut self.closure_sm);
+ tiny(&mut self.static_sm);
+ }
}
/// Normalised area pulse (0..1) at cycle phase ph.
diff --git a/crates/chimera/src/voice/human_voice.rs b/crates/chimera/src/voice/human_voice.rs
index cf1b655..7f8d1be 100644
--- a/crates/chimera/src/voice/human_voice.rs
+++ b/crates/chimera/src/voice/human_voice.rs
@@ -499,7 +499,17 @@ impl HumanVoice {
0.07
};
self.gate += (gate_goal - self.gate) * (1.0 - exp(-dt / tau));
+ // a breath let go decays toward zero for ever, and a denormal lung pressure makes denormals
+ // of the whole airway (see `AirwayNetwork::flush_tiny`): nothing is nothing
+ crate::airway::network::tiny(&mut self.gate);
+ self.glottis.flush_tiny();
+ crate::airway::network::tiny(&mut self.dc_x);
+ crate::airway::network::tiny(&mut self.dc_y);
+ crate::airway::network::tiny(&mut self.lim_env);
self.p_lung = self.source.pressure * CM_H2O * self.gate;
+ if self.p_lung == 0.0 {
+ crate::airway::network::tiny(&mut self.p_lung_now);
+ }
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
@@ -514,6 +524,7 @@ impl HumanVoice {
for k in 0..n_ph + self.airway.n_or {
let br = if k < n_ph { self.airway.branch_of(self.airway.pharynx, k as isize) } else { self.airway.branch_of(self.airway.oral, (k - n_ph) as isize) };
self.flow_sm[k] += a * (self.airway.net.u[br] - self.flow_sm[k]);
+ crate::airway::network::tiny(&mut self.flow_sm[k]);
}
}
@@ -550,6 +561,15 @@ impl HumanVoice {
changed
}
+ /// How many of the voice's decaying states are denormal numbers (for tests: none should be;
+ /// see `AirwayNetwork::flush_tiny`).
+ pub fn denormal_states(&self) -> usize {
+ use crate::airway::network::is_denormal;
+ let own = [self.gate, self.dc_x, self.dc_y, self.lim_env, self.p_lung_now];
+ let artic = ArticKey::ALL.iter().filter(|k| is_denormal(self.artic.x.get(**k))).count() + self.artic.v.iter().filter(|v| is_denormal(**v)).count();
+ self.airway.net.denormal_states() + self.glottis.denormal_states() + own.iter().filter(|x| is_denormal(**x)).count() + self.flow_sm.iter().filter(|x| is_denormal(**x)).count() + artic
+ }
+
/// Fill a telemetry snapshot and reset the accumulators.
pub fn telemetry(&mut self, out: &mut VoiceTelemetry) {
let n_t = self.airway.n_ph + self.airway.n_or;
diff --git a/crates/chimera/tests/denormals.rs b/crates/chimera/tests/denormals.rs
new file mode 100644
index 0000000..39f1c2f
--- /dev/null
+++ b/crates/chimera/tests/denormals.rs
@@ -0,0 +1,133 @@
+//! What dies away in the voice must end at zero, not among the denormals. A one-pole decay toward
+//! zero never arrives: it shrinks into the denormal range and stops there (a small enough denormal
+//! times 0.999 rounds back to itself), and a processor computes with denormals several times more
+//! slowly. WebAssembly cannot ask for them to be flushed to zero, so in the browser the engine
+//! fell behind real time and the sound broke up: after a nasal, a block took four times as long.
+use chimera::anatomy::human::{ArticKey, ArticPatch};
+use chimera::engine::Engine;
+use chimera::voice::human_voice::SourcePatch;
+
+const FS: f64 = 48000.0;
+
+fn artic(set: &[(ArticKey, f64)]) -> ArticPatch {
+ let mut p = ArticPatch::default();
+ for (k, v) in set {
+ p.values[k.index()] = Some(*v);
+ }
+ p
+}
+
+fn run(e: &mut Engine, seconds: f64) {
+ let mut buf = [0.0f32; 128];
+ for _ in 0..(seconds * FS / 128.0) as usize {
+ e.render(&mut buf);
+ }
+}
+
+fn jaw_and_tongue_moved(e: &mut Engine) {
+ e.set_artic(&artic(&[(ArticKey::Jaw, 1.2), (ArticKey::TbX, 3.4), (ArticKey::TbY, 7.6)]), Some(false));
+}
+
+fn velum_lowered_then_raised(e: &mut Engine) {
+ e.set_artic(&artic(&[(ArticKey::Velum, 0.6)]), Some(false));
+ run(e, 2.0);
+ e.set_artic(&artic(&[(ArticKey::Velum, 0.0)]), Some(false));
+}
+
+fn breath_let_go(e: &mut Engine) {
+ e.set_gate(0.0);
+}
+
+fn folds_parted(e: &mut Engine) {
+ e.set_source(&SourcePatch { voiced: Some(false), ..Default::default() });
+}
+
+fn lips_shut(e: &mut Engine) {
+ e.set_artic(&artic(&[(ArticKey::LipAp, -0.1)]), Some(false));
+}
+
+/// Each leaves some part of the voice with nothing coming into it, then holds still.
+#[cfg(target_arch = "x86_64")]
+fn disturbances() -> [(&'static str, fn(&mut Engine)); 5] {
+ [
+ ("the jaw and tongue moved once", jaw_and_tongue_moved),
+ ("the velum lowered, then raised", velum_lowered_then_raised),
+ ("the breath let go", breath_let_go),
+ ("the folds parted", folds_parted),
+ ("the lips shut", lips_shut),
+ ]
+}
+
+fn sounding() -> Engine {
+ let mut e = Engine::new(FS);
+ e.set_gate(1.0);
+ run(&mut e, 1.0);
+ e
+}
+
+fn assert_no_denormal_states(disturb: fn(&mut Engine)) {
+ let mut e = sounding();
+ disturb(&mut e);
+ // Some voice and articulator states take more than 12 s to reach the denormal range.
+ // Watch for 30 s so removing their zeroing is caught as well as the faster decays.
+ for second in 1..=30 {
+ run(&mut e, 1.0);
+ assert_eq!(e.denormal_states(), 0, "denormal states {second} s later");
+ }
+}
+
+// Separate tests let the harness run these long decay windows in parallel.
+#[test]
+fn no_denormal_states_after_jaw_and_tongue_moved() {
+ assert_no_denormal_states(jaw_and_tongue_moved);
+}
+
+#[test]
+fn no_denormal_states_after_velum_lowered_then_raised() {
+ assert_no_denormal_states(velum_lowered_then_raised);
+}
+
+#[test]
+fn no_denormal_states_after_breath_let_go() {
+ assert_no_denormal_states(breath_let_go);
+}
+
+#[test]
+fn no_denormal_states_after_folds_parted() {
+ assert_no_denormal_states(folds_parted);
+}
+
+#[test]
+fn no_denormal_states_after_lips_shut() {
+ assert_no_denormal_states(lips_shut);
+}
+
+/// The same, asked of the processor itself: it keeps a flag for having been handed a denormal to
+/// compute with, which catches the ones in passing as well as those kept in state.
+#[cfg(target_arch = "x86_64")]
+#[test]
+fn the_processor_is_never_handed_a_denormal() {
+ use core::arch::asm;
+ const DENORMAL_OPERAND: u32 = 0x0002;
+ fn mxcsr() -> u32 {
+ let mut v = 0u32;
+ unsafe { asm!("stmxcsr [{}]", in(reg) &mut v, options(nostack)) };
+ v
+ }
+ fn set_mxcsr(v: u32) {
+ unsafe { asm!("ldmxcsr [{}]", in(reg) &v, options(nostack, readonly)) };
+ }
+ for (name, disturb) in disturbances() {
+ let mut e = sounding();
+ disturb(&mut e);
+ let mut buf = [0.0f32; 128];
+ let mut dirty = 0usize;
+ let blocks = (12.0 * FS / 128.0) as usize;
+ for _ in 0..blocks {
+ set_mxcsr(mxcsr() & !0x3f);
+ e.render(&mut buf);
+ dirty += (mxcsr() & DENORMAL_OPERAND != 0) as usize;
+ }
+ assert_eq!(dirty, 0, "{name}: {dirty} of {blocks} blocks computed with denormals");
+ }
+}