rumpl 0.3.0

Sample-free General MIDI player and renderer
Documentation
//! Bowed-string digital waveguide (after McIntyre, Schumacher & Woodhouse
//! and Smith's waveguide formulation).
//!
//! The string is two delay lines meeting at the bow: one carries velocity
//! waves bow → nut → bow, the other bow → bridge → bow. The nut reflects
//! rigidly (inverting); the bridge reflects through a one-pole low-pass and a
//! loss gain — the string's own damping, set as a T60 so a lifted bow lets the
//! string ring like a real one. At the bow, the difference between bow speed
//! and string speed goes through a friction curve: near zero the bow grips
//! (the string *sticks* and is carried along), further out it lets go and the
//! string *slips* back. The alternation settles into Helmholtz motion — a
//! sawtooth-like velocity whose corner circulates around the string — without
//! any oscillator: the pitch is the loop length, the timbre falls out of bow
//! position, pressure and speed.
//!
//! The force on the bridge drives a fixed body filter: the air (A0) and
//! main wood (B1−/B1+) resonances, the "bridge hill" around 2–3 kHz and the
//! roll-off above, all scaled down for the larger instruments. Several
//! slightly detuned strings with their own vibrato make a section.

use crate::synth::patches::BowSpec;
use crate::synth::waveguide::{
  Biquad, Delay, Noise, OnePole, Ramp, Vibrato, loop_gain, note_hz,
};

/// Lowest pitch factor bend/vibrato can reach (delay headroom).
const MIN_BEND: f32 = 0.25;
/// The stick–slip cycle runs a little sharp of the loop length (the
/// Helmholtz corner is rounded by the loop filter); lengthen it to match.
const BOW_PULL: f32 = 1.0015;
/// Bow speed the friction curve's `slope` is quoted for.
const BOW_REF: f32 = 0.14;
/// Idle threshold on the output peak follower.
const SILENT: f32 = 2e-5;

#[derive(Clone, Debug)]
struct BowedString {
  neck: Delay,
  bridge: Delay,
  lp: OnePole,
  loss: f32,
  freq: f32,
  filter_delay: f32,
  beta: f32,
  vib: Vibrato,
  mix: f32,
}

impl BowedString {
  #[inline]
  fn tick(
    &mut self,
    sr: f32,
    bend: f32,
    wheel: f32,
    vbow: f32,
    contact: f32,
    slope: f32,
  ) -> f32 {
    let f = self.freq * bend * (1.0 + self.vib.tick(wheel));
    let total = (sr / f * BOW_PULL - self.filter_delay).max(4.0);
    let db = (self.beta * total).max(2.0);
    let dn = (total - db).max(2.0);
    let b_out = self.bridge.read(db);
    let n_out = self.neck.read(dn);
    let bridge_refl = -self.loss * self.lp.tick(b_out);
    let nut_refl = -n_out;
    let dv = vbow - (bridge_refl + nut_refl);
    let new = contact * dv * friction(dv, slope);
    self.neck.write(bridge_refl + new);
    self.bridge.write(nut_refl + new);
    b_out
  }
}

/// Bow–string friction as a reflection coefficient for the velocity
/// difference (the STK bow table): ≈1 while sticking, falling off steeply
/// once the string slips. `slope` grows as bow pressure falls.
#[inline]
fn friction(dv: f32, slope: f32) -> f32 {
  let x = (dv * slope).abs() + 0.75;
  let x2 = x * x;
  (1.0 / (x2 * x2)).min(1.0)
}

#[derive(Clone, Debug)]
pub struct Bowed {
  strings: Vec<BowedString>,
  body: Vec<Biquad>,
  speed: Ramp,
  contact: Ramp,
  slope: f32,
  noise: Noise,
  bow_noise: f32,
  trem_phase: f32,
  trem_inc: f32,
  release: f32,
  norm: f32,
  energy: f32,
  released: bool,
  sr: f32,
}

