SPB Git

Repository Public

shared.rs 15.6 KB 454 lines rust

1//! ORIX Sonata2//! File: crates/sonata-runtime/src/shared.rs3//! Description: State shared between the audio thread and observers through atomics only:4//! transport, meters, scope ring buffers, callback timing histogram, counters.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use sonata_ir::Strip;10use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, AtomicU8, Ordering::Relaxed};1112pub const MAX_TRACKS: usize = 256;13pub const MAX_BUSES: usize = 64;14pub const METER_SLOTS: usize = MAX_TRACKS + MAX_BUSES + 1;15/// Frames kept by each scope ring (about 2.7 s at 48 kHz).16pub const SCOPE_FRAMES: usize = 1 << 17;1718/// Slot of a strip in the meter table; `None` when the id is beyond the fixed capacity.19pub fn meter_slot(strip: Strip) -> Option<usize> {20    match strip {21        Strip::Track(i) if (i as usize) < MAX_TRACKS => Some(i as usize),22        Strip::Bus(i) if (i as usize) < MAX_BUSES => Some(MAX_TRACKS + i as usize),23        Strip::Master => Some(METER_SLOTS - 1),24        _ => None,25    }26}2728#[derive(Clone, Copy, Debug, PartialEq, Eq)]29#[repr(u8)]30pub enum TransportState {31    Stopped = 0,32    Playing = 1,33    Paused = 2,34    CountIn = 3,35}3637impl TransportState {38    pub fn from_u8(v: u8) -> TransportState {39        match v {40            1 => TransportState::Playing,41            2 => TransportState::Paused,42            3 => TransportState::CountIn,43            _ => TransportState::Stopped,44        }45    }46}4748#[derive(Default)]49pub(crate) struct MeterCell {50    /// Largest |sample| since the last snapshot (f32 bits).51    peak_l: AtomicU32,52    peak_r: AtomicU32,53    /// Mean square over a 300 ms exponential window (f32 bits).54    ms_l: AtomicU32,55    ms_r: AtomicU32,56    /// Samples at or above 0 dBFS since the last snapshot.57    over: AtomicU32,58}5960/// One reading of a strip meter. Linear amplitudes (1.0 = 0 dBFS).61#[derive(Clone, Copy, Debug, Default, PartialEq)]62pub struct MeterSnapshot {63    /// Largest sample magnitude since the previous snapshot of this strip.64    pub peak_l: f32,65    pub peak_r: f32,66    /// RMS over a 300 ms exponential window.67    pub rms_l: f32,68    pub rms_r: f32,69    /// Samples that reached 0 dBFS since the previous snapshot.70    pub overs: u32,71}7273/// Peak-hold and decay ballistics applied on the reader side (UI thread).74/// Hold 1.5 s, then fall 20 dB/s; the bar itself falls 26 dB/s.75#[derive(Clone, Copy, Debug, Default)]76pub struct MeterBallistics {77    pub level_l: f32,78    pub level_r: f32,79    pub hold_l: f32,80    pub hold_r: f32,81    hold_age_l: f32,82    hold_age_r: f32,83}8485impl MeterBallistics {86    pub fn update(&mut self, s: &MeterSnapshot, dt_sec: f32) {87        fn one(level: &mut f32, hold: &mut f32, age: &mut f32, peak: f32, dt: f32) {88            let fall = 10f32.powf(-26.0 * dt / 20.0);89            *level = peak.max(*level * fall);90            if peak >= *hold {91                *hold = peak;92                *age = 0.0;93            } else {94                *age += dt;95                if *age > 1.5 {96                    *hold *= 10f32.powf(-20.0 * dt / 20.0);97                }98            }99        }100        one(&mut self.level_l, &mut self.hold_l, &mut self.hold_age_l, s.peak_l, dt_sec);101        one(&mut self.level_r, &mut self.hold_r, &mut self.hold_age_r, s.peak_r, dt_sec);102    }103}104105/// A ring of the most recent stereo frames, written by the audio thread, read by anyone.106pub struct ScopeRing {107    l: Box<[AtomicU32]>,108    r: Box<[AtomicU32]>,109    /// Total frames ever written.110    written: AtomicU64,111}112113impl ScopeRing {114    pub(crate) fn new() -> ScopeRing {115        let mk = || (0..SCOPE_FRAMES).map(|_| AtomicU32::new(0)).collect::<Box<[AtomicU32]>>();116        ScopeRing { l: mk(), r: mk(), written: AtomicU64::new(0) }117    }118119    #[inline]120    pub(crate) fn write(&self, l: &[f32], r: &[f32]) {121        let w = self.written.load(Relaxed);122        for i in 0..l.len() {123            let k = (w as usize + i) & (SCOPE_FRAMES - 1);124            self.l[k].store(l[i].to_bits(), Relaxed);125            self.r[k].store(r[i].to_bits(), Relaxed);126        }127        self.written.store(w + l.len() as u64, std::sync::atomic::Ordering::Release);128    }129130    pub(crate) fn clear(&self) {131        // Called from the audio thread when the tap point changes: readers see silence, not a splice.132        for i in 0..SCOPE_FRAMES {133            self.l[i].store(0, Relaxed);134            self.r[i].store(0, Relaxed);135        }136    }137138    /// Total frames written so far (a frame counter usable as a time base by scopes).139    pub fn frames_written(&self) -> u64 {140        self.written.load(std::sync::atomic::Ordering::Acquire)141    }142143    /// Copies the latest `out_l.len()` frames (at most [`SCOPE_FRAMES`] / 2) and returns the frame144    /// counter just after the last copied frame. Frames not yet written read as zero. The copy is145    /// retried if the writer lapped the reader; after 4 attempts the freshest attempt is returned.146    pub fn read_latest(&self, out_l: &mut [f32], out_r: &mut [f32]) -> u64 {147        let n = out_l.len().min(out_r.len()).min(SCOPE_FRAMES / 2);148        let mut end = 0;149        for _ in 0..4 {150            end = self.frames_written();151            for i in 0..n {152                let age = (n - i) as u64;153                if age > end {154                    out_l[i] = 0.0;155                    out_r[i] = 0.0;156                    continue;157                }158                let k = ((end - age) as usize) & (SCOPE_FRAMES - 1);159                out_l[i] = f32::from_bits(self.l[k].load(Relaxed));160                out_r[i] = f32::from_bits(self.r[k].load(Relaxed));161            }162            if self.frames_written() - end < (SCOPE_FRAMES - n) as u64 {163                break;164            }165        }166        end167    }168}169170const TIMING_BUCKETS: usize = 2001;171const TIMING_BUCKET_NS: u64 = 5_000;172173/// Histogram of the time spent in `Processor::process`, 5 µs buckets up to 10 ms plus overflow.174pub(crate) struct Timing {175    buckets: Box<[AtomicU32]>,176    count: AtomicU64,177    sum_ns: AtomicU64,178    max_ns: AtomicU64,179    missed: AtomicU64,180}181182/// Callback timing figures. Percentiles are upper bounds of 5 µs buckets (values above 10 ms183/// report as `max_us`).184#[derive(Clone, Copy, Debug, Default, PartialEq)]185pub struct TimingSnapshot {186    pub callbacks: u64,187    pub mean_us: f64,188    pub p50_us: f64,189    pub p95_us: f64,190    pub p99_us: f64,191    pub p999_us: f64,192    pub max_us: f64,193    /// Callbacks that took longer than the duration of the audio they produced.194    pub missed_deadlines: u64,195}196197impl Timing {198    fn new() -> Timing {199        Timing {200            buckets: (0..TIMING_BUCKETS).map(|_| AtomicU32::new(0)).collect(),201            count: AtomicU64::new(0),202            sum_ns: AtomicU64::new(0),203            max_ns: AtomicU64::new(0),204            missed: AtomicU64::new(0),205        }206    }207    #[inline]208    pub(crate) fn record(&self, ns: u64, budget_ns: u64) {209        let b = ((ns / TIMING_BUCKET_NS) as usize).min(TIMING_BUCKETS - 1);210        self.buckets[b].fetch_add(1, Relaxed);211        self.count.fetch_add(1, Relaxed);212        self.sum_ns.fetch_add(ns, Relaxed);213        self.max_ns.fetch_max(ns, Relaxed);214        if ns > budget_ns {215            self.missed.fetch_add(1, Relaxed);216        }217    }218    fn reset(&self) {219        for b in self.buckets.iter() {220            b.store(0, Relaxed);221        }222        self.count.store(0, Relaxed);223        self.sum_ns.store(0, Relaxed);224        self.max_ns.store(0, Relaxed);225        self.missed.store(0, Relaxed);226    }227    fn snapshot(&self) -> TimingSnapshot {228        let counts: Vec<u64> = self.buckets.iter().map(|b| b.load(Relaxed) as u64).collect();229        let total: u64 = counts.iter().sum();230        let max_us = self.max_ns.load(Relaxed) as f64 / 1000.0;231        let pct = |p: f64| -> f64 {232            if total == 0 {233                return 0.0;234            }235            let want = (p * total as f64).ceil().max(1.0) as u64;236            let mut acc = 0;237            for (i, c) in counts.iter().enumerate() {238                acc += c;239                if acc >= want {240                    return if i == TIMING_BUCKETS - 1 {241                        max_us242                    } else {243                        (((i as u64 + 1) * TIMING_BUCKET_NS) as f64 / 1000.0).min(max_us.max(TIMING_BUCKET_NS as f64 / 1000.0))244                    };245                }246            }247            max_us248        };249        let n = self.count.load(Relaxed);250        TimingSnapshot {251            callbacks: n,252            mean_us: if n == 0 { 0.0 } else { self.sum_ns.load(Relaxed) as f64 / n as f64 / 1000.0 },253            p50_us: pct(0.5),254            p95_us: pct(0.95),255            p99_us: pct(0.99),256            p999_us: pct(0.999),257            max_us,258            missed_deadlines: self.missed.load(Relaxed),259        }260    }261}262263/// Everything observers can read without touching the audio thread.264pub struct Shared {265    pub(crate) sample_rate: AtomicU32,266    pub(crate) state: AtomicU8,267    pub(crate) position: AtomicU64,268    pub(crate) clock: AtomicU64,269    pub(crate) end_sample: AtomicU64,270    pub(crate) voices: AtomicU32,271    pub(crate) generation: AtomicU64,272    pub(crate) swapping: AtomicBool,273    pub(crate) scrubbed: AtomicU64,274    pub(crate) underruns: AtomicU64,275    pub(crate) dropped_commands: AtomicU64,276    pub(crate) limiter_reduction_db: AtomicU32,277    pub(crate) meters: Box<[MeterCell]>,278    pub(crate) timing: Timing,279    pub(crate) master_scope: ScopeRing,280    pub(crate) tap_scope: ScopeRing,281}282283impl Shared {284    pub(crate) fn new(sample_rate: u32) -> Shared {285        Shared {286            sample_rate: AtomicU32::new(sample_rate),287            state: AtomicU8::new(0),288            position: AtomicU64::new(0),289            clock: AtomicU64::new(0),290            end_sample: AtomicU64::new(0),291            voices: AtomicU32::new(0),292            generation: AtomicU64::new(0),293            swapping: AtomicBool::new(false),294            scrubbed: AtomicU64::new(0),295            underruns: AtomicU64::new(0),296            dropped_commands: AtomicU64::new(0),297            limiter_reduction_db: AtomicU32::new(0),298            meters: (0..METER_SLOTS).map(|_| MeterCell::default()).collect(),299            timing: Timing::new(),300            master_scope: ScopeRing::new(),301            tap_scope: ScopeRing::new(),302        }303    }304305    #[inline]306    pub(crate) fn meter_write(&self, slot: usize, peak_l: f32, peak_r: f32, ms_l: f32, ms_r: f32, overs: u32) {307        let c = &self.meters[slot];308        if peak_l > f32::from_bits(c.peak_l.load(Relaxed)) {309            c.peak_l.store(peak_l.to_bits(), Relaxed);310        }311        if peak_r > f32::from_bits(c.peak_r.load(Relaxed)) {312            c.peak_r.store(peak_r.to_bits(), Relaxed);313        }314        c.ms_l.store(ms_l.to_bits(), Relaxed);315        c.ms_r.store(ms_r.to_bits(), Relaxed);316        if overs > 0 {317            c.over.fetch_add(overs, Relaxed);318        }319    }320321    /// Reads and re-arms the meter of a strip. One reader per strip is assumed (the peak is322    /// "largest since the previous read").323    pub fn meter(&self, strip: Strip) -> MeterSnapshot {324        let Some(slot) = meter_slot(strip) else { return MeterSnapshot::default() };325        let c = &self.meters[slot];326        MeterSnapshot {327            peak_l: f32::from_bits(c.peak_l.swap(0, Relaxed)),328            peak_r: f32::from_bits(c.peak_r.swap(0, Relaxed)),329            rms_l: f32::from_bits(c.ms_l.load(Relaxed)).max(0.0).sqrt(),330            rms_r: f32::from_bits(c.ms_r.load(Relaxed)).max(0.0).sqrt(),331            overs: c.over.swap(0, Relaxed),332        }333    }334335    pub fn transport_state(&self) -> TransportState {336        TransportState::from_u8(self.state.load(Relaxed))337    }338    /// Timeline position in samples at the engine sample rate.339    pub fn position_samples(&self) -> u64 {340        self.position.load(Relaxed)341    }342    pub fn position_seconds(&self) -> f64 {343        self.position_samples() as f64 / self.sample_rate.load(Relaxed).max(1) as f64344    }345    /// Frames rendered since the engine was created (monotonic audio clock).346    pub fn clock_samples(&self) -> u64 {347        self.clock.load(Relaxed)348    }349    /// Last sample of the loaded program's musical content (tails excluded).350    pub fn end_samples(&self) -> u64 {351        self.end_sample.load(Relaxed)352    }353    pub fn sample_rate(&self) -> u32 {354        self.sample_rate.load(Relaxed)355    }356    pub fn active_voices(&self) -> u32 {357        self.voices.load(Relaxed)358    }359    /// Incremented each time a newly loaded program starts sounding.360    pub fn program_generation(&self) -> u64 {361        self.generation.load(Relaxed)362    }363    /// True while a hot swap crossfade is in progress.364    pub fn is_swapping(&self) -> bool {365        self.swapping.load(Relaxed)366    }367    /// Non-finite samples replaced by silence since creation (0 in a healthy session).368    pub fn scrubbed_samples(&self) -> u64 {369        self.scrubbed.load(Relaxed)370    }371    pub fn underruns(&self) -> u64 {372        self.underruns.load(Relaxed)373    }374    /// The host reports a buffer underrun it observed (the engine cannot see them itself).375    pub fn report_underrun(&self) {376        self.underruns.fetch_add(1, Relaxed);377    }378    /// Commands lost because the queue was full (0 in a healthy session).379    pub fn dropped_commands(&self) -> u64 {380        self.dropped_commands.load(Relaxed)381    }382    /// Current gain reduction of the master safety limiter in dB (>= 0).383    pub fn limiter_reduction_db(&self) -> f32 {384        f32::from_bits(self.limiter_reduction_db.load(Relaxed))385    }386    pub fn timing(&self) -> TimingSnapshot {387        self.timing.snapshot()388    }389    pub fn reset_timing(&self) {390        self.timing.reset()391    }392    /// The most recent master output (post limiter, what the device receives).393    pub fn master_scope(&self) -> &ScopeRing {394        &self.master_scope395    }396    /// The most recent audio at the selected tap point.397    pub fn tap_scope(&self) -> &ScopeRing {398        &self.tap_scope399    }400}401402#[cfg(test)]403mod tests {404    use super::*;405406    #[test]407    fn scope_ring_returns_latest_frames() {408        let ring = ScopeRing::new();409        let l: Vec<f32> = (0..1000).map(|i| i as f32).collect();410        ring.write(&l, &l);411        let (mut a, mut b) = (vec![0.0; 10], vec![0.0; 10]);412        assert_eq!(ring.read_latest(&mut a, &mut b), 1000);413        assert_eq!(a, (990..1000).map(|i| i as f32).collect::<Vec<_>>());414        let (mut a, mut b) = (vec![9.0; 1500], vec![9.0; 1500]);415        ring.read_latest(&mut a, &mut b);416        assert_eq!(a[0], 0.0);417        assert_eq!(a[500], 0.0);418        assert_eq!(a[501], 1.0);419    }420421    #[test]422    fn timing_percentiles() {423        let t = Timing::new();424        for i in 0..1000u64 {425            t.record(if i < 990 { 12_000 } else { 480_000 }, 1_000_000);426        }427        t.record(30_000_000, 1_000_000);428        let s = t.snapshot();429        assert_eq!(s.callbacks, 1001);430        assert_eq!(s.p50_us, 15.0);431        assert_eq!(s.p99_us, 485.0);432        assert_eq!(s.max_us, 30_000.0);433        assert_eq!(s.missed_deadlines, 1);434    }435436    #[test]437    fn meter_slots_and_ballistics() {438        assert_eq!(meter_slot(Strip::Track(0)), Some(0));439        assert_eq!(meter_slot(Strip::Bus(1)), Some(MAX_TRACKS + 1));440        assert_eq!(meter_slot(Strip::Master), Some(METER_SLOTS - 1));441        assert_eq!(meter_slot(Strip::Track(9999)), None);442        let sh = Shared::new(48_000);443        sh.meter_write(0, 0.5, 0.25, 0.04, 0.01, 0);444        let m = sh.meter(Strip::Track(0));445        assert_eq!((m.peak_l, m.peak_r), (0.5, 0.25));446        assert!((m.rms_l - 0.2).abs() < 1e-6);447        assert_eq!(sh.meter(Strip::Track(0)).peak_l, 0.0);448        let mut b = MeterBallistics::default();449        b.update(&m, 0.016);450        b.update(&MeterSnapshot::default(), 1.0);451        assert!(b.level_l < 0.5 * 0.06 && b.hold_l == 0.5);452    }453}454
Files main
Menu

Theme