rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Modal model of a struck bar, tube or tine.
//!
//! Mallet percussion, chimes and tine electric pianos are a handful of
//! decaying sinusoids (the vibration modes of the struck body) whose
//! frequency ratios are what make each instrument recognisable:
//!
//! - wooden bars tuned 1 : 4 : 10 (marimba) or 1 : 3 : 6 (xylophone), with the
//!   upper modes dying much faster than the resonator-supported fundamental;
//! - untuned steel bars at the free-free beam ratios 1 : 2.76 : 5.40 : 8.93
//!   (glockenspiel, celesta);
//! - tubes, whose modes follow (2n+1)² and whose perceived *strike tone* is
//!   an octave below the 4th mode (tubular bells);
//! - a Rhodes tine read by a magnetic pickup: an almost pure tone plus a short
//!   inharmonic "ping", with the pickup's asymmetric nonlinearity adding the
//!   velocity-dependent "bark".
//!
//! Each mode is a complex rotor `z ← z·r·e^{iω}`. The mallet is a low-pass on
//! the mode levels whose corner rises with velocity (soft notes are mellow,
//! hard ones bright) plus a short band-limited contact noise. Modes above
//! ~12 kHz are not synthesized at all — they only add harshness.

use crate::synth::filter::{FilterMode, Svf};
use crate::synth::patches::ModalSpec;

/// Highest mode frequency worth synthesizing.
const MAX_MODE_HZ: f32 = 12_000.0;
/// Velocity (after the squared curve) treated as mezzo-forte.
const MF_VELOCITY: f32 = 0.4;
/// Idle threshold on the summed rotor magnitudes.
const SILENT: f32 = 3e-5;

#[derive(Clone, Debug)]
pub struct Modal {
  re: Vec<f32>,
  im: Vec<f32>,
  cr: Vec<f32>,
  ci: Vec<f32>,
  /// Unbent angular step of each rotor (radians per sample).
  w: Vec<f32>,
  /// Pitch factor the rotors are tuned to, relative to note-on.
  bend: f32,
  sr: f32,
  damper_t60: f32,
  damped: bool,
  /// Onset ramp (approaches 1).
  ramp: f32,
  ramp_k: f32,
  /// Mallet contact noise.
  click: Svf,
  click_env: f32,
  click_coef: f32,
  rng: u32,
  /// Pickup nonlinearity amount (already scaled by velocity) and DC blocker.
  pickup: f32,
  dc_x1: f32,
  dc_y1: f32,
  dc_r: f32,
  /// Amplitude tremolo (vibraphone motor): phase increment and depth.
  trem_phase: f32,
  trem_inc: f32,
  trem_depth: f32,
  level: f32,
}

