Skip to main content

apply_chain/
apply_chain.rs

1//! Loads a WAV, runs a plugin chain over it and writes a WAV.
2//!
3//! ```text
4//! cargo run --example apply_chain -- IN.wav OUT.wav [STEP...]
5//! cargo run --example apply_chain -- --demo OUT.wav gain:gain_db=-6 frequencies:type=low,cutoff_hz=800 levels:target=peak,target_db=-1
6//! ```
7//!
8//! A STEP is `plugin:name=value,name=value`. The plugin is a full id (`weirdnet.gain`) or its short name (`gain`). Values are numbers,
9//! `true` or `false`, or a choice name, as the plugin's parameters declare. `--demo` uses a generated kick-like sound instead of an input file.
10//! A step prefixed with `!` is bypassed (`!gain:gain_db=-60`). The output is 24-bit WAV.
11
12use std::process::ExitCode;
13use weirdnet_audio_plugin::{ParamKind, ParamValues, PluginInstance, Registry, apply_chain};
14use weirdnet_media::waveform::{WavFormat, Waveform};
15
16fn demo() -> Waveform {
17    // A 150 Hz sine falling to 50 Hz over a short decay, 0.4 s at 48 kHz.
18    let rate = 48_000u32;
19    let frames = 19_200usize;
20    let mut phase = 0.0f64;
21    let samples: Vec<f32> = (0..frames)
22        .map(|i| {
23            let t = i as f64 / f64::from(rate);
24            let hz = 50.0 + 100.0 * (-t * 30.0).exp();
25            phase += std::f64::consts::TAU * hz / f64::from(rate);
26            (phase.sin() * (-t * 9.0).exp() * 0.9) as f32
27        })
28        .collect();
29    Waveform::new(rate, 1, samples).expect("a valid demo waveform")
30}
31
32fn parse_step(registry: &Registry, text: &str) -> Result<PluginInstance, String> {
33    let (bypass, text) = text.strip_prefix('!').map_or((false, text), |t| (true, t));
34    let (name, args) = text.split_once(':').unwrap_or((text, ""));
35    let id = if name.contains('.') { name.to_string() } else { format!("weirdnet.{name}") };
36    let plugin = registry.get(&id).ok_or_else(|| format!("no plugin {id:?}; have {}", registry.ids().collect::<Vec<_>>().join(", ")))?;
37    let mut values = ParamValues::new();
38    for pair in args.split(',').filter(|p| !p.is_empty()) {
39        let (key, raw) = pair.split_once('=').ok_or_else(|| format!("{pair:?} is not name=value"))?;
40        let spec = plugin.params().iter().find(|s| s.name == key).ok_or_else(|| format!("{id} has no parameter {key:?}"))?;
41        values = match &spec.kind {
42            ParamKind::Float => values.with_float(key, raw.parse().map_err(|_| format!("{key}: {raw:?} is not a number"))?),
43            ParamKind::Bool => values.with_bool(key, raw.parse().map_err(|_| format!("{key}: {raw:?} is not true or false"))?),
44            ParamKind::Choice(_) => values.with_choice(key, raw),
45        };
46    }
47    Ok(PluginInstance { plugin: id, values, bypass })
48}
49
50fn run() -> Result<(), String> {
51    let args: Vec<String> = std::env::args().skip(1).collect();
52    if args.len() < 2 {
53        return Err("usage: apply_chain IN.wav|--demo OUT.wav [STEP...]  (see the file's docs)".into());
54    }
55    let registry = Registry::with_builtins();
56    let input = if args[0] == "--demo" {
57        demo()
58    } else {
59        let bytes = std::fs::read(&args[0]).map_err(|e| format!("{}: {e}", args[0]))?;
60        Waveform::from_wav(&bytes).map_err(|e| format!("{}: {e}", args[0]))?
61    };
62    let chain = args[2..].iter().map(|s| parse_step(&registry, s)).collect::<Result<Vec<_>, _>>()?;
63    let output = apply_chain(&registry, &input, &chain).map_err(|e| e.to_string())?;
64    std::fs::write(&args[1], output.to_wav(WavFormat::Pcm24)).map_err(|e| format!("{}: {e}", args[1]))?;
65    println!(
66        "{} steps; {} Hz, {} ch, {} frames; peak {:.1} dBFS -> {:.1} dBFS; rms {:.1} dBFS -> {:.1} dBFS; wrote {}",
67        chain.len(),
68        output.sample_rate(),
69        output.channels(),
70        output.frames(),
71        input.peak_db(),
72        output.peak_db(),
73        input.rms_db(),
74        output.rms_db(),
75        args[1]
76    );
77    Ok(())
78}
79
80fn main() -> ExitCode {
81    match run() {
82        Ok(()) => ExitCode::SUCCESS,
83        Err(e) => {
84            eprintln!("error: {e}");
85            ExitCode::FAILURE
86        }
87    }
88}