rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Wind instruments as self-oscillating digital waveguides.
//!
//! A bore is a delay line closed by a reflection: a one-pole low-pass for
//! the open end, which reflects the lows and lets the highs escape, times a
//! loss gain. Nothing in it oscillates on its own; the player's steady
//! breath does, through a nonlinear valve or jet at the mouthpiece:
//!
//! - **Reed** (clarinet): the reed is a pressure-controlled valve (the STK
//!   reed table): the mouth/bore pressure difference sets how far it opens,
//!   and the reflected wave modulates that in turn. Closed at the reed and
//!   open at the bell, the cylinder's loop inverts once, so it is half a
//!   period long and supports only odd harmonics — the hollow clarinet tone.
//! - **Cone** (saxophone, double reeds): the same reed on a conical bore,
//!   which supports every harmonic. Modelled as the reed part-way along a
//!   cylinder (Cook's "Saxofony"): the short section stands in for the cone's
//!   missing apex. With the reed at ~0.4 of the length the model speaks on
//!   its fundamental across the whole range; nearer the end it jumps to an
//!   upper register.
//! - **Lips** (brass): an outward-striking valve. The lips are a damped
//!   mass-spring tuned a little below the note, driven by the mouth/mouthpiece
//!   pressure difference; their opening (rest gap plus displacement, never
//!   negative) lets through a Bernoulli flow u = h·√Δp, solved exactly
//!   against the incoming bore wave. The bore is twice the note's period long
//!   and reflects without inverting, so its modes are the half-harmonics of
//!   the note — the near-harmonic series of a flared bore — and the lips lock
//!   onto the one at the note.
//! - **Jet** (flutes): the air jet crosses the mouth hole in about half a
//!   period, is deflected in or out of the pipe by the acoustic flow there
//!   (a tanh, offset because the jet never hits the edge dead centre, which
//!   gives the even harmonics) and scales with breath. The jet's own
//!   turbulence is the breath noise. Open pipes reflect without net
//!   inversion (a full-period loop); a stopped pipe (pan flute) inverts at
//!   the embouchure only, so it is half a period long and favours odd
//!   harmonics.
//!
//! Breath pressure rises over the attack and falls at release, letting the
//! bore ring down by itself. Vibrato and pitch bend move the bore length
//! (and the lip tuning), as a player's embouchure does. The constants below
//! were found by sweeping each model over E1–C8: they keep every note
//! speaking on its fundamental and within a few cents of pitch.

use crate::synth::patches::{Exciter, WindSpec};
use crate::synth::waveguide::{
  Biquad, DcBlock, Delay, Noise, OnePole, Ramp, Vibrato, note_hz,
};
use std::f32::consts::{PI, TAU};

/// Lowest pitch factor bend/vibrato can reach (delay headroom).
const MIN_BEND: f32 = 0.25;
const SILENT: f32 = 2e-5;
/// The bell's reflection low-pass never closes below this many times the
/// fundamental — a reed needs a few harmonics fed back to keep speaking.
const MIN_CUTOFF: f32 = 3.0;

/// Breath turbulence reaches a reed through the mouthpiece and the reed
/// itself, which pass little above ~1.5 kHz. Unfiltered, it comes out of the
/// bell as a hiss that covers the attack while the reed starts up.
const REED_NOISE_HZ: f32 = 1_500.0;

/// Lip resonance relative to the note, its quality factor, the lip gap at
/// rest and the bore's wave impedance (normalised units).
const LIP_TUNE: f32 = 0.9;
const LIP_Q: f32 = 20.0;
const LIP_GAP: f32 = 0.1;
const LIP_Z: f32 = 1.0;
/// The lips pull the pitch up a little; lengthen the bore to match.
const LIP_PULL: f32 = 1.0038;

/// Centre of the steepening delay (samples); it swings ±3 around this.
const STEEP_DELAY: f32 = 6.0;

/// Jet transit time relative to the period, the jet's frequency response
/// corner (× f0), its deflection gain and offset from the edge, how much of
/// the embouchure flow deflects it and how much of the returning wave the
/// embouchure end reflects.
const JET_RATIO: f32 = 0.45;
const JET_LP: f32 = 2.0;
const JET_GAIN: f32 = 3.6;
const JET_OFFSET: f32 = 0.5;
const JET_FEEDBACK: f32 = 0.5;
const JET_REFLECT: f32 = 0.5;

#[derive(Clone, Debug)]
struct Bore {
  main: Delay,
  /// Second cylinder section (cone) or the jet's travel (flute).
  aux: Delay,
  lp: OnePole,
  loss: f32,
  dc: DcBlock,
  lip: Biquad,
  jet_lp: f32,
  /// Brass: the bore's far end (nonlinear steepening) and the bell's
  /// reflection filter on the radiated sound.
  steep: Delay,
  bell: OnePole,
  freq: f32,
  filter_delay: f32,
  vib: Vibrato,
  mix: f32,
}

