SPB Git

Repository Public

mod.rs 29.1 KB 778 lines rust

1//! ORIX Sonata2//! File: crates/sonata-instruments/src/patch/mod.rs3//! Description: The patch engine: interpreter of per-voice PatchSpec graphs.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use crate::instrument::{Instrument, NoteOn};9use crate::params::{num, resolve, Resolved};10use crate::poly::{Engine, Poly};11use sonata_dsp::core::{db_to_lin, fast_tanh, flush, semitones_to_ratio, soft_clip, DelayLine, Rng};12use sonata_dsp::env::{Adsr, AdsrStage, Lfo, LfoShape};13use sonata_dsp::filter::{Biquad, BiquadCoefs, Svf};14use sonata_dsp::osc::{FmOperator, Oscillator, PinkNoise, Waveform, Wavetable};15use sonata_ir::{EngineDesc, InstrumentSpec, NoteInput, PatchInput, PatchNodeDesc, PatchSpec, PortDesc, Rate, Unit};1617pub const MAX_NODES: usize = 4096;18const MAX_PORTS: usize = 5;19const CTRL: u32 = 32;2021#[derive(Clone, Copy, Debug, PartialEq, Eq)]22enum Kind {23    Sine,24    Saw,25    Square,26    Pulse,27    Triangle,28    Noise,29    Pink,30    Wavetable,31    Fm,32    Adsr,33    Lfo,34    Lowpass,35    Highpass,36    Bandpass,37    Svf,38    Gain,39    Add,40    Sub,41    Mul,42    Mix,43    Delay,44    Saturate,45    Clip,46    Modal,47}4849struct KindInfo {50    kind: Kind,51    name: &'static str,52    title: &'static str,53    category: &'static str,54    doc: &'static str,55    rate: Rate,56    /// (name, unit, default, min, max, constant_only, doc)57    ports: &'static [(&'static str, Unit, f64, f64, f64, bool, &'static str)],58}5960const FREQ_DOC: &str = "Frequency in Hz. 0 (the default) follows the note, pitch bend included.";61const AMP_DOC: &str = "Output amplitude.";62const IN_DOC: &str = "Input signal.";6364const KINDS: &[KindInfo] = &[65    KindInfo {66        kind: Kind::Sine,67        name: "sine",68        title: "Sine",69        category: "source",70        doc: "Sine oscillator with a phase-modulation input.",71        rate: Rate::Audio,72        ports: &[73            ("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC),74            ("pm", Unit::Scalar, 0.0, -100.0, 100.0, false, "Phase modulation in radians."),75            ("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC),76        ],77    },78    KindInfo {79        kind: Kind::Saw,80        name: "saw",81        title: "Sawtooth",82        category: "source",83        doc: "Band-limited (polyBLEP) sawtooth.",84        rate: Rate::Audio,85        ports: &[("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC), ("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC)],86    },87    KindInfo {88        kind: Kind::Square,89        name: "square",90        title: "Square",91        category: "source",92        doc: "Band-limited (polyBLEP) square.",93        rate: Rate::Audio,94        ports: &[("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC), ("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC)],95    },96    KindInfo {97        kind: Kind::Pulse,98        name: "pulse",99        title: "Pulse",100        category: "source",101        doc: "Band-limited pulse with variable width, DC removed.",102        rate: Rate::Audio,103        ports: &[104            ("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC),105            ("width", Unit::Ratio, 0.5, 0.02, 0.98, false, "Duty cycle."),106            ("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC),107        ],108    },109    KindInfo {110        kind: Kind::Triangle,111        name: "triangle",112        title: "Triangle",113        category: "source",114        doc: "Band-limited (polyBLAMP) triangle.",115        rate: Rate::Audio,116        ports: &[("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC), ("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC)],117    },118    KindInfo {119        kind: Kind::Noise,120        name: "noise",121        title: "White Noise",122        category: "source",123        doc: "Uniform white noise, seeded per note.",124        rate: Rate::Audio,125        ports: &[("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC)],126    },127    KindInfo {128        kind: Kind::Pink,129        name: "pink",130        title: "Pink Noise",131        category: "source",132        doc: "Pink (-3 dB/octave) noise, seeded per note.",133        rate: Rate::Audio,134        ports: &[("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC)],135    },136    KindInfo {137        kind: Kind::Wavetable,138        name: "wavetable",139        title: "Wavetable",140        category: "source",141        doc: "Alias-free mip-mapped wavetable oscillator.",142        rate: Rate::Audio,143        ports: &[144            ("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC),145            ("shape", Unit::Count, 0.0, 0.0, 2.0, true, "Table: 0 sawtooth (1/n), 1 square (odd 1/n), 2 soft (1/n^2)."),146            ("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC),147        ],148    },149    KindInfo {150        kind: Kind::Fm,151        name: "fm",152        title: "FM Operator",153        category: "source",154        doc: "Sine operator at `freq * ratio` with phase modulation and self-feedback.",155        rate: Rate::Audio,156        ports: &[157            ("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC),158            ("ratio", Unit::Scalar, 1.0, 0.0, 64.0, false, "Frequency multiplier."),159            ("pm", Unit::Scalar, 0.0, -100.0, 100.0, false, "Phase modulation in radians."),160            ("feedback", Unit::Scalar, 0.0, 0.0, 6.0, false, "Self-modulation in radians."),161            ("amp", Unit::Scalar, 1.0, -16.0, 16.0, false, AMP_DOC),162        ],163    },164    KindInfo {165        kind: Kind::Adsr,166        name: "adsr",167        title: "ADSR Envelope",168        category: "envelope",169        doc: "Envelope from 0 to 1. Times are read at note start and every 32 samples.",170        rate: Rate::Control,171        ports: &[172            ("gate", Unit::Scalar, -1.0, -1.0, 1.0, false, "Opens above 0.5. A negative constant (the default) follows the note's gate."),173            ("attack", Unit::Seconds, 0.01, 0.0, 20.0, false, "Attack time."),174            ("decay", Unit::Seconds, 0.1, 0.0, 20.0, false, "Decay time (60 dB)."),175            ("sustain", Unit::Ratio, 0.7, 0.0, 1.0, false, "Sustain level."),176            ("release", Unit::Seconds, 0.2, 0.001, 30.0, false, "Release time (60 dB)."),177        ],178    },179    KindInfo {180        kind: Kind::Lfo,181        name: "lfo",182        title: "LFO",183        category: "modulator",184        doc: "Low-frequency oscillator in [-amp, amp], restarted at each note.",185        rate: Rate::Control,186        ports: &[187            ("rate", Unit::Hertz, 5.0, 0.0, 200.0, false, "Rate."),188            ("shape", Unit::Count, 0.0, 0.0, 4.0, true, "0 sine, 1 triangle, 2 rising saw, 3 square, 4 sample and hold."),189            ("amp", Unit::Scalar, 1.0, -1.0e5, 1.0e5, false, AMP_DOC),190        ],191    },192    KindInfo {193        kind: Kind::Lowpass,194        name: "lowpass",195        title: "Low-pass",196        category: "filter",197        doc: "12 dB/octave state-variable low-pass.",198        rate: Rate::Audio,199        ports: &[200            ("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC),201            ("cutoff", Unit::Hertz, 1000.0, 5.0, 24_000.0, false, "Cutoff frequency."),202            ("q", Unit::Scalar, 0.707, 0.3, 40.0, false, "Resonance (Q)."),203        ],204    },205    KindInfo {206        kind: Kind::Highpass,207        name: "highpass",208        title: "High-pass",209        category: "filter",210        doc: "12 dB/octave state-variable high-pass.",211        rate: Rate::Audio,212        ports: &[213            ("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC),214            ("cutoff", Unit::Hertz, 1000.0, 5.0, 24_000.0, false, "Cutoff frequency."),215            ("q", Unit::Scalar, 0.707, 0.3, 40.0, false, "Resonance (Q)."),216        ],217    },218    KindInfo {219        kind: Kind::Bandpass,220        name: "bandpass",221        title: "Band-pass",222        category: "filter",223        doc: "State-variable band-pass (peak gain Q).",224        rate: Rate::Audio,225        ports: &[226            ("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC),227            ("cutoff", Unit::Hertz, 1000.0, 5.0, 24_000.0, false, "Centre frequency."),228            ("q", Unit::Scalar, 2.0, 0.3, 40.0, false, "Resonance (Q)."),229        ],230    },231    KindInfo {232        kind: Kind::Svf,233        name: "svf",234        title: "State-Variable Filter",235        category: "filter",236        doc: "State-variable filter with a selectable response.",237        rate: Rate::Audio,238        ports: &[239            ("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC),240            ("cutoff", Unit::Hertz, 1000.0, 5.0, 24_000.0, false, "Cutoff frequency."),241            ("q", Unit::Scalar, 0.707, 0.3, 40.0, false, "Resonance (Q)."),242            ("mode", Unit::Count, 0.0, 0.0, 3.0, true, "0 low-pass, 1 band-pass, 2 high-pass, 3 notch."),243        ],244    },245    KindInfo {246        kind: Kind::Gain,247        name: "gain",248        title: "Gain",249        category: "math",250        doc: "Scales the input by a level in decibels.",251        rate: Rate::Audio,252        ports: &[("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC), ("db", Unit::Decibel, 0.0, -120.0, 36.0, false, "Gain in dB.")],253    },254    KindInfo {255        kind: Kind::Add,256        name: "add",257        title: "Add",258        category: "math",259        doc: "a + b.",260        rate: Rate::Audio,261        ports: &[("a", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, "First operand."), ("b", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, "Second operand.")],262    },263    KindInfo {264        kind: Kind::Sub,265        name: "sub",266        title: "Subtract",267        category: "math",268        doc: "a - b.",269        rate: Rate::Audio,270        ports: &[("a", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, "First operand."), ("b", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, "Second operand.")],271    },272    KindInfo {273        kind: Kind::Mul,274        name: "mul",275        title: "Multiply",276        category: "math",277        doc: "a * b (amplitude modulation, envelopes, scaling).",278        rate: Rate::Audio,279        ports: &[("a", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, "First operand."), ("b", Unit::Scalar, 1.0, -1.0e6, 1.0e6, false, "Second operand.")],280    },281    KindInfo {282        kind: Kind::Mix,283        name: "mix",284        title: "Crossfade",285        category: "math",286        doc: "a (1 - t) + b t.",287        rate: Rate::Audio,288        ports: &[289            ("a", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, "Signal at t = 0."),290            ("b", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, "Signal at t = 1."),291            ("t", Unit::Ratio, 0.5, 0.0, 1.0, false, "Crossfade position."),292        ],293    },294    KindInfo {295        kind: Kind::Delay,296        name: "delay",297        title: "Delay",298        category: "delay",299        doc: "Interpolated delay line with internal feedback. The only node whose `in` may read a later node: a feedback loop must pass through it.",300        rate: Rate::Audio,301        ports: &[302            ("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC),303            ("time", Unit::Seconds, 0.01, 0.0, 4.0, false, "Delay time; at least one sample, at most `max`."),304            ("feedback", Unit::Scalar, 0.0, -0.999, 0.999, false, "Internal feedback gain."),305            ("max", Unit::Seconds, 1.0, 0.001, 4.0, true, "Memory reserved per voice, in seconds."),306        ],307    },308    KindInfo {309        kind: Kind::Saturate,310        name: "saturate",311        title: "Saturate",312        category: "shaper",313        doc: "tanh(drive * in): soft saturation, bounded to [-1, 1]. Not oversampled.",314        rate: Rate::Audio,315        ports: &[("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC), ("drive", Unit::Scalar, 1.0, 0.0, 100.0, false, "Input gain before the curve.")],316    },317    KindInfo {318        kind: Kind::Clip,319        name: "clip",320        title: "Clip",321        category: "shaper",322        doc: "Hard limits the input to [lo, hi].",323        rate: Rate::Audio,324        ports: &[325            ("in", Unit::Scalar, 0.0, -1.0e6, 1.0e6, false, IN_DOC),326            ("lo", Unit::Scalar, -1.0, -1.0e6, 1.0e6, false, "Lower bound."),327            ("hi", Unit::Scalar, 1.0, -1.0e6, 1.0e6, false, "Upper bound."),328        ],329    },330    KindInfo {331        kind: Kind::Modal,332        name: "modal",333        title: "Modal Resonator",334        category: "resonator",335        doc: "Two-pole resonator with unit peak gain: one mode of a vibrating body.",336        rate: Rate::Audio,337        ports: &[338            ("in", Unit::Scalar, 0.0, -1.0e3, 1.0e3, false, IN_DOC),339            ("freq", Unit::Hertz, 0.0, 0.0, 24_000.0, false, FREQ_DOC),340            ("decay", Unit::Seconds, 0.5, 0.001, 60.0, false, "Decay time of the mode (60 dB)."),341            ("gain", Unit::Scalar, 1.0, -1.0e3, 1.0e3, false, "Output gain."),342        ],343    },344];345346pub fn node_descriptors() -> Vec<PatchNodeDesc> {347    KINDS348        .iter()349        .map(|k| PatchNodeDesc {350            kind: k.name.into(),351            title: k.title.into(),352            category: k.category.into(),353            doc: k.doc.into(),354            ports: k355                .ports356                .iter()357                .map(|(name, unit, default, min, max, constant_only, doc)| PortDesc {358                    name: name.to_string(),359                    unit: *unit,360                    default: *default,361                    min: *min,362                    max: *max,363                    constant_only: *constant_only,364                    doc: doc.to_string(),365                })366                .collect(),367            output_rate: k.rate,368        })369        .collect()370}371372pub fn desc() -> EngineDesc {373    EngineDesc {374        model: "patch".into(),375        title: "Patch".into(),376        family: "synth".into(),377        method: "Per-voice interpreter of a typed signal graph (`graph { }` block): oscillators, envelopes, filters, delays and arithmetic evaluated sample by sample in declaration order".into(),378        doc: "An instrument defined entirely by its graph. The graph's output is mono; velocity is not applied automatically (read `note.velocity` in the graph). The output is scaled by `gain` and soft-clipped at full scale. Control-rate nodes are evaluated at audio rate in this version.".into(),379        range: (0, 127),380        params: vec![381            num("gain", Unit::Decibel, -60.0, 12.0, -12.0, true, "Output level applied to the graph's output."),382            num("release", Unit::Seconds, 0.001, 10.0, 0.2, false, "Fade-out after note-off, used only when the graph has no amplitude envelope."),383        ],384        presets: Vec::new(),385        articulations: vec!["normal".into()],386        pitched: true,387    }388}389390#[derive(Clone, Copy, Debug)]391enum Src {392    Const(f32),393    Node(u32),394    Freq,395    Pitch,396    Velocity,397    Gate,398    Time,399}400401#[derive(Clone, Copy)]402struct CNode {403    kind: Kind,404    ins: [Src; MAX_PORTS],405}406407enum State {408    None,409    Osc(Oscillator),410    Phase(f32),411    Noise(Rng),412    Pink(PinkNoise),413    Fm(FmOperator),414    Adsr(Adsr, bool, bool),415    Lfo(Lfo),416    Svf(Svf, f32, f32),417    Delay(DelayLine),418    Modal(Biquad, f32, f32),419}420421pub struct Patch {422    sr: f32,423    r: Resolved,424    nodes: Vec<CNode>,425    output: usize,426    amp_env: Option<usize>,427    tables: [Wavetable; 3],428}429430pub struct Voice {431    vals: Vec<f32>,432    states: Vec<State>,433    freq: f32,434    pitch: f32,435    bend: f32,436    vel: f32,437    gate: f32,438    time: f32,439    tick: u32,440    fade: f32,441    fade_step: f32,442    released: bool,443}444445fn compile(spec: &PatchSpec) -> Result<Vec<CNode>, String> {446    spec.validate()?;447    if spec.nodes.len() > MAX_NODES {448        return Err(format!("patch has {} nodes; the limit is {MAX_NODES}", spec.nodes.len()));449    }450    let mut out = Vec::with_capacity(spec.nodes.len());451    for node in &spec.nodes {452        let info = KINDS.iter().find(|k| k.name == node.kind).ok_or_else(|| format!("node '{}': unknown kind '{}'", node.name, node.kind))?;453        let mut ins = [Src::Const(0.0); MAX_PORTS];454        for (i, (name, _, default, min, max, constant_only, _)) in info.ports.iter().enumerate() {455            ins[i] = match node.inputs.get(*name) {456                None => Src::Const(*default as f32),457                Some(PatchInput::Const(c)) => {458                    if !c.is_finite() || *c < *min || *c > *max {459                        return Err(format!("node '{}': port '{}' = {} is outside [{}, {}]", node.name, name, c, min, max));460                    }461                    Src::Const(*c as f32)462                }463                Some(_) if *constant_only => return Err(format!("node '{}': port '{}' must be a constant", node.name, name)),464                Some(PatchInput::Node(j)) => Src::Node(*j),465                Some(PatchInput::Note(n)) => match n {466                    NoteInput::Freq => Src::Freq,467                    NoteInput::Pitch => Src::Pitch,468                    NoteInput::Velocity => Src::Velocity,469                    NoteInput::Gate => Src::Gate,470                    NoteInput::Time => Src::Time,471                },472            };473            // Conventions: frequency 0 follows the note; a negative constant gate follows the note's gate.474            if *name == "freq" && matches!(ins[i], Src::Const(c) if c <= 0.0) {475                ins[i] = Src::Freq;476            }477            if *name == "gate" && matches!(ins[i], Src::Const(c) if c < 0.0) {478                ins[i] = Src::Gate;479            }480        }481        for port in node.inputs.keys() {482            if !info.ports.iter().any(|p| p.0 == port) {483                return Err(format!("node '{}': kind '{}' has no port '{}'", node.name, node.kind, port));484            }485        }486        out.push(CNode { kind: info.kind, ins });487    }488    Ok(out)489}490491impl Patch {492    fn make_state(&self, n: &CNode, seed: u64, index: usize) -> State {493        let sr = self.sr;494        let osc = |w: Waveform| {495            let mut o = Oscillator::new(sr);496            o.waveform = w;497            State::Osc(o)498        };499        match n.kind {500            Kind::Sine | Kind::Wavetable => State::Phase(0.0),501            Kind::Saw => osc(Waveform::Saw),502            Kind::Square => osc(Waveform::Square),503            Kind::Pulse => osc(Waveform::Pulse),504            Kind::Triangle => osc(Waveform::Triangle),505            Kind::Noise => State::Noise(Rng::new(seed ^ (index as u64).wrapping_mul(0xA24B_AED4_963E_E407))),506            Kind::Pink => State::Pink(PinkNoise::new(seed ^ (index as u64).wrapping_mul(0x9FB2_1C65_1E98_DF25))),507            Kind::Fm => State::Fm(FmOperator::default()),508            Kind::Adsr => State::Adsr(Adsr::new(sr), false, false),509            Kind::Lfo => {510                let mut l = Lfo::new(sr, seed ^ index as u64);511                let shape = if let Src::Const(c) = n.ins[1] { c as usize } else { 0 };512                l.shape = [LfoShape::Sine, LfoShape::Triangle, LfoShape::SawUp, LfoShape::Square, LfoShape::SampleHold][shape.min(4)];513                State::Lfo(l)514            }515            Kind::Lowpass | Kind::Highpass | Kind::Bandpass | Kind::Svf => State::Svf(Svf::new(sr), -1.0, -1.0),516            Kind::Delay => {517                let max = if let Src::Const(c) = n.ins[3] { c } else { 1.0 };518                State::Delay(DelayLine::new((max.clamp(0.001, 4.0) * sr) as usize + 4))519            }520            Kind::Modal => State::Modal(Biquad::default(), -1.0, -1.0),521            _ => State::None,522        }523    }524}525526impl Engine for Patch {527    type Voice = Voice;528529    fn prepare(&mut self, sample_rate: f32, _max_block: usize) {530        self.sr = sample_rate;531    }532533    fn make_voice(&self, _sr: f32) -> Voice {534        let states = self.nodes.iter().enumerate().map(|(i, n)| self.make_state(n, 0, i)).collect();535        Voice {536            vals: vec![0.0; self.nodes.len()],537            states,538            freq: 220.0,539            pitch: 57.0,540            bend: 1.0,541            vel: 0.0,542            gate: 0.0,543            time: 0.0,544            tick: 0,545            fade: 1.0,546            fade_step: 0.0,547            released: false,548        }549    }550551    fn start(&self, v: &mut Voice, note: &NoteOn, seed: u64) {552        v.vals.iter_mut().for_each(|x| *x = 0.0);553        for (i, (st, n)) in v.states.iter_mut().zip(&self.nodes).enumerate() {554            match st {555                State::Osc(o) => o.set_phase(0.0),556                State::Phase(p) => *p = 0.0,557                State::Noise(r) => *r = Rng::new(seed ^ (i as u64).wrapping_mul(0xA24B_AED4_963E_E407)),558                State::Pink(p) => *p = PinkNoise::new(seed ^ (i as u64).wrapping_mul(0x9FB2_1C65_1E98_DF25)),559                State::Fm(f) => f.reset(),560                State::Adsr(a, open, used) => {561                    a.reset();562                    *open = false;563                    *used = false;564                }565                State::Lfo(l) => {566                    let shape = l.shape;567                    *l = Lfo::new(self.sr, seed ^ i as u64);568                    l.shape = shape;569                }570                State::Svf(f, c, q) => {571                    f.reset();572                    *c = -1.0;573                    *q = -1.0;574                }575                State::Delay(d) => d.clear(),576                State::Modal(b, f, d) => {577                    b.reset();578                    *f = -1.0;579                    *d = -1.0;580                }581                State::None => {}582            }583            let _ = n;584        }585        v.freq = note.freq;586        v.pitch = note.pitch;587        v.bend = 1.0;588        v.vel = note.velocity.clamp(0.0, 1.0);589        v.gate = 1.0;590        v.time = 0.0;591        v.tick = 0;592        v.fade = 1.0;593        v.fade_step = 0.0;594        v.released = false;595    }596597    fn release(&self, v: &mut Voice) {598        v.gate = 0.0;599        v.released = true;600        if self.amp_env.is_none() {601            v.fade_step = 1.0 / (self.r.get("release") * self.sr).max(1.0);602        }603    }604605    fn bend(&self, v: &mut Voice, semitones: f32) {606        v.bend = semitones_to_ratio(semitones);607    }608609    fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {610        let sr = self.sr;611        let inv_sr = 1.0 / sr;612        let gain = db_to_lin(self.r.v[0]);613        let nyq = 0.49 * sr;614        for i in 0..left.len() {615            let freq = v.freq * v.bend;616            let ctrl = v.tick.is_multiple_of(CTRL);617            for k in 0..self.nodes.len() {618                let n = &self.nodes[k];619                // Reads an input port; nodes read their own previous sample for later indices (delay feedback).620                macro_rules! port {621                    ($p:expr) => {622                        match n.ins[$p] {623                            Src::Const(c) => c,624                            Src::Node(j) => v.vals[j as usize],625                            Src::Freq => freq,626                            Src::Pitch => v.pitch,627                            Src::Velocity => v.vel,628                            Src::Gate => v.gate,629                            Src::Time => v.time,630                        }631                    };632                }633                let y = match (&mut v.states[k], n.kind) {634                    (State::Phase(ph), Kind::Sine) => {635                        let y = super::engines::common::sin_turns(*ph + port!(1) * (1.0 / std::f32::consts::TAU)) * port!(2);636                        *ph += port!(0).clamp(0.0, nyq) * inv_sr;637                        if *ph >= 1.0 {638                            *ph -= 1.0;639                        }640                        y641                    }642                    (State::Phase(ph), Kind::Wavetable) => {643                        let inc = port!(0).clamp(0.0, nyq) * inv_sr;644                        let shape = if let Src::Const(c) = n.ins[1] { (c as usize).min(2) } else { 0 };645                        let y = self.tables[shape].read(*ph, inc) * port!(2);646                        *ph += inc;647                        if *ph >= 1.0 {648                            *ph -= 1.0;649                        }650                        y651                    }652                    (State::Osc(o), Kind::Pulse) => {653                        o.set_freq(port!(0));654                        o.set_pulse_width(port!(1));655                        o.tick() * port!(2)656                    }657                    (State::Osc(o), _) => {658                        o.set_freq(port!(0));659                        o.tick() * port!(1)660                    }661                    (State::Noise(r), _) => r.bipolar() * port!(0),662                    (State::Pink(p), _) => p.tick() * port!(0),663                    (State::Fm(op), _) => op.tick((port!(0) * port!(1)).clamp(0.0, nyq) * inv_sr, port!(2), port!(3)) * port!(4),664                    (State::Adsr(env, open, used), _) => {665                        if ctrl {666                            env.set(port!(1), port!(2), port!(3), port!(4));667                        }668                        let g = port!(0) > 0.5;669                        if g && !*open {670                            env.gate_on();671                            *used = true;672                        } else if !g && *open {673                            env.gate_off();674                        }675                        *open = g;676                        env.tick()677                    }678                    (State::Lfo(l), _) => {679                        if ctrl {680                            l.set_rate(port!(0));681                        }682                        l.tick() * port!(2)683                    }684                    (State::Svf(f, last_c, last_q), kind) => {685                        let (c, q) = (port!(1), port!(2));686                        if c != *last_c || q != *last_q {687                            f.set(c, q);688                            *last_c = c;689                            *last_q = q;690                        }691                        let o = f.tick(port!(0));692                        match kind {693                            Kind::Lowpass => o.low,694                            Kind::Highpass => o.high,695                            Kind::Bandpass => o.band,696                            _ => match n.ins[3] {697                                Src::Const(m) if m >= 2.5 => o.low + o.high,698                                Src::Const(m) if m >= 1.5 => o.high,699                                Src::Const(m) if m >= 0.5 => o.band,700                                _ => o.low,701                            },702                        }703                    }704                    (State::Delay(d), _) => {705                        let t = (port!(1) * sr).clamp(1.0, d.capacity() as f32 - 1.0);706                        let y = d.read(t);707                        d.write(flush((port!(0) + y * port!(2).clamp(-0.999, 0.999)).clamp(-64.0, 64.0)));708                        y709                    }710                    (State::Modal(b, last_f, last_d), _) => {711                        let (f, dec) = (port!(1), port!(2));712                        if f != *last_f || dec != *last_d {713                            b.set(BiquadCoefs::resonator(f, dec, sr));714                            *last_f = f;715                            *last_d = dec;716                        }717                        b.tick(port!(0)) * port!(3)718                    }719                    (State::None, Kind::Gain) => port!(0) * db_to_lin(port!(1)),720                    (State::None, Kind::Add) => port!(0) + port!(1),721                    (State::None, Kind::Sub) => port!(0) - port!(1),722                    (State::None, Kind::Mul) => port!(0) * port!(1),723                    (State::None, Kind::Mix) => {724                        let t = port!(2).clamp(0.0, 1.0);725                        port!(0) * (1.0 - t) + port!(1) * t726                    }727                    (State::None, Kind::Saturate) => fast_tanh(port!(0) * port!(1)),728                    (State::None, Kind::Clip) => {729                        let (lo, hi) = (port!(1), port!(2));730                        if lo <= hi {731                            port!(0).clamp(lo, hi)732                        } else {733                            0.0734                        }735                    }736                    _ => 0.0,737                };738                v.vals[k] = if y.is_finite() { y } else { 0.0 };739            }740            v.tick = v.tick.wrapping_add(1);741            v.time += inv_sr;742            if v.fade_step > 0.0 {743                v.fade = (v.fade - v.fade_step).max(0.0);744            }745            let y = soft_clip(v.vals[self.output] * gain) * v.fade;746            left[i] = y;747            right[i] = y;748        }749        match self.amp_env {750            Some(e) => !matches!(&v.states[e], State::Adsr(env, _, used) if *used && env.stage() == AdsrStage::Idle),751            None => !(v.released && v.fade <= 0.0),752        }753    }754755    fn set_param(&mut self, index: usize, value: f32) {756        if index < self.r.v.len() {757            self.r.v[index] = value;758        }759    }760}761762pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {763    let r = resolve(&desc(), spec)?;764    let patch = spec.patch.as_ref().ok_or_else(|| format!("instrument '{}': model 'patch' needs a graph", spec.name))?;765    let nodes = compile(patch).map_err(|e| format!("instrument '{}': {e}", spec.name))?;766    if let Some(e) = patch.amp_envelope {767        if nodes[e as usize].kind != Kind::Adsr {768            return Err(format!("instrument '{}': the amplitude envelope must be an adsr node", spec.name));769        }770    }771    let saw: Vec<f32> = (1..512).map(|k| 1.0 / k as f32).collect();772    let square: Vec<f32> = (1..512).map(|k| if k % 2 == 1 { 1.0 / k as f32 } else { 0.0 }).collect();773    let soft: Vec<f32> = (1..512).map(|k| 1.0 / (k * k) as f32).collect();774    let tables = [Wavetable::from_harmonics(&saw), Wavetable::from_harmonics(&square), Wavetable::from_harmonics(&soft)];775    let e = Patch { sr: 48_000.0, r, nodes, output: patch.output as usize, amp_env: patch.amp_envelope.map(|e| e as usize), tables };776    Ok(Box::new(Poly::new(e, seed)))777}778
Files main
Menu

Theme