SPB Git

Repository Public

synth.rs 16.5 KB 391 lines rust

1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/synth.rs3//! Description: Subtractive synthesiser — two band-limited oscillators, sub and noise, unison,4//! state-variable filter with its own envelope, LFO and a fixed-route modulation matrix.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use super::common::{pan_gains, EnvSettings};10use crate::instrument::{Instrument, NoteOn};11use crate::params::{choice, envelope_params, num, preset, resolve, Resolved};12use crate::poly::{Engine, Poly};13use sonata_dsp::core::{fast_tanh, semitones_to_ratio, Rng};14use sonata_dsp::env::{Adsr, Lfo, LfoShape};15use sonata_dsp::filter::Svf;16use sonata_dsp::osc::{Oscillator, Waveform};17use sonata_ir::{Articulation, EngineDesc, InstrumentSpec, Unit};18use std::sync::atomic::{AtomicU32, Ordering};1920const WAVES: [&str; 5] = ["saw", "square", "pulse", "triangle", "sine"];2122fn wave(i: usize) -> Waveform {23    [Waveform::Saw, Waveform::Square, Waveform::Pulse, Waveform::Triangle, Waveform::Sine][i.min(4)]24}2526pub fn desc() -> EngineDesc {27    let mut params = vec![28        choice("osc1.wave", &WAVES, "saw", "Waveform of oscillator 1."),29        num("osc1.level", Unit::Ratio, 0.0, 1.0, 0.8, true, "Level of oscillator 1."),30        choice("osc2.wave", &WAVES, "saw", "Waveform of oscillator 2."),31        num("osc2.level", Unit::Ratio, 0.0, 1.0, 0.5, true, "Level of oscillator 2."),32        num("osc2.detune", Unit::Semitones, -24.0, 24.0, 0.08, true, "Tuning of oscillator 2 relative to oscillator 1."),33        num("pulse_width", Unit::Ratio, 0.05, 0.95, 0.5, true, "Duty cycle of the pulse waveform."),34        num("sub.level", Unit::Ratio, 0.0, 1.0, 0.0, true, "Level of the sine sub-oscillator one octave below."),35        num("noise.level", Unit::Ratio, 0.0, 1.0, 0.0, true, "Level of white noise."),36        num("unison", Unit::Count, 1.0, 7.0, 1.0, false, "Number of detuned copies of the oscillators per note."),37        num("unison.detune", Unit::Semitones, 0.0, 1.0, 0.15, false, "Total tuning spread of the unison copies."),38        num("unison.spread", Unit::Ratio, 0.0, 1.0, 0.7, false, "Stereo spread of the unison copies."),39        choice("filter.type", &["lowpass", "bandpass", "highpass"], "lowpass", "Filter response (12 dB/octave state-variable)."),40        num("filter.cutoff", Unit::Hertz, 20.0, 20_000.0, 2400.0, true, "Filter cutoff before modulation."),41        num("filter.resonance", Unit::Ratio, 0.0, 1.0, 0.2, true, "Filter resonance (Q from 0.5 to 20)."),42        num("filter.keytrack", Unit::Ratio, 0.0, 1.0, 0.5, false, "How much the cutoff follows the note (1 = one octave per octave, around middle C)."),43        num("filter.env_amount", Unit::Scalar, -8.0, 8.0, 2.5, true, "Filter envelope depth in octaves."),44        num("filter.attack", Unit::Seconds, 0.0, 10.0, 0.005, false, "Filter envelope attack."),45        num("filter.decay", Unit::Seconds, 0.0, 20.0, 0.3, false, "Filter envelope decay."),46        num("filter.sustain", Unit::Ratio, 0.0, 1.0, 0.3, false, "Filter envelope sustain."),47        num("filter.release", Unit::Seconds, 0.001, 30.0, 0.3, false, "Filter envelope release."),48        num("lfo.rate", Unit::Hertz, 0.01, 40.0, 5.0, true, "LFO rate."),49        choice("lfo.shape", &["sine", "triangle", "saw", "square", "sample_hold"], "sine", "LFO waveform."),50        num("mod.lfo_pitch", Unit::Semitones, 0.0, 12.0, 0.0, true, "LFO to pitch (vibrato)."),51        num("mod.lfo_cutoff", Unit::Scalar, 0.0, 4.0, 0.0, true, "LFO to filter cutoff, in octaves."),52        num("mod.lfo_amp", Unit::Ratio, 0.0, 1.0, 0.0, true, "LFO to amplitude (tremolo)."),53        num("mod.lfo_pulse_width", Unit::Ratio, 0.0, 0.45, 0.0, true, "LFO to pulse width."),54        num("mod.velocity_cutoff", Unit::Scalar, 0.0, 4.0, 1.0, false, "Velocity to filter cutoff, in octaves at full velocity."),55        num("mod.env_pitch", Unit::Semitones, -24.0, 24.0, 0.0, false, "Filter envelope to pitch."),56        num("glide", Unit::Seconds, 0.0, 2.0, 0.0, false, "Portamento time from the previous note."),57        num("drive", Unit::Ratio, 0.0, 1.0, 0.0, true, "Saturation after the filter."),58    ];59    params.extend(envelope_params(false, 0.005, 0.2, 0.7, 0.25));60    EngineDesc {61        model: "synth".into(),62        title: "Subtractive Synth".into(),63        family: "synth".into(),64        method: "Subtractive synthesis: polyBLEP oscillators, zero-delay-feedback state-variable filter, ADSR envelopes, LFO, fixed modulation routes".into(),65        doc: "A classic two-oscillator analogue-style synthesiser with unison. The modulation matrix is the set of `mod.*` routes.".into(),66        range: (12, 120),67        params,68        presets: vec![69            preset(70                "lead",71                "Bright unison saw lead with glide.",72                &[73                    ("unison", 3.0),74                    ("unison.detune", 0.22),75                    ("filter.cutoff", 3200.0),76                    ("filter.env_amount", 1.5),77                    ("glide", 0.04),78                    ("mod.lfo_pitch", 0.12),79                    ("envelope.sustain", 0.8),80                ],81                &[],82            ),83            preset(84                "pad",85                "Slow, wide, detuned pad.",86                &[87                    ("unison", 5.0),88                    ("unison.detune", 0.35),89                    ("unison.spread", 1.0),90                    ("filter.cutoff", 900.0),91                    ("filter.env_amount", 1.2),92                    ("filter.attack", 1.2),93                    ("filter.decay", 2.0),94                    ("filter.sustain", 0.7),95                    ("envelope.attack", 0.8),96                    ("envelope.decay", 1.0),97                    ("envelope.sustain", 0.85),98                    ("envelope.release", 1.6),99                    ("mod.lfo_cutoff", 0.25),100                    ("lfo.rate", 0.3),101                ],102                &[],103            ),104            preset(105                "pluck",106                "Short filter pluck.",107                &[108                    ("filter.cutoff", 500.0),109                    ("filter.env_amount", 4.5),110                    ("filter.decay", 0.16),111                    ("filter.sustain", 0.0),112                    ("filter.resonance", 0.35),113                    ("envelope.decay", 0.35),114                    ("envelope.sustain", 0.0),115                    ("envelope.release", 0.2),116                    ("osc2.level", 0.3),117                ],118                &[("osc2.wave", "square")],119            ),120            preset(121                "keys",122                "Hollow square keys.",123                &[124                    ("osc2.level", 0.35),125                    ("osc2.detune", 12.0),126                    ("filter.cutoff", 1500.0),127                    ("filter.env_amount", 2.0),128                    ("filter.decay", 0.5),129                    ("envelope.decay", 0.9),130                    ("envelope.sustain", 0.35),131                ],132                &[("osc1.wave", "square"), ("osc2.wave", "triangle")],133            ),134            preset(135                "strings",136                "String-machine ensemble with pulse-width modulation.",137                &[138                    ("unison", 3.0),139                    ("unison.detune", 0.2),140                    ("pulse_width", 0.4),141                    ("mod.lfo_pulse_width", 0.25),142                    ("lfo.rate", 0.8),143                    ("filter.cutoff", 2600.0),144                    ("filter.env_amount", 0.5),145                    ("envelope.attack", 0.25),146                    ("envelope.sustain", 0.9),147                    ("envelope.release", 0.6),148                ],149                &[("osc1.wave", "pulse"), ("osc2.wave", "saw")],150            ),151            preset(152                "sync_brass",153                "Brassy filter swell.",154                &[155                    ("filter.cutoff", 400.0),156                    ("filter.env_amount", 3.2),157                    ("filter.attack", 0.08),158                    ("filter.decay", 0.4),159                    ("filter.sustain", 0.55),160                    ("envelope.attack", 0.03),161                    ("osc2.detune", 0.12),162                    ("drive", 0.2),163                ],164                &[],165            ),166            preset(167                "wobble",168                "Square bass with tempo-free LFO filter wobble.",169                &[170                    ("sub.level", 0.6),171                    ("filter.cutoff", 300.0),172                    ("filter.resonance", 0.55),173                    ("mod.lfo_cutoff", 2.5),174                    ("lfo.rate", 4.0),175                    ("filter.env_amount", 0.0),176                    ("drive", 0.4),177                    ("osc2.level", 0.0),178                ],179                &[("osc1.wave", "square"), ("lfo.shape", "triangle")],180            ),181        ],182        articulations: vec!["normal".into(), "legato".into(), "staccato".into(), "accent".into()],183        pitched: true,184    }185}186187const MAX_UNISON: usize = 7;188const LEVEL: f32 = 0.22;189const CTRL: usize = 16;190191pub struct Synth {192    sr: f32,193    r: Resolved,194    env: EnvSettings,195    last_freq: AtomicU32,196}197198pub struct Voice {199    osc1: [Oscillator; MAX_UNISON],200    osc2: [Oscillator; MAX_UNISON],201    det: [f32; MAX_UNISON],202    pl: [f32; MAX_UNISON],203    pr: [f32; MAX_UNISON],204    sub_phase: f32,205    filt_l: Svf,206    filt_r: Svf,207    amp: Adsr,208    fenv: Adsr,209    lfo: Lfo,210    rng: Rng,211    freq: f32,212    cur: f32,213    glide_coef: f32,214    bend: f32,215    vel: f32,216    midi: f32,217    ctrl: usize,218    f_mul: f32,219    cutoff: f32,220    lfo_amp: f32,221}222223impl Engine for Synth {224    type Voice = Voice;225    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {226        self.sr = sample_rate;227    }228    fn make_voice(&self, sr: f32) -> Voice {229        Voice {230            osc1: [Oscillator::new(sr); MAX_UNISON],231            osc2: [Oscillator::new(sr); MAX_UNISON],232            det: [1.0; MAX_UNISON],233            pl: [1.0; MAX_UNISON],234            pr: [1.0; MAX_UNISON],235            sub_phase: 0.0,236            filt_l: Svf::new(sr),237            filt_r: Svf::new(sr),238            amp: Adsr::new(sr),239            fenv: Adsr::new(sr),240            lfo: Lfo::new(sr, 1),241            rng: Rng::new(1),242            freq: 220.0,243            cur: 220.0,244            glide_coef: 0.0,245            bend: 1.0,246            vel: 0.0,247            midi: 60.0,248            ctrl: 0,249            f_mul: 1.0,250            cutoff: 1000.0,251            lfo_amp: 1.0,252        }253    }254    fn start(&self, v: &mut Voice, note: &NoteOn, seed: u64) {255        let sr = self.sr;256        let n = (self.r.get("unison").round() as usize).clamp(1, MAX_UNISON);257        v.rng = Rng::new(seed);258        let (w1, w2) = (wave(self.r.pick("osc1.wave")), wave(self.r.pick("osc2.wave")));259        let spread = self.r.get("unison.detune");260        let width = self.r.get("unison.spread");261        for k in 0..n {262            let pos = if n == 1 { 0.0 } else { 2.0 * k as f32 / (n - 1) as f32 - 1.0 };263            v.det[k] = semitones_to_ratio(0.5 * spread * pos);264            let (l, r) = pan_gains(pos * width);265            v.pl[k] = l;266            v.pr[k] = r;267            v.osc1[k].waveform = w1;268            v.osc2[k].waveform = w2;269            // Free-running phases (seeded): a unison stack must not start phase-locked.270            v.osc1[k].set_phase(if n == 1 { 0.0 } else { v.rng.unipolar() });271            v.osc2[k].set_phase(v.rng.unipolar());272        }273        v.sub_phase = 0.0;274        v.filt_l.reset();275        v.filt_r.reset();276        v.freq = note.freq;277        v.midi = note.pitch;278        let glide = self.r.get("glide");279        let last = f32::from_bits(self.last_freq.load(Ordering::Relaxed));280        v.cur = if glide > 0.0 && last > 0.0 { last } else { note.freq };281        v.glide_coef = if glide > 0.0 { (-(CTRL as f32) / (glide * 0.3 * sr)).exp() } else { 0.0 };282        self.last_freq.store(note.freq.to_bits(), Ordering::Relaxed);283        v.bend = 1.0;284        v.vel = note.velocity.clamp(0.0, 1.0) * if note.articulation == Articulation::Accent { 1.15 } else { 1.0 };285        v.vel = v.vel.min(1.0);286        v.lfo = Lfo::new(sr, seed);287        v.lfo.shape = [LfoShape::Sine, LfoShape::Triangle, LfoShape::SawUp, LfoShape::Square, LfoShape::SampleHold][self.r.pick("lfo.shape").min(4)];288        v.fenv.reset();289        v.fenv.set(self.r.get("filter.attack"), self.r.get("filter.decay"), self.r.get("filter.sustain"), self.r.get("filter.release"));290        v.fenv.gate_on();291        self.env.start(&mut v.amp);292        v.ctrl = 0;293    }294    fn release(&self, v: &mut Voice) {295        v.amp.gate_off();296        v.fenv.gate_off();297    }298    fn bend(&self, v: &mut Voice, semitones: f32) {299        v.bend = semitones_to_ratio(semitones);300    }301    fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {302        let r = &self.r;303        let sr = self.sr;304        let n = (r.get("unison").round() as usize).clamp(1, MAX_UNISON);305        let (l1, l2) = (r.get("osc1.level"), r.get("osc2.level"));306        let (sub, noise) = (r.get("sub.level"), r.get("noise.level"));307        let det2 = semitones_to_ratio(r.get("osc2.detune"));308        let ftype = r.pick("filter.type");309        let q = 0.5 + 19.5 * r.get("filter.resonance").powi(2);310        let base_cut = r.get("filter.cutoff") * 2f32.powf(r.get("filter.keytrack") * (v.midi - 60.0) / 12.0 + r.get("mod.velocity_cutoff") * (v.vel - 0.5));311        let env_amt = r.get("filter.env_amount");312        let (lfo_pitch, lfo_cut, lfo_amp, lfo_pw) = (r.get("mod.lfo_pitch"), r.get("mod.lfo_cutoff"), r.get("mod.lfo_amp"), r.get("mod.lfo_pulse_width"));313        let env_pitch = r.get("mod.env_pitch");314        let pw = r.get("pulse_width");315        let drive = r.get("drive");316        let pre = 1.0 + 6.0 * drive;317        let norm = LEVEL * (0.25 + 0.75 * v.vel) / (n as f32).sqrt() / (1.0 + 2.0 * drive);318        v.lfo.set_rate(r.get("lfo.rate"));319        for i in 0..left.len() {320            let fe = v.fenv.tick();321            if v.ctrl == 0 {322                // Control rate (every 16 samples): modulation sources and derived coefficients.323                let lfo = v.lfo.advance(CTRL);324                if v.glide_coef > 0.0 {325                    v.cur = v.freq + (v.cur - v.freq) * v.glide_coef;326                } else {327                    v.cur = v.freq;328                }329                v.f_mul = v.bend * semitones_to_ratio(lfo * lfo_pitch + fe * env_pitch);330                v.cutoff = (base_cut * 2f32.powf(env_amt * fe + lfo_cut * lfo)).clamp(20.0, 0.45 * sr);331                v.lfo_amp = 1.0 - lfo_amp * 0.5 * (1.0 + lfo);332                let width = (pw + lfo_pw * lfo).clamp(0.05, 0.95);333                let f = v.cur * v.f_mul;334                for k in 0..n {335                    v.osc1[k].set_freq(f * v.det[k]);336                    v.osc2[k].set_freq(f * v.det[k] * det2);337                    v.osc1[k].set_pulse_width(width);338                    v.osc2[k].set_pulse_width(width);339                }340                v.filt_l.set(v.cutoff, q);341                v.filt_r.set(v.cutoff, q);342            }343            v.ctrl = (v.ctrl + 1) % CTRL;344            let (mut l, mut rr) = (0.0, 0.0);345            for k in 0..n {346                let s = l1 * v.osc1[k].tick() + l2 * v.osc2[k].tick();347                l += s * v.pl[k];348                rr += s * v.pr[k];349            }350            let mut mono = 0.0;351            if sub > 0.0 {352                v.sub_phase += 0.5 * v.cur * v.f_mul / sr;353                if v.sub_phase >= 1.0 {354                    v.sub_phase -= 1.0;355                }356                mono += sub * super::common::sin_turns(v.sub_phase) * (n as f32).sqrt();357            }358            if noise > 0.0 {359                mono += noise * v.rng.bipolar() * (n as f32).sqrt();360            }361            let (ol, or) = (v.filt_l.tick(l + mono), v.filt_r.tick(rr + mono));362            let (mut yl, mut yr) = match ftype {363                0 => (ol.low, or.low),364                1 => (ol.band, or.band),365                _ => (ol.high, or.high),366            };367            if drive > 0.0 {368                yl = fast_tanh(yl * pre);369                yr = fast_tanh(yr * pre);370            }371            let a = v.amp.tick() * norm * v.lfo_amp;372            left[i] = yl * a;373            right[i] = yr * a;374        }375        !v.amp.is_idle()376    }377    fn set_param(&mut self, index: usize, value: f32) {378        if index < self.r.v.len() {379            self.r.v[index] = value;380        }381    }382    fn reset_shared(&mut self) {383        self.last_freq.store(0, Ordering::Relaxed);384    }385}386387pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {388    let r = resolve(&desc(), spec)?;389    Ok(Box::new(Poly::new(Synth { sr: 48_000.0, env: EnvSettings::read(&r, false), last_freq: AtomicU32::new(0), r }, seed)))390}391
Files main
Menu

Theme