#[derive(Clone, Debug)]
pub struct Wind {
  bores: Vec<Bore>,
  exciter: Exciter,
  breath: Ramp,
  noise: Noise,
  noise_amt: f32,
  /// Reeds: the breath turbulence as it reaches the reed (low-passed).
  turb: OnePole,
  release: f32,
  out_dc: DcBlock,
  norm: f32,
  energy: f32,
  released: bool,
  brassy: f32,
  breath_ref: f32,
  /// Brass: how far the tone opens up, by dynamic.
  tone: Option<Biquad>,
  /// Body resonances (`WindSpec::formants`).
  body: Vec<Biquad>,
  sr: f32,
}

/// Reed opening as a reflection coefficient (STK reed table): stiffer reeds
/// (larger `slope`) close sooner; clamped where the reed beats shut.
#[inline]
fn reed(x: f32, slope: f32) -> f32 {
  (0.7 + slope * x).clamp(-1.0, 1.0)
}

impl Wind {
  /// `velocity` is 0..1 after the synth's velocity curve; it sets breath
  /// pressure (and so loudness and brightness).
  pub fn new(spec: &WindSpec, key: u8, velocity: f32, sr: f32) -> Self {
    let k = key as f32;
    let players = spec.players.len().max(1) as f32;
    let bores = spec
      .players
      .iter()
      .enumerate()
      .map(|(i, p)| {
        let freq = note_hz(k + p.detune_cents / 100.0) * 2f32.powi(p.octave);
        let lp = OnePole::corner(spec.cutoff.max(MIN_CUTOFF * freq), sr);
        let loss = (spec.loss / lp.gain(freq, sr)).min(0.999);
        let cap = 2.0 * sr / (freq * MIN_BEND) + 8.0;
        let r = i as f32;
        Bore {
          main: Delay::new(cap),
          aux: Delay::new(cap),
          lp,
          loss,
          dc: DcBlock::new(5.0, sr),
          lip: Biquad::reson(freq, 0.99, sr),
          jet_lp: 0.0,
          steep: Delay::new(2.0 * STEEP_DELAY),
          bell: lp,
          freq,
          filter_delay: lp.delay(freq, sr),
          vib: Vibrato::new(
            spec.vibrato_hz * (1.0 + 0.07 * r),
            spec.vibrato_cents,
            spec.vibrato_delay * (1.0 + 0.2 * r),
            (0.41 * r).fract(),
            sr,
          ),
          mix: p.mix,
        }
      })
      .collect();
    // Players blow harder for louder notes, but only within the range where
    // the instrument speaks: below it a reed or lip never starts.
    let v = velocity.clamp(0.0, 1.0).sqrt();
    let target = spec.breath * (1.0 + spec.dynamics * (v - 0.6)).max(0.9);
    let mut breath = Ramp::new();
    breath.go(target, spec.attack, sr);
    // Each valve settles at its own level; bring them to a common one.
    let model_gain = match spec.exciter {
      Exciter::Reed { .. } => 9.5,
      Exciter::Cone { .. } => 9.0,
      Exciter::Lips => 5.7,
      Exciter::Jet { .. } => 0.15 / spec.breath.max(0.1),
    };
    Self {
      bores,
      exciter: spec.exciter,
      breath,
      noise: Noise::new(0x6C07_8965 ^ (key as u32).wrapping_mul(0x9E37_79B9)),
      noise_amt: spec.noise,
      turb: OnePole::corner(REED_NOISE_HZ, sr),
      release: spec.release,
      out_dc: DcBlock::new(30.0, sr),
      norm: model_gain * spec.level / players.sqrt(),
      energy: 1.0,
      released: false,
      // Steepening grows with how hard the note is played.
      brassy: spec.brassy * velocity.clamp(0.0, 1.0),
      breath_ref: spec.breath.max(0.1),
      // A lip valve buzzes richly at any level, but soft brass is mellow and
      // loud brass blazes: the player's dynamic opens the tone, about three
      // octaves from pp to ff around the bell's cutoff.
      tone: matches!(spec.exciter, Exciter::Lips).then(|| {
        let corner =
          spec.cutoff * 2f32.powf(3.0 * (velocity.clamp(0.0, 1.0) - 0.5));
        Biquad::lowpass(corner, 0.6, sr)
      }),
      body: (spec.radiation > 0.0)
        .then(|| Biquad::highpass(spec.radiation, 0.7, sr))
        .into_iter()
        .chain(
          spec
            .formants
            .iter()
            .map(|f| Biquad::peak(f.hz, f.q, f.db, sr)),
        )
        .collect(),
      sr,
    }
  }

