weirdnet_audio_plugin/builtin/
duration.rs1use crate::{ParamSpec, ParamValues, Plugin, PluginError};
2use weirdnet_dsp::{FadeCurve, fade_out};
3use weirdnet_media::waveform::Waveform;
4
5pub struct Duration;
23
24fn specs() -> &'static [ParamSpec] {
25 use std::sync::OnceLock;
26 static SPECS: OnceLock<Vec<ParamSpec>> = OnceLock::new();
27 SPECS.get_or_init(|| {
28 vec![
29 ParamSpec::choice("mode", &["stretch", "trim"], "stretch"),
30 ParamSpec::float("ratio", 0.25, 4.0, 1.0, ""),
31 ParamSpec::float("target_ms", 0.0, 60_000.0, 0.0, "ms"),
32 ParamSpec::float("fade_ms", 0.0, 1_000.0, 5.0, "ms"),
33 ParamSpec::choice("quality", &["fast", "good"], "good"),
34 ]
35 })
36}
37
38impl Plugin for Duration {
39 fn id(&self) -> &'static str {
40 "weirdnet.duration"
41 }
42
43 fn params(&self) -> &[ParamSpec] {
44 specs()
45 }
46
47 fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
48 let frames = input.frames();
49 let rate = f64::from(input.sample_rate());
50 let target_ms = values.float("target_ms");
51 let target =
52 if target_ms > 0.0 { (target_ms * rate / 1000.0).round() as usize } else { (frames as f64 * values.float("ratio")).round() as usize };
53 let trim = values.choice("mode") == "trim";
54 if frames == 0 || (target == frames) || (trim && target >= frames) {
55 return Ok(input.clone());
56 }
57 let channels = usize::from(input.channels());
58 let out = if trim {
59 let mut samples = input.samples()[..target * channels].to_vec();
60 let fade = ((values.float("fade_ms") * rate / 1000.0).round() as usize).min(target);
61 fade_out(&mut samples, input.channels(), fade, FadeCurve::Linear);
62 samples
63 } else {
64 stretch(input, target, values.choice("quality") == "fast")?
65 };
66 Ok(Waveform::new(input.sample_rate(), input.channels(), out)?)
67 }
68}
69
70#[cfg(feature = "stretch")]
71fn stretch(input: &Waveform, target: usize, fast: bool) -> Result<Vec<f32>, PluginError> {
72 use weirdnet_dsp::stretch::{StretchQuality, time_stretch};
73 let quality = if fast { StretchQuality::Fast } else { StretchQuality::Good };
74 time_stretch(input.samples(), input.channels(), input.sample_rate(), target, quality).map_err(|e| PluginError::Internal(e.to_string()))
75}
76
77#[cfg(not(feature = "stretch"))]
78fn stretch(_: &Waveform, _: usize, _: bool) -> Result<Vec<f32>, PluginError> {
79 Err(PluginError::Internal("this build has no stretch (the crate feature `stretch` is off); use trim".into()))
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85 use crate::Registry;
86
87 const RATE: u32 = 48_000;
88
89 fn run(input: &Waveform, v: ParamValues) -> Result<Waveform, PluginError> {
90 Registry::with_builtins().process("weirdnet.duration", input, &v)
91 }
92
93 fn tone(frames: usize) -> Waveform {
94 Waveform::tone(RATE, 440.0, frames, 0.5).unwrap()
95 }
96
97 #[cfg(feature = "stretch")]
98 fn hz(w: &Waveform) -> f64 {
99 let x = w.samples();
100 let mid = &x[x.len() / 4..x.len() * 3 / 4];
101 mid.windows(2).filter(|p| p[0] <= 0.0 && p[1] > 0.0).count() as f64 * f64::from(w.sample_rate()) / mid.len() as f64
102 }
103
104 #[test]
105 fn defaults_and_an_unchanged_length_return_the_same_samples() {
106 let w = tone(10_000);
107 let out = run(&w, ParamValues::new()).unwrap();
108 assert!(std::ptr::eq(out.samples().as_ptr(), w.samples().as_ptr()) || out == w);
109 assert_eq!(run(&w, ParamValues::new().with_choice("mode", "trim")).unwrap(), w);
110 }
111
112 #[cfg(feature = "stretch")]
113 #[test]
114 fn stretch_scales_the_length_and_keeps_the_pitch() {
115 let w = tone(24_000);
116 for ratio in [0.5, 0.8, 1.25, 2.0] {
117 let out = run(&w, ParamValues::new().with_float("ratio", ratio)).unwrap();
118 assert_eq!(out.frames(), (w.frames() as f64 * ratio).round() as usize, "ratio {ratio}");
119 assert!((hz(&out) - 440.0).abs() < 8.0, "ratio {ratio}: {} Hz", hz(&out));
120 }
121 }
122
123 #[cfg(feature = "stretch")]
124 #[test]
125 fn target_ms_wins_over_ratio_and_stereo_is_kept() {
126 let w = tone(24_000).to_stereo().unwrap();
127 let out = run(&w, ParamValues::new().with_float("target_ms", 700.0).with_float("ratio", 3.0).with_choice("quality", "fast")).unwrap();
128 assert_eq!((out.channels(), out.frames()), (2, 33_600));
129 }
130
131 #[cfg(feature = "stretch")]
132 #[test]
133 fn short_sounds_survive_a_stretch() {
134 for frames in [100, 480, 1_200, 2_400] {
135 let w = Waveform::tone(RATE, 440.0, frames, 0.5).unwrap();
136 let out = run(&w, ParamValues::new().with_float("ratio", 1.25)).unwrap();
137 let energy = |x: &Waveform| x.samples().iter().map(|s| s * s).sum::<f32>();
138 let r = energy(&out) / energy(&w);
139 assert!((0.8..1.6).contains(&r), "{frames} frames: energy ratio {r}");
140 }
141 }
142
143 #[test]
144 fn trim_cuts_with_a_fade_and_never_lengthens() {
145 let w = Waveform::new(RATE, 1, vec![0.5; 4_800]).unwrap(); let out = run(&w, ParamValues::new().with_choice("mode", "trim").with_float("target_ms", 50.0).with_float("fade_ms", 10.0)).unwrap();
147 assert_eq!(out.frames(), 2_400);
148 assert_eq!(out.samples()[0], 0.5);
149 assert_eq!(out.samples()[1_919], 0.5, "untouched before the fade");
150 assert!(out.samples()[2_399] < 0.01, "ends near silence");
151 let longer = run(&w, ParamValues::new().with_choice("mode", "trim").with_float("ratio", 2.0)).unwrap();
152 assert_eq!(longer, w, "trim never lengthens");
153 let by_ratio = run(&w, ParamValues::new().with_choice("mode", "trim").with_float("ratio", 0.25).with_float("fade_ms", 0.0)).unwrap();
154 assert_eq!(by_ratio.frames(), 1_200);
155 assert_eq!(by_ratio.samples()[1_199], 0.5, "no fade when fade_ms is 0");
156 }
157
158 #[test]
159 fn empty_input_and_bad_values() {
160 let empty = Waveform::silence(RATE, 2, 0).unwrap();
161 assert_eq!(run(&empty, ParamValues::new().with_float("ratio", 2.0)).unwrap().frames(), 0);
162 let w = tone(1_000);
163 assert!(matches!(run(&w, ParamValues::new().with_float("ratio", 5.0)), Err(PluginError::InvalidParam { .. })));
164 assert!(matches!(run(&w, ParamValues::new().with_choice("mode", "warp")), Err(PluginError::InvalidParam { .. })));
165 }
166
167 #[cfg(not(feature = "stretch"))]
168 #[test]
169 fn without_the_feature_stretch_is_an_error() {
170 assert!(matches!(run(&tone(1_000), ParamValues::new().with_float("ratio", 2.0)), Err(PluginError::Internal(_))));
171 }
172}