oximedia-audio 0.2.1

Audio codec implementations for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
//! Professional audio metering suite.
//!
//! This module provides comprehensive audio metering tools for professional audio applications,
//! including broadcast, mixing, and mastering workflows.
//!
//! # Features
//!
//! ## Level Meters
//!
//! - **VU Meter** (IEC 60268-10) - Classic average level meter with 300ms ballistics
//! - **PPM** (Peak Programme Meter) - Multiple standards (BBC, EBU, Nordic, DIN)
//! - **Digital Peak Meter** - Sample-accurate peak detection in dBFS
//! - **RMS Level Meter** - Root mean square level measurement
//! - **LUFS Meter** - Integrated with existing loudness module (EBU R128)
//! - **Batch Meter** ([`batch::BatchMeterProcessor`]) - peak / RMS / true-peak
//!   for many channels in a single allocation-free pass (mixing-console style)
//!
//! ## Frequency Meters
//!
//! - **Spectrum Analyzer** - Integrated with existing spectrum module
//! - **Correlation Meter** - Stereo phase correlation measurement
//! - **Goniometer** - Stereo field visualization (L/R and M/S modes)
//!
//! ## Ballistics
//!
//! Proper time-domain response characteristics:
//! - Integration time constants (300ms VU, 10ms BBC PPM, etc.)
//! - Attack/release envelopes
//! - Peak hold with configurable duration
//! - Decay rates and return-to-zero behavior
//! - Overload detection with hysteresis
//!
//! ## Standards Compliance
//!
//! - **BS.6840** - BBC PPM specification
//! - **IEC 60268-10** - VU and PPM international standard
//! - **EBU R128** - Loudness normalization (via loudness module)
//! - **SMPTE RP 0155** - Reference levels for audio
//!
//! ## Visualization
//!
//! All meters provide visualization data:
//! - Normalized values (0.0 to 1.0) for bar graphs
//! - Peak markers and hold indicators
//! - Scale markings and labels
//! - Color zones (green/yellow/red)
//! - History buffers for time-domain plots
//!
//! # Examples
//!
//! ## VU Meter
//!
//! ```rust,no_run
//! use oximedia_audio::meters::{VuMeter};
//! use oximedia_audio::AudioFrame;
//!
//! let mut vu = VuMeter::new(48000.0, 2);
//!
//! # let frame = AudioFrame::new(
//! #     oximedia_core::SampleFormat::F32,
//! #     48000,
//! #     oximedia_audio::ChannelLayout::Stereo
//! # );
//! vu.process(&frame);
//!
//! println!("Left: {:.1} dBVU", vu.vu_reading(0));
//! println!("Right: {:.1} dBVU", vu.vu_reading(1));
//! ```
//!
//! ## PPM Meter
//!
//! ```rust,no_run
//! use oximedia_audio::meters::{PpmMeter, PpmStandard};
//!
//! let mut ppm = PpmMeter::new(PpmStandard::Bbc, 48000.0, 2);
//!
//! # let frame = oximedia_audio::AudioFrame::new(
//! #     oximedia_core::SampleFormat::F32,
//! #     48000,
//! #     oximedia_audio::ChannelLayout::Stereo
//! # );
//! ppm.process(&frame);
//!
//! println!("PPM reading: {:.1}", ppm.ppm_units(0));
//! ```
//!
//! ## Unified Meter Bridge
//!
//! ```rust,no_run
//! use oximedia_audio::meters::{MeterBridge, MeterBridgeConfig};
//!
//! let config = MeterBridgeConfig::default();
//! let mut bridge = MeterBridge::new(config, 48000.0, 2);
//!
//! # let frame = oximedia_audio::AudioFrame::new(
//! #     oximedia_core::SampleFormat::F32,
//! #     48000,
//! #     oximedia_audio::ChannelLayout::Stereo
//! # );
//! let readings = bridge.process(&frame);
//!
//! println!("Peak: {:.1} dBFS", readings.peak_dbfs[0]);
//! println!("RMS: {:.1} dBFS", readings.rms_dbfs[0]);
//! println!("VU: {:.1} dBVU", readings.vu_dbvu[0]);
//! println!("Correlation: {:.2}", readings.correlation);
//! ```
//!
//! ## Correlation Meter
//!
//! ```rust,no_run
//! use oximedia_audio::meters::CorrelationMeter;
//!
//! let mut correlation = CorrelationMeter::new(48000.0, 0.4);
//!
//! # let frame = oximedia_audio::AudioFrame::new(
//! #     oximedia_core::SampleFormat::F32,
//! #     48000,
//! #     oximedia_audio::ChannelLayout::Stereo
//! # );
//! correlation.process(&frame);
//!
//! let coeff = correlation.correlation();
//! if coeff > 0.95 {
//!     println!("Warning: Signal is essentially mono");
//! } else if coeff < -0.5 {
//!     println!("Warning: Phase issues detected");
//! }
//! ```
//!
//! # Files in this directory that are deliberately not modules
//!
//! `meters/itu.rs` and `meters/dolby.rs` exist on disk but are **not** declared
//! here, so they are not compiled. This is intentional, not an oversight:
//!
//! - **`itu.rs`** would add a *third* ITU-R BS.1770-4 loudness meter alongside
//!   [`crate::loudness`] and `oximedia_metering::ebu_r128_impl`, and its
//!   `Bs1770Meter` computes ITU channel weights but never applies them (5.1
//!   LFE would be metered at weight 1.0 instead of 0.0), while its
//!   `true_peak_dbtp` is a plain sample peak with no oversampling. It also has
//!   two `E0502` borrow errors and no tests.
//! - **`dolby.rs`** is a sketch: its A-weighting coefficients are hard-coded
//!   for one unstated sample rate and its `sample_rate` argument is ignored,
//!   its M-weighting is two hand-tuned biquads labelled "simplified", and its
//!   spectral-flatness helper takes the product of every sample in a frame,
//!   which underflows to zero for realistic frame sizes.
//!
//! Both need real work plus conformance tests before they can be exposed. The
//! blocker-by-blocker assessment lives in the "Orphan meter modules" section of
//! this crate's task list.

