oximedia-metering 0.1.8

Professional broadcast audio metering: ITU-R BS.1770-4, EBU R128, ATSC A/85
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
//! EBU R128 loudness normalization standard.
//!
//! Implements the European Broadcasting Union's R128 recommendation for
//! loudness normalization and permitted maximum level of audio signals.
//!
//! # Standards
//!
//! - EBU R 128 (2020): Loudness normalisation and permitted maximum level of audio signals
//! - EBU Tech 3341: Loudness Metering: 'EBU Mode' metering to supplement EBU R 128
//! - EBU Tech 3342: Loudness Range: A measure to supplement EBU R 128 loudness normalisation
//!
//! # Target Levels
//!
//! - Programme Loudness: -23.0 LUFS ±1.0 LU
//! - Maximum True Peak: -1.0 dBTP
//! - Loudness Range: No strict requirement, but typically 5-20 LU

use crate::{LoudnessMeter, LoudnessMetrics, MeterConfig, Standard};

/// EBU R128 target loudness in LUFS.
pub const EBU_TARGET_LUFS: f64 = -23.0;

/// EBU R128 tolerance in LU.
pub const EBU_TOLERANCE_LU: f64 = 1.0;

/// EBU R128 maximum true peak in dBTP.
pub const EBU_MAX_TRUEPEAK_DBTP: f64 = -1.0;

/// Recommended minimum LRA for broadcast content.
pub const EBU_LRA_MIN: f64 = 1.0;

/// Recommended maximum LRA for broadcast content.
pub const EBU_LRA_MAX: f64 = 30.0;

/// EBU R128 program type classification.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ProgramType {
    /// General broadcast programs.
    General,
    /// Drama and narrative content.
    Drama,
    /// Documentary programs.
    Documentary,
    /// Sports broadcasting.
    Sports,
    /// Music programs.
    Music,
    /// News and current affairs.
    News,
    /// Commercial advertisements.
    Commercial,
}

impl ProgramType {
    /// Get the program type name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::General => "General Broadcast",
            Self::Drama => "Drama",
            Self::Documentary => "Documentary",
            Self::Sports => "Sports",
            Self::Music => "Music",
            Self::News => "News",
            Self::Commercial => "Commercial",
        }
    }

    /// Get typical LRA range for this program type.
    pub fn typical_lra_range(&self) -> (f64, f64) {
        match self {
            Self::General => (5.0, 15.0),
            Self::Drama => (8.0, 18.0),
            Self::Documentary => (6.0, 16.0),
            Self::Sports => (4.0, 12.0),
            Self::Music => (3.0, 10.0),
            Self::News => (3.0, 8.0),
            Self::Commercial => (2.0, 6.0),
        }
    }
}

/// EBU R128 compliance status.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ComplianceStatus {
    /// Fully compliant with EBU R128.
    Compliant,
    /// Loudness too high (exceeds +1 LU tolerance).
    TooLoud,
    /// Loudness too quiet (exceeds -1 LU tolerance).
    TooQuiet,
    /// True peak exceeds -1.0 dBTP.
    PeakExceeded,
    /// Multiple non-compliances.
    Multiple,
    /// Insufficient data to determine compliance.
    Unknown,
}

impl ComplianceStatus {
    /// Check if compliant.
    pub fn is_compliant(&self) -> bool {
        matches!(self, Self::Compliant)
    }

    /// Get status description.
    pub fn description(&self) -> &'static str {
        match self {
            Self::Compliant => "Compliant with EBU R128",
            Self::TooLoud => "Programme loudness exceeds +1 LU tolerance",
            Self::TooQuiet => "Programme loudness exceeds -1 LU tolerance",
            Self::PeakExceeded => "True peak exceeds -1.0 dBTP",
            Self::Multiple => "Multiple compliance issues",
            Self::Unknown => "Insufficient data for compliance check",
        }
    }
}

/// EBU R128 compliance result.
#[derive(Clone, Debug)]
pub struct EbuR128Compliance {
    /// Compliance status.
    pub status: ComplianceStatus,
    /// Measured integrated loudness in LUFS.
    pub integrated_lufs: f64,
    /// Measured true peak in dBTP.
    pub true_peak_dbtp: f64,
    /// Measured loudness range in LU.
    pub loudness_range: f64,
    /// Deviation from target in LU.
    pub deviation_lu: f64,
    /// Is loudness within tolerance?
    pub loudness_ok: bool,
    /// Is true peak within limit?
    pub peak_ok: bool,
    /// Is LRA reasonable?
    pub lra_ok: bool,
}

