rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Source–filter model of a choir (and of synthetic "voice" sounds).
//!
//! A sung vowel is a glottal source — a buzz with one sharp closure per
//! period, so a sawtooth-like spectrum falling ~6 dB/oct, steeper when the
//! voice is soft — shaped by the vocal tract, whose resonances (formants)
//! stay at fixed frequencies while the pitch moves. The formants, not the
//! source, are what make a vowel recognisable: "ah" has F1/F2 near
//! 800/1150 Hz, "oo" near 350/600 Hz.
//!
//! - **Source.** Each singer is a band-limited sawtooth (the closure is the
//!   saw's drop) through a one-pole tilt whose corner rises with velocity:
//!   soft singing is dark, loud singing bright.
//! - **Ensemble.** A section is several singers, each with their own
//!   detune, vibrato rate and phase, a slow random pitch drift and a
//!   staggered entry. That incoherence, not a chorus effect, is what makes
//!   it sound like many people.
//! - **Breath.** Aspiration noise, gated by the glottal cycle, goes through
//!   the same tract.
//! - **Tract.** A parallel bank of five band-passes at the vowel's
//!   formants. Low and high voices sing the same vowel with different
//!   formants (bass/tenor vs alto/soprano), so the bank blends between the
//!   two by note. When the pitch rises past F1 a singer raises F1 with it
//!   (formant tuning), which keeps high notes from thinning out.
//!
//! Formant values are the classic tables for the five voice types (as used
//! by Csound's FOF examples). Output is normalised at note-on from the
//! analytic spectrum, so every vowel and key comes out at about the same
//! level.

use crate::synth::osc::poly_blep;
use crate::synth::patches::StringSpec;
use crate::synth::waveguide::{Biquad, Noise, OnePole, Ramp, Vibrato, note_hz};
use std::f32::consts::TAU;

/// One vocal-tract resonance: centre, bandwidth (Hz) and level (dB).
#[derive(Clone, Copy, Debug)]
pub struct VocalFormant {
  pub hz: f32,
  pub bw: f32,
  pub db: f32,
}

pub const fn vf(hz: f32, bw: f32, db: f32) -> VocalFormant {
  VocalFormant { hz, bw, db }
}

/// The five formants of a vowel.
pub type Vowel = [VocalFormant; 5];

#[derive(Clone, Copy, Debug)]
pub struct ChoirSpec {
  /// One entry per singer: detune (cents), octave and level.
  pub singers: &'static [StringSpec],
  /// The vowel as sung by low (bass/tenor) and high (alto/soprano) voices.
  pub low: Vowel,
  pub high: Vowel,
  /// Notes from `split - 6` to `split + 6` blend from `low` to `high`.
  pub split: f32,
  /// Source tilt corner at mf, Hz (rises with velocity).
  pub brightness: f32,
  /// Aspiration noise level.
  pub breath: f32,
  /// Slow random pitch wander per singer (cents, 1σ).
  pub drift_cents: f32,
  /// Spread of the singers' entries (s): each one starts up to this late.
  pub stagger: f32,
  pub attack: f32,
  pub release: f32,
  pub vibrato_hz: f32,
  pub vibrato_cents: f32,
  pub vibrato_delay: f32,
}

/// Corner of the singers' pitch drift (Hz).
const DRIFT_HZ: f32 = 2.5;
/// Highest frequency included in the level normalisation.
const NORM_MAX_HZ: f32 = 8_000.0;
const SILENT: f32 = 1e-4;
/// Velocity 80 as a linear value (the mezzo-forte reference).
const MF: f32 = 80.0 / 127.0;

#[derive(Clone, Debug)]
struct Singer {
  phase: f32,
  ratio: f32,
  mix: f32,
  vib: Vibrato,
  drift: f32,
  drift_a: f32,
  drift_scale: f32,
  noise: Noise,
  tilt: OnePole,
  amp: Ramp,
  attack: f32,
  delay: u32,
}

#[derive(Clone, Debug)]
pub struct Choir {
  singers: Vec<Singer>,
  f0: f32,
  sr: f32,
  formants: [Biquad; 5],
  gains: [f32; 5],
  breath: f32,
  noise: Noise,
  breath_lp: OnePole,
  amp: Ramp,
  release: f32,
  released: bool,
  norm: f32,
}

/// Deterministic scatter in −1..1 for (key, index, salt).
fn scatter(key: u8, i: usize, salt: u32) -> f32 {
  let mut h = (key as u32)
    .wrapping_mul(0x9E37_79B9)
    .wrapping_add((i as u32).wrapping_mul(0x85EB_CA6B))
    ^ salt;
  h ^= h >> 15;
  h = h.wrapping_mul(0x2C1B_3C6D);
  h ^= h >> 12;
  h = h.wrapping_mul(0x297A_2D39);
  h ^= h >> 15;
  (h & 0xFFFF) as f32 / 32_767.5 - 1.0
}

