Repository Public
1//! ORIX Sonata2//! File: crates/sonata-dsp/src/core/mod.rs3//! Description: Module core of the portable DSP library.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai7#![allow(clippy::needless_range_loop, clippy::excessive_precision)]89use std::f32::consts::PI;1011pub const TAU: f32 = 2.0 * PI;1213/// Decibels to linear amplitude.14#[inline]15pub fn db_to_lin(db: f32) -> f32 {16 (db * (std::f32::consts::LN_10 / 20.0)).exp()17}1819/// Linear amplitude to decibels, floored at -200 dB.20#[inline]21pub fn lin_to_db(lin: f32) -> f32 {22 20.0 * lin.abs().max(1e-10).log10()23}2425/// MIDI pitch (fractional) to Hz for a given A4 tuning.26#[inline]27pub fn midi_to_hz(pitch: f32, tuning_hz: f32) -> f32 {28 tuning_hz * ((pitch - 69.0) / 12.0).exp2()29}3031#[inline]32pub fn hz_to_midi(hz: f32, tuning_hz: f32) -> f32 {33 69.0 + 12.0 * (hz / tuning_hz).max(1e-9).log2()34}3536/// Frequency ratio of an interval in semitones.37#[inline]38pub fn semitones_to_ratio(st: f32) -> f32 {39 (st / 12.0).exp2()40}4142/// Replaces subnormal and non-finite values by zero.43#[inline]44pub fn flush(x: f32) -> f32 {45 if x.abs() > 1e-20 && x.is_finite() {46 x47 } else {48 0.049 }50}5152/// Sets flush-to-zero on the current thread for its lifetime (aarch64 FPCR.FZ, x86-64 MXCSR FTZ|DAZ)53/// and restores the previous mode on drop. Create one at the top of an audio callback.54pub struct DenormalGuard {55 saved: u64,56}5758impl DenormalGuard {59 #[allow(clippy::new_without_default)]60 #[inline]61 pub fn new() -> DenormalGuard {62 #[cfg(target_arch = "aarch64")]63 {64 let saved: u64;65 // SAFETY: reading and writing FPCR only changes the floating-point mode of this thread.66 unsafe {67 std::arch::asm!("mrs {}, fpcr", out(reg) saved);68 std::arch::asm!("msr fpcr, {}", in(reg) saved | (1 << 24));69 }70 DenormalGuard { saved }71 }72 #[cfg(target_arch = "x86_64")]73 {74 let mut saved: u32 = 0;75 // SAFETY: MXCSR access only changes the floating-point mode of this thread.76 unsafe {77 std::arch::asm!("stmxcsr [{}]", in(reg) &mut saved);78 let new = saved | 0x8040;79 std::arch::asm!("ldmxcsr [{}]", in(reg) &new);80 }81 DenormalGuard { saved: saved as u64 }82 }83 #[cfg(not(any(target_arch = "aarch64", target_arch = "x86_64")))]84 {85 DenormalGuard { saved: 0 }86 }87 }88}8990impl Drop for DenormalGuard {91 #[inline]92 fn drop(&mut self) {93 #[cfg(target_arch = "aarch64")]94 // SAFETY: restores the mode saved in `new`.95 unsafe {96 std::arch::asm!("msr fpcr, {}", in(reg) self.saved);97 }98 #[cfg(target_arch = "x86_64")]99 // SAFETY: restores the mode saved in `new`.100 unsafe {101 let v = self.saved as u32;102 std::arch::asm!("ldmxcsr [{}]", in(reg) &v);103 }104 }105}106107/// Rational tanh approximation (Padé 7/6 clamped), |error| < 2e-3 on the real line, exact limits ±1.108#[inline]109pub fn fast_tanh(x: f32) -> f32 {110 let x = x.clamp(-4.97, 4.97);111 let x2 = x * x;112 let n = x * (135135.0 + x2 * (17325.0 + x2 * (378.0 + x2)));113 let d = 135135.0 + x2 * (62370.0 + x2 * (3150.0 + x2 * 28.0));114 (n / d).clamp(-1.0, 1.0)115}116117/// Cubic soft clipper: linear near 0, reaches ±1 at |x| >= 1.5 with a continuous first derivative.118#[inline]119pub fn soft_clip(x: f32) -> f32 {120 let x = x.clamp(-1.5, 1.5);121 x - (4.0 / 27.0) * x * x * x122}123124/// One-pole exponential smoother for parameters (time constant in seconds).125#[derive(Clone, Copy, Debug)]126pub struct OnePoleSmoother {127 coef: f32,128 value: f32,129 target: f32,130}131132impl OnePoleSmoother {133 pub fn new(value: f32, time_sec: f32, sample_rate: f32) -> Self {134 let mut s = OnePoleSmoother { coef: 0.0, value, target: value };135 s.set_time(time_sec, sample_rate);136 s137 }138 pub fn set_time(&mut self, time_sec: f32, sample_rate: f32) {139 self.coef = if time_sec <= 0.0 { 0.0 } else { (-1.0 / (time_sec * sample_rate)).exp() };140 }141 #[inline]142 pub fn set_target(&mut self, t: f32) {143 self.target = t;144 }145 pub fn snap(&mut self, v: f32) {146 self.value = v;147 self.target = v;148 }149 #[inline]150 pub fn tick(&mut self) -> f32 {151 self.value = self.target + (self.value - self.target) * self.coef;152 self.value153 }154 /// Advances `n` samples at once (control-rate use).155 #[inline]156 pub fn advance(&mut self, n: usize) -> f32 {157 self.value = self.target + (self.value - self.target) * self.coef.powi(n as i32);158 self.value159 }160 pub fn value(&self) -> f32 {161 self.value162 }163 pub fn target(&self) -> f32 {164 self.target165 }166}167168/// Linear ramp smoother: reaches the target in exactly `ramp` samples.169#[derive(Clone, Copy, Debug)]170pub struct LinearSmoother {171 value: f32,172 target: f32,173 step: f32,174 remaining: u32,175 ramp: u32,176}177178impl LinearSmoother {179 pub fn new(value: f32, time_sec: f32, sample_rate: f32) -> Self {180 LinearSmoother { value, target: value, step: 0.0, remaining: 0, ramp: ((time_sec * sample_rate) as u32).max(1) }181 }182 pub fn set_target(&mut self, t: f32) {183 if t != self.target {184 self.target = t;185 self.remaining = self.ramp;186 self.step = (t - self.value) / self.ramp as f32;187 }188 }189 pub fn snap(&mut self, v: f32) {190 self.value = v;191 self.target = v;192 self.remaining = 0;193 }194 #[inline]195 pub fn tick(&mut self) -> f32 {196 if self.remaining > 0 {197 self.remaining -= 1;198 self.value = if self.remaining == 0 { self.target } else { self.value + self.step };199 }200 self.value201 }202 pub fn is_settled(&self) -> bool {203 self.remaining == 0204 }205 pub fn value(&self) -> f32 {206 self.value207 }208}209210/// SplitMix64: seeding and decorrelated streams.211#[derive(Clone, Copy, Debug)]212pub struct SplitMix64(pub u64);213214impl SplitMix64 {215 #[inline]216 pub fn next_u64(&mut self) -> u64 {217 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);218 let mut z = self.0;219 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);220 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);221 z ^ (z >> 31)222 }223}224225/// xorshift32 noise generator for audio-rate use. Never yields a zero state.226#[derive(Clone, Copy, Debug)]227pub struct Rng(u32);228229impl Rng {230 pub fn new(seed: u64) -> Rng {231 let s = SplitMix64(seed).next_u64() as u32;232 Rng(if s == 0 { 0x6D2B_79F5 } else { s })233 }234 #[inline]235 pub fn next_u32(&mut self) -> u32 {236 let mut x = self.0;237 x ^= x << 13;238 x ^= x >> 17;239 x ^= x << 5;240 self.0 = x;241 x242 }243 /// Uniform in [0, 1).244 #[inline]245 pub fn unipolar(&mut self) -> f32 {246 (self.next_u32() >> 8) as f32 * (1.0 / 16_777_216.0)247 }248 /// Uniform in [-1, 1).249 #[inline]250 pub fn bipolar(&mut self) -> f32 {251 self.unipolar() * 2.0 - 1.0252 }253}254255/// Circular delay line with a power-of-two buffer.256///257/// Convention: `read*(d)` called **before** `write` in a tick returns the sample written `d` ticks258/// earlier (`d >= 1`); a loop `y = read(d); write(f(y))` therefore has a total delay of `d` samples.259#[derive(Clone, Debug)]260pub struct DelayLine {261 buf: Vec<f32>,262 mask: usize,263 w: usize,264}265266impl DelayLine {267 /// Allocates room for delays up to `max_delay` samples (plus interpolation margin).268 pub fn new(max_delay: usize) -> DelayLine {269 let size = (max_delay + 4).next_power_of_two().max(8);270 DelayLine { buf: vec![0.0; size], mask: size - 1, w: 0 }271 }272 pub fn capacity(&self) -> usize {273 self.buf.len() - 4274 }275 pub fn clear(&mut self) {276 self.buf.iter_mut().for_each(|x| *x = 0.0);277 }278 #[inline]279 pub fn write(&mut self, x: f32) {280 self.buf[self.w] = x;281 self.w = (self.w + 1) & self.mask;282 }283 #[inline]284 pub fn read_int(&self, d: usize) -> f32 {285 self.buf[(self.w.wrapping_sub(d)) & self.mask]286 }287 /// Linear interpolation.288 #[inline]289 pub fn read(&self, d: f32) -> f32 {290 let d = d.max(1.0);291 let i = d as usize;292 let f = d - i as f32;293 let a = self.read_int(i);294 let b = self.read_int(i + 1);295 a + (b - a) * f296 }297 /// 4-point, 3rd-order Lagrange interpolation (flatter magnitude than linear); `d >= 2`.298 #[inline]299 pub fn read_cubic(&self, d: f32) -> f32 {300 let d = d.max(2.0);301 let i = d as usize;302 let f = d - i as f32;303 let xm1 = self.read_int(i - 1);304 let x0 = self.read_int(i);305 let x1 = self.read_int(i + 1);306 let x2 = self.read_int(i + 2);307 let c0 = -f * (f - 1.0) * (f - 2.0) / 6.0;308 let c1 = (f + 1.0) * (f - 1.0) * (f - 2.0) / 2.0;309 let c2 = -(f + 1.0) * f * (f - 2.0) / 2.0;310 let c3 = (f + 1.0) * f * (f - 1.0) / 6.0;311 xm1 * c0 + x0 * c1 + x1 * c2 + x2 * c3312 }313}314315/// Delay with first-order allpass fractional interpolation: unity magnitude at every frequency,316/// which keeps a waveguide loop's decay independent of the tuning. Not suited to fast modulation.317#[derive(Clone, Debug)]318pub struct AllpassDelay {319 line: DelayLine,320 int: usize,321 eta: f32,322 x1: f32,323 y1: f32,324}325326impl AllpassDelay {327 pub fn new(max_delay: usize) -> AllpassDelay {328 AllpassDelay { line: DelayLine::new(max_delay + 2), int: 1, eta: 0.0, x1: 0.0, y1: 0.0 }329 }330 pub fn clear(&mut self) {331 self.line.clear();332 self.x1 = 0.0;333 self.y1 = 0.0;334 }335 /// Total delay in samples (`>= 1.1`). The fractional part is kept in [0.1, 1.1) for a stable, well-conditioned allpass.336 pub fn set_delay(&mut self, d: f32) {337 let d = d.clamp(1.1, self.line.capacity() as f32);338 let mut int = (d - 0.1).floor() as usize;339 let mut frac = d - int as f32;340 if frac < 0.1 {341 int -= 1;342 frac += 1.0;343 }344 self.int = int.max(1);345 self.eta = (1.0 - frac) / (1.0 + frac);346 }347 /// Reads the delayed sample; call before `write` in the same tick.348 #[inline]349 pub fn read(&mut self) -> f32 {350 let x = self.line.read_int(self.int);351 let y = self.eta * (x - self.y1) + self.x1;352 self.x1 = x;353 self.y1 = flush(y);354 y355 }356 #[inline]357 pub fn write(&mut self, x: f32) {358 self.line.write(x);359 }360}361362/// First-order DC blocker, -3 dB at `cutoff_hz` (default use: 10-20 Hz).363#[derive(Clone, Copy, Debug)]364pub struct DcBlocker {365 r: f32,366 x1: f32,367 y1: f32,368}369370impl DcBlocker {371 pub fn new(cutoff_hz: f32, sample_rate: f32) -> DcBlocker {372 DcBlocker { r: 1.0 - TAU * cutoff_hz / sample_rate, x1: 0.0, y1: 0.0 }373 }374 pub fn reset(&mut self) {375 self.x1 = 0.0;376 self.y1 = 0.0;377 }378 #[inline]379 pub fn tick(&mut self, x: f32) -> f32 {380 let y = x - self.x1 + self.r * self.y1;381 self.x1 = x;382 self.y1 = flush(y);383 y384 }385}386387/// Amplitude of the sinusoidal component at `freq` (Goertzel over the whole slice, Hann windowed).388/// A full-scale sine at `freq` measures 1.0. Measurement helper for tests and calibration.389pub fn goertzel_amplitude(signal: &[f32], freq: f32, sample_rate: f32) -> f32 {390 let n = signal.len();391 if n == 0 {392 return 0.0;393 }394 let w = std::f64::consts::TAU * freq as f64 / sample_rate as f64;395 let (mut re, mut im, mut wsum) = (0.0f64, 0.0f64, 0.0f64);396 for (i, &x) in signal.iter().enumerate() {397 let win = 0.5 - 0.5 * (std::f64::consts::TAU * i as f64 / n as f64).cos();398 let ph = w * i as f64;399 re += x as f64 * win * ph.cos();400 im -= x as f64 * win * ph.sin();401 wsum += win;402 }403 (2.0 * (re * re + im * im).sqrt() / wsum) as f32404}405406/// Fundamental frequency estimate by normalised autocorrelation with parabolic refinement,407/// searched in `[lo_hz, hi_hz]`. Returns `None` for silence. Measurement helper (not real-time).408pub fn estimate_f0(signal: &[f32], sample_rate: f32, lo_hz: f32, hi_hz: f32) -> Option<f32> {409 let min_lag = (sample_rate / hi_hz).floor().max(2.0) as usize;410 let max_lag = (sample_rate / lo_hz).ceil() as usize;411 if signal.len() < max_lag * 2 + 2 {412 return None;413 }414 let corr = |lag: usize| -> f64 {415 let n = signal.len() - lag;416 let (mut c, mut e0, mut e1) = (0.0f64, 0.0f64, 0.0f64);417 for i in 0..n {418 c += signal[i] as f64 * signal[i + lag] as f64;419 e0 += (signal[i] as f64).powi(2);420 e1 += (signal[i + lag] as f64).powi(2);421 }422 c / (e0 * e1).sqrt().max(1e-30)423 };424 if signal.iter().map(|x| (*x as f64).powi(2)).sum::<f64>() < 1e-12 {425 return None;426 }427 let refine = |k: usize, a: f64, b: f64, c: f64| -> f64 {428 let denom = a - 2.0 * b + c;429 k as f64 + if denom.abs() > 1e-12 { (0.5 * (a - c) / denom).clamp(-1.0, 1.0) } else { 0.0 }430 };431 let vals: Vec<f64> = (min_lag - 1..=max_lag + 1).map(corr).collect();432 let best = vals[1..vals.len() - 1].iter().cloned().fold(f64::MIN, f64::max);433 // First local maximum close to the global one: avoids octave-down errors.434 let mut k = 0;435 for i in 1..vals.len() - 1 {436 if vals[i] >= 0.97 * best && vals[i] >= vals[i - 1] && vals[i] >= vals[i + 1] {437 k = i;438 break;439 }440 }441 if k == 0 {442 return None;443 }444 let mut lag = refine(min_lag - 1 + k, vals[k - 1], vals[k], vals[k + 1]);445 // Refine on multiples of the period: the interpolation bias is divided by the multiple.446 for m in [2usize, 4, 8, 16] {447 let centre = (lag * m as f64).round() as usize;448 if centre + 4 >= signal.len() / 2 {449 break;450 }451 let local: Vec<f64> = (centre - 3..=centre + 3).map(corr).collect();452 let mut j = 3;453 for i in 1..6 {454 if local[i] > local[j] {455 j = i;456 }457 }458 if local[j] < 0.5 * best {459 break;460 }461 lag = refine(centre - 3 + j, local[j - 1], local[j], local[j + 1]) / m as f64;462 }463 Some((sample_rate as f64 / lag) as f32)464}465466/// Interval in cents from `reference` to `measured`.467pub fn cents(measured: f32, reference: f32) -> f32 {468 1200.0 * (measured / reference).log2()469}470471#[cfg(test)]472mod tests {473 use super::*;474475 #[test]476 fn conversions() {477 assert!((db_to_lin(-6.0206) - 0.5).abs() < 1e-4);478 assert!((lin_to_db(0.5) + 6.0206).abs() < 1e-3);479 assert!((midi_to_hz(69.0, 440.0) - 440.0).abs() < 1e-3);480 assert!((hz_to_midi(880.0, 440.0) - 81.0).abs() < 1e-4);481 assert_eq!(flush(1e-30), 0.0);482 assert_eq!(flush(f32::NAN), 0.0);483 assert_eq!(flush(0.5), 0.5);484 }485486 #[test]487 fn tanh_accuracy_and_clip() {488 let mut worst = 0.0f32;489 for i in -1000..=1000 {490 let x = i as f32 * 0.01;491 worst = worst.max((fast_tanh(x) - x.tanh()).abs());492 }493 assert!(worst < 2e-3, "worst {worst}");494 assert_eq!(soft_clip(10.0), 1.0);495 assert_eq!(soft_clip(-10.0), -1.0);496 }497498 #[test]499 fn smoothers_reach_target() {500 let mut s = OnePoleSmoother::new(0.0, 0.01, 48_000.0);501 s.set_target(1.0);502 for _ in 0..480 {503 s.tick();504 }505 assert!((s.value() - (1.0 - (-1.0f32).exp())).abs() < 1e-3);506 let mut l = LinearSmoother::new(0.0, 0.001, 48_000.0);507 l.set_target(2.0);508 let mut v = 0.0;509 for _ in 0..48 {510 v = l.tick();511 }512 assert_eq!(v, 2.0);513 assert!(l.is_settled());514 }515516 #[test]517 fn delay_conventions_and_interpolation() {518 let mut d = DelayLine::new(64);519 let mut out = Vec::new();520 for i in 0..40 {521 out.push(d.read_int(10));522 d.write(if i == 0 { 1.0 } else { 0.0 });523 }524 assert_eq!(out.iter().position(|x| *x == 1.0), Some(10));525 let mut d = DelayLine::new(64);526 for i in 0..32 {527 d.write(i as f32);528 }529 // Ramp: last written is 31 at d=1; d=2.5 -> 29.5 for linear and cubic.530 assert!((d.read(2.5) - 29.5).abs() < 1e-5);531 assert!((d.read_cubic(2.5) - 29.5).abs() < 1e-4);532 }533534 #[test]535 fn allpass_delay_tunes_a_loop() {536 // A lossless loop of total delay D resonates at sr/D: check with f0 estimation.537 let sr = 48_000.0;538 for target in [220.0f32, 441.3, 1000.7] {539 let mut ap = AllpassDelay::new(1024);540 ap.set_delay(sr / target);541 let mut rng = Rng::new(1);542 let mut sig = Vec::with_capacity(24_000);543 for i in 0..24_000 {544 let y = ap.read();545 let x = if i < 200 { rng.bipolar() } else { 0.0 };546 ap.write(x + 0.999 * y);547 sig.push(y);548 }549 let f = estimate_f0(&sig[4000..], sr, target * 0.9, target * 1.1).unwrap();550 assert!(cents(f, target).abs() < 2.0, "target {target} got {f}");551 }552 }553554 #[test]555 fn dc_blocker_removes_offset() {556 let mut b = DcBlocker::new(20.0, 48_000.0);557 let mut y = 1.0;558 for _ in 0..48_000 {559 y = b.tick(1.0);560 }561 assert!(y.abs() < 1e-3);562 }563564 #[test]565 fn goertzel_and_rng() {566 let sr = 48_000.0;567 let sig: Vec<f32> = (0..9600).map(|i| 0.5 * (TAU * 1000.0 * i as f32 / sr).sin()).collect();568 assert!((goertzel_amplitude(&sig, 1000.0, sr) - 0.5).abs() < 0.005);569 assert!(goertzel_amplitude(&sig, 3000.0, sr) < 1e-3);570 let (mut a, mut b) = (Rng::new(7), Rng::new(7));571 let mut mean = 0.0;572 for _ in 0..10_000 {573 let v = a.bipolar();574 assert_eq!(v, b.bipolar());575 assert!((-1.0..1.0).contains(&v));576 mean += v;577 }578 assert!((mean / 10_000.0).abs() < 0.03);579 }580581 #[test]582 fn denormal_guard_flushes() {583 let _g = DenormalGuard::new();584 let tiny = std::hint::black_box(1e-38f32);585 let r = std::hint::black_box(tiny * std::hint::black_box(1e-5f32));586 assert_eq!(r, 0.0);587 }588}589