#![forbid(unsafe_code)]

pub mod ballistics;
/// Multi-lane batch metering: peak / RMS / true-peak for many channels in one
/// pass. See [`batch::BatchMeterProcessor`].
pub mod batch;
pub mod correlation;
pub mod peak;
pub mod ppm;
pub mod vu;

use crate::frame::AudioFrame;

// Re-export main types
pub use ballistics::{
    BallisticsConfig, BallisticsProcessor, OverloadDetector, PeakDetector, RmsWindow,
};
pub use batch::{BatchMeterConfig, BatchMeterProcessor, BatchMeterReading};
pub use correlation::{
    CorrelationMeter, CorrelationVisualization, GonioPoint, Goniometer, GoniometerMode,
    GoniometerVisualization,
};
pub use peak::{
    ColorZone as PeakColorZone, DigitalPeakMeter, PeakVisualization, RmsLevelMeter,
    RmsVisualization,
};
pub use ppm::{ColorZone as PpmColorZone, PpmMeter, PpmStandard, PpmVisualization};
pub use vu::{ColorZone as VuColorZone, VuMeter, VuVisualization};

/// Unified meter bridge configuration.
#[derive(Clone, Debug)]
pub struct MeterBridgeConfig {
    /// Enable VU meter.
    pub enable_vu: bool,
    /// Enable PPM meter.
    pub enable_ppm: bool,
    /// PPM standard to use.
    pub ppm_standard: PpmStandard,
    /// Enable digital peak meter.
    pub enable_peak: bool,
    /// Peak hold time in seconds.
    pub peak_hold_time: f64,
    /// Enable RMS meter.
    pub enable_rms: bool,
    /// RMS integration time in seconds.
    pub rms_integration_time: f64,
    /// Enable correlation meter.
    pub enable_correlation: bool,
    /// Correlation integration time in seconds.
    pub correlation_integration_time: f64,
    /// Enable goniometer.
    pub enable_goniometer: bool,
    /// Goniometer max points.
    pub goniometer_max_points: usize,
    /// Enable LUFS meter (requires loudness module).
    pub enable_lufs: bool,
}

impl MeterBridgeConfig {
    /// Create a minimal configuration (peak meter only).
    #[must_use]
    pub fn minimal() -> Self {
        Self {
            enable_vu: false,
            enable_ppm: false,
            ppm_standard: PpmStandard::Ebu,
            enable_peak: true,
            peak_hold_time: 2.0,
            enable_rms: false,
            rms_integration_time: 0.3,
            enable_correlation: false,
            correlation_integration_time: 0.4,
            enable_goniometer: false,
            goniometer_max_points: 1000,
            enable_lufs: false,
        }
    }