impl Choir {
  pub fn new(spec: &ChoirSpec, key: u8, velocity: f32, sr: f32) -> Self {
    let k = key as f32;
    let f0 = note_hz(k);
    let u = velocity.clamp(0.0, 1.0).sqrt();
    let corner = (spec.brightness * (u / MF)).clamp(200.0, sr * 0.4);

    // Blend the low and high voices' formants by note, then tune F1 (and
    // F2 above it) out of the way of a high fundamental.
    let t = ((k - spec.split + 6.0) / 12.0).clamp(0.0, 1.0);
    let mut fm: Vowel = spec.low;
    for (i, f) in fm.iter_mut().enumerate() {
      let (a, b) = (spec.low[i], spec.high[i]);
      *f = vf(
        a.hz + (b.hz - a.hz) * t,
        a.bw + (b.bw - a.bw) * t,
        a.db + (b.db - a.db) * t,
      );
    }
    let fund =
      f0 * 2f32.powi(spec.singers.iter().map(|s| s.octave).min().unwrap_or(0));
    if fm[0].hz < 1.1 * fund {
      fm[0].hz = 1.1 * fund;
      fm[0].bw = fm[0].bw.max(0.1 * fm[0].hz);
    }
    if fm[1].hz < fm[0].hz * 1.35 {
      fm[1].hz = fm[0].hz * 1.35;
    }

    let nyq = sr * 0.45;
    let formants: [Biquad; 5] = std::array::from_fn(|i| {
      let f = fm[i];
      Biquad::bandpass(f.hz.min(nyq), (f.hz / f.bw.max(1.0)).max(0.5), sr)
    });
    let gains: [f32; 5] = std::array::from_fn(|i| {
      if fm[i].hz < nyq {
        10f32.powf(fm[i].db / 20.0)
      } else {
        0.0
      }
    });

    let singers: Vec<Singer> = spec
      .singers
      .iter()
      .enumerate()
      .map(|(i, s)| {
        let rate =
          spec.vibrato_hz * (1.0 + 0.12 * scatter(key, i, 0x1B87_3593));
        let depth =
          spec.vibrato_cents * (1.0 + 0.25 * scatter(key, i, 0x68E3_1DA4));
        let phase = 0.5 + 0.5 * scatter(key, i, 0x5BD1_E995);
        let drift_a = (-TAU * DRIFT_HZ / sr).exp();
        let eps = 1.0 - drift_a;
        // Standard deviation of uniform white noise through the one-pole.
        let sd = (eps / (2.0 - eps) / 3.0).sqrt();
        let attack = spec.attack * (1.0 + 0.3 * scatter(key, i, 0x27D4_EB2F));
        let delay = spec.stagger * (0.5 + 0.5 * scatter(key, i, 0x1656_67B1));
        let mut amp = Ramp::new();
        if delay <= 0.0 {
          amp.go(1.0, attack, sr);
        }
        Singer {
          phase: (0.5 + 0.5 * scatter(key, i, 0x3C6E_F372)).fract(),
          ratio: 2f32.powf(s.detune_cents / 1200.0) * 2f32.powi(s.octave),
          mix: s.mix,
          vib: Vibrato::new(rate, depth, spec.vibrato_delay, phase, sr),
          drift: 0.0,
          drift_a,
          drift_scale: (2f32.powf(spec.drift_cents / 1200.0) - 1.0)
            / sd.max(1e-9),
          noise: Noise::new(0x2545_F491 ^ (key as u32) << 8 ^ i as u32),
          tilt: OnePole::corner(corner, sr),
          amp,
          attack,
          delay: (delay * sr) as u32,
        }
      })
      .collect();

    // Level of one singer's steady vowel, from the analytic spectrum: saw
    // harmonics (1/h) × tilt × formant bank.
    let tilt = OnePole::corner(corner, sr);
    let mut power = 0.0f32;
    let lim = NORM_MAX_HZ.min(nyq);
    let mut h = 1;
    while h as f32 * fund < lim {
      let f = h as f32 * fund;
      let (mut re, mut im) = (0.0, 0.0);
      for (b, g) in formants.iter().zip(&gains) {
        let (r, i) = b.response(f, sr);
        re += g * r;
        im += g * i;
      }
      let a = (2.0 / (std::f32::consts::PI * h as f32)) * tilt.gain(f, sr);
      power += 0.5 * a * a * (re * re + im * im);
      h += 1;
    }
    let mixes: f32 = spec.singers.iter().map(|s| s.mix * s.mix).sum();
    let norm = 0.3 / (power.max(1e-9) * mixes.max(1e-6)).sqrt();

    let mut amp = Ramp::new();
    amp.go(1.0, 0.005, sr);
    Self {
      singers,
      f0,
      sr,
      formants,
      gains,
      breath: spec.breath,
      noise: Noise::new(0x7F4A_7C15 ^ key as u32),
      breath_lp: OnePole::corner(6_000.0, sr),
      amp,
      release: spec.release,
      released: false,
      norm,
    }
  }

