#[cfg(feature = "serde")]
use super::short;
use super::*;
pub const AFTER: &str = "r1";
pub const AFTER_SECS: f64 = 2.0;
pub fn audition_mml(category: Category, synth: &str, timbre: &str) -> String {
let lines: Vec<&str> = timbre
.lines()
.map(str::trim)
.filter(|l| !l.is_empty())
.collect();
let (body, defs) = lines.split_last().map_or(("", &[][..]), |(b, d)| (*b, d));
let body = match body.strip_prefix('$') {
Some(rest) => rest.split_once('=').map_or(body, |(_, b)| b.trim()),
None => body,
};
let mut mml = format!("#synth {synth}\n");
for d in defs {
mml.push_str(d);
mml.push('\n');
}
mml.push_str(&format!(
"$tone = {body}\nA t120 $tone {} {AFTER}\n",
category.phrase()
));
mml
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct ToneReport {
pub category: Category,
pub metrics: ToneMetrics,
pub deviations: Vec<Deviation>,
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Option::is_none", serialize_with = "short::opt")
)]
pub gain_db: Option<f32>,
#[cfg_attr(
feature = "serde",
serde(skip_serializing_if = "Option::is_none", serialize_with = "short::opt")
)]
pub gain_factor: Option<f32>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
pub gain: Option<u32>,
pub similar: Vec<Similar>,
pub mml: String,
#[cfg_attr(feature = "serde", serde(skip))]
pub samples: Vec<[f32; 2]>,
#[cfg_attr(feature = "serde", serde(skip))]
pub release: usize,
#[cfg_attr(feature = "serde", serde(skip))]
pub sample_rate: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct AuditionOptions {
pub alias: bool,
}
impl AuditionOptions {
pub const fn with_alias(mut self, alias: bool) -> Self {
self.alias = alias;
self
}
}
pub fn audition(
category: Category,
synth: &str,
timbre: &str,
sample_rate: u32,
) -> Result<ToneReport, Vec<Diagnostic>> {
audition_with(
category,
synth,
timbre,
sample_rate,
AuditionOptions::default(),
)
}
pub fn audition_with(
category: Category,
synth: &str,
timbre: &str,
sample_rate: u32,
options: AuditionOptions,
) -> Result<ToneReport, Vec<Diagnostic>> {
let mml = audition_mml(category, synth, timbre);
let (song, diags) = crate::synth::compile(&mml);
match song {
Some(song) => Ok(report_with(category, &song, mml, sample_rate, options)),
None => Err(diags),
}
}
pub const GAIN_PARAM: &str = "gain";
pub const NOT_FOR_FIXED_LEVEL: [Metric; 4] =
[Metric::LoudDb, Metric::PeakDb, Metric::Low, Metric::High];
pub fn report(category: Category, song: &crate::Song, mml: String, sample_rate: u32) -> ToneReport {
report_with(category, song, mml, sample_rate, AuditionOptions::default())
}
pub fn report_with(
category: Category,
song: &crate::Song,
mml: String,
sample_rate: u32,
options: AuditionOptions,
) -> ToneReport {
let secs = crate::report::info::describe(song).duration_secs - AFTER_SECS;
let release = (secs.max(0.0) * f64::from(sample_rate)).round() as usize;
let samples = crate::synth::render(song, sample_rate, 0);
let edges = note_edges(song, sample_rate);
let mut metrics = measure_at(
&samples,
sample_rate,
release,
category.fundamental_hz(),
&edges,
);
if options.alias {
let (alias_db, rate_diff) = alias(song, &samples, sample_rate);
metrics.alias_db = Some(alias_db);
metrics.rate_diff = rate_diff;
}
let mut deviations = category.check(&metrics);
let gain_param = crate::synth::find(crate::synth::ALL, &song.synth.name)
.and_then(|spec| Some((spec.param_index(GAIN_PARAM)?, spec)));
let (gain_db, gain_factor, gain) = match gain_param {
Some((idx, spec)) => {
let db = round(f64::from(category.target_loud_db() - metrics.loud_db), 10.0);
let factor = 10f64.powf(db / 20.0);
let info = &spec.params[idx];
let current = first_param(song, idx).unwrap_or(info.default);
let suggested =
((f64::from(current) * factor).round() as u32).clamp(info.min, info.max);
(
Some(db as f32),
Some(round(factor, 100.0) as f32),
Some(suggested),
)
}
None => {
deviations.retain(|d| !NOT_FOR_FIXED_LEVEL.contains(&d.metric));
(None, None, None)
}
};
ToneReport {
category,
metrics,
deviations,
gain_db,
gain_factor,
gain,
similar: Vec::new(),
mml,
samples,
release,
sample_rate,
}
}
fn note_edges(song: &crate::Song, sample_rate: u32) -> Vec<usize> {
use crate::EventKind;
let frames_per_tick = f64::from(sample_rate) * 0.5 / f64::from(crate::PPQ);
let mut edges: Vec<usize> = song
.events
.iter()
.filter(|e| {
matches!(
e.kind,
EventKind::NoteOn { .. } | EventKind::Chord { .. } | EventKind::NoteOff
)
})
.map(|e| (e.tick as f64 * frames_per_tick).round() as usize)
.collect();
edges.dedup();
edges
}
fn alias(song: &crate::Song, samples: &[[f32; 2]], sample_rate: u32) -> (f32, Option<f32>) {
const ALIAS_LIMIT_HZ: f64 = 20_000.0;
const RATE_DIFF_HZ: f64 = 2_000.0;
let high_rate = sample_rate.saturating_mul(4);
let high = crate::synth::render(song, high_rate, 0);
let (base, _) = band_powers(samples, f64::from(sample_rate), 0..0, 1);
let (over, _) = band_powers(&high, f64::from(high_rate), 0..0, 1);
let usable =
|i: usize| band_hz(i) <= ALIAS_LIMIT_HZ && band_hz(i) < f64::from(sample_rate) * 0.45;
let pick = |v: &[f64; BANDS], lim: &dyn Fn(usize) -> bool| -> Vec<f64> {
(0..BANDS)
.map(|i| if lim(i) { v[i] } else { 0.0 })
.collect()
};
let (b, o) = (pick(&base, &usable), pick(&over, &usable));
let (tb, to) = (b.iter().sum::<f64>(), o.iter().sum::<f64>());
let alias_db = if tb > 0.0 && to > 0.0 {
let extra: f64 = b
.iter()
.zip(&o)
.map(|(p, q)| (p / tb - q / to).max(0.0))
.sum();
(10.0 * extra.max(1e-12).log10()).max(-80.0)
} else {
-80.0
};
let low = |i: usize| band_hz(i) < RATE_DIFF_HZ;
let rate_diff =
hellinger(&pick(&base, &low), &pick(&over, &low)).map(|d| round(d, 100.0) as f32);
(round(alias_db, 10.0) as f32, rate_diff)
}
fn first_param(song: &crate::Song, idx: usize) -> Option<u32> {
use crate::EventKind;
let first_note = song
.events
.iter()
.filter(|e| e.track == 0)
.find(|e| matches!(e.kind, EventKind::NoteOn { .. } | EventKind::Chord { .. }))
.map_or(u64::MAX, |e| e.tick);
song.events
.iter()
.filter(|e| e.track == 0 && e.tick <= first_note)
.filter_map(|e| match e.kind {
EventKind::Param { id, value } if usize::from(id) == idx => Some(value),
_ => None,
})
.next_back()
}