oximedia-audio 0.1.3

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
//! Loudness normalization for broadcast and streaming.
//!
//! This module provides comprehensive loudness measurement and normalization
//! according to international broadcast standards:
//!
//! - **EBU R128** - European Broadcasting Union loudness standard
//! - **ITU-R BS.1770-4** - International loudness measurement algorithm
//! - **ATSC A/85** - Advanced Television Systems Committee loudness standard
//!
//! # Features
//!
//! ## Loudness Measurement
//!
//! - Momentary loudness (400ms sliding window)
//! - Short-term loudness (3s sliding window)
//! - Integrated loudness (gated program loudness)
//! - Loudness range (LRA)
//! - True peak detection (prevents inter-sample clipping)
//!
//! ## K-Weighting Filter
//!
//! ITU-R BS.1770-4 K-weighting filter chain for perceptually accurate measurement:
//! - Pre-filter (high-pass at ~78 Hz)
//! - RLB filter (revised low-frequency B-weighting)
//!
//! ## Gating Algorithm
//!
//! Two-stage gating for integrated loudness:
//! - Absolute gate: -70 LUFS
//! - Relative gate: -10 LU below ungated loudness
//!
//! ## Normalization
//!
//! - Linear gain adjustment to target loudness
//! - True peak limiting for compliance
//! - Optional dynamic range compression
//! - Multi-pass analysis and processing
//! - Streaming support with pre-analyzed gain
//!
//! ## Reporting
//!
//! - Comprehensive measurement reports
//! - Compliance checking (EBU R128, ATSC A/85)
//! - Loudness history visualization
//! - Export to text, JSON, CSV
//!
//! # Example
//!
//! ```ignore
//! use oximedia_audio::loudness::{LoudnessMeter, LoudnessStandard};
//!
//! // Create a loudness meter
//! let mut meter = LoudnessMeter::new(LoudnessStandard::EbuR128, 48000.0, 2);
//!
//! // Process audio frames
//! for frame in audio_frames {
//!     let metrics = meter.measure(&frame);
//!     println!("Integrated: {:.1} LUFS", metrics.integrated_lufs);
//! }
//!
//! // Normalize to target loudness
//! let normalized = meter.normalize(&audio_frames, -23.0);
//!
//! // Generate report
//! let report = meter.report(duration_seconds);
//! println!("{}", report);
//! ```
//!
//! # Standards
//!
//! ## EBU R128
//!
//! - Target: -23 LUFS ±1 LU
//! - True peak: ≤ -1.0 dBTP
//! - Measurement: ITU-R BS.1770-4 algorithm
//!
//! ## ATSC A/85
//!
//! - Target: -24 LKFS ±2 dB
//! - True peak: typically ≤ -2.0 dBTP
//! - Measurement: Same as ITU-R BS.1770-4 (LKFS = LUFS)
//!
//! ## Streaming Platforms
//!
//! - Spotify: -14 LUFS
//! - YouTube: -14 LUFS
//! - Apple Music: -16 LUFS
//! - Tidal: -14 LUFS

#![forbid(unsafe_code)]

pub mod filter;
pub mod gate;
pub mod normalize;
pub mod peak;
pub mod r128;
pub mod report;

use crate::frame::AudioFrame;
use crate::AudioResult;

// Re-exports
pub use filter::{KWeightFilter, KWeightFilterBank};
pub use gate::{BlockAccumulator, GatingProcessor};
pub use normalize::{
    AutoGainConfig, AutoGainProcessor, BatchNormalizer, FileNormalizationStats, LoudnessNormalizer,
    NormalizationConfig, NormalizationMode, NormalizationParams, StreamingNormalizer,
};
pub use peak::{SamplePeakDetector, TruePeakDetector, TruePeakLimiter, TruePeakLimiterConfig};
pub use r128::{AtscA85Ext, AtscA85Meter, ComplianceStatus, R128Compliance, R128Meter};
pub use report::{
    AtscA85Compliance, EbuR128Compliance, LoudnessHistory, LoudnessReport, LoudnessStatistics,
    NormalizationReport,
};