impl EbuR128Compliance {
    /// Create a compliance result from measurements.
    pub fn from_metrics(metrics: &LoudnessMetrics) -> Self {
        let integrated = metrics.integrated_lufs;
        let peak = metrics.true_peak_dbtp;
        let lra = metrics.loudness_range;

        let loudness_ok = if integrated.is_finite() {
            (EBU_TARGET_LUFS - EBU_TOLERANCE_LU..=EBU_TARGET_LUFS + EBU_TOLERANCE_LU)
                .contains(&integrated)
        } else {
            false
        };

        let peak_ok = peak <= EBU_MAX_TRUEPEAK_DBTP;
        let lra_ok = (EBU_LRA_MIN..=EBU_LRA_MAX).contains(&lra);

        let deviation = if integrated.is_finite() {
            integrated - EBU_TARGET_LUFS
        } else {
            0.0
        };

        let status = if !integrated.is_finite() {
            ComplianceStatus::Unknown
        } else if loudness_ok && peak_ok {
            ComplianceStatus::Compliant
        } else if !loudness_ok && !peak_ok {
            ComplianceStatus::Multiple
        } else if !peak_ok {
            ComplianceStatus::PeakExceeded
        } else if deviation > EBU_TOLERANCE_LU {
            ComplianceStatus::TooLoud
        } else {
            ComplianceStatus::TooQuiet
        };

        Self {
            status,
            integrated_lufs: integrated,
            true_peak_dbtp: peak,
            loudness_range: lra,
            deviation_lu: deviation,
            loudness_ok,
            peak_ok,
            lra_ok,
        }
    }

    /// Get recommended gain adjustment to achieve compliance.
    ///
    /// Returns gain in dB (positive = increase, negative = decrease).
    pub fn recommended_gain(&self) -> f64 {
        if self.integrated_lufs.is_finite() {
            EBU_TARGET_LUFS - self.integrated_lufs
        } else {
            0.0
        }
    }

    /// Check if gain adjustment would cause clipping.
    ///
    /// # Arguments
    ///
    /// * `gain_db` - Proposed gain adjustment in dB
    ///
    /// # Returns
    ///
    /// `true` if adjustment would cause true peak to exceed -1 dBTP
    pub fn would_clip(&self, gain_db: f64) -> bool {
        let adjusted_peak = self.true_peak_dbtp + gain_db;
        adjusted_peak > EBU_MAX_TRUEPEAK_DBTP
    }

    /// Get safe gain adjustment that won't cause clipping.
    pub fn safe_gain(&self) -> f64 {
        let desired_gain = self.recommended_gain();
        let max_safe_gain = EBU_MAX_TRUEPEAK_DBTP - self.true_peak_dbtp;

        desired_gain.min(max_safe_gain)
    }
}

/// EBU R128 meter with program type awareness.
pub struct EbuR128Meter {
    meter: LoudnessMeter,
    program_type: ProgramType,
}

impl EbuR128Meter {
    /// Create a new EBU R128 meter.
    ///
    /// # Arguments
    ///
    /// * `sample_rate` - Sample rate in Hz
    /// * `channels` - Number of audio channels
    /// * `program_type` - Type of program being measured
    pub fn new(
        sample_rate: f64,
        channels: usize,
        program_type: ProgramType,
    ) -> crate::MeteringResult<Self> {
        let config = MeterConfig::new(Standard::EbuR128, sample_rate, channels);
        let meter = LoudnessMeter::new(config)?;

        Ok(Self {
            meter,
            program_type,
        })
    }

    /// Process f32 audio samples.
    pub fn process_f32(&mut self, samples: &[f32]) {
        self.meter.process_f32(samples);
    }

    /// Process f64 audio samples.
    pub fn process_f64(&mut self, samples: &[f64]) {
        self.meter.process_f64(samples);
    }

    /// Get current loudness metrics.
    pub fn metrics(&mut self) -> LoudnessMetrics {
        self.meter.metrics()
    }

    /// Check EBU R128 compliance.
    pub fn check_compliance(&mut self) -> EbuR128Compliance {
        let metrics = self.metrics();
        EbuR128Compliance::from_metrics(&metrics)
    }