impl Modal {
  /// `velocity` is 0..1 after the synth's velocity curve; `start_time` is the
  /// note-on time in seconds, used to keep the tremolo motor in phase across
  /// notes (one motor turns every disc on a vibraphone).
  pub fn new(
    spec: &ModalSpec,
    key: u8,
    velocity: f32,
    tuning_semitones: f32,
    start_time: f64,
    sr: f32,
  ) -> Self {
    let k = key as f32;
    let f0 = 440.0 * 2f32.powf((k + tuning_semitones - 69.0) / 12.0);
    let key_scale = 2f32.powf(-(k - 60.0) / 12.0 * spec.key_decay);
    let vel_ratio = (velocity.max(0.01) / MF_VELOCITY).powf(0.5);
    // Mallet hardness: the corner rises with velocity.
    let corner = spec.corner * vel_ratio.powf(spec.hardness);
    let nyq = (sr * 0.45).min(MAX_MODE_HZ);

    let mut re = Vec::new();
    let mut im = Vec::new();
    let mut cr = Vec::new();
    let mut ci = Vec::new();
    let mut ws = Vec::new();
    let mut norm = 0.0f32;
    let spreads: &[(f32, f32)] = if spec.spread_cents > 0.0 {
      &[(-0.5, 0.5), (0.5, 0.5)]
    } else {
      &[(0.0, 1.0)]
    };
    for (n, m) in spec.modes.iter().enumerate() {
      let f = f0 * m.ratio;
      if f >= nyq {
        continue;
      }
      // Second-order mallet low-pass on the mode level.
      let lvl = m.level / (1.0 + (f / corner).powi(2));
      norm += m.level;
      let t60 = (spec.decay * key_scale * m.decay).clamp(0.02, 30.0);
      let r = 10f32.powf(-3.0 / (t60 * sr));
      for (i, &(side, share)) in spreads.iter().enumerate() {
        // Alternate the sign of the split per mode so the doublets don't all
        // beat in step.
        let sign = if n % 2 == 0 { 1.0 } else { -1.0 };
        let fr = f * 2f32.powf(sign * side * spec.spread_cents / 1200.0);
        let w = std::f32::consts::TAU * fr / sr;
        // Stagger doublet start phases slightly so the pair doesn't cancel.
        let ph = 0.4 * i as f32;
        let a = lvl * share;
        re.push(a * ph.cos());
        im.push(a * ph.sin());
        cr.push(r * w.cos());
        ci.push(r * w.sin());
        ws.push(w);
      }
    }
    let norm = norm.max(1e-6);
    for (x, y) in re.iter_mut().zip(im.iter_mut()) {
      *x /= norm;
      *y /= norm;
    }

    let click_freq = corner.clamp(300.0, 6_000.0);
    let click_t = 0.004;
    let ramp_k = 1.0 - (-1.0 / (spec.onset.max(1e-4) * sr)).exp();
    let trem_inc = spec.tremolo_hz / sr;
    let trem_phase = ((start_time * spec.tremolo_hz as f64).fract()) as f32;
    Self {
      re,
      im,
      cr,
      ci,
      w: ws,
      bend: 1.0,
      sr,
      damper_t60: spec.damper,
      damped: false,
      ramp: 0.0,
      ramp_k,
      click: Svf::new(FilterMode::Band, sr, click_freq, 0.7),
      click_env: spec.click * vel_ratio.min(2.0),
      click_coef: 10f32.powf(-3.0 / (click_t * sr)),
      rng: 0x2545_F491 ^ (key as u32).wrapping_mul(0x9E37_79B9),
      pickup: spec.pickup * vel_ratio,
      dc_x1: 0.0,
      dc_y1: 0.0,
      dc_r: 1.0 - std::f32::consts::TAU * 20.0 / sr,
      trem_phase,
      trem_inc,
      trem_depth: spec.tremolo_depth,
      level: 1.0,
    }
  }

  /// Key released: apply the damper, if the instrument has one.
  pub fn damp(&mut self) {
    if self.damped || self.damper_t60 <= 0.0 {
      return;
    }
    self.damped = true;
    let g = 10f32.powf(-3.0 / (self.damper_t60 * self.sr));
    for (c, s) in self.cr.iter_mut().zip(self.ci.iter_mut()) {
      // Only ever shorten: a mode already dying faster keeps its rate.
      let r = (*c * *c + *s * *s).sqrt();
      if r > g {
        let k = g / r;
        *c *= k;
        *s *= k;
      }
    }
  }

  /// Retune every mode to `ratio` × its note-on frequency (live pitch bend).
  /// Rotating each coefficient by the change in its angular step keeps its
  /// magnitude, so decay and damper state are untouched. Call once per block.
  pub fn set_bend(&mut self, ratio: f32) {
    let delta = ratio - self.bend;
    if delta.abs() < 1e-6 {
      return;
    }
    self.bend = ratio;
    for i in 0..self.w.len() {
      let (s, c) = (self.w[i] * delta).sin_cos();
      let (cr, ci) = (self.cr[i], self.ci[i]);
      self.cr[i] = cr * c - ci * s;
      self.ci[i] = cr * s + ci * c;
    }
  }

  /// Called once per render block: track the level for idle detection.
  pub fn update_level(&mut self) {
    self.level = self
      .re
      .iter()
      .zip(&self.im)
      .map(|(x, y)| x.abs() + y.abs())
      .sum();
  }

  pub fn is_silent(&self) -> bool {
    self.level < SILENT && self.click_env < SILENT
  }