/// Loudness measurement standard.
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub enum LoudnessStandard {
    /// EBU R128 (European Broadcasting Union).
    ///
    /// Target: -23 LUFS ±1 LU
    /// True peak: ≤ -1.0 dBTP
    #[default]
    EbuR128,

    /// ATSC A/85 (Advanced Television Systems Committee).
    ///
    /// Target: -24 LKFS ±2 dB
    /// True peak: ≤ -2.0 dBTP
    AtscA85,

    /// Spotify streaming platform.
    ///
    /// Target: -14 LUFS
    Spotify,

    /// YouTube streaming platform.
    ///
    /// Target: -14 LUFS
    YouTube,

    /// Apple Music streaming platform.
    ///
    /// Target: -16 LUFS
    AppleMusic,

    /// Amazon Music streaming platform.
    ///
    /// Target: -14 LUFS
    AmazonMusic,

    /// Tidal streaming platform.
    ///
    /// Target: -14 LUFS
    Tidal,

    /// Custom target loudness.
    Custom(f64),
}

impl LoudnessStandard {
    /// Get the target loudness in LUFS for this standard.
    #[must_use]
    pub fn target_lufs(&self) -> f64 {
        match self {
            Self::EbuR128 => -23.0,
            Self::AtscA85 => -24.0,
            Self::Spotify => -14.0,
            Self::YouTube => -14.0,
            Self::AppleMusic => -16.0,
            Self::AmazonMusic => -14.0,
            Self::Tidal => -14.0,
            Self::Custom(target) => *target,
        }
    }

    /// Get the maximum true peak in dBTP for this standard.
    #[must_use]
    pub fn max_true_peak_dbtp(&self) -> f64 {
        match self {
            Self::EbuR128 => -1.0,
            Self::AtscA85 => -2.0,
            Self::Spotify | Self::YouTube | Self::AppleMusic | Self::AmazonMusic | Self::Tidal => {
                -1.0
            }
            Self::Custom(_) => -1.0,
        }
    }

    /// Get the tolerance in LU for this standard.
    #[must_use]
    pub fn tolerance_lu(&self) -> f64 {
        match self {
            Self::EbuR128 => 1.0,
            Self::AtscA85 => 2.0,
            Self::Spotify | Self::YouTube | Self::AppleMusic | Self::AmazonMusic | Self::Tidal => {
                1.0
            }
            Self::Custom(_) => 1.0,
        }
    }

    /// Get the standard name as a string.
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            Self::EbuR128 => "EBU R128",
            Self::AtscA85 => "ATSC A/85",
            Self::Spotify => "Spotify",
            Self::YouTube => "YouTube",
            Self::AppleMusic => "Apple Music",
            Self::AmazonMusic => "Amazon Music",
            Self::Tidal => "Tidal",
            Self::Custom(_) => "Custom",
        }
    }
}

/// Loudness measurement metrics.
#[derive(Clone, Debug)]
pub struct LoudnessMetrics {
    /// Momentary loudness in LUFS (400ms).
    pub momentary_lufs: f64,
    /// Short-term loudness in LUFS (3s).
    pub short_term_lufs: f64,
    /// Integrated loudness in LUFS (entire program).
    pub integrated_lufs: f64,
    /// Loudness range in LU.
    pub loudness_range: f64,
    /// True peak in dBTP.
    pub true_peak_dbtp: f64,
    /// True peak (linear).
    pub true_peak_linear: f64,
    /// Maximum momentary loudness seen.
    pub max_momentary: f64,
    /// Maximum short-term loudness seen.
    pub max_short_term: f64,
}

impl Default for LoudnessMetrics {
    fn default() -> Self {
        Self {
            momentary_lufs: f64::NEG_INFINITY,
            short_term_lufs: f64::NEG_INFINITY,
            integrated_lufs: f64::NEG_INFINITY,
            loudness_range: 0.0,
            true_peak_dbtp: f64::NEG_INFINITY,
            true_peak_linear: 0.0,
            max_momentary: f64::NEG_INFINITY,
            max_short_term: f64::NEG_INFINITY,
        }
    }
}

