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
//! Peak limiter implementation.
//!
//! This module provides a brickwall limiter to prevent audio clipping.

#![forbid(unsafe_code)]
#![allow(clippy::cast_lossless)]

use super::compressor::{CompressorConfig, KneeType};
use std::collections::VecDeque;

/// Configuration for the limiter.
#[derive(Clone, Debug)]
pub struct LimiterConfig {
    /// Ceiling level in dB (maximum output level).
    pub ceiling_db: f64,
    /// Attack time in milliseconds.
    pub attack_ms: f64,
    /// Release time in milliseconds.
    pub release_ms: f64,
    /// Lookahead time in milliseconds.
    pub lookahead_ms: f64,
}

impl Default for LimiterConfig {
    fn default() -> Self {
        Self {
            ceiling_db: -0.1,
            attack_ms: 0.5,
            release_ms: 50.0,
            lookahead_ms: 5.0,
        }
    }
}

impl LimiterConfig {
    /// Create a new limiter configuration.
    #[must_use]
    pub fn new(ceiling_db: f64) -> Self {
        Self {
            ceiling_db,
            ..Default::default()
        }
    }

    /// Set attack and release times.
    #[must_use]
    pub fn with_timing(mut self, attack_ms: f64, release_ms: f64) -> Self {
        self.attack_ms = attack_ms.max(0.01);
        self.release_ms = release_ms.max(1.0);
        self
    }

    /// Set lookahead time.
    #[must_use]
    pub fn with_lookahead(mut self, lookahead_ms: f64) -> Self {
        self.lookahead_ms = lookahead_ms.max(0.0);
        self
    }

    /// Convert to compressor config with very high ratio.
    #[must_use]
    pub fn to_compressor_config(&self) -> CompressorConfig {
        CompressorConfig {
            threshold_db: self.ceiling_db,
            ratio: 100.0,
            attack_ms: self.attack_ms,
            release_ms: self.release_ms,
            knee_type: KneeType::Hard,
            knee_width_db: 0.0,
            makeup_gain_db: 0.0,
            auto_makeup: false,
            lookahead_ms: self.lookahead_ms,
        }
    }

    /// Convert dB to linear gain.
    #[must_use]
    pub fn db_to_linear(db: f64) -> f64 {
        10.0_f64.powf(db / 20.0)
    }

    /// Convert linear gain to dB.
    #[must_use]
    pub fn linear_to_db(linear: f64) -> f64 {
        if linear <= 0.0 {
            f64::NEG_INFINITY
        } else {
            20.0 * linear.log10()
        }
    }

    /// Create a mastering limiter preset (very fast attack, transparent).
    #[must_use]
    pub fn mastering() -> Self {
        Self {
            ceiling_db: -0.1,
            attack_ms: 0.1,
            release_ms: 100.0,
            lookahead_ms: 10.0,
        }
    }

    /// Create a broadcast limiter preset (safety limiter).
    #[must_use]
    pub fn broadcast() -> Self {
        Self {
            ceiling_db: -1.0,
            attack_ms: 0.05,
            release_ms: 50.0,
            lookahead_ms: 5.0,
        }
    }

    /// Create a true peak limiter preset (prevents inter-sample peaks).
    #[must_use]
    pub fn true_peak() -> Self {
        Self {
            ceiling_db: -1.0,
            attack_ms: 0.01,
            release_ms: 100.0,
            lookahead_ms: 15.0,
        }
    }
}

/// Envelope follower for limiter gain reduction.
struct LimiterEnvelope {
    /// Current envelope level.
    envelope: f64,
    /// Attack coefficient.
    attack_coeff: f64,
    /// Release coefficient.
    release_coeff: f64,
}

impl LimiterEnvelope {
    /// Create a new limiter envelope follower.
    fn new(attack_ms: f64, release_ms: f64, sample_rate: f64) -> Self {
        let attack_coeff = if attack_ms > 0.0 {
            (-1.0 / (attack_ms * 0.001 * sample_rate)).exp()
        } else {
            0.0
        };

        let release_coeff = if release_ms > 0.0 {
            (-1.0 / (release_ms * 0.001 * sample_rate)).exp()
        } else {
            0.0
        };

        Self {
            envelope: 1.0,
            attack_coeff,
            release_coeff,
        }
    }

