use super::info::ticks_to_secs;
use super::tone::{measure, ToneMetrics};
use crate::Song;
pub const DEFAULT_SECTION_BARS: u64 = 8;
pub const LOUD_JUMP_DB: f32 = 6.0;
pub const PEAK_LIMIT_DB: f32 = -0.3;
pub const LOW_HEAVY: f32 = 0.85;
const MIN_SECTION_SECS: f64 = 0.5;
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Section {
pub name: String,
pub start_tick: u64,
pub start_bar: u64,
#[cfg_attr(feature = "serde", serde(serialize_with = "round2"))]
pub start_secs: f64,
#[cfg_attr(feature = "serde", serde(serialize_with = "round2"))]
pub secs: f64,
pub metrics: SectionMetrics,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SectionMetrics {
#[cfg_attr(feature = "serde", serde(serialize_with = "round1"))]
pub loud_db: f32,
#[cfg_attr(feature = "serde", serde(serialize_with = "round1"))]
pub peak_db: f32,
#[cfg_attr(feature = "serde", serde(serialize_with = "round2f"))]
pub low: f32,
#[cfg_attr(feature = "serde", serde(serialize_with = "round2f"))]
pub high: f32,
#[cfg_attr(feature = "serde", serde(serialize_with = "round2f"))]
pub width: f32,
#[cfg_attr(feature = "serde", serde(serialize_with = "round1"))]
pub mono_loss_db: f32,
}
impl From<&ToneMetrics> for SectionMetrics {
fn from(m: &ToneMetrics) -> Self {
SectionMetrics {
loud_db: m.loud_db,
peak_db: m.peak_db,
low: m.low,
high: m.high,
width: m.width,
mono_loss_db: m.mono_loss_db,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum NoteKind {
LoudJump,
NearClipping,
LowHeavy,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Note {
pub kind: NoteKind,
pub section: usize,
#[cfg_attr(feature = "serde", serde(serialize_with = "round2f"))]
pub value: f32,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct SongReport {
pub total: SectionMetrics,
pub sections: Vec<Section>,
#[cfg_attr(feature = "serde", serde(serialize_with = "round1"))]
pub max_loud_jump_db: f32,
pub notes: Vec<Note>,
#[cfg_attr(feature = "serde", serde(skip_serializing_if = "Vec::is_empty"))]
pub tracks: Vec<TrackLevel>,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct TrackLevel {
pub name: String,
#[cfg_attr(feature = "serde", serde(serialize_with = "round1"))]
pub rms_db: f32,
pub metrics: SectionMetrics,
}
pub fn track_level(name: &str, samples: &[[f32; 2]], sample_rate: u32) -> TrackLevel {
let power: f64 = samples
.iter()
.map(|f| (f64::from(f[0]).powi(2) + f64::from(f[1]).powi(2)) / 2.0)
.sum::<f64>()
/ samples.len().max(1) as f64;
let rms_db = if power > 0.0 {
(10.0 * power.log10()) as f32
} else {
-120.0
};
TrackLevel {
name: name.to_string(),
rms_db: rms_db.max(-120.0),
metrics: SectionMetrics::from(&measure(samples, sample_rate, samples.len(), None)),
}
}
#[cfg(feature = "serde")]
fn round1<S: serde::Serializer>(x: &f32, s: S) -> Result<S::Ok, S::Error> {
s.serialize_f64((f64::from(*x) * 10.0).round() / 10.0)
}
#[cfg(feature = "serde")]
fn round2f<S: serde::Serializer>(x: &f32, s: S) -> Result<S::Ok, S::Error> {
s.serialize_f64((f64::from(*x) * 100.0).round() / 100.0)
}
#[cfg(feature = "serde")]
fn round2<S: serde::Serializer>(x: &f64, s: S) -> Result<S::Ok, S::Error> {
s.serialize_f64((*x * 100.0).round() / 100.0)
}
pub fn section_starts(song: &Song) -> Vec<(u64, String)> {
let mut starts: Vec<(u64, String)> = Vec::new();
let mut marks: Vec<_> = song.markers.iter().collect();
marks.sort_by_key(|m| m.tick);
for m in marks {
if m.tick < song.length_ticks && !starts.iter().any(|(t, _)| *t == m.tick) {
starts.push((m.tick, m.name.clone()));
}
}
if starts.is_empty() {
let step = song.meter.bar_ticks(song.ppq) * DEFAULT_SECTION_BARS;
let mut t = 0;
while t < song.length_ticks.max(1) {
starts.push((t, String::new()));
t += step.max(1);
}
} else if starts[0].0 != 0 {
starts.insert(0, (0, String::new()));
}
let bar = song.meter.bar_ticks(song.ppq).max(1);
for (t, name) in &mut starts {
if name.is_empty() {
*name = format!("bar {}", *t / bar + 1);
}
}
starts
}
pub fn analyze(song: &Song, samples: &[[f32; 2]], sample_rate: u32) -> SongReport {
let sr = f64::from(sample_rate.max(1));
let to_frame = |tick: u64| ((ticks_to_secs(song, tick) * sr) as usize).min(samples.len());
let starts = section_starts(song);
let song_end = to_frame(song.length_ticks).max(1).min(samples.len());
let bar = song.meter.bar_ticks(song.ppq).max(1);
let mut sections = Vec::new();
for (i, (tick, name)) in starts.iter().enumerate() {
let from = to_frame(*tick);
let to = starts
.get(i + 1)
.map_or(song_end, |(next, _)| to_frame(*next))
.max(from);
let slice = &samples[from..to.min(samples.len())];
let m = measure(slice, sample_rate, slice.len(), None);
sections.push(Section {
name: name.clone(),
start_tick: *tick,
start_bar: *tick / bar + 1,
start_secs: from as f64 / sr,
secs: slice.len() as f64 / sr,
metrics: SectionMetrics::from(&m),
});
}
let total = SectionMetrics::from(&measure(samples, sample_rate, samples.len(), None));
let mut notes = Vec::new();
let mut max_jump = 0f32;
let mut prev: Option<&Section> = None;
for (i, s) in sections.iter().enumerate() {
if s.secs < MIN_SECTION_SECS {
continue;
}
if let Some(p) = prev {
let diff = s.metrics.loud_db - p.metrics.loud_db;
max_jump = max_jump.max(diff.abs());
if diff.abs() >= LOUD_JUMP_DB {
notes.push(Note {
kind: NoteKind::LoudJump,
section: i,
value: diff,
});
}
}
if s.metrics.peak_db > PEAK_LIMIT_DB {
notes.push(Note {
kind: NoteKind::NearClipping,
section: i,
value: s.metrics.peak_db,
});
}
if s.metrics.low > LOW_HEAVY {
notes.push(Note {
kind: NoteKind::LowHeavy,
section: i,
value: s.metrics.low,
});
}
prev = Some(s);
}
SongReport {
total,
sections,
max_loud_jump_db: max_jump,
notes,
tracks: Vec::new(),
}
}