/// Unified loudness meter supporting multiple standards.
///
/// This is the main entry point for loudness measurement and normalization.
pub struct LoudnessMeter {
    /// Loudness standard being used.
    standard: LoudnessStandard,
    /// Internal R128 meter.
    meter: R128Meter,
    /// Loudness history for visualization.
    history: LoudnessHistory,
    /// Sample rate in Hz.
    sample_rate: f64,
    /// Number of channels.
    channels: usize,
}

impl LoudnessMeter {
    /// Create a new loudness meter.
    ///
    /// # Arguments
    ///
    /// * `standard` - Loudness standard to use
    /// * `sample_rate` - Sample rate in Hz
    /// * `channels` - Number of audio channels
    #[must_use]
    pub fn new(standard: LoudnessStandard, sample_rate: f64, channels: usize) -> Self {
        let meter = R128Meter::new(sample_rate, channels);
        let history = LoudnessHistory::new(0.1); // 100ms sample interval

        Self {
            standard,
            meter,
            history,
            sample_rate,
            channels,
        }
    }

    /// Measure loudness from an audio frame.
    ///
    /// # Arguments
    ///
    /// * `frame` - Audio frame to measure
    ///
    /// # Returns
    ///
    /// Current loudness metrics
    pub fn measure(&mut self, frame: &AudioFrame) -> LoudnessMetrics {
        // Extract samples from frame
        let samples = self.extract_samples(frame);

        // Process with meter
        self.meter.process_interleaved(&samples);

        // Update history
        let timestamp = frame.timestamp.to_seconds();
        self.history.add_sample(
            self.meter.momentary_loudness(),
            self.meter.short_term_loudness(),
            timestamp,
        );

        // Return current metrics
        self.get_metrics()
    }

    /// Get current loudness metrics without processing new frames.
    #[must_use]
    pub fn get_metrics(&self) -> LoudnessMetrics {
        LoudnessMetrics {
            momentary_lufs: self.meter.momentary_loudness(),
            short_term_lufs: self.meter.short_term_loudness(),
            integrated_lufs: self.meter.integrated_loudness(),
            loudness_range: self.meter.loudness_range(),
            true_peak_dbtp: self.meter.true_peak_dbtp(),
            true_peak_linear: self.meter.true_peak_linear(),
            max_momentary: self.meter.max_momentary(),
            max_short_term: self.meter.max_short_term(),
        }
    }

    /// Normalize audio frames to target loudness.
    ///
    /// # Arguments
    ///
    /// * `frames` - Mutable slice of audio frames
    /// * `target_lufs` - Target loudness in LUFS
    ///
    /// # Returns
    ///
    /// Normalization parameters applied
    pub fn normalize(&self, frames: &mut [AudioFrame], target_lufs: f64) -> NormalizationParams {
        let config = NormalizationConfig {
            target_lufs,
            max_true_peak_dbtp: self.standard.max_true_peak_dbtp(),
            ..Default::default()
        };

        let normalizer = LoudnessNormalizer::new(config, self.sample_rate, self.channels);
        normalizer.normalize(frames)
    }

    /// Normalize to the standard's target loudness.
    ///
    /// # Arguments
    ///
    /// * `frames` - Mutable slice of audio frames
    ///
    /// # Returns
    ///
    /// Normalization parameters applied
    pub fn normalize_to_standard(&self, frames: &mut [AudioFrame]) -> NormalizationParams {
        self.normalize(frames, self.standard.target_lufs())
    }

    /// Generate a comprehensive loudness report.
    ///
    /// # Arguments
    ///
    /// * `duration_seconds` - Total duration in seconds
    ///
    /// # Returns
    ///
    /// Loudness report
    #[must_use]
    pub fn report(&self, duration_seconds: f64) -> LoudnessReport {
        LoudnessReport::from_meter(&self.meter, duration_seconds)
    }

