capri-ui: add sound module

This commit is contained in:
nocode committed 2026-11-11 20:20:49 +01:00
1 parent cee42c2b21
commit ca196320ab
1 file changed
+112
+112
View File
@@ -0,0 +1,112 @@
//! Procedural teleport cue (Capri's `avatar-teleport-sound.mjs`): Capri synthesizes it with
//! WebAudio, so it is regenerated here sample by sample instead of shipping a recording.
use std::num::NonZero;
use std::sync::mpsc::{channel, Sender};
use crate::teleport::Lcg;
const RATE: u32 = 48_000;
/// RBJ biquad (WebAudio `BiquadFilterNode` default Q = 1).
fn biquad(samples: &mut [f32], cutoff: f32, highpass: bool) {
let w = std::f32::consts::TAU * cutoff / RATE as f32;
let alpha = w.sin() / 2.0;
let c = w.cos();
let (b0, b1) = if highpass { ((1.0 + c) / 2.0, -(1.0 + c)) } else { ((1.0 - c) / 2.0, 1.0 - c) };
let (a0, a1, a2) = (1.0 + alpha, -2.0 * c, 1.0 - alpha);
let (mut x1, mut x2, mut y1, mut y2) = (0.0, 0.0, 0.0, 0.0);
for s in samples {
let x = *s;
let y = (b0 * x + b1 * x1 + b0 * x2 - a1 * y1 - a2 * y2) / a0;
(x2, x1, y2, y1) = (x1, x, y1, y);
*s = y;
}
}
/// Mono samples at 48 kHz for `spark`, `thunder` or `pulse`; empty for anything else.
pub fn synth(preset: &str) -> Vec<f32> {
let (duration, f0, f1, peak, triangle): (f32, f32, f32, f32, bool) = match preset {
"spark" => (0.16, 1900.0, 630.0, 0.085, true),
"thunder" => (0.37, 132.0, 45.0, 0.14, false),
"pulse" => (0.26, 360.0, 920.0, 0.085, false),
_ => return vec![],
};
let n = (RATE as f32 * duration) as usize;
let mut noise: Vec<f32> = if preset == "pulse" {
vec![0.0; n]
} else {
let mut random = Lcg::new(0x5ca1ab1e);
(0..n).map(|_| (random.next() * 2.0 - 1.0) * 0.6).collect()
};
match preset {
"spark" => biquad(&mut noise, 1900.0, true),
"thunder" => biquad(&mut noise, 420.0, false),
_ => {}
}
let lead = (RATE as f32 * 0.007) as usize;
let mut out = vec![0.0; lead];
let mut phase = 0.0f32;
for (i, noise) in noise.into_iter().enumerate() {
let t = i as f32 / RATE as f32;
// Exponential ramps: frequency reaches its target at 70 %, gain peaks at 25 ms.
let freq = f0 * (f1 / f0).powf((t / (duration * 0.7)).min(1.0));
let gain = if t < 0.025 { 0.0001 * (peak / 0.0001f32).powf(t / 0.025) } else { peak * (0.0001 / peak).powf((t - 0.025) / (duration - 0.025)) };
phase = (phase + freq / RATE as f32).fract();
let wave = if triangle { 1.0 - 4.0 * (phase - 0.5).abs() } else { (phase * std::f32::consts::TAU).sin() };
out.push((wave + noise) * gain);
}
out
}
/// Plays cues on a dedicated thread that owns the audio output (opened on first use).
#[derive(Clone)]
pub struct Sounds(Sender<String>);
impl Sounds {
pub fn new() -> Self {
let (tx, rx) = channel::<String>();
std::thread::Builder::new()
.name("capri-sound".into())
.spawn(move || {
let mut sink: Option<rodio::MixerDeviceSink> = None;
for preset in rx {
let samples = synth(&preset);
if samples.is_empty() {
continue;
}
if sink.is_none() {
// Failure to open audio is silent.
sink = rodio::DeviceSinkBuilder::open_default_sink().ok().map(|mut s| {
s.log_on_drop(false);
s
});
}
if let Some(sink) = &sink {
sink.mixer().add(rodio::buffer::SamplesBuffer::new(NonZero::new(1).unwrap(), NonZero::new(RATE).unwrap(), samples));
}
}
})
.expect("sound thread");
Self(tx)
}
pub fn play(&self, preset: &str) {
let _ = self.0.send(preset.to_string());
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn presets() {
let spark = synth("spark");
assert_eq!(spark.len(), (RATE as f32 * 0.007) as usize + (RATE as f32 * 0.16) as usize);
let peak = spark.iter().fold(0f32, |m, s| m.max(s.abs()));
assert!(peak > 0.03 && peak < 0.2, "{peak}");
assert!(spark.last().unwrap().abs() < 0.001, "fades out");
assert!(synth("off").is_empty());
assert_eq!(synth("thunder").len(), 336 + (RATE as f32 * 0.37) as usize);
}
}