Repository Public
1//! ORIX Sonata2//! File: crates/sonata-dsp/src/analysis/overview.rs3//! Description: Multi-resolution waveform overviews computed from real PCM: min, max and RMS per4//! block at several block sizes, so a timeline draws any zoom level without rescanning samples.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89/// What one display column shows: the extremes and RMS of the samples it covers.10#[derive(Clone, Copy, Debug, Default, PartialEq)]11pub struct Column {12 pub min: f32,13 pub max: f32,14 pub rms: f32,15}1617#[derive(Clone, Debug, PartialEq)]18struct Level {19 block: usize,20 min: Vec<f32>,21 max: Vec<f32>,22 /// Sum of squares per block (f64 so coarser levels are exact sums of finer ones).23 sq: Vec<f64>,24}2526/// Overview of one channel. Level 0 summarises blocks of `base` samples; each further level27/// summarises `factor` blocks of the previous one. Built incrementally with `append`, so it can28/// follow a recording or a streamed file; every figure derives from the samples given.29#[derive(Clone, Debug, PartialEq)]30pub struct Overview {31 base: usize,32 factor: usize,33 levels: Vec<Level>,34 len: usize,35 // Partial block of level 0.36 cur_min: f32,37 cur_max: f32,38 cur_sq: f64,39 cur_n: usize,40}4142impl Overview {43 /// `base` samples per finest block (64 to 1024 is typical), `factor` between levels (4 typical).44 pub fn new(base: usize, factor: usize) -> Overview {45 Overview {46 base: base.max(1),47 factor: factor.max(2),48 levels: vec![Level { block: base.max(1), min: vec![], max: vec![], sq: vec![] }],49 len: 0,50 cur_min: f32::INFINITY,51 cur_max: f32::NEG_INFINITY,52 cur_sq: 0.0,53 cur_n: 0,54 }55 }5657 pub fn build(samples: &[f32], base: usize, factor: usize) -> Overview {58 let mut o = Overview::new(base, factor);59 o.append(samples);60 o61 }6263 /// Samples summarised so far.64 pub fn len(&self) -> usize {65 self.len66 }67 pub fn is_empty(&self) -> bool {68 self.len == 069 }70 pub fn levels(&self) -> usize {71 self.levels.len()72 }73 /// Bytes held by the overview tables.74 pub fn memory_bytes(&self) -> usize {75 self.levels.iter().map(|l| l.min.len() * 16).sum()76 }7778 fn push_block(&mut self, level: usize, min: f32, max: f32, sq: f64) {79 if level == self.levels.len() {80 let block = self.levels[level - 1].block * self.factor;81 self.levels.push(Level { block, min: vec![], max: vec![], sq: vec![] });82 }83 let l = &mut self.levels[level];84 l.min.push(min);85 l.max.push(max);86 l.sq.push(sq);87 let n = l.min.len();88 if n.is_multiple_of(self.factor) {89 let r = n - self.factor..n;90 let (mn, mx, s) = (91 l.min[r.clone()].iter().copied().fold(f32::INFINITY, f32::min),92 l.max[r.clone()].iter().copied().fold(f32::NEG_INFINITY, f32::max),93 l.sq[r].iter().sum::<f64>(),94 );95 self.push_block(level + 1, mn, mx, s);96 }97 }9899 pub fn append(&mut self, samples: &[f32]) {100 for &s in samples {101 // Non-finite input is shown as silence rather than poisoning a whole block.102 let s = if s.is_finite() { s } else { 0.0 };103 self.cur_min = self.cur_min.min(s);104 self.cur_max = self.cur_max.max(s);105 self.cur_sq += (s as f64) * (s as f64);106 self.cur_n += 1;107 if self.cur_n == self.base {108 let (mn, mx, sq) = (self.cur_min, self.cur_max, self.cur_sq);109 self.cur_min = f32::INFINITY;110 self.cur_max = f32::NEG_INFINITY;111 self.cur_sq = 0.0;112 self.cur_n = 0;113 self.push_block(0, mn, mx, sq);114 }115 }116 self.len += samples.len();117 }118119 /// Summarises samples `[start, end)` into `columns` columns appended to `out` (cleared first).120 /// `samples` is the same PCM the overview was built from (or `None` when it is not in memory):121 /// it is read directly when a column covers less than one finest block (down to one sample per122 /// column and beyond, where columns repeat the sample they fall on) and for the partial blocks123 /// at the edges of a column, so the result is exact at every zoom. Without `samples`, columns124 /// are rounded outwards to whole finest blocks.125 pub fn summarize(&self, samples: Option<&[f32]>, start: usize, end: usize, columns: usize, out: &mut Vec<Column>) {126 out.clear();127 let end = end.min(self.len);128 if columns == 0 || start >= end {129 return;130 }131 let span = (end - start) as f64 / columns as f64;132 for c in 0..columns {133 let a = start + (c as f64 * span).floor() as usize;134 let b = (start + ((c + 1) as f64 * span).ceil() as usize).clamp(a + 1, end.max(a + 1));135 out.push(self.range(samples, a, b.min(self.len.max(a + 1))));136 }137 }138139 fn range(&self, samples: Option<&[f32]>, a: usize, b: usize) -> Column {140 let (mut mn, mut mx, mut sq, mut n) = (f32::INFINITY, f32::NEG_INFINITY, 0.0f64, 0usize);141 let raw = |x: &[f32], mn: &mut f32, mx: &mut f32, sq: &mut f64, n: &mut usize| {142 for &s in x {143 let s = if s.is_finite() { s } else { 0.0 };144 *mn = mn.min(s);145 *mx = mx.max(s);146 *sq += (s as f64) * (s as f64);147 }148 *n += x.len();149 };150 let mut pos = a;151 let b = b.min(self.len);152 while pos < b {153 // Largest aligned block that fits in [pos, b) and is complete.154 let mut used = false;155 for l in self.levels.iter().rev() {156 if pos.is_multiple_of(l.block) && pos + l.block <= b && pos / l.block < l.min.len() {157 let i = pos / l.block;158 mn = mn.min(l.min[i]);159 mx = mx.max(l.max[i]);160 sq += l.sq[i];161 n += l.block;162 pos += l.block;163 used = true;164 break;165 }166 }167 if used {168 continue;169 }170 let next = ((pos / self.base + 1) * self.base).min(b);171 match samples {172 Some(x) if next <= x.len() => raw(&x[pos..next], &mut mn, &mut mx, &mut sq, &mut n),173 _ => {174 // No PCM at hand: take the whole finest block containing `pos` when it exists.175 let i = pos / self.base;176 if let Some(l) = self.levels.first().filter(|l| i < l.min.len()) {177 mn = mn.min(l.min[i]);178 mx = mx.max(l.max[i]);179 sq += l.sq[i];180 n += l.block;181 }182 }183 }184 pos = next;185 }186 if n == 0 {187 return Column::default();188 }189 Column { min: mn, max: mx, rms: (sq / n as f64).sqrt() as f32 }190 }191}192193#[cfg(test)]194mod tests {195 use super::*;196197 fn brute(x: &[f32]) -> Column {198 Column {199 min: x.iter().copied().fold(f32::INFINITY, f32::min),200 max: x.iter().copied().fold(f32::NEG_INFINITY, f32::max),201 rms: (x.iter().map(|v| (*v as f64).powi(2)).sum::<f64>() / x.len() as f64).sqrt() as f32,202 }203 }204205 #[test]206 fn every_zoom_level_matches_a_brute_force_scan() {207 let mut s = 11u64;208 let x: Vec<f32> = (0..100_003)209 .map(|i| {210 s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);211 ((s >> 40) as f32 / (1u64 << 23) as f32 - 1.0) * if (40_000..40_010).contains(&i) { 1.0 } else { 0.1 }212 })213 .collect();214 // Built in uneven pieces, as a stream would deliver them.215 let mut o = Overview::new(64, 4);216 for chunk in x.chunks(777) {217 o.append(chunk);218 }219 assert_eq!(o.len(), x.len());220 assert!(o.levels() >= 5);221 let mut cols = Vec::new();222 for (start, end, columns) in223 [(0usize, 100_003usize, 800usize), (0, 100_003, 13), (1234, 98_765, 300), (39_990, 40_020, 30), (5, 9, 4), (100, 164, 1), (50_000, 50_010, 40)]224 {225 o.summarize(Some(&x), start, end, columns, &mut cols);226 assert_eq!(cols.len(), columns);227 let span = (end - start) as f64 / columns as f64;228 for (c, col) in cols.iter().enumerate() {229 let a = start + (c as f64 * span).floor() as usize;230 let b = (start + ((c + 1) as f64 * span).ceil() as usize).clamp(a + 1, end);231 let want = brute(&x[a..b]);232 assert_eq!((col.min, col.max), (want.min, want.max), "range {start}..{end} column {c}");233 assert!((col.rms - want.rms).abs() < 1e-6);234 }235 }236 // The 10-sample transient is visible in a whole-file view.237 o.summarize(Some(&x), 0, x.len(), 100, &mut cols);238 assert!(cols[39].max > 0.5 || cols[40].max > 0.5);239 assert!(cols[10].max <= 0.1);240 // Without PCM the answer is conservative (whole finest blocks), never smaller.241 o.summarize(None, 1000, 90_000, 50, &mut cols);242 let mut exact = Vec::new();243 o.summarize(Some(&x), 1000, 90_000, 50, &mut exact);244 assert!(cols.iter().zip(&exact).all(|(a, b)| a.max >= b.max && a.min <= b.min));245 o.summarize(Some(&x), 10, 10, 5, &mut cols);246 assert!(cols.is_empty());247 }248249 #[test]250 fn silence_clipping_and_non_finite_input() {251 let mut x = vec![0.0f32; 4096];252 x[2000] = 1.5;253 x[2001] = f32::NAN;254 let o = Overview::build(&x, 256, 4);255 let mut cols = Vec::new();256 o.summarize(Some(&x), 0, 4096, 16, &mut cols);257 assert_eq!(cols[0], Column { min: 0.0, max: 0.0, rms: 0.0 });258 assert_eq!(cols[7].max, 1.5);259 assert!(cols.iter().all(|c| c.rms.is_finite()));260 assert!(o.memory_bytes() > 0 && !o.is_empty());261 }262}263