use crate::{ParamSpec, ParamValues, Plugin, PluginError};
use weirdnet_dsp::{FadeCurve, fade_out};
use weirdnet_media::waveform::Waveform;
pub struct Duration;
fn specs() -> &'static [ParamSpec] {
use std::sync::OnceLock;
static SPECS: OnceLock<Vec<ParamSpec>> = OnceLock::new();
SPECS.get_or_init(|| {
vec![
ParamSpec::choice("mode", &["stretch", "trim"], "stretch"),
ParamSpec::float("ratio", 0.25, 4.0, 1.0, ""),
ParamSpec::float("target_ms", 0.0, 60_000.0, 0.0, "ms"),
ParamSpec::float("fade_ms", 0.0, 1_000.0, 5.0, "ms"),
ParamSpec::choice("quality", &["fast", "good"], "good"),
]
})
}
impl Plugin for Duration {
fn id(&self) -> &'static str {
"weirdnet.duration"
}
fn params(&self) -> &[ParamSpec] {
specs()
}
fn process(&self, input: &Waveform, values: &ParamValues) -> Result<Waveform, PluginError> {
let frames = input.frames();
let rate = f64::from(input.sample_rate());
let target_ms = values.float("target_ms");
let target =
if target_ms > 0.0 { (target_ms * rate / 1000.0).round() as usize } else { (frames as f64 * values.float("ratio")).round() as usize };
let trim = values.choice("mode") == "trim";
if frames == 0 || (target == frames) || (trim && target >= frames) {
return Ok(input.clone());
}
let channels = usize::from(input.channels());
let out = if trim {
let mut samples = input.samples()[..target * channels].to_vec();
let fade = ((values.float("fade_ms") * rate / 1000.0).round() as usize).min(target);
fade_out(&mut samples, input.channels(), fade, FadeCurve::Linear);
samples
} else {
stretch(input, target, values.choice("quality") == "fast")?
};
Ok(Waveform::new(input.sample_rate(), input.channels(), out)?)
}
}
#[cfg(feature = "stretch")]
fn stretch(input: &Waveform, target: usize, fast: bool) -> Result<Vec<f32>, PluginError> {
use weirdnet_dsp::stretch::{StretchQuality, time_stretch};
let quality = if fast { StretchQuality::Fast } else { StretchQuality::Good };
time_stretch(input.samples(), input.channels(), input.sample_rate(), target, quality).map_err(|e| PluginError::Internal(e.to_string()))
}
#[cfg(not(feature = "stretch"))]
fn stretch(_: &Waveform, _: usize, _: bool) -> Result<Vec<f32>, PluginError> {
Err(PluginError::Internal("this build has no stretch (the crate feature `stretch` is off); use trim".into()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Registry;
const RATE: u32 = 48_000;
fn run(input: &Waveform, v: ParamValues) -> Result<Waveform, PluginError> {
Registry::with_builtins().process("weirdnet.duration", input, &v)
}
fn tone(frames: usize) -> Waveform {
Waveform::tone(RATE, 440.0, frames, 0.5).unwrap()
}
fn hz(w: &Waveform) -> f64 {
let x = w.samples();
let mid = &x[x.len() / 4..x.len() * 3 / 4];
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
}
#[test]
fn defaults_and_an_unchanged_length_return_the_same_samples() {
let w = tone(10_000);
let out = run(&w, ParamValues::new()).unwrap();
assert!(std::ptr::eq(out.samples().as_ptr(), w.samples().as_ptr()) || out == w);
assert_eq!(run(&w, ParamValues::new().with_choice("mode", "trim")).unwrap(), w);
}
#[cfg(feature = "stretch")]
#[test]
fn stretch_scales_the_length_and_keeps_the_pitch() {
let w = tone(24_000);
for ratio in [0.5, 0.8, 1.25, 2.0] {
let out = run(&w, ParamValues::new().with_float("ratio", ratio)).unwrap();
assert_eq!(out.frames(), (w.frames() as f64 * ratio).round() as usize, "ratio {ratio}");
assert!((hz(&out) - 440.0).abs() < 8.0, "ratio {ratio}: {} Hz", hz(&out));
}
}
#[cfg(feature = "stretch")]
#[test]
fn target_ms_wins_over_ratio_and_stereo_is_kept() {
let w = tone(24_000).to_stereo().unwrap();
let out = run(&w, ParamValues::new().with_float("target_ms", 700.0).with_float("ratio", 3.0).with_choice("quality", "fast")).unwrap();
assert_eq!((out.channels(), out.frames()), (2, 33_600));
}
#[cfg(feature = "stretch")]
#[test]
fn short_sounds_survive_a_stretch() {
for frames in [100, 480, 1_200, 2_400] {
let w = Waveform::tone(RATE, 440.0, frames, 0.5).unwrap();
let out = run(&w, ParamValues::new().with_float("ratio", 1.25)).unwrap();
let energy = |x: &Waveform| x.samples().iter().map(|s| s * s).sum::<f32>();
let r = energy(&out) / energy(&w);
assert!((0.8..1.6).contains(&r), "{frames} frames: energy ratio {r}");
}
}
#[test]
fn trim_cuts_with_a_fade_and_never_lengthens() {
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();
assert_eq!(out.frames(), 2_400);
assert_eq!(out.samples()[0], 0.5);
assert_eq!(out.samples()[1_919], 0.5, "untouched before the fade");
assert!(out.samples()[2_399] < 0.01, "ends near silence");
let longer = run(&w, ParamValues::new().with_choice("mode", "trim").with_float("ratio", 2.0)).unwrap();
assert_eq!(longer, w, "trim never lengthens");
let by_ratio = run(&w, ParamValues::new().with_choice("mode", "trim").with_float("ratio", 0.25).with_float("fade_ms", 0.0)).unwrap();
assert_eq!(by_ratio.frames(), 1_200);
assert_eq!(by_ratio.samples()[1_199], 0.5, "no fade when fade_ms is 0");
}
#[test]
fn empty_input_and_bad_values() {
let empty = Waveform::silence(RATE, 2, 0).unwrap();
assert_eq!(run(&empty, ParamValues::new().with_float("ratio", 2.0)).unwrap().frames(), 0);
let w = tone(1_000);
assert!(matches!(run(&w, ParamValues::new().with_float("ratio", 5.0)), Err(PluginError::InvalidParam { .. })));
assert!(matches!(run(&w, ParamValues::new().with_choice("mode", "warp")), Err(PluginError::InvalidParam { .. })));
}
#[cfg(not(feature = "stretch"))]
#[test]
fn without_the_feature_stretch_is_an_error() {
assert!(matches!(run(&tone(1_000), ParamValues::new().with_float("ratio", 2.0)), Err(PluginError::Internal(_))));
}
}