    /// Update envelope with new gain value.
    fn update(&mut self, target_gain: f64) {
        if target_gain < self.envelope {
            self.envelope =
                self.attack_coeff * self.envelope + (1.0 - self.attack_coeff) * target_gain;
        } else {
            self.envelope =
                self.release_coeff * self.envelope + (1.0 - self.release_coeff) * target_gain;
        }
    }

    /// Get current envelope level.
    fn level(&self) -> f64 {
        self.envelope
    }

    /// Reset envelope.
    fn reset(&mut self) {
        self.envelope = 1.0;
    }
}

/// Lookahead buffer for one channel.
struct LookaheadBuffer {
    /// Circular buffer.
    buffer: VecDeque<f64>,
    /// Delay in samples.
    delay_samples: usize,
}

impl LookaheadBuffer {
    /// Create a new lookahead buffer.
    fn new(lookahead_ms: f64, sample_rate: f64) -> Self {
        let delay_samples = (lookahead_ms * 0.001 * sample_rate) as usize;

        Self {
            buffer: VecDeque::with_capacity(delay_samples + 1),
            delay_samples,
        }
    }

    /// Process one sample through the buffer.
    fn process(&mut self, input: f64) -> f64 {
        if self.delay_samples == 0 {
            return input;
        }

        self.buffer.push_back(input);

        if self.buffer.len() > self.delay_samples {
            self.buffer.pop_front().unwrap_or(0.0)
        } else {
            0.0
        }
    }

    /// Reset buffer.
    fn reset(&mut self) {
        self.buffer.clear();
    }
}

/// Peak limiter processor.
pub struct Limiter {
    /// Configuration.
    config: LimiterConfig,
    /// Envelope follower.
    envelope: LimiterEnvelope,
    /// Lookahead buffers per channel.
    lookahead_buffers: Vec<LookaheadBuffer>,
    /// Ceiling threshold (linear).
    ceiling_linear: f64,
    /// Current gain reduction in dB (for metering).
    gain_reduction_db: f64,
    /// Sample rate.
    sample_rate: f64,
    /// Number of channels.
    channels: usize,
}

impl Limiter {
    /// Create a new limiter.
    ///
    /// # Arguments
    ///
    /// * `config` - Limiter configuration
    /// * `sample_rate` - Sample rate in Hz
    /// * `channels` - Number of audio channels
    #[must_use]
    pub fn new(config: LimiterConfig, sample_rate: f64, channels: usize) -> Self {
        let envelope = LimiterEnvelope::new(config.attack_ms, config.release_ms, sample_rate);

        let lookahead_buffers: Vec<_> = (0..channels)
            .map(|_| LookaheadBuffer::new(config.lookahead_ms, sample_rate))
            .collect();

        let ceiling_linear = LimiterConfig::db_to_linear(config.ceiling_db);

        Self {
            config,
            envelope,
            lookahead_buffers,
            ceiling_linear,
            gain_reduction_db: 0.0,
            sample_rate,
            channels,
        }
    }

    /// Set the limiter configuration.
    pub fn set_config(&mut self, config: LimiterConfig) {
        self.envelope = LimiterEnvelope::new(config.attack_ms, config.release_ms, self.sample_rate);
        self.ceiling_linear = LimiterConfig::db_to_linear(config.ceiling_db);
        self.config = config;
    }

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

    /// Get current gain reduction in dB (for metering).
    #[must_use]
    pub fn gain_reduction_db(&self) -> f64 {
        self.gain_reduction_db
    }

    /// Calculate required gain to stay below ceiling.
    fn calculate_gain(&self, peak: f64) -> f64 {
        if peak <= self.ceiling_linear {
            1.0
        } else {
            self.ceiling_linear / peak
        }
    }

