weirdnet_audio_plugin/builtin/
gain.rs1use crate::{ParamSpec, ParamValues, Plugin, PluginError};
2use weirdnet_media::waveform::Waveform;
3
4pub struct Gain;
13
14static PARAMS: [ParamSpec; 2] = [ParamSpec::float("gain_db", -60.0, 24.0, 0.0, "dB"), ParamSpec::boolean("invert", false)];
15
16impl Plugin for Gain {
17 fn id(&self) -> &'static str {
18 "weirdnet.gain"
19 }
20
21 fn params(&self) -> &[ParamSpec] {
22 &PARAMS
23 }
24
25 fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
26 let gain = weirdnet_dsp::db_to_linear(values.float("gain_db") as f32);
27 let gain = if values.bool("invert") { -gain } else { gain };
28 Ok(input.gain_linear(gain)?)
29 }
30}
31
32#[cfg(test)]
33mod tests {
34 use super::*;
35 use crate::Registry;
36
37 fn run(input: &Waveform, v: ParamValues) -> Result<Waveform, PluginError> {
38 Registry::with_builtins().process("weirdnet.gain", input, &v)
39 }
40
41 #[test]
42 fn default_is_the_same_samples() {
43 let w = Waveform::tone(48_000, 440.0, 100, 0.5).unwrap();
44 let out = run(&w, ParamValues::new()).unwrap();
45 assert_eq!(out, w);
46 assert!(std::ptr::eq(out.samples().as_ptr(), w.samples().as_ptr()), "shared, not copied");
47 }
48
49 #[test]
50 fn six_db_doubles_and_minus_six_halves() {
51 let w = Waveform::new(48_000, 1, vec![0.25, -0.5, 0.0]).unwrap();
52 let up = run(&w, ParamValues::new().with_float("gain_db", 6.0206)).unwrap();
53 assert!(up.samples().iter().zip([0.5, -1.0, 0.0]).all(|(a, b)| (a - b).abs() < 1e-4), "{:?}", up.samples());
54 let down = run(&w, ParamValues::new().with_float("gain_db", -6.0206)).unwrap();
55 assert!(down.samples().iter().zip([0.125, -0.25, 0.0]).all(|(a, b)| (a - b).abs() < 1e-4));
56 }
57
58 #[test]
59 fn invert_flips_the_sign_and_twice_is_identity() {
60 let w = Waveform::new(48_000, 2, vec![0.25, -0.5, 1.0, 0.0]).unwrap();
61 let inv = run(&w, ParamValues::new().with_bool("invert", true)).unwrap();
62 assert_eq!(inv.samples(), &[-0.25, 0.5, -1.0, -0.0]);
63 assert_eq!(run(&inv, ParamValues::new().with_bool("invert", true)).unwrap().samples(), w.samples());
64 }
65
66 #[test]
67 fn limits_are_accepted_and_beyond_them_rejected() {
68 let w = Waveform::new(48_000, 1, vec![0.001]).unwrap();
69 assert!(run(&w, ParamValues::new().with_float("gain_db", -60.0)).is_ok());
70 assert!(run(&w, ParamValues::new().with_float("gain_db", 24.0)).is_ok());
71 assert!(matches!(run(&w, ParamValues::new().with_float("gain_db", 24.5)), Err(PluginError::InvalidParam { .. })));
72 }
73
74 #[test]
75 fn keeps_format_and_length_and_handles_empty() {
76 let w = Waveform::silence(44_100, 2, 0).unwrap();
77 let out = run(&w, ParamValues::new().with_float("gain_db", 3.0)).unwrap();
78 assert_eq!((out.sample_rate(), out.channels(), out.frames()), (44_100, 2, 0));
79 }
80}