rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Building blocks shared by the self-oscillating digital-waveguide models
//! (bowed strings in `bowed.rs`, reeds/lips/air jets in `wind.rs`).

use std::f32::consts::TAU;

/// Delay line with a fractional, modulatable read position (cubic Hermite
/// interpolation: flat to well above the fundamental and no phase error at
/// low frequencies, so a loop stays in tune while vibrato moves the delay).
#[derive(Clone, Debug)]
pub struct Delay {
  buf: Vec<f32>,
  mask: usize,
  w: usize,
}

impl Delay {
  /// A delay able to hold at least `max` samples.
  pub fn new(max: f32) -> Self {
    let len = ((max.max(4.0) as usize) + 4).next_power_of_two();
    Self {
      buf: vec![0.0; len],
      mask: len - 1,
      w: 0,
    }
  }

  /// Longest delay `read` supports.
  pub fn max_delay(&self) -> f32 {
    (self.buf.len() - 3) as f32
  }

  /// Read before this tick's `write`: the input from `d` ticks ago
  /// (`d` ≥ 2; the most recent write is 1).
  #[inline]
  pub fn read(&self, d: f32) -> f32 {
    let d = d.clamp(2.0, self.max_delay()) - 1.0;
    let i = d as usize;
    let t = d - i as f32;
    let at = |k: usize| self.buf[(self.w.wrapping_sub(k)) & self.mask];
    // at(k) is the input from k+1 ticks ago; interpolate between at(i) and
    // at(i+1) with their outer neighbours.
    let (xm1, x0, x1, x2) = (at(i - 1), at(i), at(i + 1), at(i + 2));
    let c1 = 0.5 * (x1 - xm1);
    let c2 = xm1 - 2.5 * x0 + 2.0 * x1 - 0.5 * x2;
    let c3 = 0.5 * (x2 - xm1) + 1.5 * (x0 - x1);
    ((c3 * t + c2) * t + c1) * t + x0
  }

  #[inline]
  pub fn write(&mut self, x: f32) {
    self.w = (self.w + 1) & self.mask;
    self.buf[self.w] = x;
  }
}

/// Unity-DC one-pole low-pass y = (1−a)·x + a·y₋₁: the frequency-dependent
/// loss of a string or bore, lumped at one reflection.
#[derive(Clone, Copy, Debug, Default)]
pub struct OnePole {
  a: f32,
  y1: f32,
}

impl OnePole {
  pub fn new(a: f32) -> Self {
    Self {
      a: a.clamp(0.0, 0.999),
      y1: 0.0,
    }
  }

  /// Low-pass with its −3 dB point at `hz`.
  pub fn corner(hz: f32, sr: f32) -> Self {
    Self::new((-TAU * hz.max(1.0) / sr).exp())
  }

  #[inline]
  pub fn tick(&mut self, x: f32) -> f32 {
    self.y1 = (1.0 - self.a) * x + self.a * self.y1;
    self.y1
  }

  /// Magnitude at `hz`.
  pub fn gain(&self, hz: f32, sr: f32) -> f32 {
    let w = TAU * hz / sr;
    let one = 1.0 - self.a;
    one / (one * one + 2.0 * self.a * (1.0 - w.cos())).sqrt()
  }

  /// Phase delay in samples at `hz`.
  pub fn delay(&self, hz: f32, sr: f32) -> f32 {
    let w = TAU * hz / sr;
    let phase = (self.a * w.sin()).atan2(1.0 - self.a * w.cos());
    phase / w
  }
}

/// DC blocker (first-order high-pass at ~`hz`).
#[derive(Clone, Copy, Debug)]
pub struct DcBlock {
  r: f32,
  x1: f32,
  y1: f32,
}

impl DcBlock {
  pub fn new(hz: f32, sr: f32) -> Self {
    Self {
      r: 1.0 - TAU * hz / sr,
      x1: 0.0,
      y1: 0.0,
    }
  }

  #[inline]
  pub fn tick(&mut self, x: f32) -> f32 {
    let y = x - self.x1 + self.r * self.y1;
    self.x1 = x;
    self.y1 = y;
    y
  }
}

/// Direct-form-I biquad.
#[derive(Clone, Copy, Debug)]
pub struct Biquad {
  b0: f32,
  b1: f32,
  b2: f32,
  a1: f32,
  a2: f32,
  x1: f32,
  x2: f32,
  y1: f32,
  y2: f32,
}