    /// Create a standard configuration (peak, RMS, VU).
    #[must_use]
    pub fn standard() -> Self {
        Self {
            enable_vu: true,
            enable_ppm: false,
            ppm_standard: PpmStandard::Ebu,
            enable_peak: true,
            peak_hold_time: 2.0,
            enable_rms: true,
            rms_integration_time: 0.3,
            enable_correlation: false,
            correlation_integration_time: 0.4,
            enable_goniometer: false,
            goniometer_max_points: 1000,
            enable_lufs: false,
        }
    }

    /// Create a professional configuration (all meters enabled).
    #[must_use]
    pub fn professional() -> Self {
        Self {
            enable_vu: true,
            enable_ppm: true,
            ppm_standard: PpmStandard::Ebu,
            enable_peak: true,
            peak_hold_time: 2.0,
            enable_rms: true,
            rms_integration_time: 0.3,
            enable_correlation: true,
            correlation_integration_time: 0.4,
            enable_goniometer: true,
            goniometer_max_points: 2000,
            enable_lufs: true,
        }
    }

    /// Create a broadcast configuration (PPM, peak, LUFS, correlation).
    #[must_use]
    pub fn broadcast() -> Self {
        Self {
            enable_vu: false,
            enable_ppm: true,
            ppm_standard: PpmStandard::Ebu,
            enable_peak: true,
            peak_hold_time: 1.0,
            enable_rms: false,
            rms_integration_time: 0.3,
            enable_correlation: true,
            correlation_integration_time: 0.4,
            enable_goniometer: true,
            goniometer_max_points: 1500,
            enable_lufs: true,
        }
    }
}

impl Default for MeterBridgeConfig {
    fn default() -> Self {
        Self::standard()
    }
}

/// Unified meter bridge.
///
/// Provides a single interface for processing audio through multiple meter types.
pub struct MeterBridge {
    /// Configuration.
    config: MeterBridgeConfig,
    /// VU meter (optional).
    vu_meter: Option<VuMeter>,
    /// PPM meter (optional).
    ppm_meter: Option<PpmMeter>,
    /// Digital peak meter (optional).
    peak_meter: Option<DigitalPeakMeter>,
    /// RMS level meter (optional).
    rms_meter: Option<RmsLevelMeter>,
    /// Correlation meter (optional).
    correlation_meter: Option<CorrelationMeter>,
    /// Goniometer (optional).
    goniometer: Option<Goniometer>,
    /// LUFS meter (optional).
    lufs_meter: Option<crate::loudness::LoudnessMeter>,
    /// Sample rate in Hz.
    #[allow(dead_code)]
    sample_rate: f64,
    /// Number of channels.
    #[allow(dead_code)]
    channels: usize,
}

impl MeterBridge {
    /// Create a new meter bridge.
    ///
    /// # Arguments
    ///
    /// * `config` - Meter bridge configuration
    /// * `sample_rate` - Sample rate in Hz
    /// * `channels` - Number of audio channels
    #[must_use]
    pub fn new(config: MeterBridgeConfig, sample_rate: f64, channels: usize) -> Self {
        let vu_meter = if config.enable_vu {
            Some(VuMeter::new(sample_rate, channels))
        } else {
            None
        };

        let ppm_meter = if config.enable_ppm {
            Some(PpmMeter::new(config.ppm_standard, sample_rate, channels))
        } else {
            None
        };

        let peak_meter = if config.enable_peak {
            Some(DigitalPeakMeter::new(
                sample_rate,
                channels,
                config.peak_hold_time,
            ))
        } else {
            None
        };

        let rms_meter = if config.enable_rms {
            Some(RmsLevelMeter::new(
                sample_rate,
                channels,
                config.rms_integration_time,
            ))
        } else {
            None
        };

        let correlation_meter = if config.enable_correlation && channels >= 2 {
            Some(CorrelationMeter::new(
                sample_rate,
                config.correlation_integration_time,
            ))
        } else {
            None
        };

        let goniometer = if config.enable_goniometer && channels >= 2 {
            Some(Goniometer::new(
                sample_rate,
                config.goniometer_max_points,
                GoniometerMode::LR,
            ))
        } else {
            None
        };

        let lufs_meter = if config.enable_lufs {
            Some(crate::loudness::LoudnessMeter::new(
                crate::loudness::LoudnessStandard::EbuR128,
                sample_rate,
                channels,
            ))
        } else {
            None
        };

        Self {
            config,
            vu_meter,
            ppm_meter,
            peak_meter,
            rms_meter,
            correlation_meter,
            goniometer,
            lufs_meter,
            sample_rate,
            channels,
        }
    }

