use crate::synth::bowed::Bowed;
use crate::synth::channel::Channel;
use crate::synth::choir::Choir;
use crate::synth::cymbal::Cymbal;
use crate::synth::drums::{DrumPatch, DrumSound};
use crate::synth::env::Env;
use crate::synth::env::EnvSpec;
use crate::synth::filter::Svf;
use crate::synth::fx::Fx;
use crate::synth::modal::Modal;
use crate::synth::osc::{FmOp, Osc, Wave};
use crate::synth::patches::{LfoTarget, Patch};
use crate::synth::perc::Perc;
use crate::synth::piano::Piano;
use crate::synth::reed::FreeReed;
use crate::synth::wind::Wind;
pub fn midi_to_hz(note: f32) -> f32 {
440.0 * (2.0_f32).powf((note - 69.0) / 12.0)
}
#[derive(Clone, Debug)]
struct OscState {
osc: Osc,
detune_cents: f32,
mix: f32,
octave: i32,
level: f32, coef: f32,
}
#[derive(Clone, Debug)]
struct LfoState {
osc: Osc,
depth: f32,
target: LfoTarget,
delay_samples: u32,
age: u32,
}
#[derive(Clone, Debug)]
struct FilterState {
svf: Svf,
base_cutoff: f32,
res: f32,
env_amount: f32,
}
#[derive(Clone, Debug)]
struct KsString {
buf: Vec<f32>,
w: usize, n: usize, freq: f32, bend: f32, sr: f32,
b0: f32,
b1: f32,
a1: f32,
lp_x1: f32,
lp_y1: f32,
ap_x1: f32, ap_y1: f32, ap_c: f32, decay: f32, buzz: f32, last: f32, mix: f32,
}
const KS_MAX_BEND_DOWN: f32 = 4.0;
const KS_HF_REF: f32 = 1_000.0;
impl KsString {
#[allow(clippy::too_many_arguments)]
fn new(
freq: f32,
sr: f32,
decay_time: f32,
damp: f32,
hf_decay: f32,
pluck_pos: f32,
noise: f32,
magnetic: bool,
buzz: f32,
mix: f32,
velocity: f32,
) -> Self {
let freq = freq.max(1.0);
let mut decay = decay_gain(freq, decay_time);
let (b0, b1, a1) = if hf_decay > 0.0 {
let target = decay;
let mut a = 0.0;
for _ in 0..3 {
a = one_pole_for_loss(freq, sr, hf_decay, decay);
decay = (target / one_pole_gain(a, freq, sr)).min(0.999_95);
}
(1.0 - a, 0.0, a)
} else {
let d = damp.clamp(0.0, 0.49);
(1.0 - d, d, 0.0)
};
let mut s = Self {
buf: Vec::new(),
w: 0,
n: 2,
freq,
bend: 1.0,
sr,
b0,
b1,
a1,
lp_x1: 0.0,
lp_y1: 0.0,
ap_x1: 0.0,
ap_y1: 0.0,
ap_c: 0.0,
decay,
buzz: buzz.max(0.0),
last: 0.0,
mix,
};
s.tune(1.0);
let n = s.n;
let cap = ((sr / freq) * KS_MAX_BEND_DOWN) as usize + 4;
s.buf = vec![0.0f32; cap.max(n + 4)];
s.w = n;
let p = pluck_pos.clamp(0.02, 0.5);
let buf = &mut s.buf[..n];
let mut rng = 0x9E37_79B9u32 ^ (n as u32).wrapping_mul(2_654_435_761);
for (i, v) in buf.iter_mut().enumerate() {
let x = i as f32 / n as f32;
let shape = if magnetic {
if x <= p { 1.0 - p } else { -p }
} else if x <= p {
x / p
} else {
(1.0 - x) / (1.0 - p)
};
rng = rng.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
let white = ((rng >> 8) as f32 / 8_388_608.0) - 1.0;
*v = shape + noise * white;
}
let alpha = 0.72 + 0.28 * velocity.clamp(0.0, 1.0);
let mut lp = 0.0f32;
for v in buf.iter_mut() {
lp += alpha * (*v - lp);
*v = lp;
}
let mean = buf.iter().sum::<f32>() / n as f32;
let mut peak = 1e-6f32;
for v in buf.iter_mut() {
*v -= mean;
peak = peak.max(v.abs());
}
for v in buf.iter_mut() {
*v /= peak;
}
s
}
fn tune(&mut self, bend: f32) {
let f = self.freq * bend;
let period = (self.sr / f).max(2.0);
let w = std::f32::consts::TAU * f / self.sr;
let num = (-self.b1 * w.sin()).atan2(self.b0 + self.b1 * w.cos());
let den = (self.a1 * w.sin()).atan2(1.0 - self.a1 * w.cos());
let filter_delay = -(num - den) / w;
let max = if self.buf.is_empty() {
f32::MAX
} else {
(self.buf.len() - 2) as f32
};
let target = (period - filter_delay).clamp(2.0, max);
let mut n = target.floor() as usize;
let mut frac = target - n as f32;
if frac < 0.1 && n > 2 {
n -= 1;
frac += 1.0;
}
self.n = n;
self.ap_c = (1.0 - frac) / (1.0 + frac);
self.bend = bend;
}
fn set_bend(&mut self, bend: f32) {
if bend != self.bend {
self.tune(bend);
}
}
#[inline]
fn tick(&mut self) -> f32 {
let len = self.buf.len();
let r = if self.buzz > 0.0 {
let short = self.buzz * self.n as f32 * self.last.max(0.0);
let d = (self.n as f32 - short).max(2.0);
let i = d as usize;
let t = d - i as f32;
let a = self.buf[(self.w + len - i) % len];
let b = self.buf[(self.w + len - i - 1) % len];
a + t * (b - a)
} else {
self.buf[(self.w + len - self.n) % len]
};
self.last = r;
let lp = self.b0 * r + self.b1 * self.lp_x1 + self.a1 * self.lp_y1;
self.lp_x1 = r;
self.lp_y1 = lp;
let ap = self.ap_c * lp + self.ap_x1 - self.ap_c * self.ap_y1;
self.ap_x1 = lp;
self.ap_y1 = ap;
self.buf[self.w] = ap * self.decay;
self.w += 1;
if self.w >= len {
self.w = 0;
}
r
}
}
fn one_pole_for_loss(freq: f32, sr: f32, hf_decay: f32, decay: f32) -> f32 {
let passes = freq * hf_decay;
let g = ((0.001f32).powf(1.0 / passes) / decay).clamp(0.0, 0.999_999);
let w = std::f32::consts::TAU * KS_HF_REF.min(sr * 0.45) / sr;
let k = 2.0 * (1.0 - w.cos()) * g * g / (1.0 - g * g).max(1e-9);
let b = 2.0 + k;
((b - (b * b - 4.0).max(0.0).sqrt()) / 2.0).clamp(0.0, 0.995)
}
fn one_pole_gain(a: f32, freq: f32, sr: f32) -> f32 {
let w = std::f32::consts::TAU * freq / sr;
let one = 1.0 - a;
one / (one * one + 2.0 * a * (1.0 - w.cos())).sqrt()
}
fn decay_gain(freq: f32, decay_time: f32) -> f32 {
if decay_time <= 0.0 || freq <= 0.0 {
return 0.9;
}
let passes = freq * decay_time;
(0.001f32).powf(1.0 / passes).clamp(0.0, 0.999_95)
}
fn key_decay_scale(note: u8) -> f32 {
(2.0f32).powf(-(note as f32 - 60.0) / 24.0).clamp(0.3, 2.5)
}
#[derive(Clone, Debug)]
enum VoiceKind {
Tonal {
oscs: Vec<OscState>,
fm: Option<FmOp>,
filter: Option<FilterState>,
lfo: Option<LfoState>,
drive: Option<Drive>,
},
Perc {
model: Box<Perc>,
group: u8,
pan: f32,
},
Plucked {
strings: Vec<KsString>,
energy: f32, bend0: f32, filter: Option<Svf>, drive: Option<Drive>,
},
Piano {
model: Box<Piano>,
bend0: f32, },
Modal {
model: Box<Modal>,
bend0: f32,
},
Bowed {
model: Box<Bowed>,
filter: Option<Svf>,
},
Wind {
model: Box<Wind>,
filter: Option<Svf>,
},
Choir {
model: Box<Choir>,
filter: Option<Svf>,
},
Reed {
model: Box<FreeReed>,
filter: Option<Svf>,
},
Fx(Box<Fx>),
Cymbal {
model: Box<Cymbal>,
group: u8,
pan: f32,
},
}
#[derive(Clone, Debug)]
pub struct Voice {
kind: VoiceKind,
env: Env,
sr: f32,
pub channel: u8,
pub note: u8,
pub velocity: f32,
pub started_at: u64,
pub released: bool,
pub held_by_sustain: bool,
pub patch_gain: f32,
mod_phase: f32,
}
impl Voice {
pub fn new_tonal(
sr: f32,
channel: u8,
note: u8,
velocity: f32,
patch: &Patch,
bend_semitones: f32,
started_at: u64,
) -> Self {
let base_freq = midi_to_hz(note as f32 + bend_semitones);
let oscs: Vec<OscState> = patch
.oscs
.iter()
.map(|spec| {
let mut o = Osc::new(spec.wave, sr);
o.set_freq(
base_freq
* detune_factor(spec.detune_cents)
* (2.0_f32).powi(spec.octave),
);
OscState {
osc: o,
detune_cents: spec.detune_cents,
mix: spec.mix,
octave: spec.octave,
level: 1.0,
coef: if spec.decay > 0.0 {
10f32.powf(-3.0 / (spec.decay * sr))
} else {
1.0
},
}
})
.collect();
let fm = patch.fm.map(|fs| {
let (ratio, index) = fs.parts();
FmOp::new(ratio, index, sr)
});
let mut filter = filter_state(patch, note, sr);
if let (Some(fs), Some(spec)) = (filter.as_mut(), patch.filter)
&& spec.vel_track != 0.0
{
let u = velocity.clamp(0.0, 1.0).sqrt() / MF_VELOCITY;
let octaves = spec.vel_track * (u - 1.0) / (1.0 / MF_VELOCITY - 1.0);
fs.base_cutoff =
(fs.base_cutoff * 2f32.powf(octaves)).clamp(40.0, sr * 0.45);
fs.env_amount *= u;
fs.svf.set(fs.base_cutoff, fs.res);
}
let lfo = patch.lfo.map(|spec| {
let mut o = Osc::new(Wave::Sine, sr);
o.set_freq(spec.rate);
LfoState {
osc: o,
depth: spec.depth,
target: spec.target,
delay_samples: (spec.delay * sr) as u32,
age: 0,
}
});
let mut env = Env::new(patch.env, sr);
env.note_on();
Self {
kind: VoiceKind::Tonal {
oscs,
fm,
filter,
lfo,
drive: Drive::new(patch.drive),
},
env,
sr,
channel,
note,
velocity,
started_at,
released: false,
held_by_sustain: false,
patch_gain: patch.gain,
mod_phase: 0.0,
}
}
pub fn new_plucked(
sr: f32,
channel: u8,
note: u8,
velocity: f32,
patch: &Patch,
bend_semitones: f32,
started_at: u64,
) -> Self {
let spec = patch.pluck.expect("new_plucked requires a PluckSpec");
let base_freq = midi_to_hz(note as f32 + bend_semitones);
let ring = spec.decay * key_decay_scale(note);
let strings = spec
.strings
.iter()
.map(|st| {
let f = base_freq
* detune_factor(st.detune_cents)
* (2.0_f32).powi(st.octave);
KsString::new(
f,
sr,
ring,
spec.damp,
spec.hf_decay,
spec.pluck_pos,
spec.noise,
spec.magnetic,
spec.buzz,
st.mix,
velocity,
)
})
.collect();
let mut env =
Env::new(EnvSpec::adsr(0.001, 0.1, 1.0, spec.damper.max(0.001)), sr);
env.note_on();
Self {
kind: VoiceKind::Plucked {
strings,
energy: 1.0,
bend0: bend_semitones,
filter: filter_state(patch, note, sr).map(|f| f.svf),
drive: Drive::new(patch.drive),
},
env,
sr,
channel,
note,
velocity,
started_at,
released: false,
held_by_sustain: false,
patch_gain: patch.gain,
mod_phase: 0.0,
}
}
pub fn new_piano(
sr: f32,
channel: u8,
note: u8,
velocity: f32,
patch: &Patch,
bend_semitones: f32,
started_at: u64,
) -> Self {
let spec = patch.piano.expect("new_piano requires a PianoSpec");
let env = Env::new(patch.env, sr);
Self {
kind: VoiceKind::Piano {
model: Box::new(Piano::new(&spec, note, velocity, bend_semitones, sr)),
bend0: bend_semitones,
},
env,
sr,
channel,
note,
velocity,
started_at,
released: false,
held_by_sustain: false,
patch_gain: patch.gain,
mod_phase: 0.0,
}
}
pub fn new_modal(
sr: f32,
channel: u8,
note: u8,
velocity: f32,
patch: &Patch,
bend_semitones: f32,
started_at: u64,
) -> Self {
let spec = patch.modal.expect("new_modal requires a ModalSpec");
let env = Env::new(patch.env, sr);
Self {
kind: VoiceKind::Modal {
model: Box::new(Modal::new(
&spec,
note,
velocity,
bend_semitones,
started_at as f64 / sr as f64,
sr,
)),
bend0: bend_semitones,
},
env,
sr,
channel,
note,
velocity,
started_at,
released: false,
held_by_sustain: false,
patch_gain: patch.gain,
mod_phase: 0.0,
}
}
pub fn new_waveguide(
sr: f32,
channel: u8,
note: u8,
velocity: f32,
patch: &Patch,
started_at: u64,
) -> Self {
let filter = filter_state(patch, note, sr).map(|f| f.svf);
let kind = if let Some(spec) = patch.bowed {
VoiceKind::Bowed {
model: Box::new(Bowed::new(&spec, note, velocity, sr)),
filter,
}
} else if let Some(spec) = patch.wind {
VoiceKind::Wind {
model: Box::new(Wind::new(&spec, note, velocity, sr)),
filter,
}
} else if let Some(spec) = patch.choir {
VoiceKind::Choir {
model: Box::new(Choir::new(&spec, note, velocity, sr)),
filter,
}
} else if let Some(spec) = patch.reed {
VoiceKind::Reed {
model: Box::new(FreeReed::new(&spec, note, velocity, sr)),
filter,
}
} else {
let kind = patch
.fx
.expect("new_waveguide requires a bow, wind, choir, reed or fx spec");
VoiceKind::Fx(Box::new(Fx::new(kind, note, velocity, sr)))
};
Self {
kind,
env: Env::new(patch.env, sr),
sr,
channel,
note,
velocity,
started_at,
released: false,
held_by_sustain: false,
patch_gain: patch.gain,
mod_phase: 0.0,
}
}
pub fn new_drum(
sr: f32,
channel: u8,
note: u8,
velocity: f32,
patch: &DrumPatch,
started_at: u64,
) -> Self {
let (group, pan) = (patch.group, patch.pan);
let kind = match patch.sound {
DrumSound::Cymbal(spec) => {
let mut c = Box::new(Cymbal::new(spec, sr));
c.strike(velocity, started_at);
VoiceKind::Cymbal {
model: c,
group,
pan,
}
}
DrumSound::Perc(spec) => VoiceKind::Perc {
model: Box::new(Perc::new(spec, velocity, started_at, sr)),
group,
pan,
},
};
Self {
kind,
env: Env::new(EnvSpec::ad(0.001, 0.1), sr),
sr,
channel,
note,
velocity,
started_at,
released: true,
held_by_sustain: false,
patch_gain: patch.gain,
mod_phase: 0.0,
}
}
pub fn note_off(&mut self, sustain_on: bool) {
if sustain_on {
self.held_by_sustain = true;
return;
}
self.release();
}
fn release(&mut self) {
self.env.note_off();
self.released = true;
match &mut self.kind {
VoiceKind::Piano { model, .. } => model.damp(),
VoiceKind::Modal { model, .. } => model.damp(),
VoiceKind::Bowed { model, .. } => model.release(),
VoiceKind::Wind { model, .. } => model.release(),
VoiceKind::Choir { model, .. } => model.release(),
VoiceKind::Reed { model, .. } => model.release(),
VoiceKind::Fx(model) => model.release(),
VoiceKind::Perc { model, .. } => model.damp(),
VoiceKind::Cymbal { model, .. } => model.damp(),
_ => {}
}
}
pub fn release_if_sustained(&mut self) {
if self.held_by_sustain {
self.held_by_sustain = false;
self.release();
}
}
pub fn is_idle(&self) -> bool {
match &self.kind {
VoiceKind::Piano { model, .. } => return model.is_silent(),
VoiceKind::Modal { model, .. } => return model.is_silent(),
VoiceKind::Bowed { model, .. } => return model.is_silent(),
VoiceKind::Wind { model, .. } => return model.is_silent(),
VoiceKind::Choir { model, .. } => return model.is_silent(),
VoiceKind::Reed { model, .. } => return model.is_silent(),
VoiceKind::Fx(model) => return model.is_silent(),
VoiceKind::Cymbal { model, .. } => return model.is_silent(),
VoiceKind::Perc { model, .. } => return model.is_silent(),
_ => {}
}
if let VoiceKind::Plucked { energy, .. } = &self.kind {
return self.env.is_idle() || *energy < 1e-4;
}
self.env.is_idle()
}
pub fn restrike(
&mut self,
channel: u8,
note: u8,
velocity: f32,
clock: u64,
) -> bool {
if self.channel != channel || self.note != note {
return false;
}
let VoiceKind::Cymbal { model, .. } = &mut self.kind else {
return false;
};
model.strike(velocity, clock);
self.started_at = clock;
true
}
pub fn drum_group(&self) -> u8 {
match &self.kind {
VoiceKind::Perc { group, .. } | VoiceKind::Cymbal { group, .. } => *group,
_ => 0,
}
}
pub fn render_add(&mut self, out: &mut [f32], channel: &Channel) {
let frames = out.len() / 2;
let chan_gain = channel.gain();
let total_gain = self.patch_gain * self.velocity * chan_gain;
let (gl, gr) = equal_power_pan(channel.pan);
match &mut self.kind {
VoiceKind::Tonal {
oscs,
fm,
filter,
lfo,
drive,
} => {
let base_freq = midi_to_hz(self.note as f32 + channel.bend_semitones());
let mod_wheel = channel.mod_wheel;
for i in 0..frames {
let (pitch_mod, filter_mod, amp_mod) = if let Some(l) = lfo.as_mut() {
l.age = l.age.saturating_add(1);
let ramp = if l.age < l.delay_samples {
0.0
} else {
let r = (l.age - l.delay_samples) as f32 / (self.sr * 0.2);
r.min(1.0)
};
let s = l.osc.tick() * ramp;
match l.target {
LfoTarget::Pitch => (s * (l.depth + mod_wheel * 0.05), 0.0, 0.0),
LfoTarget::Filter => (0.0, s * l.depth, 0.0),
LfoTarget::Amp => (0.0, 0.0, s * l.depth),
}
} else if mod_wheel > 0.0 {
self.mod_phase += 5.0 / self.sr;
if self.mod_phase >= 1.0 {
self.mod_phase -= 1.0;
}
let pm =
(self.mod_phase * std::f32::consts::TAU).sin() * mod_wheel * 0.03;
(pm, 0.0, 0.0)
} else {
(0.0, 0.0, 0.0)
};
let pitch_factor = 2.0_f32.powf(pitch_mod);
let mut sample = 0.0;
if let Some(fop) = fm.as_mut() {
sample = fop.tick(base_freq * pitch_factor);
} else {
let mut total_mix = 0.0;
for o in oscs.iter_mut() {
let f = base_freq
* detune_factor(o.detune_cents)
* (2.0_f32).powi(o.octave)
* pitch_factor;
o.osc.set_freq(f);
sample += o.osc.tick() * o.mix * o.level;
o.level *= o.coef;
total_mix += o.mix;
}
if total_mix > 1e-6 {
sample /= total_mix.max(1.0);
}
}
if let Some(d) = drive {
sample = d.tick(sample);
}
let env = self.env.tick();
let amp = env * total_gain * (1.0 + amp_mod);
if let Some(fs) = filter.as_mut() {
let env_offset = env * fs.env_amount * 4_000.0;
let cutoff = (fs.base_cutoff + env_offset + filter_mod)
.clamp(40.0, self.sr * 0.45);
fs.svf.set(cutoff, fs.res);
sample = fs.svf.tick(sample);
}
let s = sample * amp;
out[i * 2] += s * gl;
out[i * 2 + 1] += s * gr;
}
}
VoiceKind::Plucked {
strings,
energy,
bend0,
filter,
drive,
} => {
let total_mix: f32 = strings.iter().map(|s| s.mix).sum();
let inv = if total_mix > 1e-6 {
1.0 / total_mix
} else {
1.0
};
let bend = 2f32.powf((channel.bend_semitones() - *bend0) / 12.0);
for s in strings.iter_mut() {
s.set_bend(bend);
}
for i in 0..frames {
let mut sample = 0.0;
for s in strings.iter_mut() {
sample += s.tick() * s.mix;
}
sample *= inv;
*energy = (*energy * 0.9995).max(sample.abs());
if let Some(d) = drive {
sample = d.tick(sample);
}
if let Some(f) = filter.as_mut() {
sample = f.tick(sample);
}
let amp = self.env.tick() * total_gain;
let v = sample * amp;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Piano { model: p, bend0 } => {
let (gl, gr) = equal_power_pan(channel.pan + 0.35 * p.key_pan());
p.set_bend(2f32.powf((channel.bend_semitones() - *bend0) / 12.0));
p.cull();
for i in 0..frames {
let v = p.tick() * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Modal { model: m, bend0 } => {
m.set_bend(2f32.powf((channel.bend_semitones() - *bend0) / 12.0));
m.update_level();
for i in 0..frames {
let v = m.tick() * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Bowed { model, filter } => {
let bend = 2f32.powf(channel.bend_semitones() / 12.0);
let wheel = channel.mod_wheel * MOD_WHEEL_VIBRATO;
for i in 0..frames {
let mut v = model.tick(bend, wheel);
if let Some(f) = filter.as_mut() {
v = f.tick(v);
}
let v = v * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Wind { model, filter } => {
let bend = 2f32.powf(channel.bend_semitones() / 12.0);
let wheel = channel.mod_wheel * MOD_WHEEL_VIBRATO;
for i in 0..frames {
let mut v = model.tick(bend, wheel);
if let Some(f) = filter.as_mut() {
v = f.tick(v);
}
let v = v * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Choir { model, filter } => {
let bend = 2f32.powf(channel.bend_semitones() / 12.0);
let wheel = channel.mod_wheel * MOD_WHEEL_VIBRATO;
for i in 0..frames {
let mut v = model.tick(bend, wheel);
if let Some(f) = filter.as_mut() {
v = f.tick(v);
}
let v = v * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Reed { model, filter } => {
let bend = 2f32.powf(channel.bend_semitones() / 12.0);
let wheel = channel.mod_wheel * MOD_WHEEL_VIBRATO;
for i in 0..frames {
let mut v = model.tick(bend, wheel);
if let Some(f) = filter.as_mut() {
v = f.tick(v);
}
let v = v * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Fx(model) => {
for i in 0..frames {
let v = model.tick() * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Cymbal { model, pan, .. } => {
let gain = self.patch_gain * chan_gain;
let (gl, gr) = equal_power_pan((channel.pan + *pan).clamp(-1.0, 1.0));
model.cull();
for i in 0..frames {
let v = model.tick() * gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
VoiceKind::Perc { model, pan, .. } => {
let (gl, gr) = equal_power_pan((channel.pan + *pan).clamp(-1.0, 1.0));
model.update_level();
for i in 0..frames {
let v = model.tick() * total_gain;
out[i * 2] += v * gl;
out[i * 2 + 1] += v * gr;
}
}
}
}
}
const MF_VELOCITY: f32 = 80.0 / 127.0;
const MOD_WHEEL_VIBRATO: f32 = 0.018;
fn filter_state(patch: &Patch, note: u8, sr: f32) -> Option<FilterState> {
patch.filter.map(|fs| {
let kt = key_track_factor(note, fs.key_track);
let cutoff = (fs.cutoff * kt).clamp(40.0, sr * 0.45);
FilterState {
svf: Svf::new(fs.mode, sr, cutoff, fs.res),
base_cutoff: cutoff,
res: fs.res,
env_amount: fs.env_amount,
}
})
}
#[derive(Clone, Copy, Debug)]
struct Drive {
k: f32,
norm: f32,
}
impl Drive {
fn new(drive: f32) -> Option<Self> {
(drive > 0.0).then(|| Self {
k: drive,
norm: 1.0 / drive.tanh(),
})
}
#[inline]
fn tick(self, x: f32) -> f32 {
(self.k * x).tanh() * self.norm
}
}
fn detune_factor(cents: f32) -> f32 {
(2.0_f32).powf(cents / 1200.0)
}
fn key_track_factor(note: u8, amount: f32) -> f32 {
if amount <= 0.0 {
return 1.0;
}
let octaves_from_c4 = (note as f32 - 60.0) / 12.0;
(2.0_f32).powf(octaves_from_c4 * amount)
}
pub fn equal_power_pan(pan: f32) -> (f32, f32) {
let p = pan.clamp(-1.0, 1.0);
let theta = (p + 1.0) * 0.25 * std::f32::consts::PI;
(theta.cos(), theta.sin())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn plucked_string_is_in_tune_and_decays() {
let sr = 44_100.0;
let mut s = KsString::new(
440.0, sr, 2.0, 0.12, 0.0, 0.13, 0.85, false, 0.0, 1.0, 1.0,
);
let n = 8192;
let buf: Vec<f32> = (0..n).map(|_| s.tick()).collect();
let expected = sr / 440.0; let lo = (expected * 0.5) as usize;
let hi = (expected * 1.5) as usize;
let seg = &buf[1000..];
let (mut best_lag, mut best) = (lo, f32::MIN);
for lag in lo..hi {
let acc: f32 = (0..seg.len() - lag).map(|i| seg[i] * seg[i + lag]).sum();
if acc > best {
best = acc;
best_lag = lag;
}
}
let f0 = sr / best_lag as f32;
let cents = 1200.0 * (f0 / 440.0).log2();
assert!(cents.abs() < 35.0, "f0 = {f0} Hz ({cents:+.1} cents)");
let rms = |w: &[f32]| {
(w.iter().map(|x| x * x).sum::<f32>() / w.len() as f32).sqrt()
};
let early = rms(&buf[..1000]);
let late = rms(&buf[n - 1000..]);
assert!(early > 1e-4, "string is silent (early rms = {early})");
assert!(
late < early,
"string did not decay (early {early}, late {late})"
);
}
fn zc_freq(x: &[f32], sr: f32) -> f32 {
let mut times = Vec::new();
for i in 1..x.len() {
if x[i - 1] < 0.0 && x[i] >= 0.0 {
times.push((i - 1) as f32 + x[i - 1] / (x[i - 1] - x[i]));
}
}
let n = times.len() - 1;
n as f32 * sr / (times[n] - times[0])
}
#[test]
fn damped_bass_string_is_in_tune() {
let sr = 44_100.0;
let f = 41.203;
let mut s =
KsString::new(f, sr, 3.0, 0.0, 0.1, 0.24, 0.0, false, 0.0, 1.0, 1.0);
let buf: Vec<f32> = (0..(2.0 * sr) as usize).map(|_| s.tick()).collect();
let got = zc_freq(&buf[(0.5 * sr) as usize..], sr);
let cents = 1200.0 * (got / f).log2();
assert!(cents.abs() < 3.0, "f0 = {got} Hz ({cents:+.1} cents)");
let rms = |w: &[f32]| {
(w.iter().map(|x| x * x).sum::<f32>() / w.len() as f32).sqrt()
};
let (a, b) = (
rms(&buf[(0.5 * sr) as usize..(0.6 * sr) as usize]),
rms(&buf[(1.5 * sr) as usize..(1.6 * sr) as usize]),
);
let db_per_s = 20.0 * (a / b).log10();
assert!(
(db_per_s - 20.0).abs() < 4.0,
"fundamental decays {db_per_s:.1} dB/s, want 20"
);
}
#[test]
fn plucked_string_follows_pitch_bend() {
let sr = 44_100.0;
let f = 110.0;
let mut s =
KsString::new(f, sr, 4.0, 0.0, 0.1, 0.2, 0.0, true, 0.0, 1.0, 1.0);
let half = (0.6 * sr) as usize;
let a: Vec<f32> = (0..half).map(|_| s.tick()).collect();
s.set_bend(2f32.powf(2.0 / 12.0));
let b: Vec<f32> = (0..half).map(|_| s.tick()).collect();
let (fa, fb) = (zc_freq(&a[half / 2..], sr), zc_freq(&b[half / 2..], sr));
let cents = 1200.0 * (fb / fa).log2();
assert!(
(cents - 200.0).abs() < 5.0,
"bend moved {fa} → {fb} Hz ({cents:.1} cents)"
);
let down = 1200.0 * (fa / f).log2();
assert!(down.abs() < 3.0, "unbent f0 {fa} Hz");
}
}