Repository Public
1//! ORIX Sonata2//! File: crates/sonata-ffi/src/analysis.rs3//! Description: C ABI of the stateless analysis functions (calibrated spectrum, pitch and4//! harmonic measurements, stereo and loudness figures) and the reader-side live loudness meter.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::util::{error_json, give_json, guard, guard_json};10use serde_json::{json, Value};11use sonata_dsp::analysis::fft::{Spectrum, Window};12use sonata_dsp::analysis::measure::{analyze_harmonics, estimate_pitch, stereo_measure};13use sonata_dsp::analysis::meters::{dc_offset, rms, sample_peak, to_db, LoudnessMeter, TruePeak};14use std::cell::RefCell;15use std::ffi::c_char;1617fn window_of(code: i32) -> Window {18 match code {19 0 => Window::Rectangular,20 2 => Window::Blackman,21 3 => Window::BlackmanHarris,22 _ => Window::Hann,23 }24}2526/// JSON number, or null for a non-finite value (JSON has no infinity).27pub fn num(x: f64) -> Value {28 if x.is_finite() {29 json!(x)30 } else {31 Value::Null32 }33}3435/// dB value for JSON: -200 stands for silence instead of -inf so Swift can decode a number.36fn db(x: f64) -> Value {37 json!(if x.is_finite() {38 x.max(-200.0)39 } else if x > 0.0 {40 200.041 } else {42 -200.043 })44}4546thread_local! {47 /// Analysers are reused per thread and per (size, window): the UI asks for spectra 60 times a second.48 static SPECTRA: RefCell<Vec<Spectrum>> = const { RefCell::new(Vec::new()) };49}5051/// # Safety52/// `samples` valid for `size` floats, `out_db` valid for `size / 2 + 1` floats.53#[no_mangle]54pub unsafe extern "C" fn sonata_spectrum(samples: *const f32, size: u32, window: i32, out_db: *mut f32) -> bool {55 let n = size as usize;56 if samples.is_null() || out_db.is_null() || !n.is_power_of_two() || !(256..=32768).contains(&n) {57 return false;58 }59 let input = std::slice::from_raw_parts(samples, n);60 let out = std::slice::from_raw_parts_mut(out_db, n / 2 + 1);61 guard(false, || {62 let w = window_of(window);63 SPECTRA.with(|cell| {64 let mut list = cell.borrow_mut();65 let idx = match list.iter().position(|s| s.size() == n && s.window() == w) {66 Some(i) => i,67 None => {68 if list.len() >= 16 {69 list.remove(0);70 }71 list.push(Spectrum::new(n, w));72 list.len() - 173 }74 };75 list[idx].analyze_db(input, out);76 });77 for v in out.iter_mut() {78 if !v.is_finite() {79 *v = -200.0;80 }81 }82 true83 })84}8586/// # Safety87/// `samples` valid for `count` floats.88#[no_mangle]89pub unsafe extern "C" fn sonata_measure(samples: *const f32, count: usize, sample_rate: f64) -> *mut c_char {90 if samples.is_null() || count == 0 || !sample_rate.is_finite() || sample_rate < 1000.0 {91 return error_json("nothing to measure");92 }93 let x = std::slice::from_raw_parts(samples, count.min(1 << 24));94 guard_json(|| {95 let sr = sample_rate as f32;96 let peak = sample_peak(x);97 let r = rms(x);98 let pitch = estimate_pitch(x, sr, 20.0, (sr / 4.0).min(5000.0));99 let mut out = json!({100 "fundamental_hz": Value::Null,101 "confidence": 0.0,102 "peak_db": db(to_db(peak) as f64),103 "rms_db": db(to_db(r) as f64),104 "dc": dc_offset(x),105 "thd_percent": Value::Null,106 "harmonics": [],107 "inharmonicity": Value::Null,108 "noise_db": Value::Null,109 "crest_db": db(if r > 0.0 { (to_db(peak) - to_db(r)) as f64 } else { 0.0 }),110 });111 if let Some(p) = pitch {112 out["fundamental_hz"] = num(p.frequency_hz as f64);113 out["confidence"] = num(p.clarity as f64);114 // Largest power-of-two window that fits the signal, at most 32768 samples.115 let mut size = 32768usize;116 while size > x.len() && size > 1024 {117 size /= 2;118 }119 if x.len() >= size {120 let h = analyze_harmonics(x, sr, p.frequency_hz, 32, size);121 out["thd_percent"] = num(h.thd_percent as f64);122 out["inharmonicity"] = num(h.inharmonicity_b as f64);123 out["noise_db"] = db(h.noise_db as f64);124 out["fundamental_hz"] = num(h.fundamental_hz as f64);125 out["harmonics"] =126 Value::Array(h.harmonics.iter().map(|k| json!({ "n": k.index, "hz": k.measured_hz, "db": db(k.level_db as f64) })).collect());127 }128 }129 give_json(&out)130 })131}132133/// # Safety134/// `left` and `right` valid for `count` floats.135#[no_mangle]136pub unsafe extern "C" fn sonata_measure_stereo(left: *const f32, right: *const f32, count: usize) -> *mut c_char {137 if left.is_null() || right.is_null() || count == 0 {138 return error_json("nothing to measure");139 }140 let l = std::slice::from_raw_parts(left, count.min(1 << 26));141 let r = std::slice::from_raw_parts(right, count.min(1 << 26));142 guard_json(|| {143 let m = stereo_measure(l, r);144 let width = if m.mid_rms > 0.0 {145 (m.side_rms / m.mid_rms) as f64146 } else if m.side_rms > 0.0 {147 99.0148 } else {149 0.0150 };151 give_json(&json!({152 "correlation": num(m.correlation as f64).as_f64().unwrap_or(0.0),153 "balance": num(m.balance as f64).as_f64().unwrap_or(0.0),154 "width": width.min(99.0),155 "mid_rms_db": db(to_db(m.mid_rms) as f64),156 "side_rms_db": db(to_db(m.side_rms) as f64),157 }))158 })159}160161/// Loudness figures of a whole stereo buffer: integrated, maxima of short-term and momentary,162/// loudness range (difference between the 95th and 10th percentiles of the gated short-term163/// values, a simplified LRA), true peak and sample peak.164pub fn loudness_of(l: &[f32], r: &[f32], sample_rate: u32) -> Value {165 let mut meter = LoudnessMeter::new(sample_rate, 2);166 let hop = (sample_rate as usize / 10).max(1);167 let (mut st_max, mut m_max) = (f64::NEG_INFINITY, f64::NEG_INFINITY);168 let mut st: Vec<f64> = Vec::new();169 let n = l.len().min(r.len());170 let mut i = 0;171 while i < n {172 let e = (i + hop).min(n);173 meter.process(&l[i..e], &r[i..e]);174 let (m, s) = (meter.momentary(), meter.short_term());175 if m > m_max {176 m_max = m;177 }178 if s > st_max {179 st_max = s;180 }181 if s > -70.0 {182 st.push(s);183 }184 i = e;185 }186 let integrated = meter.integrated();187 let range = if st.len() >= 10 {188 let gate = integrated - 20.0;189 let mut v: Vec<f64> = st.into_iter().filter(|s| *s >= gate).collect();190 v.sort_by(|a, b| a.total_cmp(b));191 if v.len() >= 2 {192 let at = |q: f64| v[((v.len() - 1) as f64 * q).round() as usize];193 at(0.95) - at(0.10)194 } else {195 0.0196 }197 } else {198 0.0199 };200 let mut tp = TruePeak::new(sample_rate as f32);201 tp.process(&l[..n]);202 let a = tp.peak();203 tp.reset();204 tp.process(&r[..n]);205 let true_peak = a.max(tp.peak());206 let peak = sample_peak(&l[..n]).max(sample_peak(&r[..n]));207 json!({208 "integrated": db(integrated),209 "short_term_max": db(st_max),210 "momentary_max": db(m_max),211 "range": range,212 "true_peak_db": db(to_db(true_peak) as f64),213 "sample_peak_db": db(to_db(peak) as f64),214 })215}216217/// # Safety218/// `left` and `right` valid for `count` floats.219#[no_mangle]220pub unsafe extern "C" fn sonata_loudness(left: *const f32, right: *const f32, count: usize, sample_rate: f64) -> *mut c_char {221 if left.is_null() || right.is_null() || count == 0 || !sample_rate.is_finite() || !(8000.0..=384_000.0).contains(&sample_rate) {222 return error_json("nothing to measure");223 }224 let l = std::slice::from_raw_parts(left, count);225 let r = std::slice::from_raw_parts(right, count);226 guard_json(|| give_json(&loudness_of(l, r, sample_rate.round() as u32)))227}228229/// Loudness of the engine's master, fed by the UI thread from the scope ring.230pub struct LiveLoudness {231 meter: LoudnessMeter,232 tp_l: TruePeak,233 tp_r: TruePeak,234}235236impl LiveLoudness {237 pub fn new(sample_rate: f64) -> LiveLoudness {238 LiveLoudness {239 meter: LoudnessMeter::new(sample_rate.round() as u32, 2),240 tp_l: TruePeak::new(sample_rate as f32),241 tp_r: TruePeak::new(sample_rate as f32),242 }243 }244 pub fn push(&mut self, l: &[f32], r: &[f32]) {245 self.meter.process(l, r);246 self.tp_l.process(l);247 self.tp_r.process(r);248 }249 /// (momentary, short-term, integrated) in LUFS and true peak in dBTP; -inf when silent.250 pub fn read(&self) -> (f64, f64, f64, f64) {251 let f = |x: f64| if x <= -199.0 { f64::NEG_INFINITY } else { x };252 (f(self.meter.momentary()), f(self.meter.short_term()), f(self.meter.integrated()), f(to_db(self.tp_l.peak().max(self.tp_r.peak())) as f64))253 }254}255