    /// Check if LRA is typical for the program type.
    pub fn is_lra_typical(&mut self) -> bool {
        let metrics = self.metrics();
        let (min, max) = self.program_type.typical_lra_range();
        metrics.loudness_range >= min && metrics.loudness_range <= max
    }

    /// Get program type.
    pub fn program_type(&self) -> ProgramType {
        self.program_type
    }

    /// Set program type.
    pub fn set_program_type(&mut self, program_type: ProgramType) {
        self.program_type = program_type;
    }

    /// Reset the meter.
    pub fn reset(&mut self) {
        self.meter.reset();
    }

    /// Get the underlying meter.
    pub fn meter(&self) -> &LoudnessMeter {
        &self.meter
    }

    /// Get mutable reference to underlying meter.
    pub fn meter_mut(&mut self) -> &mut LoudnessMeter {
        &mut self.meter
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_ebu_constants() {
        assert_eq!(EBU_TARGET_LUFS, -23.0);
        assert_eq!(EBU_TOLERANCE_LU, 1.0);
        assert_eq!(EBU_MAX_TRUEPEAK_DBTP, -1.0);
    }

    #[test]
    fn test_program_type_names() {
        assert_eq!(ProgramType::General.name(), "General Broadcast");
        assert_eq!(ProgramType::Drama.name(), "Drama");
    }

    #[test]
    fn test_program_type_lra_ranges() {
        let (min, max) = ProgramType::News.typical_lra_range();
        assert!(min < max);
        assert!(min >= 0.0);
    }

    #[test]
    fn test_compliance_status_descriptions() {
        assert!(!ComplianceStatus::TooLoud.is_compliant());
        assert!(ComplianceStatus::Compliant.is_compliant());
    }

    #[test]
    fn test_compliance_from_metrics() {
        let metrics = LoudnessMetrics {
            integrated_lufs: -23.0,
            true_peak_dbtp: -2.0,
            loudness_range: 10.0,
            ..Default::default()
        };

        let compliance = EbuR128Compliance::from_metrics(&metrics);
        assert!(compliance.status.is_compliant());
        assert!(compliance.loudness_ok);
        assert!(compliance.peak_ok);
    }

    #[test]
    fn test_compliance_too_loud() {
        let metrics = LoudnessMetrics {
            integrated_lufs: -20.0,
            true_peak_dbtp: -2.0,
            loudness_range: 10.0,
            ..Default::default()
        };

        let compliance = EbuR128Compliance::from_metrics(&metrics);
        assert_eq!(compliance.status, ComplianceStatus::TooLoud);
    }

    #[test]
    fn test_compliance_peak_exceeded() {
        let metrics = LoudnessMetrics {
            integrated_lufs: -23.0,
            true_peak_dbtp: 0.5,
            loudness_range: 10.0,
            ..Default::default()
        };

        let compliance = EbuR128Compliance::from_metrics(&metrics);
        assert_eq!(compliance.status, ComplianceStatus::PeakExceeded);
    }

    #[test]
    fn test_recommended_gain() {
        let metrics = LoudnessMetrics {
            integrated_lufs: -20.0,
            true_peak_dbtp: -2.0,
            loudness_range: 10.0,
            ..Default::default()
        };

        let compliance = EbuR128Compliance::from_metrics(&metrics);
        assert_eq!(compliance.recommended_gain(), -3.0);
    }

    #[test]
    fn test_safe_gain() {
        let metrics = LoudnessMetrics {
            integrated_lufs: -30.0,
            true_peak_dbtp: -2.0,
            loudness_range: 10.0,
            ..Default::default()
        };

        let compliance = EbuR128Compliance::from_metrics(&metrics);
        let safe = compliance.safe_gain();

        // Safe gain should not cause peak to exceed -1 dBTP
        assert!(compliance.true_peak_dbtp + safe <= EBU_MAX_TRUEPEAK_DBTP);
    }

    #[test]
    fn test_would_clip() {
        let metrics = LoudnessMetrics {
            integrated_lufs: -25.0,
            true_peak_dbtp: -1.5,
            loudness_range: 10.0,
            ..Default::default()
        };

        let compliance = EbuR128Compliance::from_metrics(&metrics);
        assert!(compliance.would_clip(1.0)); // -1.5 + 1.0 = -0.5 > -1.0
        assert!(!compliance.would_clip(0.4)); // -1.5 + 0.4 = -1.1 < -1.0
    }
}