  pub fn release(&mut self) {
    if !self.released {
      self.released = true;
      self.amp.go(0.0, self.release, self.sr);
    }
  }

  pub fn is_silent(&self) -> bool {
    self.released && self.amp.value < SILENT
  }

  /// One output sample. `bend` is the pitch factor from pitch bend, `wheel`
  /// the extra vibrato depth from the mod wheel.
  #[inline]
  pub fn tick(&mut self, bend: f32, wheel: f32) -> f32 {
    let a = self.amp.tick();
    let sr = self.sr;
    let mut src = 0.0;
    let mut open = 0.0;
    for s in self.singers.iter_mut() {
      if s.delay > 0 {
        s.delay -= 1;
        if s.delay == 0 {
          s.amp.go(1.0, s.attack, sr);
        }
      }
      let g = s.amp.tick();
      s.drift = s.drift_a * s.drift + (1.0 - s.drift_a) * s.noise.tick();
      let f = self.f0
        * s.ratio
        * bend
        * (1.0 + s.vib.tick(wheel) + s.drift * s.drift_scale);
      let dt = (f / sr).min(0.5);
      let p = s.phase;
      s.phase += dt;
      if s.phase >= 1.0 {
        s.phase -= 1.0;
      }
      let saw = 2.0 * p - 1.0 - poly_blep(p, dt);
      src += s.tilt.tick(saw) * s.mix * g;
      // The glottis is open for the first part of the cycle; aspiration
      // noise rides on that.
      open += g * s.mix * (1.0 - p);
    }
    let n = self.breath_lp.tick(self.noise.tick());
    src += self.breath * n * open;

    let mut y = 0.0;
    for (b, g) in self.formants.iter_mut().zip(&self.gains) {
      y += g * b.tick(src);
    }
    y * self.norm * a
  }
}

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

  const SINGER: &[StringSpec] = &[StringSpec {
    detune_cents: 0.0,
    octave: 0,
    mix: 1.0,
  }];

  const AH: Vowel = [
    vf(800.0, 80.0, 0.0),
    vf(1150.0, 90.0, -4.0),
    vf(2800.0, 120.0, -20.0),
    vf(3500.0, 130.0, -36.0),
    vf(4950.0, 140.0, -60.0),
  ];
  const OO: Vowel = [
    vf(325.0, 50.0, 0.0),
    vf(700.0, 60.0, -12.0),
    vf(2530.0, 170.0, -30.0),
    vf(3500.0, 180.0, -40.0),
    vf(4950.0, 200.0, -64.0),
  ];

  fn spec(v: Vowel) -> ChoirSpec {
    ChoirSpec {
      singers: SINGER,
      low: v,
      high: v,
      split: 60.0,
      brightness: 3_000.0,
      breath: 0.0,
      drift_cents: 0.0,
      stagger: 0.0,
      attack: 0.02,
      release: 0.1,
      vibrato_hz: 5.0,
      vibrato_cents: 0.0,
      vibrato_delay: 0.0,
    }
  }

  fn tone(x: &[f32], f: f32, sr: f32) -> f32 {
    let w = TAU * f / sr;
    let (mut re, mut im) = (0.0f32, 0.0f32);
    for (i, v) in x.iter().enumerate() {
      re += v * (w * i as f32).cos();
      im += v * (w * i as f32).sin();
    }
    (re * re + im * im).sqrt() / x.len() as f32
  }

  /// The formants, not the pitch, decide where the energy is: at the same
  /// note, "ah" peaks near 800–1150 Hz and "oo" near 350 Hz.
  #[test]
  fn vowels_have_their_formants() {
    let sr = 44_100.0;
    let f0 = note_hz(57.0); // A3, 220 Hz
    let render = |v| {
      let mut c = Choir::new(&spec(v), 57, 0.4, sr);
      let x: Vec<f32> = (0..22_050).map(|_| c.tick(1.0, 0.0)).collect();
      x[4_410..].to_vec()
    };
    let (ah, oo) = (render(AH), render(OO));
    // Harmonics 4/5 (880/1100 Hz) vs 1/2 (220/440 Hz).
    let hi = |x: &[f32]| tone(x, 4.0 * f0, sr) + tone(x, 5.0 * f0, sr);
    let lo = |x: &[f32]| tone(x, f0, sr) + tone(x, 2.0 * f0, sr);
    assert!(hi(&ah) > lo(&ah), "ah: hi {} lo {}", hi(&ah), lo(&ah));
    assert!(lo(&oo) > 4.0 * hi(&oo), "oo: hi {} lo {}", hi(&oo), lo(&oo));
    // Normalised: similar levels.
    let rms = |x: &[f32]| {
      (x.iter().map(|v| v * v).sum::<f32>() / x.len() as f32).sqrt()
    };
    let r = rms(&ah) / rms(&oo);
    assert!((0.5..2.0).contains(&r), "level ratio {r}");
  }
}