Skip to main content

weirdnet_audio_plugin/
params.rs

1use crate::PluginError;
2use std::collections::BTreeMap;
3
4/// The type of a parameter.
5#[derive(Debug, Clone, PartialEq)]
6pub enum ParamKind {
7    /// A number between [`ParamSpec::min`] and [`ParamSpec::max`].
8    Float,
9    /// On or off.
10    Bool,
11    /// One of a fixed list of names.
12    Choice(&'static [&'static str]),
13}
14
15/// One parameter's value.
16#[derive(Debug, Clone, PartialEq)]
17pub enum ParamValue {
18    Float(f64),
19    Bool(bool),
20    Choice(String),
21}
22
23/// A parameter a plugin takes.
24#[derive(Debug, Clone, PartialEq)]
25pub struct ParamSpec {
26    pub name: &'static str,
27    pub kind: ParamKind,
28    /// The lowest allowed value (floats only).
29    pub min: f64,
30    /// The highest allowed value (floats only).
31    pub max: f64,
32    pub default: ParamValue,
33    /// `"dB"`, `"Hz"`, `""` and so on, for display.
34    pub unit: &'static str,
35}
36
37impl ParamSpec {
38    pub const fn float(name: &'static str, min: f64, max: f64, default: f64, unit: &'static str) -> Self {
39        ParamSpec { name, kind: ParamKind::Float, min, max, default: ParamValue::Float(default), unit }
40    }
41
42    pub const fn boolean(name: &'static str, default: bool) -> Self {
43        ParamSpec { name, kind: ParamKind::Bool, min: 0.0, max: 1.0, default: ParamValue::Bool(default), unit: "" }
44    }
45
46    pub fn choice(name: &'static str, options: &'static [&'static str], default: &str) -> Self {
47        assert!(options.contains(&default), "the default {default:?} of {name} is not one of its options");
48        ParamSpec { name, kind: ParamKind::Choice(options), min: 0.0, max: 0.0, default: ParamValue::Choice(default.to_string()), unit: "" }
49    }
50
51    fn check(&self, value: &ParamValue) -> Result<(), PluginError> {
52        match (&self.kind, value) {
53            (ParamKind::Float, ParamValue::Float(x)) => {
54                if !x.is_finite() {
55                    Err(PluginError::invalid(self.name, "not a finite number"))
56                } else if *x < self.min || *x > self.max {
57                    Err(PluginError::invalid(self.name, format!("{x} is outside {} to {} {}", self.min, self.max, self.unit).trim_end().to_string()))
58                } else {
59                    Ok(())
60                }
61            }
62            (ParamKind::Bool, ParamValue::Bool(_)) => Ok(()),
63            (ParamKind::Choice(options), ParamValue::Choice(c)) => {
64                if options.contains(&c.as_str()) {
65                    Ok(())
66                } else {
67                    Err(PluginError::invalid(self.name, format!("{c:?} is not one of {}", options.join(", "))))
68                }
69            }
70            _ => Err(PluginError::invalid(self.name, "the value has the wrong type")),
71        }
72    }
73}
74
75/// Values for one use of a plugin, by parameter name. Missing names mean the default.
76#[derive(Debug, Clone, PartialEq, Default)]
77pub struct ParamValues {
78    values: BTreeMap<String, ParamValue>,
79}
80
81impl ParamValues {
82    pub fn new() -> Self {
83        ParamValues::default()
84    }
85
86    pub fn set(&mut self, name: &str, value: ParamValue) {
87        self.values.insert(name.to_string(), value);
88    }
89
90    pub fn with_float(mut self, name: &str, x: f64) -> Self {
91        self.set(name, ParamValue::Float(x));
92        self
93    }
94
95    pub fn with_bool(mut self, name: &str, b: bool) -> Self {
96        self.set(name, ParamValue::Bool(b));
97        self
98    }
99
100    pub fn with_choice(mut self, name: &str, c: &str) -> Self {
101        self.set(name, ParamValue::Choice(c.to_string()));
102        self
103    }
104
105    pub fn get(&self, name: &str) -> Option<&ParamValue> {
106        self.values.get(name)
107    }
108
109    /// Entries in name order.
110    pub fn iter(&self) -> impl Iterator<Item = (&str, &ParamValue)> {
111        self.values.iter().map(|(k, v)| (k.as_str(), v))
112    }
113
114    pub fn len(&self) -> usize {
115        self.values.len()
116    }
117
118    pub fn is_empty(&self) -> bool {
119        self.values.is_empty()
120    }
121
122    /// Checks every value against `specs` (unknown names, wrong types and out-of-range values are errors) and fills in the defaults.
123    /// The result has exactly one value per spec, so two uses that mean the same thing resolve to equal values.
124    pub fn resolve(&self, specs: &[ParamSpec]) -> Result<ParamValues, PluginError> {
125        for name in self.values.keys() {
126            if !specs.iter().any(|s| s.name == name) {
127                return Err(PluginError::invalid(name, "no such parameter"));
128            }
129        }
130        let mut out = ParamValues::new();
131        for spec in specs {
132            let value = match self.values.get(spec.name) {
133                Some(v) => {
134                    spec.check(v)?;
135                    v.clone()
136                }
137                None => spec.default.clone(),
138            };
139            out.values.insert(spec.name.to_string(), value);
140        }
141        Ok(out)
142    }
143
144    /// A resolved float. Panics if the name is not a resolved float, which only a plugin with a mismatched spec can cause.
145    pub fn float(&self, name: &str) -> f64 {
146        match self.values.get(name) {
147            Some(ParamValue::Float(x)) => *x,
148            other => panic!("parameter {name} is not a resolved float: {other:?}"),
149        }
150    }
151
152    /// A resolved bool. Panics under the same condition as [`ParamValues::float`].
153    pub fn bool(&self, name: &str) -> bool {
154        match self.values.get(name) {
155            Some(ParamValue::Bool(b)) => *b,
156            other => panic!("parameter {name} is not a resolved bool: {other:?}"),
157        }
158    }
159
160    /// A resolved choice. Panics under the same condition as [`ParamValues::float`].
161    pub fn choice(&self, name: &str) -> &str {
162        match self.values.get(name) {
163            Some(ParamValue::Choice(c)) => c,
164            other => panic!("parameter {name} is not a resolved choice: {other:?}"),
165        }
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use super::*;
172
173    fn specs() -> Vec<ParamSpec> {
174        vec![
175            ParamSpec::float("gain_db", -60.0, 24.0, 0.0, "dB"),
176            ParamSpec::boolean("invert", false),
177            ParamSpec::choice("type", &["low", "high"], "low"),
178        ]
179    }
180
181    #[test]
182    fn defaults_fill_in_and_equal_meanings_resolve_equal() {
183        let empty = ParamValues::new().resolve(&specs()).unwrap();
184        let explicit = ParamValues::new().with_float("gain_db", 0.0).with_bool("invert", false).with_choice("type", "low").resolve(&specs()).unwrap();
185        assert_eq!(empty, explicit);
186        assert_eq!(empty.len(), 3);
187        assert_eq!(empty.float("gain_db"), 0.0);
188        assert!(!empty.bool("invert"));
189        assert_eq!(empty.choice("type"), "low");
190    }
191
192    #[test]
193    fn rejects_unknown_wrong_type_and_out_of_range() {
194        let s = specs();
195        let err = |v: ParamValues| match v.resolve(&s) {
196            Err(PluginError::InvalidParam { name, .. }) => name,
197            other => panic!("expected InvalidParam, got {other:?}"),
198        };
199        assert_eq!(err(ParamValues::new().with_float("volume", 1.0)), "volume");
200        assert_eq!(err(ParamValues::new().with_float("gain_db", 24.1)), "gain_db");
201        assert_eq!(err(ParamValues::new().with_float("gain_db", -60.1)), "gain_db");
202        assert_eq!(err(ParamValues::new().with_float("gain_db", f64::NAN)), "gain_db");
203        assert_eq!(err(ParamValues::new().with_float("gain_db", f64::INFINITY)), "gain_db");
204        assert_eq!(err(ParamValues::new().with_bool("gain_db", true)), "gain_db");
205        assert_eq!(err(ParamValues::new().with_choice("type", "band")), "type");
206        assert_eq!(err(ParamValues::new().with_float("invert", 1.0)), "invert");
207        assert!(ParamValues::new().with_float("gain_db", 24.0).resolve(&s).is_ok(), "the limits are inclusive");
208        assert!(ParamValues::new().with_float("gain_db", -60.0).resolve(&s).is_ok());
209    }
210
211    #[test]
212    #[should_panic(expected = "not one of its options")]
213    fn a_choice_default_must_be_an_option() {
214        let _ = ParamSpec::choice("type", &["low"], "high");
215    }
216}