weirdnet-audio-plugin 0.3.0

Audio plugins for Weirdnet: the Plugin trait, typed parameters, a registry, chain processing with a content-hash cache key, and the built-ins gain, levels and frequencies.
Documentation
//! Loads a WAV, runs a plugin chain over it and writes a WAV.
//!
//! ```text
//! cargo run --example apply_chain -- IN.wav OUT.wav [STEP...]
//! cargo run --example apply_chain -- --demo OUT.wav gain:gain_db=-6 frequencies:type=low,cutoff_hz=800 levels:target=peak,target_db=-1
//! ```
//!
//! A STEP is `plugin:name=value,name=value`. The plugin is a full id (`weirdnet.gain`) or its short name (`gain`). Values are numbers,
//! `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.
//! A step prefixed with `!` is bypassed (`!gain:gain_db=-60`). The output is 24-bit WAV.

use std::process::ExitCode;
use weirdnet_audio_plugin::{ParamKind, ParamValues, PluginInstance, Registry, apply_chain};
use weirdnet_media::waveform::{WavFormat, Waveform};

fn demo() -> Waveform {
    // A 150 Hz sine falling to 50 Hz over a short decay, 0.4 s at 48 kHz.
    let rate = 48_000u32;
    let frames = 19_200usize;
    let mut phase = 0.0f64;
    let samples: Vec<f32> = (0..frames)
        .map(|i| {
            let t = i as f64 / f64::from(rate);
            let hz = 50.0 + 100.0 * (-t * 30.0).exp();
            phase += std::f64::consts::TAU * hz / f64::from(rate);
            (phase.sin() * (-t * 9.0).exp() * 0.9) as f32
        })
        .collect();
    Waveform::new(rate, 1, samples).expect("a valid demo waveform")
}

fn parse_step(registry: &Registry, text: &str) -> Result<PluginInstance, String> {
    let (bypass, text) = text.strip_prefix('!').map_or((false, text), |t| (true, t));
    let (name, args) = text.split_once(':').unwrap_or((text, ""));
    let id = if name.contains('.') { name.to_string() } else { format!("weirdnet.{name}") };
    let plugin = registry.get(&id).ok_or_else(|| format!("no plugin {id:?}; have {}", registry.ids().collect::<Vec<_>>().join(", ")))?;
    let mut values = ParamValues::new();
    for pair in args.split(',').filter(|p| !p.is_empty()) {
        let (key, raw) = pair.split_once('=').ok_or_else(|| format!("{pair:?} is not name=value"))?;
        let spec = plugin.params().iter().find(|s| s.name == key).ok_or_else(|| format!("{id} has no parameter {key:?}"))?;
        values = match &spec.kind {
            ParamKind::Float => values.with_float(key, raw.parse().map_err(|_| format!("{key}: {raw:?} is not a number"))?),
            ParamKind::Bool => values.with_bool(key, raw.parse().map_err(|_| format!("{key}: {raw:?} is not true or false"))?),
            ParamKind::Choice(_) => values.with_choice(key, raw),
        };
    }
    Ok(PluginInstance { plugin: id, values, bypass })
}

fn run() -> Result<(), String> {
    let args: Vec<String> = std::env::args().skip(1).collect();
    if args.len() < 2 {
        return Err("usage: apply_chain IN.wav|--demo OUT.wav [STEP...]  (see the file's docs)".into());
    }
    let registry = Registry::with_builtins();
    let input = if args[0] == "--demo" {
        demo()
    } else {
        let bytes = std::fs::read(&args[0]).map_err(|e| format!("{}: {e}", args[0]))?;
        Waveform::from_wav(&bytes).map_err(|e| format!("{}: {e}", args[0]))?
    };
    let chain = args[2..].iter().map(|s| parse_step(&registry, s)).collect::<Result<Vec<_>, _>>()?;
    let output = apply_chain(&registry, &input, &chain).map_err(|e| e.to_string())?;
    std::fs::write(&args[1], output.to_wav(WavFormat::Pcm24)).map_err(|e| format!("{}: {e}", args[1]))?;
    println!(
        "{} steps; {} Hz, {} ch, {} frames; peak {:.1} dBFS -> {:.1} dBFS; rms {:.1} dBFS -> {:.1} dBFS; wrote {}",
        chain.len(),
        output.sample_rate(),
        output.channels(),
        output.frames(),
        input.peak_db(),
        output.peak_db(),
        input.rms_db(),
        output.rms_db(),
        args[1]
    );
    Ok(())
}

fn main() -> ExitCode {
    match run() {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            eprintln!("error: {e}");
            ExitCode::FAILURE
        }
    }
}