    /// Check compliance with the selected standard.
    #[must_use]
    pub fn check_compliance(&self) -> ComplianceStatus {
        let integrated = self.meter.integrated_loudness();
        let target = self.standard.target_lufs();
        let tolerance = self.standard.tolerance_lu();

        if integrated.is_infinite() {
            ComplianceStatus::Unknown
        } else if integrated >= target - tolerance && integrated <= target + tolerance {
            ComplianceStatus::Compliant
        } else if integrated > target + tolerance {
            ComplianceStatus::TooLoud(integrated - target)
        } else {
            ComplianceStatus::TooQuiet(target - integrated)
        }
    }

    /// Get the loudness history for visualization.
    #[must_use]
    pub fn history(&self) -> &LoudnessHistory {
        &self.history
    }

    /// Reset the meter.
    pub fn reset(&mut self) {
        self.meter.reset();
        self.history = LoudnessHistory::new(0.1);
    }

    /// Get the loudness standard being used.
    #[must_use]
    pub fn standard(&self) -> LoudnessStandard {
        self.standard
    }

    /// Set the loudness standard.
    pub fn set_standard(&mut self, standard: LoudnessStandard) {
        self.standard = standard;
    }

    /// Extract samples from an audio frame as f64.
    fn extract_samples(&self, frame: &AudioFrame) -> Vec<f64> {
        match &frame.samples {
            crate::frame::AudioBuffer::Interleaved(data) => self.bytes_to_samples_f64(data),
            crate::frame::AudioBuffer::Planar(planes) => {
                // Interleave planar samples
                if planes.is_empty() {
                    return Vec::new();
                }

                let channels = planes.len();
                let sample_size = std::mem::size_of::<f32>();
                let frames = planes[0].len() / sample_size;
                let mut interleaved = Vec::with_capacity(frames * channels);

                for frame_idx in 0..frames {
                    for plane in planes {
                        let samples = self.bytes_to_samples_f64(plane);
                        if let Some(&sample) = samples.get(frame_idx) {
                            interleaved.push(sample);
                        }
                    }
                }

                interleaved
            }
        }
    }

    /// Convert bytes to f64 samples (simplified - assumes f32 for now).
    fn bytes_to_samples_f64(&self, bytes: &bytes::Bytes) -> Vec<f64> {
        // Simplified: would need to handle different sample formats
        // For now, assume f32
        let sample_count = bytes.len() / 4;
        let mut samples = Vec::with_capacity(sample_count);

        for i in 0..sample_count {
            let offset = i * 4;
            if offset + 4 <= bytes.len() {
                let bytes_array = [
                    bytes[offset],
                    bytes[offset + 1],
                    bytes[offset + 2],
                    bytes[offset + 3],
                ];
                let sample = f32::from_le_bytes(bytes_array);
                samples.push(f64::from(sample));
            }
        }

        samples
    }
}

/// Quick loudness measurement function.
///
/// Measure loudness of audio frames without creating a persistent meter.
///
/// # Arguments
///
/// * `frames` - Slice of audio frames
/// * `sample_rate` - Sample rate in Hz
/// * `channels` - Number of channels
///
/// # Returns
///
/// Loudness metrics
pub fn measure_loudness(
    frames: &[AudioFrame],
    sample_rate: f64,
    channels: usize,
) -> AudioResult<LoudnessMetrics> {
    let mut meter = LoudnessMeter::new(LoudnessStandard::EbuR128, sample_rate, channels);

    for frame in frames {
        meter.measure(frame);
    }

    Ok(meter.get_metrics())
}

/// Quick normalization function.
///
/// Normalize audio frames to target loudness.
///
/// # Arguments
///
/// * `frames` - Mutable slice of audio frames
/// * `target_lufs` - Target loudness in LUFS
/// * `sample_rate` - Sample rate in Hz
/// * `channels` - Number of channels
///
/// # Returns
///
/// Normalization parameters
pub fn normalize_loudness(
    frames: &mut [AudioFrame],
    target_lufs: f64,
    sample_rate: f64,
    channels: usize,
) -> AudioResult<NormalizationParams> {
    let meter = LoudnessMeter::new(LoudnessStandard::Custom(target_lufs), sample_rate, channels);
    Ok(meter.normalize(frames, target_lufs))
}