use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};
use super::catalog::{find, includes_for, tones, LibraryTone};
use crate::report::tone::{self, Category, ToneMetrics, ToneReport};
use crate::synth::{SynthPreset, SynthSpec};
use crate::Diagnostic;
pub fn audition_mml(t: &LibraryTone) -> Option<String> {
let mml = tone::audition_mml(t.category()?, t.synth, &format!("${}", t.name));
let (head, rest) = mml.split_once('\n')?;
Some(format!("{head}\n{}\n{rest}", t.include_line()))
}
pub fn audition_mml_for(spec: &SynthSpec, category: Category, timbre: &str) -> String {
let includes = includes_for(spec, timbre);
if includes.is_empty() {
return tone::audition_mml(category, spec.name, timbre);
}
let text = format!("{}\n{timbre}", includes.join("\n"));
tone::audition_mml(category, spec.name, &text)
}
pub fn report(t: &LibraryTone, sample_rate: u32) -> Option<Result<ToneReport, Vec<Diagnostic>>> {
let category = t.category()?;
let mml = audition_mml(t)?;
let (song, diags) = crate::synth::compile(&mml);
Some(match song {
Some(song) => Ok(tone::report(category, &song, mml, sample_rate)),
None => Err(diags),
})
}
pub fn preset_category(p: &SynthPreset) -> Category {
let n = p.name;
match p.kind {
"drum" if n.contains("kick") => Category::Kick,
"drum" if n.contains("snare") || n.contains("clap") => Category::Snare,
"drum" if n.contains("crash") => Category::Crash,
"drum" if n.contains("tom") => Category::Tom,
"drum" => Category::Hat,
other => Category::from_name(other).unwrap_or(Category::Lead),
}
}
pub fn references(
spec: &SynthSpec,
category: Category,
sample_rate: u32,
) -> Arc<Vec<(String, ToneMetrics)>> {
type Cache = Mutex<HashMap<(String, &'static str, u32), Arc<Vec<(String, ToneMetrics)>>>>;
static CACHE: OnceLock<Cache> = OnceLock::new();
let key = (spec.name.to_string(), category.name(), sample_rate);
let cache = CACHE.get_or_init(Default::default);
if let Some(v) = cache.lock().ok().and_then(|c| c.get(&key).cloned()) {
return v;
}
let mut out = Vec::new();
for t in tones(spec)
.iter()
.filter(|t| t.category() == Some(category))
{
if let Some(Ok(r)) = report(t, sample_rate) {
out.push((t.name.to_string(), r.metrics));
}
}
for p in spec
.presets
.iter()
.filter(|p| preset_category(p) == category && find(spec, p.name).is_none())
{
if let Ok(r) = tone::audition(category, spec.name, p.body, sample_rate) {
out.push((p.name.to_string(), r.metrics));
}
}
let out = Arc::new(out);
if let Ok(mut c) = cache.lock() {
c.insert(key, out.clone());
}
out
}
pub fn compare(r: &mut ToneReport, spec: &SynthSpec, sample_rate: u32, limit: usize) {
let refs = references(spec, r.category, sample_rate);
let mut v = tone::similar(&r.metrics, refs.iter().map(|(n, m)| (n.as_str(), m)));
v.truncate(limit);
r.similar = v;
}