rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Rotating-speaker cabinet (Leslie), applied to a whole channel.
//!
//! A crossover splits the organ into a treble horn and a bass drum (a
//! rotating baffle over the woofer), each spinning at its own speed. As a
//! rotor turns, its distance to each microphone changes — a Doppler pitch
//! swing — and it beams towards and away from the mic, an amplitude and
//! brightness swing. The two rotors run at different speeds and never stay
//! in step, which gives the cabinet its swirl. The rotors have inertia:
//! switching between chorale (slow) and tremolo (fast) makes the light horn
//! catch up in about a second and the heavy drum take several.
//!
//! It is a per-channel effect because a real cabinet is one speaker for all
//! notes; a per-voice vibrato (what this replaces) moves every note in
//! lockstep and sounds like a pitch LFO, not a room full of moving sound.

use crate::synth::waveguide::{Delay, OnePole};
use std::f32::consts::TAU;

#[derive(Clone, Copy, Debug)]
pub struct LeslieSpec {
  /// Start in tremolo (fast) rather than chorale (slow). The mod wheel
  /// (≥ half) switches a slow cabinet to fast.
  pub fast: bool,
}

/// Crossover frequency between drum and horn.
const CROSSOVER_HZ: f32 = 800.0;
/// Rotor speeds (Hz): chorale and tremolo.
const HORN_SLOW: f32 = 0.83;
const HORN_FAST: f32 = 6.75;
const DRUM_SLOW: f32 = 0.67;
const DRUM_FAST: f32 = 5.9;
/// Time constants (s) to spin up / down.
const HORN_UP: f32 = 0.6;
const HORN_DOWN: f32 = 0.9;
const DRUM_UP: f32 = 3.5;
const DRUM_DOWN: f32 = 4.5;
/// Peak Doppler path swing (s): rotor radius / speed of sound.
const HORN_SWING: f32 = 0.15 / 343.0;
const DRUM_SWING: f32 = 0.06 / 343.0;
/// Amplitude swing as the rotor beams towards / away from a mic.
const HORN_AM: f32 = 0.55;
const DRUM_AM: f32 = 0.35;
/// Angle between the two microphones.
const MIC_SPREAD: f32 = 0.6 * std::f32::consts::PI;
/// Fixed part of the path (s), so the swing never needs a negative delay.
const BASE_DELAY: f32 = 0.001;

#[derive(Clone, Debug)]
struct Rotor {
  angle: f32, // turns
  speed: f32, // Hz
  delay: Delay,
  swing: f32, // samples
  am: f32,
  /// Brightness swing: the horn's high end beams more than its mids.
  shade: [OnePole; 2],
}

impl Rotor {
  fn new(speed: f32, swing: f32, am: f32, start: f32, sr: f32) -> Self {
    let swing = swing * sr;
    Self {
      angle: start,
      speed,
      delay: Delay::new(BASE_DELAY * sr + 2.0 * swing + 8.0),
      swing,
      am,
      shade: [OnePole::corner(3_000.0, sr); 2],
    }
  }

  #[inline]
  fn tick(
    &mut self,
    x: f32,
    target: f32,
    k_up: f32,
    k_down: f32,
    sr: f32,
  ) -> (f32, f32) {
    let k = if target > self.speed { k_up } else { k_down };
    self.speed += k * (target - self.speed);
    self.angle += self.speed / sr;
    if self.angle >= 1.0 {
      self.angle -= 1.0;
    }
    let base = BASE_DELAY * sr + self.swing;
    let th = TAU * self.angle;
    let mut out = [0.0; 2];
    for (m, o) in out.iter_mut().enumerate() {
      let c = (th + m as f32 * MIC_SPREAD).cos();
      // Facing the mic (c = 1): shortest path, loudest, brightest.
      let d = self.delay.read(base - self.swing * c);
      let gain = 1.0 + self.am * c;
      let dull = self.shade[m].tick(d);
      let bright = 0.5 + 0.5 * c;
      *o = gain * (dull + bright * (d - dull));
    }
    self.delay.write(x);
    (out[0], out[1])
  }
}

