use crate::synth::osc::poly_blep;
use crate::synth::patches::StringSpec;
use crate::synth::waveguide::{Biquad, Noise, OnePole, Ramp, Vibrato, note_hz};
use std::f32::consts::TAU;
#[derive(Clone, Copy, Debug)]
pub struct VocalFormant {
pub hz: f32,
pub bw: f32,
pub db: f32,
}
pub const fn vf(hz: f32, bw: f32, db: f32) -> VocalFormant {
VocalFormant { hz, bw, db }
}
pub type Vowel = [VocalFormant; 5];
#[derive(Clone, Copy, Debug)]
pub struct ChoirSpec {
pub singers: &'static [StringSpec],
pub low: Vowel,
pub high: Vowel,
pub split: f32,
pub brightness: f32,
pub breath: f32,
pub drift_cents: f32,
pub stagger: f32,
pub attack: f32,
pub release: f32,
pub vibrato_hz: f32,
pub vibrato_cents: f32,
pub vibrato_delay: f32,
}
const DRIFT_HZ: f32 = 2.5;
const NORM_MAX_HZ: f32 = 8_000.0;
const SILENT: f32 = 1e-4;
const MF: f32 = 80.0 / 127.0;
#[derive(Clone, Debug)]
struct Singer {
phase: f32,
ratio: f32,
mix: f32,
vib: Vibrato,
drift: f32,
drift_a: f32,
drift_scale: f32,
noise: Noise,
tilt: OnePole,
amp: Ramp,
attack: f32,
delay: u32,
}
#[derive(Clone, Debug)]
pub struct Choir {
singers: Vec<Singer>,
f0: f32,
sr: f32,
formants: [Biquad; 5],
gains: [f32; 5],
breath: f32,
noise: Noise,
breath_lp: OnePole,
amp: Ramp,
release: f32,
released: bool,
norm: f32,
}
fn scatter(key: u8, i: usize, salt: u32) -> f32 {
let mut h = (key as u32)
.wrapping_mul(0x9E37_79B9)
.wrapping_add((i as u32).wrapping_mul(0x85EB_CA6B))
^ salt;
h ^= h >> 15;
h = h.wrapping_mul(0x2C1B_3C6D);
h ^= h >> 12;
h = h.wrapping_mul(0x297A_2D39);
h ^= h >> 15;
(h & 0xFFFF) as f32 / 32_767.5 - 1.0
}
impl Choir {
pub fn new(spec: &ChoirSpec, key: u8, velocity: f32, sr: f32) -> Self {
let k = key as f32;
let f0 = note_hz(k);
let u = velocity.clamp(0.0, 1.0).sqrt();
let corner = (spec.brightness * (u / MF)).clamp(200.0, sr * 0.4);
let t = ((k - spec.split + 6.0) / 12.0).clamp(0.0, 1.0);
let mut fm: Vowel = spec.low;
for (i, f) in fm.iter_mut().enumerate() {
let (a, b) = (spec.low[i], spec.high[i]);
*f = vf(
a.hz + (b.hz - a.hz) * t,
a.bw + (b.bw - a.bw) * t,
a.db + (b.db - a.db) * t,
);
}
let fund =
f0 * 2f32.powi(spec.singers.iter().map(|s| s.octave).min().unwrap_or(0));
if fm[0].hz < 1.1 * fund {
fm[0].hz = 1.1 * fund;
fm[0].bw = fm[0].bw.max(0.1 * fm[0].hz);
}
if fm[1].hz < fm[0].hz * 1.35 {
fm[1].hz = fm[0].hz * 1.35;
}
let nyq = sr * 0.45;
let formants: [Biquad; 5] = std::array::from_fn(|i| {
let f = fm[i];
Biquad::bandpass(f.hz.min(nyq), (f.hz / f.bw.max(1.0)).max(0.5), sr)
});
let gains: [f32; 5] = std::array::from_fn(|i| {
if fm[i].hz < nyq {
10f32.powf(fm[i].db / 20.0)
} else {
0.0
}
});
let singers: Vec<Singer> = spec
.singers
.iter()
.enumerate()
.map(|(i, s)| {
let rate =
spec.vibrato_hz * (1.0 + 0.12 * scatter(key, i, 0x1B87_3593));
let depth =
spec.vibrato_cents * (1.0 + 0.25 * scatter(key, i, 0x68E3_1DA4));
let phase = 0.5 + 0.5 * scatter(key, i, 0x5BD1_E995);
let drift_a = (-TAU * DRIFT_HZ / sr).exp();
let eps = 1.0 - drift_a;
let sd = (eps / (2.0 - eps) / 3.0).sqrt();
let attack = spec.attack * (1.0 + 0.3 * scatter(key, i, 0x27D4_EB2F));
let delay = spec.stagger * (0.5 + 0.5 * scatter(key, i, 0x1656_67B1));
let mut amp = Ramp::new();
if delay <= 0.0 {
amp.go(1.0, attack, sr);
}
Singer {
phase: (0.5 + 0.5 * scatter(key, i, 0x3C6E_F372)).fract(),
ratio: 2f32.powf(s.detune_cents / 1200.0) * 2f32.powi(s.octave),
mix: s.mix,
vib: Vibrato::new(rate, depth, spec.vibrato_delay, phase, sr),
drift: 0.0,
drift_a,
drift_scale: (2f32.powf(spec.drift_cents / 1200.0) - 1.0)
/ sd.max(1e-9),
noise: Noise::new(0x2545_F491 ^ (key as u32) << 8 ^ i as u32),
tilt: OnePole::corner(corner, sr),
amp,
attack,
delay: (delay * sr) as u32,
}
})
.collect();
let tilt = OnePole::corner(corner, sr);
let mut power = 0.0f32;
let lim = NORM_MAX_HZ.min(nyq);
let mut h = 1;
while h as f32 * fund < lim {
let f = h as f32 * fund;
let (mut re, mut im) = (0.0, 0.0);
for (b, g) in formants.iter().zip(&gains) {
let (r, i) = b.response(f, sr);
re += g * r;
im += g * i;
}
let a = (2.0 / (std::f32::consts::PI * h as f32)) * tilt.gain(f, sr);
power += 0.5 * a * a * (re * re + im * im);
h += 1;
}
let mixes: f32 = spec.singers.iter().map(|s| s.mix * s.mix).sum();
let norm = 0.3 / (power.max(1e-9) * mixes.max(1e-6)).sqrt();
let mut amp = Ramp::new();
amp.go(1.0, 0.005, sr);
Self {
singers,
f0,
sr,
formants,
gains,
breath: spec.breath,
noise: Noise::new(0x7F4A_7C15 ^ key as u32),
breath_lp: OnePole::corner(6_000.0, sr),
amp,
release: spec.release,
released: false,
norm,
}
}
pub fn release(&mut self) {
if !self.released {
self.released = true;
self.amp.go(0.0, self.release, self.sr);
}
}
pub fn is_silent(&self) -> bool {
self.released && self.amp.value < SILENT
}
#[inline]
pub fn tick(&mut self, bend: f32, wheel: f32) -> f32 {
let a = self.amp.tick();
let sr = self.sr;
let mut src = 0.0;
let mut open = 0.0;
for s in self.singers.iter_mut() {
if s.delay > 0 {
s.delay -= 1;
if s.delay == 0 {
s.amp.go(1.0, s.attack, sr);
}
}
let g = s.amp.tick();
s.drift = s.drift_a * s.drift + (1.0 - s.drift_a) * s.noise.tick();
let f = self.f0
* s.ratio
* bend
* (1.0 + s.vib.tick(wheel) + s.drift * s.drift_scale);
let dt = (f / sr).min(0.5);
let p = s.phase;
s.phase += dt;
if s.phase >= 1.0 {
s.phase -= 1.0;
}
let saw = 2.0 * p - 1.0 - poly_blep(p, dt);
src += s.tilt.tick(saw) * s.mix * g;
open += g * s.mix * (1.0 - p);
}
let n = self.breath_lp.tick(self.noise.tick());
src += self.breath * n * open;
let mut y = 0.0;
for (b, g) in self.formants.iter_mut().zip(&self.gains) {
y += g * b.tick(src);
}
y * self.norm * a
}
}
#[cfg(test)]
mod tests {
use super::*;
const SINGER: &[StringSpec] = &[StringSpec {
detune_cents: 0.0,
octave: 0,
mix: 1.0,
}];
const AH: Vowel = [
vf(800.0, 80.0, 0.0),
vf(1150.0, 90.0, -4.0),
vf(2800.0, 120.0, -20.0),
vf(3500.0, 130.0, -36.0),
vf(4950.0, 140.0, -60.0),
];
const OO: Vowel = [
vf(325.0, 50.0, 0.0),
vf(700.0, 60.0, -12.0),
vf(2530.0, 170.0, -30.0),
vf(3500.0, 180.0, -40.0),
vf(4950.0, 200.0, -64.0),
];
fn spec(v: Vowel) -> ChoirSpec {
ChoirSpec {
singers: SINGER,
low: v,
high: v,
split: 60.0,
brightness: 3_000.0,
breath: 0.0,
drift_cents: 0.0,
stagger: 0.0,
attack: 0.02,
release: 0.1,
vibrato_hz: 5.0,
vibrato_cents: 0.0,
vibrato_delay: 0.0,
}
}
fn tone(x: &[f32], f: f32, sr: f32) -> f32 {
let w = TAU * f / sr;
let (mut re, mut im) = (0.0f32, 0.0f32);
for (i, v) in x.iter().enumerate() {
re += v * (w * i as f32).cos();
im += v * (w * i as f32).sin();
}
(re * re + im * im).sqrt() / x.len() as f32
}
#[test]
fn vowels_have_their_formants() {
let sr = 44_100.0;
let f0 = note_hz(57.0); let render = |v| {
let mut c = Choir::new(&spec(v), 57, 0.4, sr);
let x: Vec<f32> = (0..22_050).map(|_| c.tick(1.0, 0.0)).collect();
x[4_410..].to_vec()
};
let (ah, oo) = (render(AH), render(OO));
let hi = |x: &[f32]| tone(x, 4.0 * f0, sr) + tone(x, 5.0 * f0, sr);
let lo = |x: &[f32]| tone(x, f0, sr) + tone(x, 2.0 * f0, sr);
assert!(hi(&ah) > lo(&ah), "ah: hi {} lo {}", hi(&ah), lo(&ah));
assert!(lo(&oo) > 4.0 * hi(&oo), "oo: hi {} lo {}", hi(&oo), lo(&oo));
let rms = |x: &[f32]| {
(x.iter().map(|v| v * v).sum::<f32>() / x.len() as f32).sqrt()
};
let r = rms(&ah) / rms(&oo);
assert!((0.5..2.0).contains(&r), "level ratio {r}");
}
}