rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Free reeds: accordion, harmonica, harmonium.
//!
//! A free reed is a brass tongue swinging through a closely fitting slot.
//! Unlike a clarinet reed it is barely coupled to any pipe, so it vibrates at
//! its own natural frequency — the instrument needs no bore model, and the
//! pitch is fixed by the reed. What it does to the air is the interesting
//! part: while the tongue is inside the slot almost nothing flows; once it
//! swings out past the slot's edge the gap opens quickly and a puff of air
//! passes. The sound is the derivative of that pulsed flow — a buzzy,
//! harmonic-rich spectrum with odd and even harmonics.
//!
//! - **Reed.** Displacement `x = a·sin φ`. The opening is a small leak plus a
//!   steep ramp beyond the slot edge `s` that saturates at the slot's own
//!   area — on the outward swing and (weaker, by `asym`) on the inward one.
//!   Each puff is thus a near-rectangular pulse whose width grows with the
//!   swing (louder notes are longer, sharper-edged puffs). The knees are
//!   rounded over a few samples so they don't alias.
//! - **Flow.** u = opening × √p (Bernoulli), radiated as u below ~1 kHz and
//!   as du/dt above (the reed chamber's opening is a small monopole).
//! - **Dynamics.** Bellows / breath pressure `p` follows velocity. The swing
//!   `a` builds up over a few dozen periods (a reed is a high-Q resonator,
//!   so low reeds speak more slowly) and grows with pressure: a soft note
//!   barely clears the slot, a loud one swings well past it.
//! - **Body.** Fixed peaking resonances (reed chamber, comb, the player's
//!   mouth for a harmonica) and a radiation low-pass that opens with
//!   pressure.
//! - **Ranks.** An accordion sounds several reeds per key (musette: tuned a
//!   few cents apart, so they beat); a bandoneon pairs octaves.

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

#[derive(Clone, Copy, Debug)]
pub struct FreeReedSpec {
  /// One entry per reed sounding on the key.
  pub reeds: &'static [StringSpec],
  /// Slot edge as a fraction of the mf swing (0..1): higher gives shorter,
  /// sharper puffs — a reedier, brighter tone.
  pub slot: f32,
  /// Flow on the inward swing relative to the outward one (0..1).
  pub asym: f32,
  /// How much velocity changes the pressure (0 = none).
  pub dynamics: f32,
  pub attack: f32,
  pub release: f32,
  /// Air noise level.
  pub noise: f32,
  /// Radiation low-pass corner at mf, Hz (opens with pressure).
  pub tone: f32,
  pub formants: &'static [Formant],
  pub vibrato_hz: f32,
  pub vibrato_cents: f32,
  /// Amplitude part of the same LFO (bellows shake, hand tremolo), 0..1.
  pub tremolo: f32,
  pub level: f32,
}

/// Velocity 80 as a linear value (the mezzo-forte reference).
const MF: f32 = 80.0 / 127.0;
/// Air leaking past the tongue while it is inside the slot.
const LEAK: f32 = 0.03;
/// Once the tongue has swung this far (fraction of the mf swing) past the
/// slot edge, the gap is as wide as the slot itself: the opening saturates,
/// so each puff is a near-rectangular pulse with sharp edges.
const OPEN_SWING: f32 = 0.2;
/// The opening's knee is rounded over about this many samples.
const KNEE_SAMPLES: f32 = 1.5;
/// Above this the radiated sound follows dU/dt rather than the flow.
const RADIATION_HZ: f32 = 1_000.0;
/// A reed's swing builds up over about this many periods.
const BUILD_PERIODS: f32 = 10.0;
const SILENT: f32 = 1e-4;

#[derive(Clone, Debug)]
struct Tongue {
  phase: f32,
  freq: f32,
  mix: f32,
  swing: Ramp,
  build: f32,
  u1: f32,
}

#[derive(Clone, Debug)]
pub struct FreeReed {
  tongues: Vec<Tongue>,
  sr: f32,
  slot: f32,
  asym: f32,
  pressure: Ramp,
  release: f32,
  released: bool,
  rad: f32,
  noise: Noise,
  noise_amt: f32,
  noise_lp: Biquad,
  formants: Vec<Biquad>,
  tone: Biquad,
  dc: DcBlock,
  vib: Vibrato,
  trem_phase: f32,
  trem_inc: f32,
  trem_depth: f32,
  level: f32,
  norm: f32,
}

#[inline]
fn knee(z: f32, w: f32) -> f32 {
  0.5 * (z + (z * z + w * w).sqrt())
}

