rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Global room reverb: an 8-line feedback delay network (FDN).
//!
//! Every channel sends part of its signal here (MIDI CC91, default 40 as in
//! GM2/GS); the wet output is mixed back into the master bus. Structure:
//!
//! ```text
//! send ─ pre-delay ─ 4 series all-pass diffusers ─┬─► 8 delay lines ─┬─► L/R taps
//!                                                 └─ Householder ◄──┘
//!                                                    feedback, damped
//! ```
//!
//! - **Pre-delay** separates the dry sound from the room, as in a real hall.
//! - **Diffusers** smear the input into a dense cloud before it enters the
//!   loop, standing in for the early reflections.
//! - **Delay lines** have mutually prime lengths (30–73 ms) so their echoes
//!   never line up. Each is slowly modulated by a fraction of a millisecond,
//!   which breaks up the metallic ringing a static FDN gets on sustained tones
//!   such as piano tails.
//! - **Feedback** goes through a Householder matrix (lossless and maximally
//!   mixing, O(N)), then a per-line gain sets the mid-band RT60 and a one-pole
//!   low-pass in each line makes the highs die away faster, as air and
//!   absorbent surfaces do.
//! - **Output** taps the lines with two orthogonal sign patterns for a wide,
//!   decorrelated stereo image.
//!
//! The reverb is fully deterministic, so offline renders stay reproducible.

/// Mid-band reverberation time in seconds.
const RT60: f32 = 1.9;
/// Pre-delay in seconds.
const PREDELAY: f32 = 0.018;
/// Corner of the in-loop damping low-pass (Hz): higher = brighter tail.
const DAMP_HZ: f32 = 7_000.0;
/// Wet output level for a send of 1.0. Calibrated so that at the GM default
/// send (CC91 = 40) the reverb sits ~15 dB below the dry signal while notes
/// sound, about where FluidSynth's default reverb sits.
const WET: f32 = 0.8;

const N: usize = 8;
/// Delay-line lengths in samples at 44.1 kHz (scaled to the actual rate).
const LINE_SAMPLES_44K: [f32; N] = [
  1327.0, 1601.0, 1867.0, 2053.0, 2311.0, 2633.0, 2903.0, 3209.0,
];
/// Modulation depth in samples at 44.1 kHz and per-line rates in Hz.
const MOD_DEPTH_44K: f32 = 7.0;
const MOD_RATES: [f32; N] = [0.13, 0.21, 0.29, 0.37, 0.43, 0.53, 0.61, 0.71];
/// Diffuser all-pass lengths (samples at 44.1 kHz) and coefficient.
const DIFFUSER_SAMPLES_44K: [f32; 4] = [210.0, 158.0, 561.0, 410.0];
const DIFFUSION: f32 = 0.65;

const IN_SIGNS: [f32; N] = [1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0];
const OUT_L: [f32; N] = [1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0];
const OUT_R: [f32; N] = [1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, -1.0];

#[derive(Clone, Debug)]
struct Delay {
  buf: Vec<f32>,
  pos: usize,
}

impl Delay {
  fn new(len: usize) -> Self {
    Self {
      buf: vec![0.0; len.max(1)],
      pos: 0,
    }
  }

  /// Read the sample written `delay` samples ago (fractional, linear interp).
  #[inline]
  fn read(&self, delay: f32) -> f32 {
    let len = self.buf.len();
    let d = delay.clamp(1.0, (len - 1) as f32);
    let i = d.floor();
    let frac = d - i;
    let a = self.buf[(self.pos + len - i as usize) % len];
    let b = self.buf[(self.pos + len - i as usize - 1) % len];
    a + (b - a) * frac
  }

  #[inline]
  fn write(&mut self, x: f32) {
    self.pos += 1;
    if self.pos == self.buf.len() {
      self.pos = 0;
    }
    self.buf[self.pos] = x;
  }
}

/// Lattice all-pass: flat magnitude, smeared phase.
#[derive(Clone, Debug)]
struct Allpass {
  delay: Delay,
  len: f32,
}

impl Allpass {
  #[inline]
  fn process(&mut self, x: f32) -> f32 {
    let d = self.delay.read(self.len);
    let v = x - DIFFUSION * d;
    self.delay.write(v);
    d + DIFFUSION * v
  }
}

#[derive(Clone, Debug)]
pub struct Reverb {
  predelay: Delay,
  predelay_len: f32,
  diffusers: Vec<Allpass>,
  lines: Vec<Delay>,
  line_len: [f32; N],
  gains: [f32; N],
  lp: [f32; N],
  damp: f32,
  mod_depth: f32,
  phase: [f32; N],
  phase_inc: [f32; N],
}

