SPB Git

Repository Public

organ.rs 9.8 KB 237 lines rust

1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/organ.rs3//! Description: Organ — additive synthesis of nine drawbar footages with key click, percussion,4//! pipe chiff, vibrato and a rotary-style tremolo.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::bowed::semitones_to_ratio_fast;10use super::common::{sin_turns, vibrato_params, EnvSettings, Vibrato};11use crate::instrument::{Instrument, NoteOn};12use crate::params::{choice, envelope_params, num, preset, resolve, Resolved};13use crate::poly::{Engine, Poly};14use sonata_dsp::core::{semitones_to_ratio, Rng};15use sonata_dsp::env::Adsr;16use sonata_dsp::filter::{OnePole, Svf};17use sonata_ir::{EngineDesc, InstrumentSpec, Unit};1819const FOOTAGES: [(&str, f32, &str); 9] = [20    ("drawbar.f16", 0.5, "16' sub-octave."),21    ("drawbar.f5_1_3", 1.5, "5 1/3' fifth above the sub-octave."),22    ("drawbar.f8", 1.0, "8' unison (the written pitch)."),23    ("drawbar.f4", 2.0, "4' octave."),24    ("drawbar.f2_2_3", 3.0, "2 2/3' twelfth."),25    ("drawbar.f2", 4.0, "2' fifteenth."),26    ("drawbar.f1_3_5", 5.0, "1 3/5' seventeenth."),27    ("drawbar.f1_1_3", 6.0, "1 1/3' nineteenth."),28    ("drawbar.f1", 8.0, "1' twenty-second."),29];3031pub fn desc() -> EngineDesc {32    let defaults = [1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0];33    let mut params: Vec<_> =34        FOOTAGES.iter().zip(defaults).map(|((name, _, doc), d)| num(name, Unit::Ratio, 0.0, 1.0, d, true, &format!("Level of the {doc}"))).collect();35    params.extend([36        num("click", Unit::Ratio, 0.0, 1.0, 0.3, false, "Key click at the start of each note."),37        num("percussion", Unit::Ratio, 0.0, 1.0, 0.0, false, "Level of the decaying percussion harmonic."),38        choice("percussion.harmonic", &["second", "third"], "second", "Harmonic used by the percussion."),39        num("percussion.decay", Unit::Seconds, 0.05, 2.0, 0.25, false, "Decay time of the percussion."),40        num("chiff", Unit::Ratio, 0.0, 1.0, 0.0, false, "Pipe speech noise at the attack (pipe organ presets)."),41        num("tremolo.rate", Unit::Hertz, 0.1, 12.0, 6.6, true, "Rotation rate of the rotary-style tremolo."),42        num("tremolo.depth", Unit::Ratio, 0.0, 1.0, 0.0, true, "Depth of the rotary-style tremolo (amplitude, opposite in the two channels)."),43    ]);44    params.extend(vibrato_params(6.8, 0.0, 0.0));45    params.extend(envelope_params(false, 0.004, 0.0, 1.0, 0.03));46    let bars = |v: [f64; 9]| -> Vec<(&'static str, f64)> { FOOTAGES.iter().zip(v).map(|((n, _, _), x)| (*n, x)).collect() };47    let with = |v: [f64; 9], extra: &[(&'static str, f64)]| -> Vec<(&'static str, f64)> {48        let mut b = bars(v);49        b.extend_from_slice(extra);50        b51    };52    EngineDesc {53        model: "organ".into(),54        title: "Organ".into(),55        family: "organ".into(),56        method: "Additive synthesis: nine sinusoids at the drawbar footages (0.5, 1.5, 1, 2, 3, 4, 5, 6, 8 times the note), plus click, percussion and chiff transients".into(),57        doc: "A drawbar organ. Each drawbar sets the level of one sine-wave footage; partials above the Nyquist frequency are muted. Presets cover tonewheel and pipe registrations.".into(),58        range: (24, 108),59        params,60        presets: vec![61            preset("jazz", "888000000 with percussion and a little click.", &with([1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], &[("percussion", 0.6), ("click", 0.4), ("tremolo.depth", 0.25)]), &[("percussion.harmonic", "third")]),62            preset("full", "All drawbars out.", &with([1.0; 9], &[("tremolo.depth", 0.4), ("click", 0.35)]), &[]),63            preset("gospel", "888800008: strong fundamental with a top sparkle.", &with([1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0], &[("tremolo.depth", 0.5), ("tremolo.rate", 7.0)]), &[]),64            preset("flute_pipe", "Stopped flute pipe: fundamental and a soft third harmonic, with chiff.", &with([0.0, 0.0, 1.0, 0.0, 0.3, 0.0, 0.05, 0.0, 0.0], &[("chiff", 0.6), ("click", 0.0), ("envelope.attack", 0.04), ("envelope.release", 0.12)]), &[]),65            preset("principal", "Principal chorus of a pipe organ.", &with([0.0, 0.0, 1.0, 0.8, 0.5, 0.6, 0.3, 0.3, 0.25], &[("chiff", 0.4), ("click", 0.0), ("envelope.attack", 0.03), ("envelope.release", 0.15)]), &[]),66            preset("cathedral", "Full pipe organ with 16' foundation.", &with([0.9, 0.3, 1.0, 0.8, 0.5, 0.7, 0.3, 0.4, 0.5], &[("chiff", 0.3), ("click", 0.0), ("envelope.attack", 0.05), ("envelope.release", 0.3)]), &[]),67        ],68        articulations: vec!["normal".into(), "legato".into(), "staccato".into(), "tenuto".into()],69        pitched: true,70    }71}7273const LEVEL: f32 = 0.2;7475pub struct Organ {76    sr: f32,77    r: Resolved,78    env: EnvSettings,79    trem_phase: f32,80    i_trem_rate: usize,81    i_trem_depth: usize,82    i_vdepth: usize,83}8485pub struct Voice {86    phase: f32,87    freq: f32,88    bend: f32,89    vel: f32,90    env: Adsr,91    vib: Vibrato,92    rng: Rng,93    click: f32,94    click_decay: f32,95    click_hp: OnePole,96    perc: f32,97    perc_decay: f32,98    chiff: f32,99    chiff_decay: f32,100    chiff_bp: Svf,101}102103impl Engine for Organ {104    type Voice = Voice;105    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {106        self.sr = sample_rate;107    }108    fn make_voice(&self, sr: f32) -> Voice {109        Voice {110            phase: 0.0,111            freq: 220.0,112            bend: 1.0,113            vel: 0.0,114            env: Adsr::new(sr),115            vib: Vibrato::default(),116            rng: Rng::new(1),117            click: 0.0,118            click_decay: 0.9,119            click_hp: OnePole::new(1500.0, sr),120            perc: 0.0,121            perc_decay: 0.999,122            chiff: 0.0,123            chiff_decay: 0.999,124            chiff_bp: Svf::new(sr),125        }126    }127    fn start(&self, v: &mut Voice, note: &NoteOn, seed: u64) {128        let sr = self.sr;129        v.phase = 0.0;130        v.freq = note.freq;131        v.bend = 1.0;132        // Organs have no touch response; a moderate one is kept so that dynamics written in a score are audible.133        v.vel = 0.4 + 0.6 * note.velocity.clamp(0.0, 1.0);134        v.rng = Rng::new(seed);135        v.click = self.r.get("click");136        v.click_decay = (-1.0 / (0.0025 * sr)).exp();137        v.click_hp.reset();138        v.perc = self.r.get("percussion");139        v.perc_decay = (-6.9 / (self.r.get("percussion.decay") * sr)).exp();140        v.chiff = self.r.get("chiff");141        v.chiff_decay = (-1.0 / (0.035 * sr)).exp();142        v.chiff_bp.reset();143        v.chiff_bp.set((note.freq * 3.0).min(0.4 * sr), 3.0);144        v.vib.start(self.r.get("vibrato.rate"), 1.0, self.r.get("vibrato.delay"), sr, 0.0);145        self.env.start(&mut v.env);146    }147    fn release(&self, v: &mut Voice) {148        v.env.gate_off();149    }150    fn bend(&self, v: &mut Voice, semitones: f32) {151        v.bend = semitones_to_ratio(semitones);152    }153    fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {154        let sr = self.sr;155        let mut levels = [0.0f32; 9];156        let nyq = 0.45 * sr / (v.freq * v.bend).max(1.0);157        let mut total = 0.0;158        for k in 0..9 {159            levels[k] = if FOOTAGES[k].1 < nyq { self.r.v[k] } else { 0.0 };160            total += self.r.v[k];161        }162        // Registration gain: constant loudness feel between one drawbar and all nine.163        let norm = LEVEL * v.vel / (1.0 + 0.35 * (total - 1.0).max(0.0));164        let perc_ratio = if self.r.pick("percussion.harmonic") == 0 { 2.0 } else { 3.0 };165        let vdepth = self.r.v[self.i_vdepth];166        for i in 0..left.len() {167            let f = v.freq * v.bend * if vdepth > 0.0 { semitones_to_ratio_fast(v.vib.tick() * vdepth) } else { 1.0 };168            // The phase wraps every two cycles so that the 0.5x and 1.5x footages stay continuous.169            v.phase += f / sr;170            if v.phase >= 2.0 {171                v.phase -= 2.0;172            }173            let mut y = 0.0;174            for k in 0..9 {175                if levels[k] > 0.0 {176                    y += levels[k] * sin_turns(v.phase * FOOTAGES[k].1);177                }178            }179            if v.perc > 1e-4 && perc_ratio < nyq {180                y += 1.5 * v.perc * sin_turns(v.phase * perc_ratio);181                v.perc *= v.perc_decay;182            }183            let mut y = y * norm;184            if v.click > 1e-4 {185                y += v.click_hp.highpass(v.rng.bipolar()) * v.click * 0.25 * v.vel * LEVEL * 4.0;186                v.click *= v.click_decay;187            }188            if v.chiff > 1e-4 {189                y += v.chiff_bp.tick(v.rng.bipolar()).band * v.chiff * 0.35 * LEVEL * 4.0;190                v.chiff *= v.chiff_decay;191            }192            let y = y * v.env.tick();193            left[i] = y;194            right[i] = y;195        }196        !v.env.is_idle()197    }198    fn set_param(&mut self, index: usize, value: f32) {199        if index < self.r.v.len() {200            self.r.v[index] = value;201        }202    }203    fn post(&mut self, left: &mut [f32], right: &mut [f32], _pedal: bool) {204        let depth = self.r.v[self.i_trem_depth] * 0.45;205        if depth <= 0.0 {206            return;207        }208        let inc = self.r.v[self.i_trem_rate] / self.sr;209        for i in 0..left.len() {210            self.trem_phase += inc;211            if self.trem_phase >= 1.0 {212                self.trem_phase -= 1.0;213            }214            let m = sin_turns(self.trem_phase);215            left[i] *= 1.0 + depth * m;216            right[i] *= 1.0 - depth * m;217        }218    }219    fn reset_shared(&mut self) {220        self.trem_phase = 0.0;221    }222}223224pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {225    let r = resolve(&desc(), spec)?;226    let e = Organ {227        sr: 48_000.0,228        env: EnvSettings::read(&r, false),229        trem_phase: 0.0,230        i_trem_rate: r.idx("tremolo.rate"),231        i_trem_depth: r.idx("tremolo.depth"),232        i_vdepth: r.idx("vibrato.depth"),233        r,234    };235    Ok(Box::new(Poly::new(e, seed)))236}237
Files main
Menu

Theme