Repository Public
1//! ORIX Sonata2//! File: crates/sonata-instruments/src/params.rs3//! Description: Helpers to declare engine parameters and to resolve an InstrumentSpec against an EngineDesc.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use sonata_ir::{EngineDesc, InstrumentSpec, ParamDesc, ParamValue, PresetDesc, Unit};910/// Numeric parameter.11pub fn num(name: &str, unit: Unit, min: f64, max: f64, default: f64, automatable: bool, doc: &str) -> ParamDesc {12 ParamDesc::num(name, unit, min, max, default, automatable, doc)13}1415pub fn choice(name: &str, choices: &[&str], default: &str, doc: &str) -> ParamDesc {16 ParamDesc::choice(name, choices, default, doc)17}1819/// The five parameters of the `envelope` slot: `envelope natural|adsr(attack:, decay:, sustain:, release:)`.20///21/// `natural` (struck and plucked engines only) keeps the engine's own decay and uses only22/// `envelope.release` as the damping time after note-off.23pub fn envelope_params(natural: bool, attack: f64, decay: f64, sustain: f64, release: f64) -> Vec<ParamDesc> {24 let kinds: &[&str] = if natural { &["natural", "adsr"] } else { &["adsr"] };25 vec![26 choice(27 "envelope",28 kinds,29 kinds[0],30 "Amplitude envelope: `adsr` shapes the level; `natural` leaves the model's own decay and only damps after note-off.",31 ),32 num("envelope.attack", Unit::Seconds, 0.0, 10.0, attack, false, "Attack time (linear rise to full level)."),33 num("envelope.decay", Unit::Seconds, 0.0, 20.0, decay, false, "Decay time: 60 dB of the distance to the sustain level."),34 num("envelope.sustain", Unit::Ratio, 0.0, 1.0, sustain, false, "Sustain level."),35 num("envelope.release", Unit::Seconds, 0.001, 30.0, release, false, "Release time after note-off (60 dB)."),36 ]37}3839pub fn preset(name: &str, doc: &str, values: &[(&str, f64)], choices: &[(&str, &str)]) -> PresetDesc {40 PresetDesc {41 name: name.into(),42 doc: doc.into(),43 values: values.iter().map(|(k, v)| (k.to_string(), *v)).collect(),44 choices: choices.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect(),45 }46}4748/// Parameter values of one instrument instance, indexed like `EngineDesc::params`.49#[derive(Clone, Debug)]50pub struct Resolved {51 /// Numeric value (canonical unit); 0 for choices and lists.52 pub v: Vec<f32>,53 /// Index of the selected choice; 0 for other parameters.54 pub c: Vec<usize>,55 names: Vec<String>,56}5758impl Resolved {59 /// Index of a parameter by name. Panics on an unknown name: engines only ask for their own60 /// parameters, and a unit test resolves every engine.61 pub fn idx(&self, name: &str) -> usize {62 self.names.iter().position(|n| n == name).unwrap_or_else(|| panic!("engine parameter '{name}' is not declared"))63 }64 pub fn get(&self, name: &str) -> f32 {65 self.v[self.idx(name)]66 }67 pub fn pick(&self, name: &str) -> usize {68 self.c[self.idx(name)]69 }70}7172/// Resolves defaults, then the preset named by `"preset"`, then the spec's own overrides.73/// Unknown names, wrong value kinds and unknown choices are errors; numbers are clamped to the74/// declared range (the compiler already rejects out-of-range literals with a diagnostic).75pub fn resolve(desc: &EngineDesc, spec: &InstrumentSpec) -> Result<Resolved, String> {76 let mut r = Resolved {77 v: desc.params.iter().map(|p| p.default as f32).collect(),78 c: vec![0; desc.params.len()],79 names: desc.params.iter().map(|p| p.name.clone()).collect(),80 };81 for (i, p) in desc.params.iter().enumerate() {82 if let Some(d) = &p.default_choice {83 r.c[i] = p.choices.iter().position(|c| c == d).unwrap_or(0);84 }85 }86 let find = |name: &str| {87 desc.params.iter().position(|p| p.name == name).ok_or_else(|| format!("instrument '{}': model '{}' has no parameter '{}'", spec.name, desc.model, name))88 };89 if let Some(pv) = spec.params.get("preset") {90 let name = pv.as_text().ok_or_else(|| format!("instrument '{}': preset must be a name", spec.name))?;91 let pr = desc92 .presets93 .iter()94 .find(|p| p.name == name)95 .ok_or_else(|| format!("instrument '{}': model '{}' has no preset '{}'", spec.name, desc.model, name))?;96 for (k, v) in &pr.values {97 r.v[find(k)?] = *v as f32;98 }99 for (k, v) in &pr.choices {100 let i = find(k)?;101 r.c[i] = desc.params[i].choices.iter().position(|c| c == v).unwrap_or(0);102 }103 }104 for (k, value) in &spec.params {105 if k == "preset" {106 continue;107 }108 let i = find(k)?;109 let p = &desc.params[i];110 match (p.unit, value) {111 (Unit::Choice, ParamValue::Text(t)) => {112 r.c[i] = p113 .choices114 .iter()115 .position(|c| c == t)116 .ok_or_else(|| format!("instrument '{}': '{}' is not a valid {} (expected one of {})", spec.name, t, k, p.choices.join(", ")))?;117 }118 (Unit::HertzList | Unit::ScalarList, ParamValue::List(l)) => {119 if l.iter().any(|x| !x.is_finite() || *x < p.min || *x > p.max) {120 return Err(format!("instrument '{}': a value of '{}' is outside [{}, {}]", spec.name, k, p.min, p.max));121 }122 }123 (Unit::Choice | Unit::HertzList | Unit::ScalarList, _) => {124 return Err(format!("instrument '{}': parameter '{}' has the wrong kind of value", spec.name, k))125 }126 (_, ParamValue::Num(x)) if x.is_finite() => r.v[i] = x.clamp(p.min, p.max) as f32,127 _ => return Err(format!("instrument '{}': parameter '{}' needs a finite number", spec.name, k)),128 }129 }130 Ok(r)131}132133/// A list parameter of the spec (empty when absent).134pub fn list(spec: &InstrumentSpec, name: &str) -> Vec<f32> {135 spec.params.get(name).and_then(|v| v.as_list()).map(|l| l.iter().map(|x| *x as f32).collect()).unwrap_or_default()136}137