Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/src/engines/fm.rs3//! Description: Four-operator FM (phase modulation) synthesiser with six algorithms.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use super::common::EnvSettings;9use crate::instrument::{Instrument, NoteOn};10use crate::params::{envelope_params, num, preset, resolve, Resolved};11use crate::poly::{Engine, Poly};12use sonata_dsp::core::semitones_to_ratio;13use sonata_dsp::env::Adsr;14use sonata_dsp::osc::FmOperator;15use sonata_ir::{EngineDesc, InstrumentSpec, Unit};1617pub fn desc() -> EngineDesc {18 let mut params = vec![19 num("algorithm", Unit::Count, 1.0, 6.0, 4.0, false, "Routing of the four operators. 1: 4>3>2>1. 2: (4+3)>2>1. 3: (4>3)+2 >1. 4: (4>3) + (2>1), two carriers. 5: 4 > 1, 2 and 3, three carriers. 6: four carriers (additive)."),20 num("feedback", Unit::Ratio, 0.0, 1.0, 0.0, true, "Self-modulation of operator 4 (towards a sawtooth, then noise)."),21 num("velocity_to_index", Unit::Ratio, 0.0, 1.0, 0.6, false, "How much the modulator levels follow velocity (brighter when played harder)."),22 ];23 let defaults = [(1.0, 1.0, 0.001, 1.2, 0.0), (1.0, 0.35, 0.001, 0.5, 0.0), (1.0, 0.8, 0.001, 1.5, 0.0), (14.0, 0.25, 0.001, 0.12, 0.0)];24 for (k, (ratio, level, attack, decay, sustain)) in defaults.iter().enumerate() {25 let n = k + 1;26 params.push(num(27 &format!("op{n}.ratio"),28 Unit::Scalar,29 0.25,30 32.0,31 *ratio,32 false,33 &format!("Frequency of operator {n} as a multiple of the note frequency."),34 ));35 params.push(num(36 &format!("op{n}.level"),37 Unit::Ratio,38 0.0,39 1.0,40 *level,41 true,42 &format!("Output level of operator {n}: loudness for a carrier, modulation index (up to 4 pi radians) for a modulator."),43 ));44 params.push(num(&format!("op{n}.attack"), Unit::Seconds, 0.0, 5.0, *attack, false, &format!("Attack of operator {n}'s envelope.")));45 params.push(num(&format!("op{n}.decay"), Unit::Seconds, 0.005, 20.0, *decay, false, &format!("Decay of operator {n}'s envelope.")));46 params.push(num(&format!("op{n}.sustain"), Unit::Ratio, 0.0, 1.0, *sustain, false, &format!("Sustain level of operator {n}'s envelope.")));47 }48 params.extend(envelope_params(false, 0.001, 0.0, 1.0, 0.25));49 EngineDesc {50 model: "fm".into(),51 title: "FM Synth".into(),52 family: "synth".into(),53 method: "Phase-modulation synthesis: four sine operators with individual envelopes, six routings, feedback on operator 4".into(),54 doc: "Classic four-operator FM. Each operator is a sine with its own envelope; modulators change the timbre over time. The `envelope` slot is a master amplitude envelope applied after the operators.".into(),55 range: (12, 120),56 params,57 presets: vec![58 preset("epiano", "Tine electric piano: two carrier/modulator pairs.", &[], &[]),59 preset("bell", "Inharmonic bell.", &[("algorithm", 4.0), ("op1.ratio", 1.0), ("op1.decay", 5.0), ("op2.ratio", 3.5), ("op2.level", 0.55), ("op2.decay", 4.0), ("op3.ratio", 2.01), ("op3.level", 0.5), ("op3.decay", 3.0), ("op4.ratio", 7.07), ("op4.level", 0.5), ("op4.decay", 1.5), ("envelope.release", 2.0)], &[]),60 preset("brass", "Swelling FM brass.", &[("algorithm", 1.0), ("op1.attack", 0.05), ("op1.decay", 0.3), ("op1.sustain", 0.85), ("op2.ratio", 1.0), ("op2.level", 0.5), ("op2.attack", 0.08), ("op2.decay", 0.4), ("op2.sustain", 0.6), ("op3.level", 0.0), ("op4.level", 0.0), ("envelope.release", 0.12), ("velocity_to_index", 0.8)], &[]),61 preset("bass", "Punchy FM bass.", &[("algorithm", 1.0), ("op1.decay", 1.0), ("op1.sustain", 0.5), ("op2.ratio", 1.0), ("op2.level", 0.6), ("op2.decay", 0.18), ("op3.ratio", 2.0), ("op3.level", 0.3), ("op3.decay", 0.08), ("op4.level", 0.0), ("envelope.release", 0.1)], &[]),62 preset("organ", "Additive drawbar-like tone.", &[("algorithm", 6.0), ("op1.sustain", 1.0), ("op2.ratio", 2.0), ("op2.level", 0.6), ("op2.sustain", 1.0), ("op3.ratio", 3.0), ("op3.level", 0.4), ("op3.sustain", 1.0), ("op4.ratio", 4.0), ("op4.level", 0.3), ("op4.sustain", 1.0), ("envelope.release", 0.05), ("velocity_to_index", 0.0)], &[]),63 preset("mallet", "Wooden mallet strike.", &[("algorithm", 4.0), ("op1.decay", 0.7), ("op2.ratio", 4.0), ("op2.level", 0.3), ("op2.decay", 0.06), ("op3.ratio", 1.0), ("op3.level", 0.0), ("op4.level", 0.0), ("envelope.release", 0.3)], &[]),64 ],65 articulations: vec!["normal".into(), "staccato".into(), "legato".into(), "accent".into()],66 pitched: true,67 }68}6970const LEVEL: f32 = 0.3;71const MAX_INDEX: f32 = 4.0 * std::f32::consts::PI;7273pub struct Fm {74 sr: f32,75 r: Resolved,76 env: EnvSettings,77 base: usize,78}7980pub struct Voice {81 ops: [FmOperator; 4],82 envs: [Adsr; 4],83 amp: Adsr,84 inc: [f32; 4],85 freq: f32,86 bend: f32,87 vel: f32,88}8990impl Engine for Fm {91 type Voice = Voice;92 fn prepare(&mut self, sample_rate: f32, _max_block: usize) {93 self.sr = sample_rate;94 }95 fn make_voice(&self, sr: f32) -> Voice {96 Voice { ops: [FmOperator::default(); 4], envs: [Adsr::new(sr); 4], amp: Adsr::new(sr), inc: [0.0; 4], freq: 220.0, bend: 1.0, vel: 0.0 }97 }98 fn start(&self, v: &mut Voice, note: &NoteOn, _seed: u64) {99 v.freq = note.freq;100 v.bend = 1.0;101 v.vel = note.velocity.clamp(0.0, 1.0);102 for k in 0..4 {103 let b = self.base + 5 * k;104 v.ops[k].reset();105 v.envs[k].reset();106 v.envs[k].set(self.r.v[b + 2], self.r.v[b + 3], self.r.v[b + 4], self.env.release);107 v.envs[k].gate_on();108 let f = note.freq * self.r.v[b];109 v.inc[k] = if f < 0.45 * self.sr { f / self.sr } else { 0.0 };110 }111 self.env.start(&mut v.amp);112 }113 fn release(&self, v: &mut Voice) {114 v.amp.gate_off();115 v.envs.iter_mut().for_each(|e| e.gate_off());116 }117 fn bend(&self, v: &mut Voice, semitones: f32) {118 v.bend = semitones_to_ratio(semitones);119 }120 fn render(&self, v: &mut Voice, left: &mut [f32], right: &mut [f32]) -> bool {121 let alg = self.r.get("algorithm").round() as u32;122 let fb = self.r.get("feedback") * 2.5;123 let v2i = self.r.get("velocity_to_index");124 let mod_scale = MAX_INDEX * (1.0 - v2i + v2i * v.vel);125 let lv: [f32; 4] = std::array::from_fn(|k| self.r.v[self.base + 5 * k + 1]);126 let carriers = match alg {127 1..=3 => 1.0,128 4 => lv[0] + lv[2],129 5 => lv[0] + lv[1] + lv[2],130 _ => lv[0] + lv[1] + lv[2] + lv[3],131 };132 let norm = LEVEL * (0.2 + 0.8 * v.vel) / carriers.max(1.0);133 let b = v.bend;134 for i in 0..left.len() {135 let e: [f32; 4] = std::array::from_fn(|k| v.envs[k].tick() * lv[k]);136 let o4 = v.ops[3].tick(v.inc[3] * b, 0.0, fb) * e[3];137 let y = match alg {138 1 => {139 let o3 = v.ops[2].tick(v.inc[2] * b, o4 * mod_scale, 0.0) * e[2];140 let o2 = v.ops[1].tick(v.inc[1] * b, o3 * mod_scale, 0.0) * e[1];141 v.ops[0].tick(v.inc[0] * b, o2 * mod_scale, 0.0) * e[0]142 }143 2 => {144 let o3 = v.ops[2].tick(v.inc[2] * b, 0.0, 0.0) * e[2];145 let o2 = v.ops[1].tick(v.inc[1] * b, (o3 + o4) * mod_scale, 0.0) * e[1];146 v.ops[0].tick(v.inc[0] * b, o2 * mod_scale, 0.0) * e[0]147 }148 3 => {149 let o3 = v.ops[2].tick(v.inc[2] * b, o4 * mod_scale, 0.0) * e[2];150 let o2 = v.ops[1].tick(v.inc[1] * b, 0.0, 0.0) * e[1];151 v.ops[0].tick(v.inc[0] * b, (o2 + o3) * mod_scale, 0.0) * e[0]152 }153 4 => {154 let o3 = v.ops[2].tick(v.inc[2] * b, o4 * mod_scale, 0.0) * e[2];155 let o2 = v.ops[1].tick(v.inc[1] * b, 0.0, 0.0) * e[1];156 v.ops[0].tick(v.inc[0] * b, o2 * mod_scale, 0.0) * e[0] + o3157 }158 5 => {159 let m = o4 * mod_scale;160 v.ops[0].tick(v.inc[0] * b, m, 0.0) * e[0] + v.ops[1].tick(v.inc[1] * b, m, 0.0) * e[1] + v.ops[2].tick(v.inc[2] * b, m, 0.0) * e[2]161 }162 _ => {163 v.ops[0].tick(v.inc[0] * b, 0.0, 0.0) * e[0]164 + v.ops[1].tick(v.inc[1] * b, 0.0, 0.0) * e[1]165 + v.ops[2].tick(v.inc[2] * b, 0.0, 0.0) * e[2]166 + o4167 }168 };169 let y = y * norm * v.amp.tick();170 left[i] = y;171 right[i] = y;172 }173 // The note ends with the master envelope, or when every carrier envelope has decayed to silence.174 let carriers_idle = match alg {175 1..=3 => v.envs[0].value() < 1e-4 && v.envs[0].stage() != sonata_dsp::env::AdsrStage::Attack,176 _ => false,177 };178 !(v.amp.is_idle() || carriers_idle)179 }180 fn set_param(&mut self, index: usize, value: f32) {181 if index < self.r.v.len() {182 self.r.v[index] = value;183 }184 }185 fn decays_naturally(&self) -> bool {186 true187 }188}189190pub fn build(spec: &InstrumentSpec, _tuning: f64, seed: u64) -> Result<Box<dyn Instrument>, String> {191 let r = resolve(&desc(), spec)?;192 Ok(Box::new(Poly::new(Fm { sr: 48_000.0, env: EnvSettings::read(&r, false), base: r.idx("op1.ratio"), r }, seed)))193}194