  #[inline]
  pub fn tick(&mut self) -> f32 {
    let mut s = 0.0;
    for i in 0..self.re.len() {
      let (x, y) = (self.re[i], self.im[i]);
      self.re[i] = x * self.cr[i] - y * self.ci[i];
      self.im[i] = x * self.ci[i] + y * self.cr[i];
      s += self.im[i];
    }
    self.ramp += self.ramp_k * (1.0 - self.ramp);
    s *= self.ramp;

    if self.pickup > 0.0 {
      // Magnetic pickup: asymmetric response to tine displacement. The
      // quadratic term adds even harmonics that grow with amplitude (the
      // Rhodes "bark") and fade as the note decays. Its DC is blocked.
      let y = s + self.pickup * s * s;
      let out = y - self.dc_x1 + self.dc_r * self.dc_y1;
      self.dc_x1 = y;
      self.dc_y1 = out;
      s = out;
    }

    if self.click_env > SILENT {
      self.rng = self.rng.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
      let white = ((self.rng >> 8) as f32 / 8_388_608.0) - 1.0;
      s += self.click.tick(white) * self.click_env;
      self.click_env *= self.click_coef;
    }

    if self.trem_depth > 0.0 {
      self.trem_phase += self.trem_inc;
      if self.trem_phase >= 1.0 {
        self.trem_phase -= 1.0;
      }
      let lfo = 0.5 + 0.5 * (self.trem_phase * std::f32::consts::TAU).sin();
      s *= 1.0 - self.trem_depth * lfo;
    }
    s
  }
}

#[cfg(test)]
mod tests {
  use super::*;
  use crate::synth::patches::{ModalSpec, Mode};

  const SPEC: ModalSpec = ModalSpec {
    modes: &[Mode {
      ratio: 1.0,
      level: 1.0,
      decay: 1.0,
    }],
    decay: 3.0,
    key_decay: 0.0,
    corner: 5_000.0,
    hardness: 0.0,
    click: 0.0,
    onset: 0.001,
    spread_cents: 0.0,
    pickup: 0.0,
    damper: 0.1,
    tremolo_hz: 0.0,
    tremolo_depth: 0.0,
  };

  fn rms_after(m: &mut Modal, skip: usize, n: usize) -> f32 {
    for _ in 0..skip {
      m.tick();
    }
    let ss: f32 = (0..n).map(|_| m.tick().powi(2)).sum();
    (ss / n as f32).sqrt()
  }

  /// Fundamental from interpolated positive-going zero crossings.
  fn zc_freq(x: &[f32], sr: f32) -> f32 {
    let mut times = Vec::new();
    for i in 1..x.len() {
      if x[i - 1] < 0.0 && x[i] >= 0.0 {
        times.push((i - 1) as f32 + x[i - 1] / (x[i - 1] - x[i]));
      }
    }
    let n = times.len() - 1;
    n as f32 * sr / (times[n] - times[0])
  }

  #[test]
  fn follows_live_pitch_bend() {
    let sr = 44_100.0;
    let mut m = Modal::new(&SPEC, 69, 0.4, 0.0, 0.0, sr);
    let a: Vec<f32> = (0..8_192).map(|_| m.tick()).collect();
    m.set_bend(2f32.powf(2.0 / 12.0));
    let b: Vec<f32> = (0..8_192).map(|_| m.tick()).collect();
    let (fa, fb) = (zc_freq(&a[1_000..], sr), zc_freq(&b, sr));
    assert!((fa - 440.0).abs() < 0.5, "unbent {fa} Hz");
    let cents = 1200.0 * (fb / fa).log2();
    assert!((cents - 200.0).abs() < 1.0, "bent {fa} → {fb} Hz");
    // The decay rate is unchanged by the bend.
    let (ea, eb) = (
      a[4_000..].iter().fold(0f32, |m, x| m.max(x.abs())),
      b[..4_000].iter().fold(0f32, |m, x| m.max(x.abs())),
    );
    assert!(eb < ea * 1.01, "bend raised the level {ea} → {eb}");
  }

  #[test]
  fn decays_at_its_t60_and_damper_cuts_it_short() {
    let sr = 44_100.0;
    let mut ringing = Modal::new(&SPEC, 69, 0.4, 0.0, 0.0, sr);
    let start = rms_after(&mut ringing, 441, 4410);
    // After 1 s more of a 3 s T60 the level is down ~20 dB.
    let later = rms_after(&mut ringing, 44_100 - 4410, 4410);
    let db = 20.0 * (later / start).log10();
    assert!((db + 20.0).abs() < 1.5, "decayed {db:.1} dB in 1 s");

    let mut damped = Modal::new(&SPEC, 69, 0.4, 0.0, 0.0, sr);
    rms_after(&mut damped, 441, 4410);
    damped.damp();
    let after = rms_after(&mut damped, 4410, 4410);
    assert!(after < start * 0.01, "damper left {after} of {start}");
    damped.update_level();
    for _ in 0..sr as usize {
      damped.tick();
    }
    damped.update_level();
    assert!(damped.is_silent());
  }
}