SPB Git

Repository Public

measure.rs 18.7 KB 424 lines rust

1//! ORIX Sonata2//! File: crates/sonata-dsp/src/analysis/measure.rs3//! Description: Signal measurements for WaveLab: fundamental frequency (YIN), harmonic levels,4//! THD and THD+N, inharmonicity, stereo correlation and balance, amplitude envelope and5//! attack/decay/sustain/release times. Offline helpers (they allocate).6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use super::fft::{interpolate_peak, Spectrum, Window};1112/// Result of a fundamental frequency estimation.13#[derive(Clone, Copy, Debug, PartialEq)]14pub struct Pitch {15    pub frequency_hz: f32,16    /// 1 - d'(tau): 1.0 for a perfectly periodic signal; below about 0.8 the estimate is unreliable.17    pub clarity: f32,18}1920/// Estimates the fundamental of `x` with the YIN algorithm (de Cheveigné & Kawahara, 2002):21/// cumulative mean normalised difference function, absolute threshold 0.1, parabolic refinement.22/// Searches `[min_hz, max_hz]`; needs at least two periods of the lowest frequency. Returns23/// `None` for silence, too short a signal, or when no dip of the difference function falls24/// below 0.35 (aperiodic).25pub fn estimate_pitch(x: &[f32], sample_rate: f32, min_hz: f32, max_hz: f32) -> Option<Pitch> {26    let max_tau = ((sample_rate / min_hz.max(1.0)).ceil() as usize).min(x.len() / 2);27    let min_tau = ((sample_rate / max_hz.max(min_hz + 1.0)).floor() as usize).max(2);28    if max_tau <= min_tau + 2 {29        return None;30    }31    let w = x.len() - max_tau;32    if x[..w].iter().map(|v| (*v as f64).powi(2)).sum::<f64>() / (w as f64) < 1e-10 {33        return None;34    }35    let mut d = vec![0.0f64; max_tau + 1];36    for (tau, dv) in d.iter_mut().enumerate().skip(1) {37        let mut acc = 0.0f64;38        for i in 0..w {39            let diff = (x[i] - x[i + tau]) as f64;40            acc += diff * diff;41        }42        *dv = acc;43    }44    let mut cmnd = vec![1.0f64; max_tau + 1];45    let mut running = 0.0;46    for tau in 1..=max_tau {47        running += d[tau];48        cmnd[tau] = if running > 0.0 { d[tau] * tau as f64 / running } else { 1.0 };49    }50    let mut pick = None;51    let mut tau = min_tau;52    while tau < max_tau {53        if cmnd[tau] < 0.1 {54            while tau + 1 < max_tau && cmnd[tau + 1] < cmnd[tau] {55                tau += 1;56            }57            pick = Some(tau);58            break;59        }60        tau += 1;61    }62    let tau = match pick {63        Some(t) => t,64        None => {65            let t = (min_tau..max_tau).min_by(|a, b| cmnd[*a].partial_cmp(&cmnd[*b]).unwrap_or(std::cmp::Ordering::Equal))?;66            if cmnd[t] > 0.35 {67                return None;68            }69            t70        }71    };72    let (a, b, c) = (cmnd[tau - 1], cmnd[tau], cmnd[(tau + 1).min(max_tau)]);73    let denom = a - 2.0 * b + c;74    let shift = if denom.abs() < 1e-12 { 0.0 } else { (0.5 * (a - c) / denom).clamp(-0.5, 0.5) };75    Some(Pitch { frequency_hz: (sample_rate as f64 / (tau as f64 + shift)) as f32, clarity: (1.0 - b).clamp(0.0, 1.0) as f32 })76}7778/// One partial of a harmonic analysis.79#[derive(Clone, Copy, Debug, PartialEq)]80pub struct Harmonic {81    /// 1 = fundamental.82    pub index: u32,83    pub expected_hz: f32,84    /// Frequency of the spectral peak found near `expected_hz` (equals it when none was found).85    pub measured_hz: f32,86    /// Level in dBFS (-200 when no peak was found).87    pub level_db: f32,88    /// `1200 * log2(measured / expected)`.89    pub deviation_cents: f32,90}9192/// Harmonic content of a steady tone.93#[derive(Clone, Debug, PartialEq)]94pub struct HarmonicAnalysis {95    pub fundamental_hz: f32,96    pub harmonics: Vec<Harmonic>,97    /// Total harmonic distortion: RMS of harmonics 2..N over the fundamental, percent.98    pub thd_percent: f32,99    /// Everything that is not the fundamental (harmonics and noise) over the fundamental, percent.100    pub thd_n_percent: f32,101    /// Level of everything that is neither fundamental nor a measured harmonic, dBFS RMS.102    pub noise_db: f32,103    /// Inharmonicity coefficient B fitted to `f_n = n f_1 sqrt(1 + B n^2)` (stiff string), from104    /// the partials found; 0 when fewer than three were found.105    pub inharmonicity_b: f32,106    /// Conditions of the measurement, to display next to the figures.107    pub fft_size: usize,108    pub window: Window,109    pub bin_hz: f32,110    pub analysed_bandwidth_hz: f32,111}112113/// Analyses up to `max_harmonics` partials of a steady tone whose fundamental is near114/// `fundamental_hz`, on the first `fft_size` samples of `x` with a Blackman-Harris window.115///116/// Conditions and limits: the tone must be stationary over the window; partials are searched117/// within +/-4 % of `n * f1` (so strong inharmonicity beyond that is missed); the noise figure118/// integrates the bins outside +/-4 bins of each found partial, corrected for the window's noise119/// bandwidth; levels below about -110 dBFS are dominated by window side lobes and float32 noise.120pub fn analyze_harmonics(x: &[f32], sample_rate: f32, fundamental_hz: f32, max_harmonics: u32, fft_size: usize) -> HarmonicAnalysis {121    let window = Window::BlackmanHarris;122    let mut sp = Spectrum::new(fft_size, window);123    let mut lin = vec![0.0f32; sp.bins()];124    sp.analyze(x, &mut lin);125    let db: Vec<f32> = lin.iter().map(|v| if *v > 1e-10 { 20.0 * v.log10() } else { -200.0 }).collect();126    let bin_hz = sp.bin_hz(sample_rate);127    let nyquist = sample_rate / 2.0;128    let mut harmonics = Vec::new();129    let mut used = vec![false; lin.len()];130    let mut f1 = fundamental_hz;131    for n in 1..=max_harmonics.max(1) {132        let expected = fundamental_hz * n as f32;133        if expected >= nyquist - 4.0 * bin_hz {134            break;135        }136        let target = if n == 1 { expected } else { f1 * n as f32 };137        let lo = ((target * 0.96 / bin_hz).floor() as usize).max(1);138        let hi = ((target * 1.04 / bin_hz).ceil() as usize).max(lo + 1).min(lin.len() - 2);139        let k = (lo..=hi).max_by(|a, b| db[*a].partial_cmp(&db[*b]).unwrap_or(std::cmp::Ordering::Equal)).unwrap_or(lo);140        match interpolate_peak(&db, k, bin_hz) {141            Some(p) if p.level_db > -150.0 => {142                if n == 1 {143                    f1 = p.frequency_hz;144                }145                for u in used.iter_mut().take((k + 5).min(lin.len())).skip(k.saturating_sub(4)) {146                    *u = true;147                }148                let exp = f1 * n as f32;149                harmonics.push(Harmonic {150                    index: n,151                    expected_hz: exp,152                    measured_hz: p.frequency_hz,153                    level_db: p.level_db,154                    deviation_cents: 1200.0 * (p.frequency_hz / exp).log2(),155                });156            }157            _ => harmonics.push(Harmonic { index: n, expected_hz: f1 * n as f32, measured_hz: f1 * n as f32, level_db: -200.0, deviation_cents: 0.0 }),158        }159    }160    let amp = |h: &Harmonic| 10f64.powf(h.level_db as f64 / 20.0);161    let a1 = harmonics.first().map(amp).unwrap_or(0.0).max(1e-12);162    let harm_pow: f64 = harmonics.iter().skip(1).map(|h| amp(h).powi(2)).sum();163    // Residual power: sum of |amplitude|^2 / 2 over unused bins, divided by the noise bandwidth.164    let enbw = window.noise_bandwidth_bins(fft_size);165    let noise_pow: f64 = lin.iter().enumerate().skip(1).filter(|(k, _)| !used[*k]).map(|(_, v)| (*v as f64).powi(2) / 2.0).sum::<f64>() / enbw;166    let thd = (harm_pow.sqrt() / a1) as f32 * 100.0;167    let thd_n = (((harm_pow / 2.0 + noise_pow) / (a1 * a1 / 2.0)).sqrt()) as f32 * 100.0;168    // Least squares for B on (f_n / (n f_1))^2 - 1 = B n^2 (n >= 2).169    let (mut sxx, mut sxy, mut count) = (0.0f64, 0.0f64, 0);170    for h in harmonics.iter().skip(1).filter(|h| h.level_db > -150.0) {171        let n2 = (h.index as f64).powi(2);172        let y = (h.measured_hz as f64 / (h.index as f64 * f1 as f64)).powi(2) - 1.0;173        sxx += n2 * n2;174        sxy += n2 * y;175        count += 1;176    }177    HarmonicAnalysis {178        fundamental_hz: f1,179        harmonics,180        thd_percent: thd,181        thd_n_percent: thd_n,182        noise_db: if noise_pow > 1e-20 { (10.0 * noise_pow.log10()) as f32 } else { -200.0 },183        inharmonicity_b: if count >= 2 && sxx > 0.0 { (sxy / sxx) as f32 } else { 0.0 },184        fft_size,185        window,186        bin_hz,187        analysed_bandwidth_hz: nyquist,188    }189}190191/// Stereo relationship of two channels.192#[derive(Clone, Copy, Debug, PartialEq)]193pub struct StereoMeasure {194    /// Pearson-style phase correlation in [-1, 1]: +1 mono, 0 unrelated, -1 out of phase. 0 for silence.195    pub correlation: f32,196    /// (R - L) / (R + L) on RMS levels, in [-1, 1]; 0 for silence.197    pub balance: f32,198    pub mid_rms: f32,199    pub side_rms: f32,200}201202pub fn stereo_measure(left: &[f32], right: &[f32]) -> StereoMeasure {203    let n = left.len().min(right.len());204    let (mut ll, mut rr, mut lr, mut mm, mut ss) = (0.0f64, 0.0f64, 0.0f64, 0.0f64, 0.0f64);205    for i in 0..n {206        let (l, r) = (left[i] as f64, right[i] as f64);207        ll += l * l;208        rr += r * r;209        lr += l * r;210        mm += ((l + r) * 0.5).powi(2);211        ss += ((l - r) * 0.5).powi(2);212    }213    let denom = (ll * rr).sqrt();214    let (rl, rrms) = ((ll / n.max(1) as f64).sqrt(), (rr / n.max(1) as f64).sqrt());215    StereoMeasure {216        correlation: if denom > 1e-20 { (lr / denom) as f32 } else { 0.0 },217        balance: if rl + rrms > 1e-12 { ((rrms - rl) / (rrms + rl)) as f32 } else { 0.0 },218        mid_rms: (mm / n.max(1) as f64).sqrt() as f32,219        side_rms: (ss / n.max(1) as f64).sqrt() as f32,220    }221}222223/// Peak envelope follower with separate attack and release time constants. Allocation-free.224pub struct EnvelopeFollower {225    attack: f32,226    release: f32,227    value: f32,228}229230impl EnvelopeFollower {231    pub fn new(sample_rate: f32, attack_sec: f32, release_sec: f32) -> EnvelopeFollower {232        let c = |t: f32| if t <= 0.0 { 0.0 } else { (-1.0 / (t * sample_rate)).exp() };233        EnvelopeFollower { attack: c(attack_sec), release: c(release_sec), value: 0.0 }234    }235    #[inline]236    pub fn next(&mut self, x: f32) -> f32 {237        let a = x.abs();238        let c = if a > self.value { self.attack } else { self.release };239        self.value = a + (self.value - a) * c;240        self.value241    }242    pub fn reset(&mut self) {243        self.value = 0.0;244    }245}246247/// Amplitude envelope: peak magnitude of consecutive blocks of `hop` samples.248pub fn peak_envelope(x: &[f32], hop: usize) -> Vec<f32> {249    x.chunks(hop.max(1)).map(|c| c.iter().fold(0.0f32, |a, b| a.max(b.abs()))).collect()250}251252/// Times measured on the envelope of one note.253#[derive(Clone, Copy, Debug, PartialEq)]254pub struct EnvelopeMeasure {255    pub peak: f32,256    pub peak_time_sec: f32,257    /// Time from 10 % to 90 % of the peak on the way up.258    pub attack_10_90_sec: f32,259    /// Median level over the last quarter of the held part (before `gate_off_sec`).260    pub sustain_level: f32,261    /// Time from the peak until the envelope first comes within 10 % of the peak-to-sustain span above the sustain level.262    pub decay_sec: f32,263    /// Time after `gate_off_sec` for the envelope to fall 60 dB below the sustain level,264    /// extrapolated from the first 20 dB of fall when the recording is too short (`None` when265    /// even that is not reached).266    pub release_t60_sec: Option<f32>,267}268269/// Measures attack, decay, sustain and release of a recorded note. `hop` is the envelope270/// resolution in samples (measured times are quantised to `hop / sample_rate`);271/// `gate_off_sec` is the note-off time relative to the start of `x`.272pub fn measure_envelope(x: &[f32], sample_rate: f32, hop: usize, gate_off_sec: f32) -> Option<EnvelopeMeasure> {273    let env = peak_envelope(x, hop);274    let dt = hop.max(1) as f32 / sample_rate;275    let gate = ((gate_off_sec / dt) as usize).min(env.len());276    let (pk_i, peak) = env[..gate.max(1).min(env.len())].iter().copied().enumerate().fold((0, 0.0f32), |a, b| if b.1 > a.1 { b } else { a });277    if peak <= 1e-9 {278        return None;279    }280    let first = |thr: f32| env[..=pk_i].iter().position(|v| *v >= thr).unwrap_or(pk_i);281    let attack = (first(0.9 * peak) as f32 - first(0.1 * peak) as f32).max(0.0) * dt;282    let held = &env[pk_i..gate.max(pk_i + 1).min(env.len())];283    let mut tail: Vec<f32> = held[held.len() - (held.len() / 4).max(1)..].to_vec();284    tail.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));285    let sustain = tail[tail.len() / 2];286    let thr = sustain + 0.1 * (peak - sustain);287    let decay = held.iter().position(|v| *v <= thr).unwrap_or(held.len()) as f32 * dt;288    let after = &env[gate.min(env.len())..];289    let fall = |db: f32| after.iter().position(|v| *v <= sustain * 10f32.powf(-db / 20.0)).map(|i| i as f32 * dt);290    let release = fall(60.0).or_else(|| fall(20.0).map(|t| t * 3.0));291    Some(EnvelopeMeasure {292        peak,293        peak_time_sec: pk_i as f32 * dt,294        attack_10_90_sec: attack,295        sustain_level: sustain,296        decay_sec: decay,297        release_t60_sec: release,298    })299}300301#[cfg(test)]302mod tests {303    use super::*;304    use std::f64::consts::TAU;305306    #[test]307    fn yin_estimates_pitch_and_rejects_noise_and_silence() {308        let sr = 48_000.0;309        for f in [55.0f64, 110.0, 440.0, 1318.5, 3520.0] {310            let x: Vec<f32> = (0..8192)311                .map(|i| {312                    ((TAU * f * i as f64 / sr).sin() * 0.5 + (TAU * 2.0 * f * i as f64 / sr).sin() * 0.3 + (TAU * 3.0 * f * i as f64 / sr).sin() * 0.2) as f32313                })314                .collect();315            let p = estimate_pitch(&x, sr as f32, 40.0, 5000.0).unwrap();316            // Tolerance: 3 cents.317            assert!((1200.0 * (p.frequency_hz as f64 / f).log2()).abs() < 3.0, "{f}: {}", p.frequency_hz);318            assert!(p.clarity > 0.95);319        }320        let mut s = 1u64;321        let noise: Vec<f32> = (0..8192)322            .map(|_| {323                s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);324                (s >> 40) as f32 / (1u64 << 23) as f32 - 1.0325            })326            .collect();327        assert!(estimate_pitch(&noise, sr as f32, 40.0, 5000.0).is_none());328        assert!(estimate_pitch(&[0.0; 8192], sr as f32, 40.0, 5000.0).is_none());329        assert!(estimate_pitch(&[0.1; 16], sr as f32, 40.0, 5000.0).is_none());330    }331332    #[test]333    fn thd_of_known_harmonic_mixtures() {334        let sr = 48_000.0;335        let f = 1000.0;336        // Pure sine: THD below 0.001 % (float32 and window floor).337        let pure: Vec<f32> = (0..32_768).map(|i| (TAU * f * i as f64 / sr).sin() as f32 * 0.5).collect();338        let a = analyze_harmonics(&pure, sr as f32, 1000.0, 10, 32_768);339        assert!(a.thd_percent < 0.001 && a.thd_n_percent < 0.01, "{} {}", a.thd_percent, a.thd_n_percent);340        assert!((a.fundamental_hz - 1000.0).abs() < 0.05);341        // 1 % second and 0.5 % third harmonic: THD = sqrt(0.01^2 + 0.005^2) = 1.118 %.342        let x: Vec<f32> = (0..32_768)343            .map(|i| {344                (0.5 * ((TAU * f * i as f64 / sr).sin() + 0.01 * (TAU * 2.0 * f * i as f64 / sr).sin() + 0.005 * (TAU * 3.0 * f * i as f64 / sr).sin())) as f32345            })346            .collect();347        let a = analyze_harmonics(&x, sr as f32, 1000.0, 10, 32_768);348        assert!((a.thd_percent - 1.118).abs() < 0.01, "{}", a.thd_percent);349        assert!((a.harmonics[0].level_db + 6.02).abs() < 0.05 && (a.harmonics[1].level_db + 46.02).abs() < 0.1);350        assert!(a.harmonics[1].deviation_cents.abs() < 0.5);351        assert_eq!(a.harmonics.len(), 10);352        // Added white noise at -60 dBFS RMS shows in THD+N (0.1 / 0.3536 = 0.283 %) and in the noise figure.353        let mut s = 3u64;354        let noisy: Vec<f32> = pure355            .iter()356            .map(|v| {357                s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);358                v + ((s >> 40) as f32 / (1u64 << 23) as f32 - 1.0) * 0.001 * 3f32.sqrt()359            })360            .collect();361        let a = analyze_harmonics(&noisy, sr as f32, 1000.0, 10, 32_768);362        assert!((a.noise_db + 60.0).abs() < 0.5, "{}", a.noise_db);363        assert!((a.thd_n_percent - 0.283).abs() < 0.03, "{}", a.thd_n_percent);364    }365366    #[test]367    fn inharmonicity_of_a_stiff_string_spectrum() {368        let sr = 48_000.0;369        let (f1, b) = (220.0f64, 0.0004f64);370        let x: Vec<f32> = (0..32_768)371            .map(|i| (1..=12).map(|n| (TAU * n as f64 * f1 * (1.0 + b * (n * n) as f64).sqrt() * i as f64 / sr).sin() * 0.05).sum::<f64>() as f32)372            .collect();373        let a = analyze_harmonics(&x, sr as f32, 220.0, 12, 32_768);374        // The fit is relative to the measured first partial, itself sharp by sqrt(1 + B).375        assert!((a.inharmonicity_b as f64 - b).abs() < 0.1 * b, "{}", a.inharmonicity_b);376        assert!(a.harmonics[11].deviation_cents > 40.0);377    }378379    #[test]380    fn stereo_measures() {381        let l: Vec<f32> = (0..4800).map(|i| (i as f32 * 0.1).sin()).collect();382        let neg: Vec<f32> = l.iter().map(|v| -v).collect();383        let quad: Vec<f32> = (0..4800).map(|i| (i as f32 * 0.1).cos()).collect();384        assert!((stereo_measure(&l, &l).correlation - 1.0).abs() < 1e-6);385        assert!((stereo_measure(&l, &neg).correlation + 1.0).abs() < 1e-6);386        assert!(stereo_measure(&l, &quad).correlation.abs() < 0.01);387        assert!(stereo_measure(&l, &neg).mid_rms < 1e-6 && stereo_measure(&l, &l).side_rms < 1e-6);388        let half: Vec<f32> = l.iter().map(|v| v * 0.5).collect();389        assert!((stereo_measure(&l, &half).balance + 1.0 / 3.0).abs() < 1e-4);390        assert_eq!(stereo_measure(&[0.0; 10], &[0.0; 10]).correlation, 0.0);391    }392393    #[test]394    fn envelope_times_of_a_synthetic_adsr() {395        let sr = 48_000.0f32;396        // Linear attack 20 ms to 1.0, exponential decay (tau 30 ms) to 0.5, gate off at 0.5 s, release tau 50 ms.397        let x: Vec<f32> = (0..72_000)398            .map(|i| {399                let t = i as f32 / sr;400                let e = if t < 0.02 {401                    t / 0.02402                } else if t < 0.5 {403                    0.5 + 0.5 * (-(t - 0.02) / 0.03).exp()404                } else {405                    0.5 * (-(t - 0.5) / 0.05).exp()406                };407                e * (std::f32::consts::TAU * 1000.0 * t).sin()408            })409            .collect();410        let m = measure_envelope(&x, sr, 48, 0.5).unwrap();411        assert!((m.peak - 1.0).abs() < 0.02 && (m.peak_time_sec - 0.02).abs() < 0.003);412        assert!((m.attack_10_90_sec - 0.016).abs() < 0.003, "{}", m.attack_10_90_sec);413        assert!((m.sustain_level - 0.5).abs() < 0.01);414        // Decay to within 10 % of the span: tau * ln(10) = 69 ms.415        assert!((m.decay_sec - 0.069).abs() < 0.006, "{}", m.decay_sec);416        // T60 = tau * ln(1000) = 345 ms.417        assert!((m.release_t60_sec.unwrap() - 0.345).abs() < 0.01, "{:?}", m.release_t60_sec);418        assert!(measure_envelope(&[0.0; 1000], sr, 48, 0.01).is_none());419        let mut f = EnvelopeFollower::new(sr, 0.0, 0.01);420        assert_eq!(f.next(-0.8), 0.8);421        assert!(f.next(0.0) < 0.8 && f.next(0.0) > 0.79);422    }423}424
Files main
Menu

Theme