use crate::synth::patches::{Formant, StringSpec};
use crate::synth::waveguide::{Biquad, DcBlock, Noise, Ramp, Vibrato, note_hz};
use std::f32::consts::TAU;
#[derive(Clone, Copy, Debug)]
pub struct FreeReedSpec {
pub reeds: &'static [StringSpec],
pub slot: f32,
pub asym: f32,
pub dynamics: f32,
pub attack: f32,
pub release: f32,
pub noise: f32,
pub tone: f32,
pub formants: &'static [Formant],
pub vibrato_hz: f32,
pub vibrato_cents: f32,
pub tremolo: f32,
pub level: f32,
}
const MF: f32 = 80.0 / 127.0;
const LEAK: f32 = 0.03;
const OPEN_SWING: f32 = 0.2;
const KNEE_SAMPLES: f32 = 1.5;
const RADIATION_HZ: f32 = 1_000.0;
const BUILD_PERIODS: f32 = 10.0;
const SILENT: f32 = 1e-4;
#[derive(Clone, Debug)]
struct Tongue {
phase: f32,
freq: f32,
mix: f32,
swing: Ramp,
build: f32,
u1: f32,
}
#[derive(Clone, Debug)]
pub struct FreeReed {
tongues: Vec<Tongue>,
sr: f32,
slot: f32,
asym: f32,
pressure: Ramp,
release: f32,
released: bool,
rad: f32,
noise: Noise,
noise_amt: f32,
noise_lp: Biquad,
formants: Vec<Biquad>,
tone: Biquad,
dc: DcBlock,
vib: Vibrato,
trem_phase: f32,
trem_inc: f32,
trem_depth: f32,
level: f32,
norm: f32,
}
#[inline]
fn knee(z: f32, w: f32) -> f32 {
0.5 * (z + (z * z + w * w).sqrt())
}
impl FreeReed {
pub fn new(spec: &FreeReedSpec, key: u8, velocity: f32, sr: f32) -> Self {
let f0 = note_hz(key as f32);
let u = velocity.clamp(0.0, 1.0).sqrt();
let p_target = (1.0 + spec.dynamics * (u / MF - 1.0)).clamp(0.25, 2.0);
let mut pressure = Ramp::new();
pressure.go(p_target, spec.attack, sr);
let tongues = spec
.reeds
.iter()
.map(|r| {
let freq =
f0 * 2f32.powf(r.detune_cents / 1200.0) * 2f32.powi(r.octave);
let build = spec.attack.max(BUILD_PERIODS / freq);
let mut swing = Ramp::new();
swing.go(p_target.sqrt(), build, sr);
Tongue {
phase: 0.0,
freq,
mix: r.mix,
swing,
build,
u1: 0.0,
}
})
.collect();
let formants = spec
.formants
.iter()
.map(|f| Biquad::peak(f.hz, f.q, f.db, sr))
.collect();
let tone_hz = (spec.tone * p_target.sqrt()).clamp(200.0, sr * 0.45);
let mix: f32 = spec.reeds.iter().map(|r| r.mix * r.mix).sum();
Self {
tongues,
sr,
slot: spec.slot,
asym: spec.asym,
pressure,
release: spec.release,
released: false,
rad: sr / (TAU * RADIATION_HZ),
noise: Noise::new(0x6A09_E667 ^ (key as u32) << 4),
noise_amt: spec.noise,
noise_lp: Biquad::bandpass(2_500.0, 0.6, sr),
formants,
tone: Biquad::lowpass(tone_hz, 0.707, sr),
dc: DcBlock::new(20.0, sr),
vib: Vibrato::new(spec.vibrato_hz, spec.vibrato_cents, 0.0, 0.0, sr),
trem_phase: 0.0,
trem_inc: spec.vibrato_hz / sr,
trem_depth: spec.tremolo,
level: spec.level,
norm: 1.0 / mix.max(1e-6).sqrt(),
}
}
pub fn release(&mut self) {
if !self.released {
self.released = true;
self.pressure.go(0.0, self.release, self.sr);
for t in &mut self.tongues {
t.swing.go(0.0, self.release.max(0.5 * t.build), self.sr);
}
}
}
pub fn is_silent(&self) -> bool {
self.released
&& self.pressure.value < SILENT
&& self.tongues.iter().all(|t| t.swing.value < SILENT)
}
#[inline]
pub fn tick(&mut self, bend: f32, wheel: f32) -> f32 {
let p = self.pressure.tick().max(0.0);
let sq = p.sqrt();
let vib = self.vib.tick(wheel);
let sr = self.sr;
let mut s = 0.0;
for t in self.tongues.iter_mut() {
let a = t.swing.tick().max(0.0);
let f = t.freq * bend * (1.0 + vib);
let dphi = (f / sr).min(0.45);
t.phase += dphi;
if t.phase >= 1.0 {
t.phase -= 1.0;
}
let x = a * (TAU * t.phase).sin();
let w = (KNEE_SAMPLES * a * TAU * dphi).max(1e-4);
let ramp = |z: f32| (knee(z, w) - knee(z - OPEN_SWING, w)) / OPEN_SWING;
let open = LEAK + ramp(x - self.slot) + self.asym * ramp(-x - self.slot);
let flow = open * sq;
let d = flow + (flow - t.u1) * self.rad;
t.u1 = flow;
s += d * t.mix;
}
s = self.dc.tick(s * self.norm);
s += self.noise_amt * p * self.noise_lp.tick(self.noise.tick());
for f in self.formants.iter_mut() {
s = f.tick(s);
}
s = self.tone.tick(s);
if self.trem_depth > 0.0 {
self.trem_phase += self.trem_inc;
if self.trem_phase >= 1.0 {
self.trem_phase -= 1.0;
}
s *= 1.0 - self.trem_depth * (0.5 - 0.5 * (TAU * self.trem_phase).cos());
}
s * self.level
}
}
#[cfg(test)]
mod tests {
use super::*;
const ONE: &[StringSpec] = &[StringSpec {
detune_cents: 0.0,
octave: 0,
mix: 1.0,
}];
fn spec() -> FreeReedSpec {
FreeReedSpec {
reeds: ONE,
slot: 0.45,
asym: 0.15,
dynamics: 0.6,
attack: 0.03,
release: 0.05,
noise: 0.0,
tone: 6_000.0,
formants: &[],
vibrato_hz: 5.0,
vibrato_cents: 0.0,
tremolo: 0.0,
level: 1.0,
}
}
fn harmonic(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 speaks_in_tune_with_a_rich_spectrum_and_stops() {
let sr = 44_100.0;
let mut r = FreeReed::new(&spec(), 57, 0.4, sr);
let x: Vec<f32> = (0..22_050).map(|_| r.tick(1.0, 0.0)).collect();
let seg = &x[8_820..];
let f0 = 220.0;
let h: Vec<f32> =
(1..=8).map(|k| harmonic(seg, k as f32 * f0, sr)).collect();
let off = harmonic(seg, f0 * 1.03, sr);
assert!(h[0] > 10.0 * off, "not at 220 Hz: {h:?} vs {off}");
let upper: f32 = h[2..].iter().sum();
assert!(h[0] >= h[1] && upper > 0.5 * h[0], "dull: {h:?}");
r.release();
for _ in 0..22_050 {
r.tick(1.0, 0.0);
}
assert!(r.is_silent());
}
}