impl Biquad {
  fn from(b: [f32; 3], a: [f32; 3]) -> Self {
    Self {
      b0: b[0] / a[0],
      b1: b[1] / a[0],
      b2: b[2] / a[0],
      a1: a[1] / a[0],
      a2: a[2] / a[0],
      x1: 0.0,
      x2: 0.0,
      y1: 0.0,
      y2: 0.0,
    }
  }

  fn w(hz: f32, sr: f32) -> f32 {
    TAU * hz.clamp(10.0, sr * 0.45) / sr
  }

  /// RBJ peaking EQ: `db` of boost/cut at `hz` with quality `q`.
  pub fn peak(hz: f32, q: f32, db: f32, sr: f32) -> Self {
    let w = Self::w(hz, sr);
    let a = 10f32.powf(db / 40.0);
    let al = w.sin() / (2.0 * q);
    let c = w.cos();
    Self::from(
      [1.0 + al * a, -2.0 * c, 1.0 - al * a],
      [1.0 + al / a, -2.0 * c, 1.0 - al / a],
    )
  }

  pub fn lowpass(hz: f32, q: f32, sr: f32) -> Self {
    let w = Self::w(hz, sr);
    let al = w.sin() / (2.0 * q);
    let c = w.cos();
    Self::from(
      [(1.0 - c) / 2.0, 1.0 - c, (1.0 - c) / 2.0],
      [1.0 + al, -2.0 * c, 1.0 - al],
    )
  }

  pub fn highpass(hz: f32, q: f32, sr: f32) -> Self {
    let w = Self::w(hz, sr);
    let al = w.sin() / (2.0 * q);
    let c = w.cos();
    Self::from(
      [(1.0 + c) / 2.0, -(1.0 + c), (1.0 + c) / 2.0],
      [1.0 + al, -2.0 * c, 1.0 - al],
    )
  }

  /// RBJ band-pass with 0 dB gain at its centre `hz`.
  pub fn bandpass(hz: f32, q: f32, sr: f32) -> Self {
    let w = Self::w(hz, sr);
    let al = w.sin() / (2.0 * q);
    Self::from([al, 0.0, -al], [1.0 + al, -2.0 * w.cos(), 1.0 - al])
  }

  /// Complex frequency response (re, im) at `hz`.
  pub fn response(&self, hz: f32, sr: f32) -> (f32, f32) {
    let w = TAU * hz / sr;
    let (c1, s1, c2, s2) =
      (w.cos(), -w.sin(), (2.0 * w).cos(), -(2.0 * w).sin());
    let (nr, ni) = (
      self.b0 + self.b1 * c1 + self.b2 * c2,
      self.b1 * s1 + self.b2 * s2,
    );
    let (dr, di) = (
      1.0 + self.a1 * c1 + self.a2 * c2,
      self.a1 * s1 + self.a2 * s2,
    );
    let d = dr * dr + di * di;
    ((nr * dr + ni * di) / d, (ni * dr - nr * di) / d)
  }

  /// Unity-peak two-pole resonator with poles at radius `r` (a mass-spring:
  /// a lip or a reed); zeros at DC and Nyquist.
  pub fn reson(hz: f32, r: f32, sr: f32) -> Self {
    let w = Self::w(hz, sr);
    let g = 0.5 * (1.0 - r * r);
    Self::from([g, 0.0, -g], [1.0, -2.0 * r * w.cos(), r * r])
  }

  /// Retune a `reson` in place, keeping its state.
  pub fn set_reson(&mut self, hz: f32, r: f32, sr: f32) {
    let n = Self::reson(hz, r, sr);
    (self.b0, self.b1, self.b2, self.a1, self.a2) =
      (n.b0, n.b1, n.b2, n.a1, n.a2);
  }

  /// Retune as a unity-DC-gain resonator (a driven mass-spring with
  /// damping set by pole radius `r`), keeping its state.
  pub fn set_lip(&mut self, hz: f32, r: f32, sr: f32) {
    let c = 2.0 * r * Self::w(hz, sr).cos();
    self.a1 = -c;
    self.a2 = r * r;
    self.b0 = 0.0;
    self.b1 = 1.0 - c + r * r;
    self.b2 = 0.0;
  }

