SPB Git

Repository Public

registry.rs 10.2 KB 274 lines rust

1//! ORIX Sonata2//! File: crates/sonata-ir/src/registry.rs3//! Description: Metadata types describing instrument engines, effects and patch nodes. The DSP4//! crates publish the tables; the compiler validates against them; the documentation and the5//! inspectors are generated from them, so the three can never diverge.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use crate::patch::Rate;11use serde::{Deserialize, Serialize};1213/// Physical dimension of a parameter, with its canonical unit.14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]15#[serde(rename_all = "snake_case")]16pub enum Unit {17    /// Dimensionless number.18    Scalar,19    /// Dimensionless in [0, 1] (accepts `%` literals).20    Ratio,21    /// Level, canonical dB.22    Decibel,23    /// Frequency, canonical Hz.24    Hertz,25    /// Absolute time, canonical seconds (accepts `ms`, `s`).26    Seconds,27    /// Pitch interval, canonical semitones (accepts `st`, `cents`).28    Semitones,29    /// Integer count.30    Count,31    /// Angle, canonical degrees.32    Degrees,33    /// List of frequencies (Hz).34    HertzList,35    /// List of dimensionless numbers.36    ScalarList,37    /// One of `ParamDesc::choices`.38    Choice,39}4041#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]42pub struct ParamDesc {43    /// Dotted for slot parameters (`excitation.position`).44    pub name: String,45    pub unit: Unit,46    pub min: f64,47    pub max: f64,48    pub default: f64,49    /// Default of a `Choice` parameter, and the accepted values.50    #[serde(default, skip_serializing_if = "Option::is_none")]51    pub default_choice: Option<String>,52    #[serde(default, skip_serializing_if = "Vec::is_empty")]53    pub choices: Vec<String>,54    /// Can be automated and changed while sounding (smoothed by the runtime).55    pub automatable: bool,56    pub doc: String,57}5859impl ParamDesc {60    pub fn num(name: &str, unit: Unit, min: f64, max: f64, default: f64, automatable: bool, doc: &str) -> ParamDesc {61        ParamDesc { name: name.into(), unit, min, max, default, default_choice: None, choices: Vec::new(), automatable, doc: doc.into() }62    }63    pub fn choice(name: &str, choices: &[&str], default: &str, doc: &str) -> ParamDesc {64        ParamDesc {65            name: name.into(),66            unit: Unit::Choice,67            min: 0.0,68            max: 0.0,69            default: 0.0,70            default_choice: Some(default.into()),71            choices: choices.iter().map(|s| s.to_string()).collect(),72            automatable: false,73            doc: doc.into(),74        }75    }76    pub fn list(name: &str, unit: Unit, min: f64, max: f64, doc: &str) -> ParamDesc {77        ParamDesc { name: name.into(), unit, min, max, default: 0.0, default_choice: None, choices: Vec::new(), automatable: false, doc: doc.into() }78    }79}8081#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]82pub struct PresetDesc {83    pub name: String,84    pub doc: String,85    /// Numeric overrides, canonical units.86    pub values: Vec<(String, f64)>,87    /// Choice overrides.88    #[serde(default, skip_serializing_if = "Vec::is_empty")]89    pub choices: Vec<(String, String)>,90}9192/// Latency of an effect: `seconds * sample_rate` rounded half up, plus `samples`.93#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]94pub struct LatencySpec {95    pub seconds: f64,96    pub samples: u32,97}9899impl LatencySpec {100    pub fn at(&self, sample_rate: u32) -> u32 {101        (self.seconds * sample_rate as f64 + 0.5).floor() as u32 + self.samples102    }103}104105#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]106pub struct EffectDesc {107    /// Identifier used in source (`reverb`, `eq`, `compressor`).108    pub kind: String,109    pub title: String,110    pub category: String,111    pub doc: String,112    pub params: Vec<ParamDesc>,113    pub presets: Vec<PresetDesc>,114    pub latency: LatencySpec,115    /// Default dry/wet mix in [0, 1].116    pub default_mix: f64,117}118119#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]120pub struct EngineDesc {121    /// Identifier used after `model` (`piano`, `plucked_string`, `bowed_string`, `patch`).122    pub model: String,123    pub title: String,124    /// `keyboard`, `plucked`, `bowed`, `woodwind`, `brass`, `organ`, `bass`, `synth`, `percussion`, `voice`.125    pub family: String,126    /// Synthesis method in plain words (shown in Instrument Lab and the docs).127    pub method: String,128    pub doc: String,129    /// Playable MIDI range (inclusive). Notes outside produce warning M4xxx and are still rendered.130    pub range: (u8, u8),131    pub params: Vec<ParamDesc>,132    pub presets: Vec<PresetDesc>,133    /// Articulations the engine responds to (snake_case names of `Articulation`).134    pub articulations: Vec<String>,135    /// Unpitched engines ignore the note pitch (kick, snare, hi-hat).136    pub pitched: bool,137}138139#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]140pub struct PortDesc {141    pub name: String,142    pub unit: Unit,143    pub default: f64,144    pub min: f64,145    pub max: f64,146    /// A constant-only port cannot be driven by another node (table sizes, modes).147    pub constant_only: bool,148    pub doc: String,149}150151#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]152pub struct PatchNodeDesc {153    pub kind: String,154    pub title: String,155    /// `source`, `envelope`, `modulator`, `filter`, `math`, `delay`, `shaper`, `resonator`.156    pub category: String,157    pub doc: String,158    pub ports: Vec<PortDesc>,159    pub output_rate: Rate,160}161162/// Everything the compiler needs to know about the DSP layer.163#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]164pub struct Registry {165    pub engines: Vec<EngineDesc>,166    pub effects: Vec<EffectDesc>,167    pub patch_nodes: Vec<PatchNodeDesc>,168}169170impl Registry {171    pub fn engine(&self, model: &str) -> Option<&EngineDesc> {172        self.engines.iter().find(|e| e.model == model)173    }174    pub fn effect(&self, kind: &str) -> Option<&EffectDesc> {175        self.effects.iter().find(|e| e.kind == kind)176    }177    pub fn patch_node(&self, kind: &str) -> Option<&PatchNodeDesc> {178        self.patch_nodes.iter().find(|e| e.kind == kind)179    }180181    /// Internal consistency of the tables (run as a unit test by the crates that publish them).182    pub fn validate(&self) -> Result<(), String> {183        fn params(owner: &str, ps: &[ParamDesc], presets: &[PresetDesc]) -> Result<(), String> {184            let mut seen = std::collections::BTreeSet::new();185            for p in ps {186                if !seen.insert(&p.name) {187                    return Err(format!("{owner}: duplicate parameter '{}'", p.name));188                }189                if p.doc.trim().is_empty() {190                    return Err(format!("{owner}: parameter '{}' is undocumented", p.name));191                }192                match p.unit {193                    Unit::Choice => {194                        let d = p.default_choice.as_ref().ok_or(format!("{owner}: choice '{}' has no default", p.name))?;195                        if !p.choices.contains(d) {196                            return Err(format!("{owner}: default of '{}' is not a choice", p.name));197                        }198                    }199                    Unit::HertzList | Unit::ScalarList => {}200                    _ => {201                        if !(p.min.is_finite() && p.max.is_finite() && p.min <= p.default && p.default <= p.max) {202                            return Err(format!("{owner}: parameter '{}' default {} is outside [{}, {}]", p.name, p.default, p.min, p.max));203                        }204                    }205                }206            }207            for pr in presets {208                for (k, v) in &pr.values {209                    let p = ps.iter().find(|p| &p.name == k).ok_or(format!("{owner}: preset '{}' sets unknown parameter '{k}'", pr.name))?;210                    if *v < p.min || *v > p.max {211                        return Err(format!("{owner}: preset '{}' sets '{k}' = {v} outside [{}, {}]", pr.name, p.min, p.max));212                    }213                }214                for (k, v) in &pr.choices {215                    let p = ps.iter().find(|p| &p.name == k).ok_or(format!("{owner}: preset '{}' sets unknown choice '{k}'", pr.name))?;216                    if !p.choices.contains(v) {217                        return Err(format!("{owner}: preset '{}' sets '{k}' to unknown choice '{v}'", pr.name));218                    }219                }220            }221            Ok(())222        }223        let mut names = std::collections::BTreeSet::new();224        for e in &self.engines {225            if !names.insert(format!("engine:{}", e.model)) {226                return Err(format!("duplicate engine '{}'", e.model));227            }228            if e.range.0 > e.range.1 {229                return Err(format!("engine '{}' has an empty range", e.model));230            }231            params(&format!("engine '{}'", e.model), &e.params, &e.presets)?;232        }233        for e in &self.effects {234            if !names.insert(format!("effect:{}", e.kind)) {235                return Err(format!("duplicate effect '{}'", e.kind));236            }237            if !(0.0..=1.0).contains(&e.default_mix) {238                return Err(format!("effect '{}' default mix is outside [0, 1]", e.kind));239            }240            params(&format!("effect '{}'", e.kind), &e.params, &e.presets)?;241        }242        for n in &self.patch_nodes {243            if !names.insert(format!("node:{}", n.kind)) {244                return Err(format!("duplicate patch node '{}'", n.kind));245            }246        }247        Ok(())248    }249}250251#[cfg(test)]252mod tests {253    use super::*;254255    #[test]256    fn validation_catches_bad_tables() {257        let mut r = Registry::default();258        r.effects.push(EffectDesc {259            kind: "delay".into(),260            title: "Delay".into(),261            category: "time".into(),262            doc: "d".into(),263            params: vec![ParamDesc::num("time", Unit::Seconds, 0.001, 4.0, 0.25, true, "Delay time.")],264            presets: vec![PresetDesc { name: "slap".into(), doc: "".into(), values: vec![("time".into(), 0.09)], choices: vec![] }],265            latency: LatencySpec::default(),266            default_mix: 0.3,267        });268        r.validate().unwrap();269        r.effects[0].presets[0].values[0].1 = 9.0;270        assert!(r.validate().is_err());271        assert_eq!(LatencySpec { seconds: 0.005, samples: 1 }.at(48_000), 241);272    }273}274
Files main
Menu

Theme