    /// Process an audio frame and update all enabled meters.
    ///
    /// # Arguments
    ///
    /// * `frame` - Audio frame to process
    ///
    /// # Returns
    ///
    /// Combined meter readings
    pub fn process(&mut self, frame: &AudioFrame) -> MeterReadings {
        // Process each enabled meter
        if let Some(ref mut meter) = self.vu_meter {
            meter.process(frame);
        }

        if let Some(ref mut meter) = self.ppm_meter {
            meter.process(frame);
        }

        if let Some(ref mut meter) = self.peak_meter {
            meter.process(frame);
        }

        if let Some(ref mut meter) = self.rms_meter {
            meter.process(frame);
        }

        if let Some(ref mut meter) = self.correlation_meter {
            meter.process(frame);
        }

        if let Some(ref mut meter) = self.goniometer {
            meter.process(frame);
        }

        if let Some(ref mut meter) = self.lufs_meter {
            meter.measure(frame);
        }

        // Collect readings
        self.get_readings()
    }

    /// Get current meter readings without processing new audio.
    #[must_use]
    pub fn get_readings(&self) -> MeterReadings {
        let mut peak_dbfs = vec![f64::NEG_INFINITY; self.channels];
        let mut rms_dbfs = vec![f64::NEG_INFINITY; self.channels];
        let mut vu_dbvu = vec![f64::NEG_INFINITY; self.channels];
        let mut ppm_db = vec![f64::NEG_INFINITY; self.channels];

        // Collect peak readings
        if let Some(ref meter) = self.peak_meter {
            for ch in 0..self.channels {
                peak_dbfs[ch] = meter.peak_dbfs(ch);
            }
        }

        // Collect RMS readings
        if let Some(ref meter) = self.rms_meter {
            for ch in 0..self.channels {
                rms_dbfs[ch] = meter.rms_dbfs(ch);
            }
        }

        // Collect VU readings
        if let Some(ref meter) = self.vu_meter {
            for ch in 0..self.channels {
                vu_dbvu[ch] = meter.vu_reading(ch);
            }
        }

        // Collect PPM readings
        if let Some(ref meter) = self.ppm_meter {
            for ch in 0..self.channels {
                ppm_db[ch] = meter.ppm_reading(ch);
            }
        }

        // Collect correlation
        let correlation = self
            .correlation_meter
            .as_ref()
            .map_or(0.0, CorrelationMeter::correlation);

        // Collect LUFS
        let lufs = self
            .lufs_meter
            .as_ref()
            .map(|m| m.get_metrics().integrated_lufs);

        MeterReadings {
            peak_dbfs,
            rms_dbfs,
            vu_dbvu,
            ppm_db,
            correlation,
            lufs,
            has_overload: self.has_overload(),
            has_phase_issues: self
                .correlation_meter
                .as_ref()
                .map_or(false, CorrelationMeter::has_phase_issues),
        }
    }

    /// Check if any channel has overload.
    #[must_use]
    pub fn has_overload(&self) -> bool {
        if let Some(ref meter) = self.peak_meter {
            (0..self.channels).any(|ch| meter.is_overload(ch))
        } else if let Some(ref meter) = self.vu_meter {
            (0..self.channels).any(|ch| meter.is_overload(ch))
        } else if let Some(ref meter) = self.ppm_meter {
            (0..self.channels).any(|ch| meter.is_overload(ch))
        } else {
            false
        }
    }