  /// Current output (the resonator's displacement).
  pub fn state(&self) -> f32 {
    // Next output given no new input beyond what is already latched.
    self.b1 * self.x1 - self.a1 * self.y1 - self.a2 * self.y2
  }

  #[inline]
  pub fn tick(&mut self, x: f32) -> f32 {
    let y = self.b0 * x + self.b1 * self.x1 + self.b2 * self.x2
      - self.a1 * self.y1
      - self.a2 * self.y2;
    self.x2 = self.x1;
    self.x1 = x;
    self.y2 = self.y1;
    self.y1 = y;
    y
  }
}

/// Deterministic white noise in −1..1.
#[derive(Clone, Copy, Debug)]
pub struct Noise(u32);

impl Noise {
  pub fn new(seed: u32) -> Self {
    Self(seed | 1)
  }

  #[inline]
  pub fn tick(&mut self) -> f32 {
    self.0 = self.0.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
    ((self.0 >> 8) as f32 / 8_388_608.0) - 1.0
  }
}

/// Sine LFO with a delayed ramp-in (performer vibrato).
#[derive(Clone, Copy, Debug)]
pub struct Vibrato {
  phase: f32,
  inc: f32,
  depth: f32, // fractional pitch deviation at full depth
  ramp: f32,
  ramp_inc: f32,
  delay: u32,
}

impl Vibrato {
  /// `cents` peak deviation, fading in over 0.3 s after `delay` seconds.
  pub fn new(hz: f32, cents: f32, delay: f32, phase: f32, sr: f32) -> Self {
    Self {
      phase,
      inc: hz / sr,
      depth: 2f32.powf(cents / 1200.0) - 1.0,
      ramp: 0.0,
      ramp_inc: 1.0 / (0.3 * sr),
      delay: (delay * sr) as u32,
    }
  }

  /// Pitch factor deviation (add to 1); `extra` is added depth (mod wheel).
  #[inline]
  pub fn tick(&mut self, extra: f32) -> f32 {
    self.phase += self.inc;
    if self.phase >= 1.0 {
      self.phase -= 1.0;
    }
    if self.delay > 0 {
      self.delay -= 1;
      return 0.0;
    }
    self.ramp = (self.ramp + self.ramp_inc).min(1.0);
    (self.phase * TAU).sin() * (self.depth * self.ramp + extra)
  }
}

/// Exponential approach to a target, for bow speed and breath pressure.
#[derive(Clone, Copy, Debug)]
pub struct Ramp {
  pub value: f32,
  target: f32,
  k: f32,
}

impl Default for Ramp {
  fn default() -> Self {
    Self::new()
  }
}

impl Ramp {
  pub fn new() -> Self {
    Self {
      value: 0.0,
      target: 0.0,
      k: 0.0,
    }
  }

  /// Head for `target`, getting ~95 % of the way there in `time` seconds.
  pub fn go(&mut self, target: f32, time: f32, sr: f32) {
    self.target = target;
    self.k = 1.0 - (-3.0 / (time.max(1e-4) * sr)).exp();
  }

  #[inline]
  pub fn tick(&mut self) -> f32 {
    self.value += self.k * (self.target - self.value);
    self.value
  }
}

/// Pitch factor for MIDI note `note` (fractional semitones allowed).
pub fn note_hz(note: f32) -> f32 {
  440.0 * 2f32.powf((note - 69.0) / 12.0)
}

/// Per-trip loss gain making the fundamental `f` decay 60 dB in `t60` s.
pub fn loop_gain(f: f32, t60: f32) -> f32 {
  (0.001f32)
    .powf(1.0 / (f * t60).max(1e-3))
    .clamp(0.0, 0.999_9)
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn fractional_delay_is_accurate() {
    // A slow sine through a 10.3-sample delay comes out shifted by 10.3.
    let sr = 44_100.0;
    let f = 440.0;
    let mut d = Delay::new(64.0);
    let mut err = 0.0f32;
    for n in 0..2_000 {
      if n > 100 {
        let want = (TAU * f * (n as f32 - 10.3) / sr).sin();
        err = err.max((d.read(10.3) - want).abs());
      }
      d.write((TAU * f * n as f32 / sr).sin());
    }
    assert!(err < 1e-3, "max error {err}");
  }
}