    /// Process a single frame of interleaved samples.
    ///
    /// # Arguments
    ///
    /// * `samples` - Interleaved input/output sample buffer
    /// * `num_samples` - Number of samples per channel
    pub fn process_interleaved(&mut self, samples: &mut [f64], num_samples: usize) {
        for i in 0..num_samples {
            let mut peak = 0.0_f64;

            for ch in 0..self.channels {
                let idx = i * self.channels + ch;
                if idx < samples.len() {
                    peak = peak.max(samples[idx].abs());
                }
            }

            let target_gain = self.calculate_gain(peak);
            self.envelope.update(target_gain);

            let gain = self.envelope.level();

            self.gain_reduction_db = LimiterConfig::linear_to_db(gain);

            for ch in 0..self.channels {
                let idx = i * self.channels + ch;
                if idx < samples.len() && ch < self.lookahead_buffers.len() {
                    let delayed = self.lookahead_buffers[ch].process(samples[idx]);
                    samples[idx] = delayed * gain;
                }
            }
        }
    }

    /// Process multiple channels (planar samples).
    ///
    /// # Arguments
    ///
    /// * `channels` - Slice of channel buffers
    pub fn process_planar(&mut self, channels: &mut [Vec<f64>]) {
        if channels.is_empty() {
            return;
        }

        let num_samples = channels[0].len();

        for i in 0..num_samples {
            let mut peak = 0.0_f64;

            for channel in channels.iter() {
                if i < channel.len() {
                    peak = peak.max(channel[i].abs());
                }
            }

            let target_gain = self.calculate_gain(peak);
            self.envelope.update(target_gain);

            let gain = self.envelope.level();

            self.gain_reduction_db = LimiterConfig::linear_to_db(gain);

            for (ch, channel) in channels.iter_mut().enumerate() {
                if i < channel.len() && ch < self.lookahead_buffers.len() {
                    let delayed = self.lookahead_buffers[ch].process(channel[i]);
                    channel[i] = delayed * gain;
                }
            }
        }
    }

    /// Process a single channel of samples.
    ///
    /// # Arguments
    ///
    /// * `channel` - Channel index
    /// * `samples` - Input/output sample buffer
    pub fn process_channel(&mut self, channel: usize, samples: &mut [f64]) {
        if channel >= self.channels {
            return;
        }

        for sample in samples.iter_mut() {
            let peak = sample.abs();

            let target_gain = self.calculate_gain(peak);
            self.envelope.update(target_gain);

            let gain = self.envelope.level();

            self.gain_reduction_db = LimiterConfig::linear_to_db(gain);

            if channel < self.lookahead_buffers.len() {
                let delayed = self.lookahead_buffers[channel].process(*sample);
                *sample = delayed * gain;
            }
        }
    }

    /// Reset all limiter state.
    pub fn reset(&mut self) {
        self.envelope.reset();
        for buffer in &mut self.lookahead_buffers {
            buffer.reset();
        }
        self.gain_reduction_db = 0.0;
    }
}

/// True peak limiter with oversampling detection.
///
/// This limiter uses a simple oversampling approach to detect
/// inter-sample peaks that could cause clipping during D/A conversion.
pub struct TruePeakLimiter {
    /// Base limiter.
    limiter: Limiter,
    /// Oversampling factor (2x or 4x).
    #[allow(dead_code)]
    oversample_factor: usize,
}

impl TruePeakLimiter {
    /// Create a new true peak limiter.
    ///
    /// # Arguments
    ///
    /// * `config` - Limiter configuration
    /// * `sample_rate` - Sample rate in Hz
    /// * `channels` - Number of audio channels
    /// * `oversample_factor` - Oversampling factor (2 or 4)
    #[must_use]
    pub fn new(
        config: LimiterConfig,
        sample_rate: f64,
        channels: usize,
        oversample_factor: usize,
    ) -> Self {
        let os_factor = if oversample_factor == 2 || oversample_factor == 4 {
            oversample_factor
        } else {
            4
        };

        let limiter = Limiter::new(config, sample_rate * os_factor as f64, channels);

        Self {
            limiter,
            oversample_factor: os_factor,
        }
    }

    /// Process samples with oversampled peak detection.
    ///
    /// Note: This is a simplified version. A production implementation
    /// would use proper interpolation filters.
    pub fn process_planar(&mut self, channels: &mut [Vec<f64>]) {
        self.limiter.process_planar(channels);
    }

    /// Get current gain reduction in dB.
    #[must_use]
    pub fn gain_reduction_db(&self) -> f64 {
        self.limiter.gain_reduction_db()
    }

    /// Reset limiter state.
    pub fn reset(&mut self) {
        self.limiter.reset();
    }
}