Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/common.rs3//! Description: Building blocks shared by the engines: amplitude envelope slot, panning, fast sine, string loop.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use crate::params::Resolved;9use sonata_dsp::core::{flush, DelayLine};10use sonata_dsp::env::Adsr;11use sonata_dsp::filter::Allpass1;1213/// Values of the `envelope` slot read once per instrument.14#[derive(Clone, Copy, Debug)]15pub struct EnvSettings {16 pub natural: bool,17 pub attack: f32,18 pub decay: f32,19 pub sustain: f32,20 pub release: f32,21}2223impl EnvSettings {24 pub fn read(r: &Resolved, has_natural: bool) -> EnvSettings {25 EnvSettings {26 natural: has_natural && r.pick("envelope") == 0,27 attack: r.get("envelope.attack"),28 decay: r.get("envelope.decay"),29 sustain: r.get("envelope.sustain"),30 release: r.get("envelope.release"),31 }32 }33 /// Configures and opens an envelope for a new note.34 pub fn start(&self, env: &mut Adsr) {35 env.reset();36 if self.natural {37 env.set(0.0, 0.0, 1.0, self.release);38 } else {39 env.set(self.attack, self.decay, self.sustain, self.release);40 }41 env.gate_on();42 }43}4445/// Constant-power pan gains for `pan` in [-1, 1] (-3 dB at the centre), scaled so the centre is unity.46#[inline]47pub fn pan_gains(pan: f32) -> (f32, f32) {48 let a = (pan.clamp(-1.0, 1.0) + 1.0) * std::f32::consts::FRAC_PI_4;49 (a.cos() * std::f32::consts::SQRT_2, a.sin() * std::f32::consts::SQRT_2)50}5152/// sin(2 pi x) for any `x` in cycles: odd polynomial of degree 9 after folding to a quarter53/// period, absolute error below 4e-6 (-108 dB).54#[inline]55pub fn sin_turns(x: f32) -> f32 {56 let mut q = x - (x + 0.5).floor();57 if q > 0.25 {58 q = 0.5 - q;59 } else if q < -0.25 {60 q = -0.5 - q;61 }62 let t = q * std::f32::consts::TAU;63 let t2 = t * t;64 t * (1.0 + t2 * (-1.0 / 6.0 + t2 * (1.0 / 120.0 + t2 * (-1.0 / 5040.0 + t2 * (1.0 / 362_880.0)))))65}6667/// Phase delay in samples at `w` (rad/sample) of the two-point loss filter `(1-b) + b z^-1`.68pub fn one_zero_phase_delay(b: f32, w: f32) -> f32 {69 if w <= 0.0 {70 return b;71 }72 (b * w.sin()).atan2(1.0 - b + b * w.cos()) / w73}7475/// Magnitude at `w` of the loss filter `(1-b) + b z^-1`.76pub fn one_zero_gain(b: f32, w: f32) -> f32 {77 let re = 1.0 - b + b * w.cos();78 let im = b * w.sin();79 (re * re + im * im).sqrt()80}8182/// Phase delay in samples at `w` of the one-pole low-pass `a / (1 - (1-a) z^-1)`.83pub fn one_pole_phase_delay(a: f32, w: f32) -> f32 {84 let p = 1.0 - a;85 if w <= 0.0 {86 return p / (1.0 - p);87 }88 (p * w.sin()).atan2(1.0 - p * w.cos()) / w89}9091/// Magnitude at `w` of the one-pole low-pass `a / (1 - (1-a) z^-1)`.92pub fn one_pole_gain(a: f32, w: f32) -> f32 {93 let p = 1.0 - a;94 a / (1.0 - 2.0 * p * w.cos() + p * p).sqrt()95}9697/// Magnitude at `w` of the 4-point Lagrange interpolator used by `DelayLine::read_cubic` for a98/// fractional delay `frac` in [0, 1).99pub fn lagrange3_gain(frac: f32, w: f32) -> f32 {100 let f = frac;101 let c = [-f * (f - 1.0) * (f - 2.0) / 6.0, (f + 1.0) * (f - 1.0) * (f - 2.0) / 2.0, -(f + 1.0) * f * (f - 2.0) / 2.0, (f + 1.0) * f * (f - 1.0) / 6.0];102 let (mut re, mut im) = (0.0f32, 0.0f32);103 for (k, ck) in c.iter().enumerate() {104 re += ck * (w * k as f32).cos();105 im -= ck * (w * k as f32).sin();106 }107 (re * re + im * im).sqrt().max(0.5)108}109110/// Digital-waveguide string loop (extended Karplus-Strong):111/// delay line (cubic interpolation) -> two-point loss filter -> dispersion allpass -> gain.112///113/// The delay is solved so that the loop's total phase delay at the fundamental equals one114/// period, including the loss filter and the allpass; the loop gain is solved so that the115/// fundamental decays by 60 dB in the requested time.116#[derive(Clone, Debug)]117pub struct StringLoop {118 line: DelayLine,119 delay: f32,120 b: f32,121 gain: f32,122 z1: f32,123 ap: Allpass1,124 sr: f32,125 freq: f32,126 t60: f32,127}128129impl StringLoop {130 pub fn new(sample_rate: f32, lowest_hz: f32) -> StringLoop {131 StringLoop {132 line: DelayLine::new((sample_rate / lowest_hz) as usize + 8),133 delay: 100.0,134 b: 0.3,135 gain: 0.99,136 z1: 0.0,137 ap: Allpass1::new(0.0),138 sr: sample_rate,139 freq: 110.0,140 t60: 2.0,141 }142 }143 pub fn clear(&mut self) {144 self.line.clear();145 self.z1 = 0.0;146 self.ap.reset();147 }148 /// `damp` in [0, 0.5] is the weight of the previous sample in the loss filter (0 = bright);149 /// `dispersion` in [0, 0.9] is the allpass coefficient magnitude (stiffness).150 pub fn tune(&mut self, freq: f32, t60: f32, damp: f32, dispersion: f32) {151 self.freq = freq.clamp(self.sr / (self.line.capacity() as f32 - 4.0), self.sr * 0.25);152 self.t60 = t60.max(0.005);153 self.b = damp.clamp(0.0, 0.5);154 self.ap.a = -dispersion.clamp(0.0, 0.9);155 self.solve();156 }157 pub fn set_freq(&mut self, freq: f32) {158 self.freq = freq.clamp(self.sr / (self.line.capacity() as f32 - 4.0), self.sr * 0.25);159 self.solve();160 }161 pub fn set_t60(&mut self, t60: f32) {162 self.t60 = t60.max(0.005);163 self.solve();164 }165 fn solve(&mut self) {166 let w = std::f32::consts::TAU * self.freq / self.sr;167 let period = self.sr / self.freq;168 let extra = one_zero_phase_delay(self.b, w) + if self.ap.a != 0.0 { Allpass1::phase_delay(self.ap.a, w) } else { 0.0 };169 self.delay = (period - extra).max(2.0);170 // Per-period gain for the requested T60, compensated for the loss filter at the fundamental.171 // The gain never exceeds 1 (the loop must stay passive at DC): with strong damping on a high172 // note the decay is therefore shorter than requested.173 let per_period = 10f32.powf(-3.0 / (self.freq * self.t60));174 self.gain = (per_period / (one_zero_gain(self.b, w) * lagrange3_gain(self.delay - self.delay.floor(), w))).min(1.0);175 }176 pub fn period(&self) -> f32 {177 self.sr / self.freq178 }179 /// One sample: returns the string output, feeding `excitation` into the loop.180 #[inline]181 pub fn tick(&mut self, excitation: f32) -> f32 {182 let y = self.line.read_cubic(self.delay);183 let lp = (1.0 - self.b) * y + self.b * self.z1;184 self.z1 = y;185 let d = if self.ap.a != 0.0 { self.ap.tick(lp) } else { lp };186 self.line.write(flush(d * self.gain + excitation));187 y188 }189}190191#[cfg(test)]192mod tests {193 use super::*;194 use sonata_dsp::core::{cents, estimate_f0};195196 #[test]197 fn fast_sine_accuracy() {198 let mut worst = 0.0f32;199 for i in -4000..4000 {200 let x = i as f32 / 1000.0;201 worst = worst.max((sin_turns(x) - (x * std::f32::consts::TAU).sin()).abs());202 }203 assert!(worst < 2e-5, "{worst}");204 }205206 #[test]207 fn pan_law() {208 let (l, r) = pan_gains(0.0);209 assert!((l - 1.0).abs() < 1e-6 && (r - 1.0).abs() < 1e-6);210 let (l, r) = pan_gains(-1.0);211 assert!((l - std::f32::consts::SQRT_2).abs() < 1e-6 && r.abs() < 1e-6);212 }213214 #[test]215 fn string_loop_is_in_tune_and_decays_as_requested() {216 let sr = 48_000.0;217 for (f, damp, disp) in [(82.41f32, 0.3f32, 0.0f32), (440.0, 0.2, 0.3), (1318.5, 0.1, 0.5), (2093.0, 0.01, 0.0)] {218 let mut s = StringLoop::new(sr, 30.0);219 s.tune(f, 2.0, damp, disp);220 let n = s.period() as usize;221 let out: Vec<f32> = (0..48_000).map(|i| s.tick(if i < n { ((i * 7919) % 101) as f32 / 50.0 - 1.0 } else { 0.0 })).collect();222 let est = estimate_f0(&out[4800..28_800], sr, f * 0.94, f * 1.06).unwrap();223 assert!(cents(est, f).abs() < 1.5, "f {f}: {est} ({} cents)", cents(est, f));224 // T60 = 2 s -> the fundamental loses 15 dB between 0.25 s and 0.75 s (tolerance 1.5 dB).225 let a = sonata_dsp::core::goertzel_amplitude(&out[9600..14_400], f, sr);226 let b = sonata_dsp::core::goertzel_amplitude(&out[33_600..38_400], f, sr);227 let drop = 20.0 * (b / a).log10();228 assert!((drop + 15.0).abs() < 1.5, "f {f}: drop {drop} dB");229 }230 }231}232233/// Piecewise-linear lookup in a table sorted by x; clamps outside the table. Empty table = 0.234pub fn interp_table(table: &[(f32, f32)], x: f32) -> f32 {235 match table {236 [] => 0.0,237 [only] => only.1,238 _ => {239 if x <= table[0].0 {240 return table[0].1;241 }242 for w in table.windows(2) {243 if x <= w[1].0 {244 let t = (x - w[0].0) / (w[1].0 - w[0].0);245 return w[0].1 + (w[1].1 - w[0].1) * t;246 }247 }248 table[table.len() - 1].1249 }250 }251}252253/// Coefficient `a` of the one-pole low-pass `a / (1 - (1-a) z^-1)` for a cutoff in Hz.254pub fn one_pole_coef(cutoff_hz: f32, sample_rate: f32) -> f32 {255 1.0 - (-std::f32::consts::TAU * cutoff_hz.clamp(1.0, 0.49 * sample_rate) / sample_rate).exp()256}257258/// Shared vibrato: delayed onset, sine, depth in semitones. Returns a frequency ratio.259#[derive(Clone, Copy, Debug, Default)]260pub struct Vibrato {261 phase: f32,262 inc: f32,263 depth: f32,264 onset: f32,265 onset_step: f32,266}267268impl Vibrato {269 pub fn start(&mut self, rate_hz: f32, depth_st: f32, delay_sec: f32, sample_rate: f32, phase: f32) {270 self.phase = phase;271 self.inc = rate_hz / sample_rate;272 self.depth = depth_st;273 self.onset = 0.0;274 self.onset_step = 1.0 / (delay_sec.max(0.001) * sample_rate);275 }276 /// Semitone offset for this sample.277 #[inline]278 pub fn tick(&mut self) -> f32 {279 self.phase += self.inc;280 if self.phase >= 1.0 {281 self.phase -= 1.0;282 }283 if self.onset < 1.0 {284 self.onset = (self.onset + self.onset_step).min(1.0);285 }286 // Onset is squared: vibrato enters gently.287 sin_turns(self.phase) * self.depth * self.onset * self.onset288 }289}290291/// The three vibrato parameters shared by the sustained engines.292pub fn vibrato_params(rate: f64, depth: f64, delay: f64) -> Vec<sonata_ir::ParamDesc> {293 use sonata_ir::{ParamDesc, Unit};294 vec![295 ParamDesc::num("vibrato.rate", Unit::Hertz, 0.0, 12.0, rate, true, "Vibrato rate."),296 ParamDesc::num("vibrato.depth", Unit::Semitones, 0.0, 1.0, depth, true, "Vibrato depth (peak deviation)."),297 ParamDesc::num("vibrato.delay", Unit::Seconds, 0.0, 2.0, delay, false, "Time after the note start for the vibrato to reach its full depth."),298 ]299}300