  /// Stop blowing: the breath falls away and the bore rings down.
  pub fn release(&mut self) {
    if !self.released {
      self.released = true;
      self.breath.go(0.0, self.release, self.sr);
    }
  }

  pub fn is_silent(&self) -> bool {
    self.released && self.energy < SILENT && self.breath.value < 1e-3
  }

  /// 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 p = self.breath.tick();
    let n = self.noise.tick();
    // Low-passed turbulence for the reeds; a one-pole at 1.5 kHz keeps about
    // a third of white noise's level, so scale it back up.
    let n_reed = 2.5 * self.turb.tick(n);
    let sr = self.sr;
    let mut s = 0.0;
    for b in self.bores.iter_mut() {
      let f = b.freq * bend * (1.0 + b.vib.tick(wheel));
      let period = sr / f;
      let y = match self.exciter {
        Exciter::Reed { slope } => {
          let mouth = p * (1.0 + self.noise_amt * n_reed);
          let d = (0.5 * period - b.filter_delay).max(2.0);
          let o = b.main.read(d);
          let refl = -b.loss * b.lp.tick(o);
          let diff = refl - mouth;
          b.main.write(mouth + diff * reed(diff, -slope));
          o + refl
        }
        Exciter::Cone { slope, pos } => {
          let mouth = p * (1.0 + self.noise_amt * n_reed);
          let total = (period - b.filter_delay).max(4.0);
          let d1 = (pos * total).max(2.0);
          let d0 = (total - d1).max(2.0);
          let o0 = b.main.read(d0);
          let o1 = b.aux.read(d1);
          let bell = -b.loss * b.lp.tick(o0);
          let out = bell - o1;
          let diff = mouth - out;
          b.aux.write(bell);
          b.main.write(mouth - diff * reed(diff, slope) - bell);
          o0 + bell
        }
        Exciter::Lips => {
          let mouth = p * (1.0 + self.noise_amt * n);
          let d = (2.0 * period * LIP_PULL - b.filter_delay).max(2.0);
          let o = b.main.read(d);
          let back = b.loss * b.lp.tick(o);
          let r = (-PI * f * LIP_TUNE / (LIP_Q * sr)).exp();
          b.lip.set_lip(f * LIP_TUNE, r, sr);
          let h = (LIP_GAP + b.lip.state()).max(0.0);
          // Δp = mouth − (2·back + Z·u) and u = h·√Δp (signed).
          let a = mouth - 2.0 * back;
          let zh = LIP_Z * h;
          let u = if a >= 0.0 {
            h * 0.5 * (-zh + (zh * zh + 4.0 * a).sqrt())
          } else {
            -h * 0.5 * (-zh + (zh * zh - 4.0 * a).sqrt())
          };
          b.lip.tick(a - LIP_Z * u);
          b.main.write(b.dc.tick(back + LIP_Z * u));
          // Loud notes steepen into near-shocks on their way down the tube
          // (the sound travels faster where the pressure is higher): an
          // amplitude-dependent delay before the bell.
          b.steep.write(o);
          let shift = self.brassy * (p / self.breath_ref) * o;
          let o = b.steep.read(STEEP_DELAY - shift.clamp(-3.0, 3.0));
          o - b.loss * b.bell.tick(o)
        }
        Exciter::Jet { stopped } => {
          let (len, sign) = if stopped {
            (0.5 * period, -1.0)
          } else {
            (period, 1.0)
          };
          let d = (len - b.filter_delay).max(2.0);
          let o = b.main.read(d);
          let back = b.dc.tick(sign * b.loss * b.lp.tick(o));
          let jetted = b.aux.read((JET_RATIO * period).max(2.0));
          b.aux.write(-JET_FEEDBACK * back + self.noise_amt * n);
          let k = 1.0 - (-TAU * JET_LP * f / sr).exp();
          b.jet_lp += k * (jetted - b.jet_lp);
          let deflect =
            (JET_GAIN * b.jet_lp + JET_OFFSET).tanh() - JET_OFFSET.tanh();
          b.main.write(p * deflect + JET_REFLECT * back);
          o
        }
      };
      s += b.mix * y;
    }
    if let Some(t) = self.tone.as_mut() {
      s = t.tick(s);
    }
    for b in self.body.iter_mut() {
      s = b.tick(s);
    }
    let out = self.out_dc.tick(s) * self.norm;
    self.energy = (self.energy * 0.9995).max(out.abs());
    out
  }
}