use super::*;
use pikopiko::report::tone::{self, AuditionOptions, Category, ToneMetrics};
use pikopiko_cli::reference::{self, Cut, ReferenceError, WavError};
const RATE: u32 = 44_100;
const SIMILAR: usize = 3;
const TOP_DIFFS: usize = 5;
pub(crate) struct ToneArgs<'a> {
pub category: &'a str,
pub src: Option<&'a str>,
pub synth: Option<&'a str>,
pub out: Option<&'a str>,
pub json: bool,
pub alias: bool,
pub reference: Option<ToneReference>,
}
pub(crate) struct ToneReference {
pub path: String,
pub cut: Cut,
}
pub(crate) fn tone(args: ToneArgs<'_>) -> Result<ExitCode, String> {
let category = args.category;
let Some(cat) = Category::from_name(category) else {
let names: Vec<&str> = tone::ALL.iter().map(|c| c.name()).collect();
return Err(ta(
"cli-err-unknown-category",
&[
("name", category.into()),
("names", names.join(", ").into()),
],
));
};
let reference = match &args.reference {
Some(r) => Some((r.path.as_str(), read_reference(r)?)),
None => None,
};
let Some(src) = args.src else {
let Some((path, m)) = reference else {
return Err(t("cli-err-tone-nothing"));
};
if args.json {
let v = serde_json::json!({ "reference": m });
println!("{}", serde_json::to_string_pretty(&v).map_err(json_error)?);
return Ok(ExitCode::SUCCESS);
}
println!(
"{}",
ta("cli-tone-reference-header", &[("path", path.into())])
);
print_rows(&m, None);
return Ok(ExitCode::SUCCESS);
};
let timbre: Vec<&str> = src
.lines()
.map(str::trim)
.filter(|l| {
!l.is_empty()
&& !l.starts_with(';')
&& (!l.starts_with('#') || l.starts_with("#include"))
})
.collect();
let timbre = timbre.join("\n");
let synth = args.synth.unwrap_or("va");
let spec = pikopiko::synth::find(pikopiko::synth::all(), synth);
let mml = match spec {
Some(spec) => pikopiko::synth::tones::audition_mml_for(spec, cat, &timbre),
None => tone::audition_mml(cat, synth, &timbre),
};
let (song, diags) = pikopiko::synth::compile(&mml);
let Some(song) = song else {
print_diagnostics(&mml, "<tone>", &diags);
return Ok(ExitCode::from(1));
};
let options = AuditionOptions::default().with_alias(args.alias);
let mut report = tone::report_with(cat, &song, mml, RATE, options);
if let Some(spec) = spec {
pikopiko::synth::tones::compare(&mut report, spec, RATE, SIMILAR);
}
if let Some(path) = args.out {
use pikopiko_cli::audio_file::{encode, AudioFormat, EncodeError};
let bytes = encode(&report.samples, RATE, AudioFormat::from_path(path)).map_err(|e| {
let key = match e {
EncodeError::Mp3Unavailable => "cli-err-mp3-unavailable",
EncodeError::Mp3Failed => "cli-err-mp3-failed",
};
ta(key, &[("path", path.into())])
})?;
std::fs::write(path, bytes).map_err(|e| write_error(path, e))?;
}
let comparison = reference
.as_ref()
.map(|(_, m)| tone::compare_audition(&report, m));
if args.json {
let mut v = serde_json::to_value(&report).map_err(json_error)?;
if let (Some((_, m)), Some(c), Some(obj)) = (&reference, &comparison, v.as_object_mut()) {
obj.insert(
"reference".into(),
serde_json::to_value(m).map_err(json_error)?,
);
obj.insert(
"comparison".into(),
serde_json::to_value(c).map_err(json_error)?,
);
}
println!("{}", serde_json::to_string_pretty(&v).map_err(json_error)?);
return Ok(ExitCode::SUCCESS);
}
println!(
"{}",
ta(
"cli-tone-header",
&[("category", cat.name().into()), ("synth", synth.into())]
)
);
if let Some((path, _)) = &reference {
println!(
"{}",
ta("cli-tone-reference-header", &[("path", (*path).into())])
);
}
print_rows(&report.metrics, reference.as_ref().map(|(_, m)| m));
if report.deviations.is_empty() {
println!("{}", t("cli-tone-ok"));
} else {
for d in &report.deviations {
let range = format!(
"{}〜{}",
d.min.map_or(String::new(), |v| v.to_string()),
d.max.map_or(String::new(), |v| v.to_string())
);
println!(
"{}",
ta(
"cli-tone-out",
&[
("metric", d.metric.name().into()),
("value", d.value.to_string().into()),
("range", range.into()),
]
)
);
}
}
match (report.gain_db, report.gain_factor, report.gain) {
(Some(db), Some(factor), Some(gain)) => println!(
"{}",
ta(
"cli-tone-gain",
&[
("db", format!("{db:+.1}").into()),
("gain", gain.to_string().into()),
("factor", format!("{factor:.2}").into()),
]
)
),
_ => println!("{}", t("cli-tone-gain-none")),
}
for s in &report.similar {
let key = if s.too_close {
"cli-tone-too-close"
} else {
"cli-tone-similar"
};
println!(
"{}",
ta(
key,
&[
("name", s.name.clone().into()),
("distance", format!("{:.3}", s.distance).into()),
]
)
);
}
if let Some(c) = &comparison {
print_comparison(c);
}
if let Some(path) = args.out {
eprintln!("{}", ta("cli-tone-wrote", &[("path", path.into())]));
}
Ok(ExitCode::SUCCESS)
}
fn read_reference(r: &ToneReference) -> Result<ToneMetrics, String> {
let path = r.path.as_str();
let bytes = std::fs::read(path).map_err(|e| {
ta(
"cli-err-read-file",
&[("path", path.into()), ("error", i18n().io_error(&e).into())],
)
})?;
reference::measure_reference(&bytes, &r.cut).map_err(|e| match e {
ReferenceError::Wav(WavError::NotWav) => {
ta("cli-err-ref-not-wav", &[("path", path.into())])
}
ReferenceError::Wav(WavError::Truncated) => {
ta("cli-err-ref-truncated", &[("path", path.into())])
}
ReferenceError::Wav(WavError::Unsupported { format, bits }) => ta(
"cli-err-ref-unsupported",
&[
("path", path.into()),
("format", format.to_string().into()),
("bits", bits.to_string().into()),
],
),
ReferenceError::BadNote(n) => ta("cli-err-ref-note", &[("note", n.into())]),
ReferenceError::BadRange => t("cli-err-ref-range"),
})
}
fn print_rows(m: &ToneMetrics, reference: Option<&ToneMetrics>) {
let rows = |m: &ToneMetrics| -> Vec<(&'static str, Option<f64>, usize)> {
let o = |v: Option<f32>| v.map(f64::from);
vec![
("loud_db", Some(f64::from(m.loud_db)), 1),
("peak_db", Some(f64::from(m.peak_db)), 1),
("attack_ms", Some(f64::from(m.attack_ms)), 0),
("sustain", Some(f64::from(m.sustain)), 2),
("tail_s", Some(f64::from(m.tail_s)), 2),
("low", Some(f64::from(m.low)), 2),
("high", Some(f64::from(m.high)), 2),
("harm", o(m.harm), 2),
("mono_loss_db", Some(f64::from(m.mono_loss_db)), 1),
("width", Some(f64::from(m.width)), 2),
("motion", o(m.motion), 2),
("flux", o(m.flux), 2),
("amp_mod", o(m.amp_mod), 2),
("click_db", o(m.click_db), 1),
("alias_db", o(m.alias_db), 1),
("rate_diff", o(m.rate_diff), 2),
]
};
let show =
|v: Option<f64>, digits: usize| v.map_or("-".to_string(), |v| format!("{v:.digits$}"));
let ours = rows(m);
let Some(r) = reference else {
for (name, v, d) in ours {
if v.is_none() && matches!(name, "alias_db" | "rate_diff") {
continue;
}
println!(" {name:<13} {}", show(v, d));
}
return;
};
println!(
" {:<13} {:>9} {:>9} {:>9}",
"",
t("cli-tone-col-ours"),
t("cli-tone-col-reference"),
t("cli-tone-col-diff")
);
for ((name, a, d), (_, b, _)) in ours.into_iter().zip(rows(r)) {
if a.is_none() && b.is_none() && matches!(name, "alias_db" | "rate_diff") {
continue;
}
let diff = a.zip(b).map(|(a, b)| a - b);
let diff = diff.map_or("-".to_string(), |v| format!("{v:+.d$}"));
println!(
" {name:<13} {:>9} {:>9} {:>9}",
show(a, d),
show(b, d),
diff
);
}
}
fn print_comparison(c: &tone::Comparison) {
println!(
"{}",
ta(
"cli-tone-distance",
&[
("distance", format!("{:.3}", c.distance).into()),
("gain", format!("{:+.1}", c.gain_db).into()),
]
)
);
println!("{}", t("cli-tone-top-diffs"));
for d in c.diffs.iter().take(TOP_DIFFS) {
println!(" {:<13} {:+.2} ({:.2})", d.metric, d.diff, d.score);
}
println!("{}", t("cli-tone-bands-diff"));
for (i, db) in c.bands_db.iter().enumerate() {
let hz = tone::band_hz(i);
let label = if hz >= 1000.0 {
format!("{:.1}k", hz / 1000.0)
} else {
format!("{hz:.0}")
};
let n = ((db.abs() / 2.0).round() as usize).min(15);
let bar = if *db < 0.0 {
"-".repeat(n)
} else {
"+".repeat(n)
};
println!(" {label:>6} {db:+6.1} {bar}");
}
}