impl FreeReed {
  pub fn new(spec: &FreeReedSpec, key: u8, velocity: f32, sr: f32) -> Self {
    let f0 = note_hz(key as f32);
    let u = velocity.clamp(0.0, 1.0).sqrt();
    let p_target = (1.0 + spec.dynamics * (u / MF - 1.0)).clamp(0.25, 2.0);
    let mut pressure = Ramp::new();
    pressure.go(p_target, spec.attack, sr);
    let tongues = spec
      .reeds
      .iter()
      .map(|r| {
        let freq =
          f0 * 2f32.powf(r.detune_cents / 1200.0) * 2f32.powi(r.octave);
        let build = spec.attack.max(BUILD_PERIODS / freq);
        let mut swing = Ramp::new();
        swing.go(p_target.sqrt(), build, sr);
        Tongue {
          phase: 0.0,
          freq,
          mix: r.mix,
          swing,
          build,
          u1: 0.0,
        }
      })
      .collect();
    let formants = spec
      .formants
      .iter()
      .map(|f| Biquad::peak(f.hz, f.q, f.db, sr))
      .collect();
    let tone_hz = (spec.tone * p_target.sqrt()).clamp(200.0, sr * 0.45);
    let mix: f32 = spec.reeds.iter().map(|r| r.mix * r.mix).sum();
    Self {
      tongues,
      sr,
      slot: spec.slot,
      asym: spec.asym,
      pressure,
      release: spec.release,
      released: false,
      rad: sr / (TAU * RADIATION_HZ),
      noise: Noise::new(0x6A09_E667 ^ (key as u32) << 4),
      noise_amt: spec.noise,
      noise_lp: Biquad::bandpass(2_500.0, 0.6, sr),
      formants,
      tone: Biquad::lowpass(tone_hz, 0.707, sr),
      dc: DcBlock::new(20.0, sr),
      vib: Vibrato::new(spec.vibrato_hz, spec.vibrato_cents, 0.0, 0.0, sr),
      trem_phase: 0.0,
      trem_inc: spec.vibrato_hz / sr,
      trem_depth: spec.tremolo,
      level: spec.level,
      norm: 1.0 / mix.max(1e-6).sqrt(),
    }
  }

  pub fn release(&mut self) {
    if !self.released {
      self.released = true;
      self.pressure.go(0.0, self.release, self.sr);
      for t in &mut self.tongues {
        // The swing dies with the pressure, a little behind it.
        t.swing.go(0.0, self.release.max(0.5 * t.build), self.sr);
      }
    }
  }

  pub fn is_silent(&self) -> bool {
    self.released
      && self.pressure.value < SILENT
      && self.tongues.iter().all(|t| t.swing.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 p = self.pressure.tick().max(0.0);
    let sq = p.sqrt();
    let vib = self.vib.tick(wheel);
    let sr = self.sr;
    let mut s = 0.0;
    for t in self.tongues.iter_mut() {
      let a = t.swing.tick().max(0.0);
      let f = t.freq * bend * (1.0 + vib);
      let dphi = (f / sr).min(0.45);
      t.phase += dphi;
      if t.phase >= 1.0 {
        t.phase -= 1.0;
      }
      let x = a * (TAU * t.phase).sin();
      let w = (KNEE_SAMPLES * a * TAU * dphi).max(1e-4);
      let ramp = |z: f32| (knee(z, w) - knee(z - OPEN_SWING, w)) / OPEN_SWING;
      let open = LEAK + ramp(x - self.slot) + self.asym * ramp(-x - self.slot);
      let flow = open * sq;
      // Radiation: the reed chamber passes the flow itself at low
      // frequencies and its rate of change (a monopole, ∝ dU/dt) above
      // `RADIATION_HZ`.
      let d = flow + (flow - t.u1) * self.rad;
      t.u1 = flow;
      s += d * t.mix;
    }
    s = self.dc.tick(s * self.norm);
    s += self.noise_amt * p * self.noise_lp.tick(self.noise.tick());
    for f in self.formants.iter_mut() {
      s = f.tick(s);
    }
    s = self.tone.tick(s);
    if self.trem_depth > 0.0 {
      self.trem_phase += self.trem_inc;
      if self.trem_phase >= 1.0 {
        self.trem_phase -= 1.0;
      }
      s *= 1.0 - self.trem_depth * (0.5 - 0.5 * (TAU * self.trem_phase).cos());
    }
    s * self.level
  }
}

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

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

  fn spec() -> FreeReedSpec {
    FreeReedSpec {
      reeds: ONE,
      slot: 0.45,
      asym: 0.15,
      dynamics: 0.6,
      attack: 0.03,
      release: 0.05,
      noise: 0.0,
      tone: 6_000.0,
      formants: &[],
      vibrato_hz: 5.0,
      vibrato_cents: 0.0,
      tremolo: 0.0,
      level: 1.0,
    }
  }

  fn harmonic(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
  }

  #[test]
  fn speaks_in_tune_with_a_rich_spectrum_and_stops() {
    let sr = 44_100.0;
    let mut r = FreeReed::new(&spec(), 57, 0.4, sr);
    let x: Vec<f32> = (0..22_050).map(|_| r.tick(1.0, 0.0)).collect();
    let seg = &x[8_820..];
    let f0 = 220.0;
    let h: Vec<f32> =
      (1..=8).map(|k| harmonic(seg, k as f32 * f0, sr)).collect();
    let off = harmonic(seg, f0 * 1.03, sr);
    assert!(h[0] > 10.0 * off, "not at 220 Hz: {h:?} vs {off}");
    // Reedy: plenty of energy in the upper harmonics (the pulse width puts
    // notches in the spectrum, so no single harmonic is guaranteed), but
    // still on the fundamental.
    let upper: f32 = h[2..].iter().sum();
    assert!(h[0] >= h[1] && upper > 0.5 * h[0], "dull: {h:?}");
    r.release();
    for _ in 0..22_050 {
      r.tick(1.0, 0.0);
    }
    assert!(r.is_silent());
  }
}