impl Bowed {
  /// `velocity` is 0..1 after the synth's velocity curve and sets bow speed.
  pub fn new(spec: &BowSpec, key: u8, velocity: f32, sr: f32) -> Self {
    let k = key as f32;
    // Free-string ring (bow lifted) shortens up the neck, like a plucked one.
    let ring = spec.ring * 2f32.powf(-(k - 60.0) / 24.0).clamp(0.3, 2.5);
    let players = spec.players.len().max(1) as f32;
    let strings = 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.brightness * freq.max(80.0), sr);
        let loss = (loop_gain(freq, ring) / lp.gain(freq, sr)).min(0.9995);
        let cap = sr / (freq * MIN_BEND) + 8.0;
        // Each player has their own vibrato rate and phase.
        let r = i as f32;
        let vib = Vibrato::new(
          spec.vibrato_hz
            * (1.0 + 0.06 * r * if i % 2 == 0 { 1.0 } else { -1.0 }),
          spec.vibrato_cents,
          spec.vibrato_delay * (1.0 + 0.15 * r),
          (0.37 * r).fract(),
          sr,
        );
        BowedString {
          neck: Delay::new(cap),
          bridge: Delay::new(cap),
          lp,
          loss,
          freq,
          filter_delay: lp.delay(freq, sr),
          beta: spec.bow_pos * (1.0 + 0.1 * r),
          vib,
          mix: p.mix,
        }
      })
      .collect();

    let s = if spec.body_follows_key {
      // Violin from about A4 up, viola/cello/bass below: the body's air
      // resonance stays near or below the note (0.3 = double bass).
      (note_hz(k) / 440.0).clamp(0.3, 1.0)
    } else {
      spec.body
    };
    let hill = s.sqrt();
    let body = vec![
      Biquad::highpass(190.0 * s, 0.7, sr),
      Biquad::peak(275.0 * s, 6.0, 7.0, sr), // A0 air mode
      Biquad::peak(460.0 * s, 10.0, 9.0, sr), // B1− corpus mode
      Biquad::peak(560.0 * s, 9.0, 7.0, sr), // B1+
      Biquad::peak(2_600.0 * hill, 1.4, 7.0, sr), // bridge hill
      Biquad::lowpass(6_500.0 * hill, 0.7, sr),
    ];

    let v = velocity.clamp(0.0, 1.0).sqrt();
    // Bow speed rises with velocity, and so does bow force: a player keeps
    // the force/speed ratio inside Schelleng's window (too little force and
    // the string slips several times per period — a whistly octave; too much
    // and it crunches). The friction curve is scaled by the bow speed for the
    // same reason, while extra force with velocity brightens the tone.
    let vbow = 0.08 + 0.12 * v;
    let pressure = (spec.pressure + 0.25 * (v - 0.6)).clamp(0.0, 1.0);
    let mut speed = Ramp::new();
    speed.go(vbow, spec.attack, sr);
    let mut contact = Ramp::new();
    contact.go(1.0, spec.attack * 0.3, sr);
    Self {
      strings,
      body,
      speed,
      contact,
      slope: (5.0 - 4.0 * pressure) * BOW_REF / vbow,
      noise: Noise::new(0x51ED_270B ^ (key as u32).wrapping_mul(0x9E37_79B9)),
      bow_noise: spec.bow_noise,
      trem_phase: 0.0,
      trem_inc: spec.tremolo_hz / sr,
      release: spec.release,
      norm: spec.bow_pos / (vbow * players.sqrt()) * 0.6,
      energy: 1.0,
      released: false,
      sr,
    }
  }

  /// Lift the bow: speed and grip fade, and the strings ring on freely.
  pub fn release(&mut self) {
    if !self.released {
      self.released = true;
      self.speed.go(0.0, self.release, self.sr);
      self.contact.go(0.0, self.release, self.sr);
    }
  }

  pub fn is_silent(&self) -> bool {
    self.released && self.energy < 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 mut v = self.speed.tick();
    if self.trem_inc > 0.0 {
      // Bowed tremolo: rapid up/down strokes, each reversal a new attack.
      self.trem_phase += self.trem_inc;
      if self.trem_phase >= 1.0 {
        self.trem_phase -= 1.0;
      }
      v *= (4.0 * (self.trem_phase * std::f32::consts::TAU).sin()).tanh();
    }
    // Rosin: the grip is never perfectly even.
    v *= 1.0 + self.bow_noise * self.noise.tick();
    let c = self.contact.tick();
    let mut s = 0.0;
    for st in self.strings.iter_mut() {
      s += st.mix * st.tick(self.sr, bend, wheel, v, c, self.slope);
    }
    for b in self.body.iter_mut() {
      s = b.tick(s);
    }
    let out = s * self.norm;
    self.energy = (self.energy * 0.9995).max(out.abs());
    out
  }
}