Skip to main content

sva_samples/measure/
self_similarity.rs

1// Concern: how a target's stretches resemble one another: chroma and band-level matrices, stripes, novelty | Non-concern: picking partials, band filters, verdicts | IO: (planes, Asked) -> SelfSimilarity
2
3use super::bands;
4use super::harmony::{above, measured};
5use super::pitch::{HIGHEST_HZ, LOWEST_HZ, midi_of};
6use super::sliding::{self, Span};
7
8/// The most cells one side of the matrix holds: its lower triangle is 524 800 entries.
9pub const MAX_CELLS: usize = 1024;
10const CLASSES: usize = 12;
11
12pub const MODEL: &str = "self-similarity matrix of Foote, J. (1999), Visualizing music and \
13                         audio using self-similarity, Proc. ACM Multimedia 77-80, read for \
14                         repetition as Bartsch, M. A. and Wakefield, G. H. (2001), To catch a \
15                         chorus: using chroma-based representations for audio thumbnailing, \
16                         Proc. IEEE WASPAA 15-18, and for boundaries as Foote, J. (2000), \
17                         Automatic audio segmentation using a measure of audio novelty, Proc. \
18                         IEEE ICME 452-455, each step as Mueller, M. (2015), Fundamentals of \
19                         Music Processing, Springer, ch. 4 (FMP) writes it. Frames: a Hann \
20                         frame of `frame_window_secs` of each channel centred every \
21                         `hop_secs` from the target's start, their power per bin averaged over \
22                         the channels, its partials picked and refined \
23                         as the harmonic readings pick them (see their method), \
24                         `resolution_hz` apart before refinement, so two partials within about \
25                         that of each other, as two notes a semitone apart under some 17 \
26                         times `resolution_hz`, are not resolved. \
27                         Chroma view: per frame each partial at or above `floor_db` from \
28                         `min_hz` to `max_hz` adds its squared amplitude to the pitch class \
29                         of its nearest equal-tempered note (A4 = 440 Hz), C first; \
30                         harmonics are not removed, so a tone's third harmonic adds to its \
31                         fifth's class, as Bartsch and Wakefield's chroma does. Timbre view: \
32                         the RMS of each ERB band of `bands` (`centres_hz`), every channel's \
33                         band energy averaged, each band's level \
34                         in dB above `floor_db`, zero under it. Cells: `frames_per_cell` \
35                         frames, `cell_secs`, centred every `cell_secs` from the start as \
36                         every framed reading steps, `from`/`to` the first frame centre in it \
37                         and the next cell's, the first clipped at the target's start, and \
38                         frames past the last cell's `to`, under half a cell, in none; a \
39                         cell's chroma is its frames' mean, its band levels those of its \
40                         bands' mean energy over that span. similarity(i, j): the cosine of \
41                         cells i and j's vectors, in [0, 1] as no entry is negative, and 0 \
42                         where either vector is all zero (silence, or nothing over the floor), \
43                         itself included. matrix, where asked: row i lists \
44                         similarity(i, i - lag) for lag 0 to i, the lower triangle in \
45                         time-lag form; it is symmetric. Stripes: a repeat is a stripe \
46                         parallel to the diagonal. Each diagonal is first averaged along its \
47                         length over `smooth_cells` cells centred on each, over the cells it \
48                         holds (FMP 4.2.2's path enhancement), so a held chord's square block \
49                         does not hide which lag repeats; a cell is on a stripe where that \
50                         average exceeds the one at one cell less lag and is no lower than \
51                         the one at one cell more, in its row (a missing neighbour counts as \
52                         lower); a stripe is a run of such cells at one lag, `cells` long, \
53                         `later` repeating `earlier` `lag_secs` before it. Lags from one \
54                         cell; a repeat under two cells away merges with the diagonal and is \
55                         not read. A stripe's ends stand within half `smooth_cells` of where \
56                         the repeat's do. `similarity_mean`/`_min` are the raw similarity along \
57                         it, unaveraged. Transposition, chroma view: the same search runs on \
58                         the matrix of each cell against each earlier cell's chroma rotated up \
59                         `shift_semitones` (Goto, M. (2003), A chorus-section detecting \
60                         method for musical audio signals, Proc. IEEE ICASSP 437-440; FMP \
61                         4.2.2), shifts -5 to 6, so an exact repeat reads at shift 0 and one \
62                         transposed up two semitones at shift 2; a shift is mod 12, so a \
63                         repeat an octave up reads at 0, and a sustained glide reads as \
64                         transposed repeats of itself at every shift. A symmetric chord (an \
65                         augmented triad at 4, a diminished seventh at 3) reads at more than \
66                         one shift. The matrix lists shift 0 alone; the timbre view has no \
67                         shift. No threshold: every stripe is counted in `stripes_found`, \
68                         the `listed` with the largest summed similarity listed, largest \
69                         first, so a short weak stripe from noise reads with its small sum, \
70                         never dropped unasked. Novelty: per boundary between two adjacent \
71                         cells, sum over a and b of K(a, b) similarity(i + a, i + b), a and b \
72                         from -L to L - 1 cells, L = `kernel_cells`, K Foote's checkerboard \
73                         sign(u_a) sign(u_b) tapered by a Gaussian exp(-u^2 / (2 L^2)) at \
74                         u = a + 1/2 (FMP's default variance), normalized so sum |K| = 1, \
75                         cells past the target zero (so a boundary near either end reads \
76                         against silence); in [-0.5, 0.5], 0.5 for a cut between two \
77                         blocks each wholly alike within and wholly unlike across. `values` \
78                         from `from_secs` by `cell_secs`; peaks: those over the one before \
79                         and no lower than the one after, the `listed` highest, highest \
80                         first, every one counted in `peaks_found`. Exact path: none; a \
81                         closed form is read off its rendered samples, because a frame's \
82                         partials over a floor and a band's energy over a span are stated by \
83                         no closed form";
84
85/// Each reading's arguments: the frame `hop_secs`, the matrix's `cell_secs`, the stripe
86/// average's `smooth_secs`, the novelty kernel's whole `window_secs`, the floor, how many
87/// stripes and peaks are listed, and whether the cells and matrices are.
88#[derive(Clone, Copy, Debug, PartialEq)]
89pub struct Asked {
90    pub hop_secs: f64,
91    pub cell_secs: f64,
92    pub smooth_secs: f64,
93    pub window_secs: f64,
94    pub floor_db: f64,
95    pub listed: usize,
96    pub curve: bool,
97}
98
99/// `least_cell_secs` is the finest cell that fits the cap; `most_secs` the longest target
100/// the cell asked fits.
101#[derive(Clone, Copy, Debug, PartialEq)]
102pub struct TooManyCells {
103    pub cells: usize,
104    pub cap: usize,
105    pub cell_secs: f64,
106    pub held_secs: f64,
107    pub least_cell_secs: f64,
108    pub most_secs: f64,
109}
110
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum View {
113    Chroma,
114    Timbre,
115}
116
117impl View {
118    pub fn key(self) -> &'static str {
119        match self {
120            View::Chroma => "chroma",
121            View::Timbre => "timbre",
122        }
123    }
124}
125
126#[derive(Clone, Debug, PartialEq)]
127pub struct Cell {
128    pub t_secs: f64,
129    pub from_secs: f64,
130    pub to_secs: f64,
131    /// Mean squared amplitude per frame, C to B.
132    pub chroma: [f64; CLASSES],
133    /// dB against full scale, one per band in `centres_hz`.
134    pub levels_db: Vec<f64>,
135}
136
137#[derive(Clone, Copy, Debug, PartialEq)]
138pub struct Stripe {
139    pub shift_semitones: i32,
140    pub lag_secs: f64,
141    pub earlier: (f64, f64),
142    pub later: (f64, f64),
143    pub cells: usize,
144    pub similarity_mean: f64,
145    pub similarity_min: f64,
146}
147
148#[derive(Clone, Copy, Debug, PartialEq)]
149pub struct Peak {
150    pub t_secs: f64,
151    pub novelty: f64,
152}
153
154#[derive(Clone, Debug, PartialEq)]
155pub struct Reading {
156    pub view: View,
157    pub stripes_found: usize,
158    /// Largest summed similarity first.
159    pub stripes: Vec<Stripe>,
160    /// One per boundary, the first at `novelty_from_secs`, `cell_secs` apart.
161    pub novelty: Vec<f64>,
162    pub peaks_found: usize,
163    /// Highest first.
164    pub peaks: Vec<Peak>,
165    /// Row i holds lags 0 to i; listed where asked.
166    pub matrix: Option<Vec<Vec<f64>>>,
167}
168
169#[derive(Clone, Debug, PartialEq)]
170pub struct SelfSimilarity {
171    pub hop_secs: f64,
172    pub frame_window_secs: f64,
173    pub resolution_hz: f64,
174    pub cell_secs: f64,
175    pub frames_per_cell: usize,
176    pub cell_count: usize,
177    pub smooth_cells: usize,
178    pub kernel_cells: usize,
179    pub floor_db: f64,
180    pub listed: usize,
181    pub min_hz: f64,
182    pub max_hz: f64,
183    pub centres_hz: Vec<f64>,
184    pub novelty_from_secs: f64,
185    /// Listed where asked.
186    pub cells: Option<Vec<Cell>>,
187    pub views: Vec<Reading>,
188}
189
190pub fn measure(
191    planes: &[&[f64]],
192    sample_rate: f64,
193    start_secs: f64,
194    asked: Asked,
195) -> Result<SelfSimilarity, TooManyCells> {
196    let held = crate::measure::held(planes);
197    let frame_hop = ((asked.hop_secs * sample_rate).round() as usize).max(1);
198    let per_cell = ((asked.cell_secs * sample_rate / frame_hop as f64).round() as usize).max(1);
199    let cell_hop = per_cell * frame_hop;
200    let cell_secs = cell_hop as f64 / sample_rate;
201    let count = held.div_ceil(cell_hop);
202    if count > MAX_CELLS {
203        let least = held.div_ceil(MAX_CELLS * frame_hop) * frame_hop;
204        return Err(TooManyCells {
205            cells: count,
206            cap: MAX_CELLS,
207            cell_secs,
208            held_secs: held as f64 / sample_rate,
209            least_cell_secs: least as f64 / sample_rate,
210            most_secs: (MAX_CELLS * cell_hop) as f64 / sample_rate,
211        });
212    }
213    let (moments, framing) = measured::moments(
214        planes,
215        sample_rate,
216        start_secs,
217        frame_hop as f64 / sample_rate,
218    );
219    let window = framing.window.expect("measured frames have a window");
220    let chroma: Vec<[f64; CLASSES]> = moments
221        .iter()
222        .map(|m| {
223            let mut held = [0.0; CLASSES];
224            for p in above(m, asked.floor_db) {
225                if (LOWEST_HZ..=HIGHEST_HZ).contains(&p.hz) {
226                    held[(midi_of(p.hz).round() as i64).rem_euclid(12) as usize] +=
227                        p.amplitude * p.amplitude;
228                }
229            }
230            held
231        })
232        .collect();
233    let split = bands::analyze(planes, sample_rate, start_secs);
234    let grid = |rate: f64, len: usize| {
235        sliding::spans(
236            held,
237            sample_rate,
238            start_secs,
239            cell_secs,
240            rate,
241            cell_secs,
242            len,
243        )
244        .spans
245    };
246    let framed = grid(sample_rate / frame_hop as f64, chroma.len());
247    let banded = grid(
248        split.rate_hz,
249        split.bands.first().map_or(0, |b| b.rms.len()),
250    );
251    let cells: Vec<Cell> = framed
252        .iter()
253        .zip(&banded)
254        .map(|(f, b)| cell(f, b, &chroma, &split))
255        .collect();
256    let smooth_cells = ((asked.smooth_secs / cell_secs).round() as usize).max(1);
257    let kernel_cells = ((asked.window_secs / (2.0 * cell_secs)).round() as usize).max(1);
258    let read = Read {
259        cells: &cells,
260        cell_secs,
261        smooth_cells,
262        kernel_cells,
263        listed: asked.listed,
264        curve: asked.curve,
265    };
266    let chroma_of = |c: &Cell| c.chroma.to_vec();
267    let timbre_of = |c: &Cell| {
268        c.levels_db
269            .iter()
270            .map(|l| (l - asked.floor_db).max(0.0))
271            .collect()
272    };
273    Ok(SelfSimilarity {
274        hop_secs: framing.hop_secs,
275        frame_window_secs: window.secs,
276        resolution_hz: window.resolution_hz,
277        cell_secs,
278        frames_per_cell: per_cell,
279        cell_count: cells.len(),
280        smooth_cells,
281        kernel_cells,
282        floor_db: asked.floor_db,
283        listed: asked.listed,
284        min_hz: LOWEST_HZ,
285        max_hz: HIGHEST_HZ,
286        centres_hz: split.bands.iter().map(|b| b.centre_hz).collect(),
287        novelty_from_secs: start_secs + 0.5 * cell_secs,
288        views: vec![
289            read.view(View::Chroma, chroma_of, -5..=6),
290            read.view(View::Timbre, timbre_of, 0..=0),
291        ],
292        cells: asked.curve.then_some(cells),
293    })
294}
295
296fn cell(f: &Span, b: &Span, chroma: &[[f64; CLASSES]], split: &bands::Bands) -> Cell {
297    let frames = &chroma[f.from..f.to];
298    let mut mean = [0.0; CLASSES];
299    for frame in frames {
300        for (m, e) in mean.iter_mut().zip(frame) {
301            *m += e / frames.len() as f64;
302        }
303    }
304    let levels_db = split
305        .bands
306        .iter()
307        .map(|band| {
308            let held = &band.rms[b.from..b.to];
309            let energy = held.iter().map(|r| r * r).sum::<f64>() / held.len() as f64;
310            10.0 * energy.log10()
311        })
312        .collect();
313    Cell {
314        t_secs: f.t_secs,
315        from_secs: f.from_secs,
316        to_secs: f.to_secs,
317        chroma: mean,
318        levels_db,
319    }
320}
321
322struct Read<'a> {
323    cells: &'a [Cell],
324    cell_secs: f64,
325    smooth_cells: usize,
326    kernel_cells: usize,
327    listed: usize,
328    curve: bool,
329}
330
331impl Read<'_> {
332    /// `shifts` rotate each earlier cell's vector, which only chroma's twelve classes mean.
333    fn view(
334        &self,
335        view: View,
336        vector: impl Fn(&Cell) -> Vec<f64>,
337        shifts: std::ops::RangeInclusive<i32>,
338    ) -> Reading {
339        let vectors: Vec<Vec<f64>> = self.cells.iter().map(vector).collect();
340        let norms: Vec<f64> = vectors
341            .iter()
342            .map(|v| v.iter().map(|x| x * x).sum::<f64>().sqrt())
343            .collect();
344        let mut raw = Vec::new();
345        let mut stripes = Vec::new();
346        for shift in shifts {
347            let k = shift.rem_euclid(CLASSES as i32) as usize;
348            let rotated = |j: usize, p: usize| {
349                let v = &vectors[j];
350                v[(p + v.len() - k % v.len()) % v.len()]
351            };
352            let held = diagonals(self.cells.len(), |i, j| {
353                let dot: f64 = (0..vectors[i].len())
354                    .map(|p| vectors[i][p] * rotated(j, p))
355                    .sum();
356                match norms[i] > 0.0 && norms[j] > 0.0 {
357                    true => dot / (norms[i] * norms[j]),
358                    false => 0.0,
359                }
360            });
361            stripes.extend(self.stripes(&held, shift));
362            if shift == 0 {
363                raw = held;
364            }
365        }
366        stripes.sort_by(|a, b| {
367            let sum = |s: &Stripe| s.similarity_mean * s.cells as f64;
368            sum(b)
369                .total_cmp(&sum(a))
370                .then(a.later.0.total_cmp(&b.later.0))
371        });
372        let novelty = novelty(&raw, self.kernel_cells);
373        let mut peaks: Vec<Peak> = (0..novelty.len())
374            .filter(|&i| {
375                (i == 0 || novelty[i] > novelty[i - 1])
376                    && novelty.get(i + 1).is_none_or(|next| novelty[i] >= *next)
377            })
378            .map(|i| Peak {
379                t_secs: self.cells[0].t_secs + (i as f64 + 0.5) * self.cell_secs,
380                novelty: novelty[i],
381            })
382            .collect();
383        peaks.sort_by(|a, b| b.novelty.total_cmp(&a.novelty));
384        let (stripes_found, peaks_found) = (stripes.len(), peaks.len());
385        stripes.truncate(self.listed);
386        peaks.truncate(self.listed);
387        let matrix = self.curve.then(|| {
388            (0..raw.len())
389                .map(|i| (0..=i).map(|lag| raw[lag][i - lag]).collect())
390                .collect()
391        });
392        Reading {
393            view,
394            stripes_found,
395            stripes,
396            novelty,
397            peaks_found,
398            peaks,
399            matrix,
400        }
401    }
402
403    /// Ridges of the averaged diagonals, as MODEL states, run along each lag.
404    fn stripes(&self, raw: &[Vec<f64>], shift: i32) -> Vec<Stripe> {
405        let smooth: Vec<Vec<f64>> = raw.iter().map(|d| averaged(d, self.smooth_cells)).collect();
406        let mut found = Vec::new();
407        for lag in 1..smooth.len() {
408            let on = |j: usize| {
409                let v = smooth[lag][j];
410                v > smooth[lag - 1][j + 1] && (j == 0 || v >= smooth[lag + 1][j - 1])
411            };
412            let mut run: Option<usize> = None;
413            for j in 0..=smooth[lag].len() {
414                match (run, j < smooth[lag].len() && on(j)) {
415                    (None, true) => run = Some(j),
416                    (Some(from), false) => {
417                        found.push(self.stripe(&raw[lag][from..j], shift, lag, from));
418                        run = None;
419                    }
420                    _ => {}
421                }
422            }
423        }
424        found
425    }
426
427    fn stripe(&self, along: &[f64], shift: i32, lag: usize, from: usize) -> Stripe {
428        let to = from + along.len() - 1;
429        let span = |a: usize, b: usize| (self.cells[a].from_secs, self.cells[b].to_secs);
430        Stripe {
431            shift_semitones: shift,
432            lag_secs: lag as f64 * self.cell_secs,
433            earlier: span(from, to),
434            later: span(from + lag, to + lag),
435            cells: along.len(),
436            similarity_mean: along.iter().sum::<f64>() / along.len() as f64,
437            similarity_min: along.iter().copied().fold(f64::INFINITY, f64::min),
438        }
439    }
440}
441
442/// `held[lag][j]` is `similarity(j + lag, j)`.
443fn diagonals(n: usize, similarity: impl Fn(usize, usize) -> f64) -> Vec<Vec<f64>> {
444    (0..n)
445        .map(|lag| (0..n - lag).map(|j| similarity(j + lag, j)).collect())
446        .collect()
447}
448
449/// The mean over `len` entries centred on each, over those the diagonal holds.
450fn averaged(d: &[f64], len: usize) -> Vec<f64> {
451    let before = (len - 1) / 2;
452    let after = len - 1 - before;
453    let mut sums = vec![0.0; d.len() + 1];
454    for (i, v) in d.iter().enumerate() {
455        sums[i + 1] = sums[i] + v;
456    }
457    (0..d.len())
458        .map(|j| {
459            let lo = j.saturating_sub(before);
460            let hi = (j + after + 1).min(d.len());
461            (sums[hi] - sums[lo]) / (hi - lo) as f64
462        })
463        .collect()
464}
465
466/// Foote's tapered checkerboard over the boundary before each cell but the first.
467fn novelty(raw: &[Vec<f64>], half: usize) -> Vec<f64> {
468    let n = raw.len();
469    let taper: Vec<f64> = (0..2 * half)
470        .map(|a| {
471            let u = a as f64 - half as f64 + 0.5;
472            u.signum() * (-u * u / (2.0 * (half * half) as f64)).exp()
473        })
474        .collect();
475    let total: f64 = taper.iter().map(|g| g.abs()).sum::<f64>().powi(2);
476    let at = |p: usize, q: usize| raw[p.abs_diff(q)][p.min(q)];
477    (1..n)
478        .map(|i| {
479            let first = i.saturating_sub(half);
480            let last = (i + half).min(n);
481            let mut sum = 0.0;
482            for p in first..last {
483                for q in first..last {
484                    sum += taper[p + half - i] * taper[q + half - i] * at(p, q);
485                }
486            }
487            sum / total
488        })
489        .collect()
490}