    /// Reset all meters.
    pub fn reset(&mut self) {
        if let Some(ref mut meter) = self.vu_meter {
            meter.reset();
        }
        if let Some(ref mut meter) = self.ppm_meter {
            meter.reset();
        }
        if let Some(ref mut meter) = self.peak_meter {
            meter.reset();
        }
        if let Some(ref mut meter) = self.rms_meter {
            meter.reset();
        }
        if let Some(ref mut meter) = self.correlation_meter {
            meter.reset();
        }
        if let Some(ref mut meter) = self.goniometer {
            meter.clear();
        }
        if let Some(ref mut meter) = self.lufs_meter {
            meter.reset();
        }
    }

    /// Reset peak holds only.
    pub fn reset_peaks(&mut self) {
        if let Some(ref mut meter) = self.vu_meter {
            meter.reset_peaks();
        }
        if let Some(ref mut meter) = self.ppm_meter {
            meter.reset_peaks();
        }
        if let Some(ref mut meter) = self.peak_meter {
            meter.reset_peak_hold();
        }
    }

    /// Get VU meter reference.
    #[must_use]
    pub fn vu_meter(&self) -> Option<&VuMeter> {
        self.vu_meter.as_ref()
    }

    /// Get PPM meter reference.
    #[must_use]
    pub fn ppm_meter(&self) -> Option<&PpmMeter> {
        self.ppm_meter.as_ref()
    }

    /// Get peak meter reference.
    #[must_use]
    pub fn peak_meter(&self) -> Option<&DigitalPeakMeter> {
        self.peak_meter.as_ref()
    }

    /// Get RMS meter reference.
    #[must_use]
    pub fn rms_meter(&self) -> Option<&RmsLevelMeter> {
        self.rms_meter.as_ref()
    }

    /// Get correlation meter reference.
    #[must_use]
    pub fn correlation_meter(&self) -> Option<&CorrelationMeter> {
        self.correlation_meter.as_ref()
    }

    /// Get goniometer reference.
    #[must_use]
    pub fn goniometer(&self) -> Option<&Goniometer> {
        self.goniometer.as_ref()
    }

    /// Get LUFS meter reference.
    #[must_use]
    pub fn lufs_meter(&self) -> Option<&crate::loudness::LoudnessMeter> {
        self.lufs_meter.as_ref()
    }

    /// Get configuration.
    #[must_use]
    pub fn config(&self) -> &MeterBridgeConfig {
        &self.config
    }
}

/// Combined meter readings.
#[derive(Clone, Debug)]
pub struct MeterReadings {
    /// Peak levels per channel (dBFS).
    pub peak_dbfs: Vec<f64>,
    /// RMS levels per channel (dBFS).
    pub rms_dbfs: Vec<f64>,
    /// VU readings per channel (dBVU).
    pub vu_dbvu: Vec<f64>,
    /// PPM readings per channel (dB or PPM units).
    pub ppm_db: Vec<f64>,
    /// Stereo correlation coefficient.
    pub correlation: f64,
    /// Integrated loudness (LUFS).
    pub lufs: Option<f64>,
    /// Overload indicator.
    pub has_overload: bool,
    /// Phase issues indicator.
    pub has_phase_issues: bool,
}

impl MeterReadings {
    /// Get stereo peak level (max of L/R).
    #[must_use]
    pub fn stereo_peak_dbfs(&self) -> f64 {
        self.peak_dbfs
            .iter()
            .copied()
            .fold(f64::NEG_INFINITY, f64::max)
    }

    /// Get stereo RMS level (average of L/R in linear domain).
    #[must_use]
    pub fn stereo_rms_dbfs(&self) -> f64 {
        if self.rms_dbfs.len() >= 2 {
            let left = self.rms_dbfs[0];
            let right = self.rms_dbfs[1];
            if left.is_finite() && right.is_finite() {
                let left_lin = ballistics::db_to_linear(left);
                let right_lin = ballistics::db_to_linear(right);
                ballistics::linear_to_db((left_lin + right_lin) / 2.0)
            } else if left.is_finite() {
                left
            } else {
                right
            }
        } else if let Some(&first) = self.rms_dbfs.first() {
            first
        } else {
            f64::NEG_INFINITY
        }
    }

    /// Check if signal is safe for broadcast.
    #[must_use]
    pub fn is_broadcast_safe(&self) -> bool {
        !self.has_overload
            && !self.has_phase_issues
            && self
                .lufs
                .map_or(true, |l| l.is_finite() && l > -40.0 && l < -10.0)
    }
}