impl Reverb {
  pub fn new(sr: f32) -> Self {
    let scale = sr / 44_100.0;
    let mod_depth = MOD_DEPTH_44K * scale;
    let mut line_len = [0.0; N];
    let mut gains = [0.0; N];
    let mut lines = Vec::with_capacity(N);
    let mut phase = [0.0; N];
    let mut phase_inc = [0.0; N];
    for i in 0..N {
      let len = LINE_SAMPLES_44K[i] * scale;
      line_len[i] = len;
      // -60 dB after RT60 seconds: per pass of `len` samples.
      gains[i] = 10f32.powf(-3.0 * len / (RT60 * sr));
      lines.push(Delay::new((len + mod_depth) as usize + 4));
      phase[i] = i as f32 / N as f32; // spread the LFOs apart
      phase_inc[i] = MOD_RATES[i] / sr;
    }
    let diffusers = DIFFUSER_SAMPLES_44K
      .iter()
      .map(|&l| {
        let len = l * scale;
        Allpass {
          delay: Delay::new(len as usize + 2),
          len,
        }
      })
      .collect();
    let predelay_len = PREDELAY * sr;
    Self {
      predelay: Delay::new(predelay_len as usize + 2),
      predelay_len,
      diffusers,
      lines,
      line_len,
      gains,
      lp: [0.0; N],
      damp: (-std::f32::consts::TAU * DAMP_HZ / sr).exp(),
      mod_depth,
      phase,
      phase_inc,
    }
  }

  /// Run the interleaved-stereo `send` bus through the room and add the wet
  /// signal to `out` (same layout).
  // The per-line loops walk several parallel N-element arrays in lockstep;
  // one index reads more clearly than a five-way zip.
  #[allow(clippy::needless_range_loop)]
  pub fn process(&mut self, send: &[f32], out: &mut [f32]) {
    let in_gain = 1.0 / (N as f32).sqrt();
    let out_gain = WET / (N as f32).sqrt();
    for (s, o) in send
      .as_chunks::<2>()
      .0
      .iter()
      .zip(out.as_chunks_mut::<2>().0.iter_mut())
    {
      let x = 0.5 * (s[0] + s[1]);
      self.predelay.write(x);
      let mut d = self.predelay.read(self.predelay_len);
      for ap in &mut self.diffusers {
        d = ap.process(d);
      }

      let mut taps = [0.0f32; N];
      for i in 0..N {
        self.phase[i] += self.phase_inc[i];
        if self.phase[i] >= 1.0 {
          self.phase[i] -= 1.0;
        }
        let m = (self.phase[i] * std::f32::consts::TAU).sin() * self.mod_depth;
        taps[i] = self.lines[i].read(self.line_len[i] + m);
      }

      // Damping low-pass, then Householder feedback: y = x − (2/N)·Σx.
      for i in 0..N {
        self.lp[i] = taps[i] + self.damp * (self.lp[i] - taps[i]);
      }
      let mix = self.lp.iter().sum::<f32>() * (2.0 / N as f32);
      for i in 0..N {
        let fb = (self.lp[i] - mix) * self.gains[i];
        self.lines[i].write(fb + d * IN_SIGNS[i] * in_gain);
      }

      let (mut l, mut r) = (0.0, 0.0);
      for i in 0..N {
        l += taps[i] * OUT_L[i];
        r += taps[i] * OUT_R[i];
      }
      o[0] += l * out_gain;
      o[1] += r * out_gain;
    }
  }
}

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

  const SR: f32 = 44_100.0;

  fn impulse_response(secs: f32) -> Vec<f32> {
    let mut rv = Reverb::new(SR);
    let n = (secs * SR) as usize;
    let mut send = vec![0.0; n * 2];
    send[0] = 1.0;
    send[1] = 1.0;
    let mut out = vec![0.0; n * 2];
    rv.process(&send, &mut out);
    out
  }

  fn energy(x: &[f32]) -> f32 {
    x.iter().map(|v| v * v).sum()
  }

  #[test]
  fn tail_starts_after_predelay_and_decays_at_rt60() {
    let ir = impulse_response(3.0);
    let pre = (PREDELAY * SR) as usize * 2;
    assert!(energy(&ir[..pre]) == 0.0, "output before the pre-delay");

    // Energy in 0.2 s windows starting at 0.3 s and 1.3 s: one second apart,
    // so the drop should be about 60/RT60 dB.
    let w = |t: f32| {
      let a = (t * SR) as usize * 2;
      energy(&ir[a..a + (0.2 * SR) as usize * 2])
    };
    let drop_db = 10.0 * (w(0.3) / w(1.3)).log10();
    let expected = 60.0 / RT60;
    assert!(
      (drop_db - expected).abs() < 0.35 * expected,
      "decayed {drop_db:.1} dB in 1 s, expected ~{expected:.1}"
    );
  }

  #[test]
  fn stereo_output_is_decorrelated() {
    let ir = impulse_response(1.0);
    let (mut lr, mut ll, mut rr) = (0.0f64, 0.0f64, 0.0f64);
    for f in ir.chunks_exact(2) {
      lr += (f[0] * f[1]) as f64;
      ll += (f[0] * f[0]) as f64;
      rr += (f[1] * f[1]) as f64;
    }
    let corr = lr / (ll * rr).sqrt();
    assert!(corr.abs() < 0.3, "L/R correlation {corr:.2}");
  }

  #[test]
  fn silence_in_silence_out() {
    let mut rv = Reverb::new(SR);
    let send = vec![0.0; 4096];
    let mut out = vec![0.0; 4096];
    rv.process(&send, &mut out);
    assert!(out.iter().all(|&v| v == 0.0));
  }
}