#[derive(Clone, Debug)]
pub struct Leslie {
  sr: f32,
  split: [OnePole; 2],
  horn: Rotor,
  drum: Rotor,
  k: [f32; 4],
}

impl Leslie {
  pub fn new(spec: LeslieSpec, sr: f32) -> Self {
    let (h, d) = if spec.fast {
      (HORN_FAST, DRUM_FAST)
    } else {
      (HORN_SLOW, DRUM_SLOW)
    };
    let k = |t: f32| 1.0 - (-1.0 / (t * sr)).exp();
    Self {
      sr,
      split: [OnePole::corner(CROSSOVER_HZ, sr); 2],
      horn: Rotor::new(h, HORN_SWING, HORN_AM, 0.0, sr),
      drum: Rotor::new(d, DRUM_SWING, DRUM_AM, 0.37, sr),
      k: [k(HORN_UP), k(HORN_DOWN), k(DRUM_UP), k(DRUM_DOWN)],
    }
  }

  /// Process interleaved stereo `buf` in place. The input is folded to mono
  /// (a cabinet has one input); `pan` gains place the cabinet's two mics.
  pub fn process(&mut self, buf: &mut [f32], fast: bool, gl: f32, gr: f32) {
    let (ht, dt) = if fast {
      (HORN_FAST, DRUM_FAST)
    } else {
      (HORN_SLOW, DRUM_SLOW)
    };
    let inv = 1.0 / (gl + gr).max(1e-6);
    let sr = self.sr;
    // The beaming adds up to ~+1.5 dB on average; take it back out.
    let norm = 0.85;
    for f in buf.as_chunks_mut::<2>().0 {
      let x = (f[0] + f[1]) * inv;
      // Second-order crossover; the horn gets the complement so the two
      // bands sum back to the input.
      let lo1 = self.split[0].tick(x);
      let lo = self.split[1].tick(lo1);
      let hi = x - lo;
      let (hl, hr) = self.horn.tick(hi, ht, self.k[0], self.k[1], sr);
      let (dl, dr) = self.drum.tick(lo, dt, self.k[2], self.k[3], sr);
      f[0] = (hl + dl) * norm * gl;
      f[1] = (hr + dr) * norm * gr;
    }
  }
}

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

  /// A steady tone comes out with its level swinging at the horn's rate, and
  /// the two mics swing out of phase (a moving stereo image).
  #[test]
  fn tremolo_moves_the_sound() {
    let sr = 44_100.0;
    let mut l = Leslie::new(LeslieSpec { fast: true }, sr);
    let n = 44_100;
    let mut buf: Vec<f32> = (0..n)
      .flat_map(|i| {
        let s = (TAU * 2_000.0 * i as f32 / sr).sin();
        [s * 0.707, s * 0.707]
      })
      .collect();
    l.process(&mut buf, true, 0.707, 0.707);
    // Envelope per 5 ms window on each side.
    let win = 220;
    let env = |c: usize| -> Vec<f32> {
      buf
        .chunks(win * 2)
        .map(|w| {
          w.iter()
            .skip(c)
            .step_by(2)
            .fold(0f32, |m, x| m.max(x.abs()))
        })
        .collect()
    };
    let (el, er) = (env(0), env(1));
    let (lmax, lmin) = el[20..]
      .iter()
      .fold((0f32, 9f32), |(a, b), &x| (a.max(x), b.min(x)));
    assert!(lmax > 1.5 * lmin, "no tremolo: {lmin}..{lmax}");
    let diff: f32 = el[20..]
      .iter()
      .zip(&er[20..])
      .map(|(a, b)| (a - b).abs())
      .sum::<f32>()
      / (el.len() - 20) as f32;
    assert!(diff > 0.05, "mics move together ({diff})");
  }
}