SPB Git

Repository Public

modal.rs 10.1 KB 233 lines rust

1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/modal.rs3//! Description: Modal percussion — a struck resonator as a bank of exponentially damped modes4//! (bars, bells, tubes, glass), with strike hardness, noise transient and vibraphone tremolo.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::common::{pan_gains, sin_turns, EnvSettings};10use crate::instrument::{Instrument, NoteOn};11use crate::params::{choice, envelope_params, list, num, preset, resolve, Resolved};12use crate::poly::{Engine, Poly};13use sonata_dsp::core::Rng;14use sonata_dsp::env::Adsr;15use sonata_dsp::filter::Svf;16use sonata_dsp::osc::AdditiveBank;17use sonata_ir::{EngineDesc, InstrumentSpec, ParamDesc, Unit};1819/// (frequency ratio, relative amplitude, relative decay time).20type Mode = (f32, f32, f32);2122struct Body {23    name: &'static str,24    /// T60 of the fundamental at middle C, seconds.25    t60: f32,26    modes: &'static [Mode],27}2829const BODIES: &[Body] = &[30    // Bars tuned by an arch cut: second mode at the double octave, third near 10x.31    Body { name: "marimba", t60: 1.1, modes: &[(1.0, 1.0, 1.0), (4.0, 0.22, 0.25), (9.9, 0.07, 0.1), (17.6, 0.02, 0.05)] },32    Body { name: "vibraphone", t60: 7.0, modes: &[(1.0, 1.0, 1.0), (4.0, 0.3, 0.4), (10.0, 0.1, 0.15), (18.6, 0.03, 0.06)] },33    // Uniform free bar (Euler-Bernoulli): 1 : 2.756 : 5.404 : 8.933.34    Body { name: "glockenspiel", t60: 3.5, modes: &[(1.0, 1.0, 1.0), (2.756, 0.4, 0.5), (5.404, 0.2, 0.3), (8.933, 0.1, 0.15), (13.34, 0.04, 0.08)] },35    // Church bell partials relative to the prime: hum, prime, tierce, quint, nominal, ...36    Body {37        name: "bell",38        t60: 10.0,39        modes: &[40            (0.5, 0.6, 1.6),41            (1.0, 1.0, 1.0),42            (1.2, 0.8, 0.8),43            (1.5, 0.4, 0.6),44            (2.0, 0.9, 0.6),45            (2.6, 0.35, 0.4),46            (3.0, 0.3, 0.3),47            (4.0, 0.25, 0.25),48            (5.2, 0.12, 0.2),49            (6.6, 0.08, 0.15),50        ],51    },52    // Tubular bell: the strike tone is the missing fundamental of partials near 2 : 3 : 4.53    Body { name: "tubular", t60: 8.0, modes: &[(1.0, 0.12, 1.2), (2.0, 1.0, 1.0), (3.01, 0.8, 0.8), (4.03, 0.6, 0.6), (5.08, 0.35, 0.4), (6.15, 0.2, 0.3)] },54    Body { name: "glass", t60: 4.5, modes: &[(1.0, 1.0, 1.0), (2.32, 0.5, 0.6), (4.25, 0.3, 0.4), (6.63, 0.15, 0.25), (9.38, 0.08, 0.15)] },55    // Clamped-free tine: 1 : 6.27 : 17.55.56    Body { name: "kalimba", t60: 1.6, modes: &[(1.0, 1.0, 1.0), (6.27, 0.18, 0.15), (17.55, 0.04, 0.05)] },57    Body { name: "woodblock", t60: 0.12, modes: &[(1.0, 1.0, 1.0), (2.57, 0.5, 0.6), (4.1, 0.3, 0.4)] },58];5960pub fn desc() -> EngineDesc {61    let names: Vec<&str> = BODIES.iter().map(|b| b.name).collect();62    let mut params = vec![63        choice("body", &names, "marimba", "Resonator: its set of mode ratios, amplitudes and decays."),64        ParamDesc::list(65            "partials",66            Unit::ScalarList,67            0.1,68            64.0,69            "Custom mode frequency ratios replacing those of `body` (at most 16; amplitudes fall as 1/k, decays as 1/sqrt(ratio)).",70        ),71        num("decay", Unit::Scalar, 0.05, 5.0, 1.0, false, "Multiplier of every mode's decay time."),72        num("hardness", Unit::Ratio, 0.0, 1.0, 0.5, false, "Mallet hardness: a hard mallet excites the high modes, more so at high velocity."),73        num("strike.noise", Unit::Ratio, 0.0, 1.0, 0.25, false, "Level of the contact noise of the mallet."),74        num("tremolo.rate", Unit::Hertz, 0.1, 12.0, 5.0, true, "Rate of the amplitude tremolo (vibraphone motor)."),75        num("tremolo.depth", Unit::Ratio, 0.0, 1.0, 0.0, true, "Depth of the tremolo."),76        num("width", Unit::Ratio, 0.0, 1.0, 0.5, false, "Stereo spread by pitch."),77    ];78    params.extend(envelope_params(true, 0.0, 1.0, 1.0, 0.25));79    EngineDesc {80        model: "modal_percussion".into(),81        title: "Modal Percussion".into(),82        family: "percussion".into(),83        method: "Modal synthesis: a sum of exponentially damped sinusoids whose frequency ratios are those of the vibrating body; amplitudes shaped by the mallet's contact spectrum".into(),84        doc: "Pitched percussion built from the modes of bars, bells, tubes and glass. Mode ratios come from the physics of each body or from measurements reported in the acoustics literature; amplitudes and decays are plausible, not measured on a specific instrument.".into(),85        range: (36, 108),86        params,87        presets: vec![88            preset("marimba", "Rosewood bars, medium mallets.", &[("hardness", 0.4)], &[("body", "marimba")]),89            preset("vibraphone", "Metal bars with motor tremolo; rings until damped.", &[("hardness", 0.45), ("tremolo.depth", 0.45), ("tremolo.rate", 5.2), ("envelope.release", 0.4)], &[("body", "vibraphone")]),90            preset("glockenspiel", "Small steel bars, hard mallets.", &[("hardness", 0.85), ("strike.noise", 0.15), ("envelope.release", 2.0)], &[("body", "glockenspiel")]),91            preset("bell", "Church bell with hum, tierce and nominal.", &[("hardness", 0.6), ("strike.noise", 0.3), ("envelope.release", 6.0)], &[("body", "bell")]),92            preset("tubular", "Orchestral chime.", &[("hardness", 0.65), ("envelope.release", 4.0)], &[("body", "tubular")]),93            preset("glass", "Struck glass.", &[("hardness", 0.7), ("strike.noise", 0.1), ("envelope.release", 2.5)], &[("body", "glass")]),94            preset("kalimba", "Thumb piano.", &[("hardness", 0.55), ("strike.noise", 0.4), ("envelope.release", 0.8)], &[("body", "kalimba")]),95            preset("woodblock", "Dry wooden knock.", &[("hardness", 0.8), ("strike.noise", 0.5)], &[("body", "woodblock")]),96        ],97        articulations: vec!["normal".into(), "accent".into(), "staccato".into()],98        pitched: true,99    }100}101102const LEVEL: f32 = 0.42;103const MAX_MODES: usize = 16;104105pub struct Modal {106    sr: f32,107    r: Resolved,108    env: EnvSettings,109    modes: Vec<Mode>,110    base_t60: f32,111    trem_phase: f32,112    i_rate: usize,113    i_depth: usize,114}115116pub struct Voice {117    bank: AdditiveBank,118    env: Adsr,119    rng: Rng,120    noise: f32,121    noise_decay: f32,122    bp: Svf,123    gl: f32,124    gr: f32,125}126127impl Engine for Modal {128    type Voice = Voice;129    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {130        self.sr = sample_rate;131    }132    fn make_voice(&self, sr: f32) -> Voice {133        Voice { bank: AdditiveBank::new(MAX_MODES), env: Adsr::new(sr), rng: Rng::new(1), noise: 0.0, noise_decay: 0.9, bp: Svf::new(sr), gl: 1.0, gr: 1.0 }134    }135    fn start(&self, v: &mut Voice, note: &NoteOn, seed: u64) {136        let sr = self.sr;137        let vel = note.velocity.clamp(0.0, 1.0);138        let hard = self.r.get("hardness");139        // Contact low-pass: a soft mallet stays on the bar longer and cannot excite high modes.140        let fc = 300.0 + 14_000.0 * hard * hard * (0.3 + 0.7 * vel) + 1.5 * note.freq;141        let t_base = self.base_t60 * self.r.get("decay") * (261.6 / note.freq.max(20.0)).powf(0.6);142        v.bank.clear();143        let mut norm = 0.0;144        for (ratio, amp, _) in &self.modes {145            if ratio * note.freq < 0.45 * sr {146                norm += amp / (1.0 + (ratio * note.freq / fc).powi(2));147            }148        }149        let gain = LEVEL * (0.08 + 0.92 * vel.powf(1.5)) / norm.max(1e-6);150        for (ratio, amp, dec) in &self.modes {151            let f = ratio * note.freq;152            let a = amp / (1.0 + (f / fc).powi(2)) * gain;153            // Sine start: the strike is an impulse of velocity, so each mode's displacement starts at zero.154            v.bank.push(f, a, 0.0, (t_base * dec).max(0.02), sr);155        }156        v.rng = Rng::new(seed);157        v.noise = self.r.get("strike.noise") * 0.6 * LEVEL * vel;158        v.noise_decay = (-1.0 / ((0.004 + 0.012 * (1.0 - hard)) * sr)).exp();159        v.bp.reset();160        v.bp.set((800.0 + 5000.0 * hard).min(0.4 * sr), 1.2);161        let (gl, gr) = pan_gains(((note.pitch - 66.0) / 36.0).clamp(-1.0, 1.0) * self.r.get("width"));162        v.gl = gl;163        v.gr = gr;164        self.env.start(&mut v.env);165    }166    fn release(&self, v: &mut Voice) {167        v.env.gate_off();168    }169    fn bend(&self, _v: &mut Voice, _semitones: f32) {}170    fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {171        for i in 0..left.len() {172            let mut y = v.bank.tick();173            if v.noise > 1e-5 {174                y += v.bp.tick(v.rng.bipolar()).band * v.noise;175                v.noise *= v.noise_decay;176            }177            y *= v.env.tick();178            left[i] = y * v.gl;179            right[i] = y * v.gr;180        }181        !v.env.is_idle()182    }183    fn set_param(&mut self, index: usize, value: f32) {184        if index < self.r.v.len() {185            self.r.v[index] = value;186        }187    }188    fn post(&mut self, left: &mut [f32], right: &mut [f32], _pedal: bool) {189        let depth = self.r.v[self.i_depth] * 0.5;190        if depth <= 0.0 {191            return;192        }193        let inc = self.r.v[self.i_rate] / self.sr;194        for i in 0..left.len() {195            self.trem_phase += inc;196            if self.trem_phase >= 1.0 {197                self.trem_phase -= 1.0;198            }199            let m = 1.0 - depth * (0.5 + 0.5 * sin_turns(self.trem_phase));200            left[i] *= m;201            right[i] *= m;202        }203    }204    fn reset_shared(&mut self) {205        self.trem_phase = 0.0;206    }207    fn decays_naturally(&self) -> bool {208        true209    }210}211212pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {213    let r = resolve(&desc(), spec)?;214    let body = &BODIES[r.pick("body").min(BODIES.len() - 1)];215    let custom = list(spec, "partials");216    let modes: Vec<Mode> = if custom.is_empty() {217        body.modes.to_vec()218    } else {219        custom.iter().take(MAX_MODES).enumerate().map(|(k, ratio)| (*ratio, 1.0 / (k + 1) as f32, 1.0 / ratio.max(0.1).sqrt())).collect()220    };221    let e = Modal {222        sr: 48_000.0,223        env: EnvSettings::read(&r, true),224        modes,225        base_t60: body.t60,226        trem_phase: 0.0,227        i_rate: r.idx("tremolo.rate"),228        i_depth: r.idx("tremolo.depth"),229        r,230    };231    Ok(Box::new(Poly::new(e, seed)))232}233
Files main
Menu

Theme