use std::process::ExitCode;
use weirdnet_audio_plugin::{ParamKind, ParamValues, PluginInstance, Registry, apply_chain};
use weirdnet_media::waveform::{WavFormat, Waveform};
fn demo() -> Waveform {
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(®istry, s)).collect::<Result<Vec<_>, _>>()?;
let output = apply_chain(®istry, &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
}
}
}