alpha2-audio 0.9.0

Platform-independent audio DSP core for alpha2.
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
#![allow(clippy::cast_precision_loss)]

use crate::{Biquad, BiquadKind, ProcessCtx, Processor, StateBlob, StateError};

/// Largest ratio a compressor or expander renders.
pub const MAX_RATIO: f32 = 100.0;

/// Widest knee a compressor renders, in decibels.
pub const MAX_KNEE_DB: f32 = 24.0;

/// Largest makeup gain a compressor renders, in decibels either way.
pub const MAX_MAKEUP_DB: f32 = 24.0;

/// How a compressor measures the level it compresses by.
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub enum Detector {
    /// The largest sample magnitude, smoothed by the attack and release.
    #[default]
    Peak,
    /// The square root of the mean square, smoothed by the attack and release: a sine reads
    /// 3 dB under its peak.
    Rms,
}

/// One static filter a compressor or expander puts before its level detector, so that only a
/// band of the detected signal drives the gain.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct DetectorFilter {
    /// Filter shape. The gain of a peaking or shelving shape is 0 dB.
    pub kind: BiquadKind,
    /// Centre or corner frequency in hertz.
    pub frequency_hz: f32,
    /// Resonance.
    pub q: f32,
}

impl DetectorFilter {
    pub(crate) fn build(filter: Option<Self>) -> Option<Biquad> {
        filter.map(|filter| Biquad::new(filter.kind, filter.frequency_hz, filter.q, 0.0))
    }
}

/// What a [`Compressor`] is built from. Invalid values are replaced by conservative defaults
/// and the rest clamped to what renders.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct CompressorSettings {
    /// Level above which gain reduction begins, in decibels from -96 to 0.
    pub threshold_db: f32,
    /// Downward ratio, from 1 to [`MAX_RATIO`].
    pub ratio: f32,
    /// Width of the knee centred on the threshold, in decibels up to [`MAX_KNEE_DB`]; 0 is a
    /// hard knee.
    pub knee_db: f32,
    /// Gain applied after the reduction, in decibels up to [`MAX_MAKEUP_DB`] either way.
    pub makeup_db: f32,
    /// Attack time in milliseconds.
    pub attack_ms: f32,
    /// Release time in milliseconds.
    pub release_ms: f32,
    /// Lookahead in milliseconds, up to 100; the compressor's latency.
    pub lookahead_ms: f32,
    /// How the level is measured.
    pub detector: Detector,
    /// A filter before the detector.
    pub detector_filter: Option<DetectorFilter>,
}

impl CompressorSettings {
    /// A hard-knee peak compressor with no makeup gain, lookahead or detector filter.
    #[must_use]
    pub const fn new(threshold_db: f32, ratio: f32, attack_ms: f32, release_ms: f32) -> Self {
        Self {
            threshold_db,
            ratio,
            knee_db: 0.0,
            makeup_db: 0.0,
            attack_ms,
            release_ms,
            lookahead_ms: 0.0,
            detector: Detector::Peak,
            detector_filter: None,
        }
    }

    /// These settings with a lookahead in milliseconds.
    #[must_use]
    pub const fn lookahead(mut self, lookahead_ms: f32) -> Self {
        self.lookahead_ms = lookahead_ms;
        self
    }
}

/// Linked-channel compressor with deterministic lookahead and soft attack/release.
///
/// The static curve is the one of Giannoulis, Massberg and Reiss (2012): with level `x`,
/// threshold `T`, ratio `R` and knee `W` in decibels, the gain is 0 dB while `2 (x - T) < -W`,
/// `(1/R - 1) (x - T + W/2)^2 / (2 W)` while `2 |x - T| <= W`, and `T + (x - T) / R - x` above.
///
/// Retuned ([`Processor::control`]), its threshold, ratio and knee and the linear gain of its
/// makeup move in a straight line from one control point's values to the next's.
#[derive(Clone, Debug)]
pub struct Compressor {
    threshold_db: f32,
    ratio: f32,
    knee_db: f32,
    makeup_db: f32,
    makeup: f32,
    attack_ms: f32,
    release_ms: f32,
    lookahead_ms: f32,
    detector: Detector,
    filter: Option<Biquad>,
    envelope: f32,
    attack_coefficient: f32,
    release_coefficient: f32,
    /// Linear threshold; envelopes at or under it skip the logarithm.
    threshold_amplitude: f32,
    delay: [Vec<f32>; 2],
    cursor: usize,
    latency: u32,
    bypass: bool,
    keyed: bool,
    ramp: Option<CurveRamp>,
}

#[derive(Clone, Copy, Debug)]
struct Curve {
    threshold_db: f32,
    ratio: f32,
    knee_db: f32,
    makeup: f32,
    unity_at_or_under: f32,
}

#[derive(Clone, Copy, Debug)]
struct CurveRamp {
    from: [f32; 4],
    change: [f32; 4],
    unity_at_or_under: f32,
    phase: usize,
}

impl CurveRamp {
    fn at(&self, frame: usize) -> Curve {
        let progress = crate::control::progress(self.phase, frame);
        let [threshold_db, ratio, knee_db, makeup] =
            core::array::from_fn(|index| self.from[index] + self.change[index] * progress);
        Curve {
            threshold_db,
            ratio,
            knee_db,
            makeup,
            unity_at_or_under: self.unity_at_or_under,
        }
    }
}

impl Compressor {
    /// Creates a compressor.
    #[must_use]
    pub fn new(settings: CompressorSettings) -> Self {
        let makeup_db = clamped_makeup(settings.makeup_db);
        Self {
            threshold_db: clamped_threshold(settings.threshold_db),
            ratio: clamped_ratio(settings.ratio),
            knee_db: clamped_knee(settings.knee_db),
            makeup_db,
            makeup: libm::exp10f(makeup_db / 20.0),
            attack_ms: positive(settings.attack_ms, 10.0),
            release_ms: positive(settings.release_ms, 100.0),
            lookahead_ms: finite(settings.lookahead_ms, 0.0).clamp(0.0, 100.0),
            detector: settings.detector,
            filter: DetectorFilter::build(settings.detector_filter),
            envelope: 0.0,
            attack_coefficient: 0.0,
            release_coefficient: 0.0,
            threshold_amplitude: 0.0,
            delay: [Vec::new(), Vec::new()],
            cursor: 0,
            latency: 0,
            bypass: false,
            keyed: false,
            ramp: None,
        }
    }

    /// Makes the level of a key drive the reduction instead of the program's own: the inputs are
    /// then the program channels followed by matching key channels.
    #[must_use]
    pub const fn keyed(mut self) -> Self {
        self.keyed = true;
        self
    }

    /// Enables latency-preserving bypass.
    pub fn set_bypass(&mut self, bypass: bool) {
        self.bypass = bypass;
    }
}

#[inline]
pub(crate) fn detected_peak(
    filter: &mut Option<Biquad>,
    inputs: &[&[f32]],
    (first, channels): (usize, usize),
    frame: usize,
) -> f32 {
    let Some(filter) = filter else {
        return inputs[first..first + channels]
            .iter()
            .map(|channel| finite(channel[frame], 0.0).abs())
            .fold(0.0_f32, f32::max);
    };
    let mut peak = 0.0_f32;
    for channel in 0..channels {
        let detected = filter.detect(channel, finite(inputs[first + channel][frame], 0.0));
        peak = peak.max(detected.abs());
    }
    peak
}

impl Compressor {
    fn run<const PLAIN: bool>(
        &mut self,
        inputs: &[&[f32]],
        outputs: &mut [&mut [f32]],
        curve_at_frame: impl Fn(usize) -> Curve,
    ) -> usize {
        let planes = if self.keyed { 2 } else { 1 };
        let channels = (inputs.len() / planes).min(outputs.len()).min(2);
        let frames = inputs
            .iter()
            .take(channels * planes)
            .map(|input| input.len())
            .chain(outputs.iter().take(channels).map(|output| output.len()))
            .min()
            .unwrap_or(0);
        if self.delay[0].is_empty() {
            return 0;
        }
        let detector = if self.keyed { channels } else { 0 };
        let rms = !PLAIN && self.detector == Detector::Rms;
        for frame in 0..frames {
            let curve = curve_at_frame(frame);
            let peak = if PLAIN {
                inputs[detector..detector + channels]
                    .iter()
                    .map(|channel| finite(channel[frame], 0.0).abs())
                    .fold(0.0_f32, f32::max)
            } else {
                detected_peak(&mut self.filter, inputs, (detector, channels), frame)
            };
            let measured = if rms { peak * peak } else { peak };
            if !self.envelope.is_finite() {
                self.envelope = 0.0;
            }
            let coefficient = if measured > self.envelope {
                self.attack_coefficient
            } else {
                self.release_coefficient
            };
            self.envelope = coefficient * self.envelope + (1.0 - coefficient) * measured;
            // Keep a released envelope out of the slow subnormal range.
            if self.envelope < 1.0e-30 {
                self.envelope = 0.0;
            }
            let level = if rms {
                libm::sqrtf(self.envelope)
            } else {
                self.envelope
            };
            // Under the threshold the gain is exactly one. Over it, `exp10f` is as portable as
            // `powf(10, x)` and about nine times cheaper.
            let reduction_db = if level <= curve.unity_at_or_under {
                0.0
            } else {
                let level_db = 20.0 * libm::log10f(level.max(1.0e-12));
                if !PLAIN && curve.knee_db > 0.0 {
                    let over = level_db - curve.threshold_db;
                    if 2.0 * over < -curve.knee_db {
                        0.0
                    } else if 2.0 * over.abs() <= curve.knee_db {
                        let into_knee = over + curve.knee_db / 2.0;
                        (1.0 / curve.ratio - 1.0) * into_knee * into_knee / (2.0 * curve.knee_db)
                    } else {
                        (curve.threshold_db + over / curve.ratio) - level_db
                    }
                } else if level_db > curve.threshold_db {
                    (curve.threshold_db + (level_db - curve.threshold_db) / curve.ratio) - level_db
                } else {
                    0.0
                }
            };
            let gain = if self.bypass || (PLAIN && reduction_db == 0.0) {
                1.0
            } else if PLAIN {
                libm::exp10f(reduction_db / 20.0)
            } else if reduction_db == 0.0 {
                curve.makeup
            } else {
                libm::exp10f(reduction_db / 20.0) * curve.makeup
            };
            for channel in 0..channels {
                let input = finite(inputs[channel][frame], 0.0);
                let delayed = if self.latency == 0 {
                    input
                } else {
                    let delayed = self.delay[channel][self.cursor];
                    self.delay[channel][self.cursor] = input;
                    finite(delayed, 0.0)
                };
                outputs[channel][frame] = delayed * gain;
            }
            if self.latency != 0 {
                self.cursor = (self.cursor + 1) % self.delay[0].len();
            }
        }
        frames
    }

    fn curve(&self) -> [f32; 4] {
        [self.threshold_db, self.ratio, self.knee_db, self.makeup]
    }
}

fn clamped_curve(values: &[f32]) -> Option<([f32; 4], f32)> {
    let &[threshold_db, ratio, knee_db, makeup_db] = values else {
        return None;
    };
    let makeup_db = clamped_makeup(makeup_db);
    Some((
        [
            clamped_threshold(threshold_db),
            clamped_ratio(ratio),
            clamped_knee(knee_db),
            libm::exp10f(makeup_db / 20.0),
        ],
        makeup_db,
    ))
}

impl Processor for Compressor {
    /// The program, then the key when [`Compressor::keyed`].
    fn inputs_per_output(&self) -> usize {
        if self.keyed { 2 } else { 1 }
    }

    /// The threshold in decibels, the ratio, the knee in decibels and the makeup gain in
    /// decibels.
    fn control_params(&self) -> usize {
        4
    }

    fn control(&mut self, span: &crate::ControlSpan<'_>) {
        let (Some((from, makeup_db)), Some((to, _))) =
            (clamped_curve(span.from), clamped_curve(span.to))
        else {
            return;
        };
        if span.is_steady() {
            if from.map(f32::to_bits) != self.curve().map(f32::to_bits) {
                self.threshold_amplitude = threshold_amplitude(from[0] - from[2] / 2.0);
            }
            [self.threshold_db, self.ratio, self.knee_db, self.makeup] = from;
            self.makeup_db = makeup_db;
            self.ramp = None;
            return;
        }
        let knee_starts = |curve: [f32; 4]| curve[0] - curve[2] / 2.0;
        self.ramp = Some(CurveRamp {
            from,
            change: core::array::from_fn(|index| to[index] - from[index]),
            unity_at_or_under: threshold_amplitude(knee_starts(from).min(knee_starts(to))),
            phase: span.phase,
        });
    }

    fn prepare(&mut self, sample_rate: u32, _max_block: usize) {
        let rate = sample_rate.max(1) as f32;
        self.attack_coefficient = libm::expf(-1.0 / (self.attack_ms * 0.001 * rate));
        self.release_coefficient = libm::expf(-1.0 / (self.release_ms * 0.001 * rate));
        self.threshold_amplitude = threshold_amplitude(self.threshold_db - self.knee_db / 2.0);
        if let Some(filter) = &mut self.filter {
            filter.prepare(sample_rate, 1);
        }
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        {
            self.latency = (self.lookahead_ms * 0.001 * rate).round() as u32;
        }
        let size = usize::try_from(self.latency).unwrap_or(0).max(1);
        self.delay = [vec![0.0; size], vec![0.0; size]];
        self.cursor = 0;
    }

    fn process(&mut self, _ctx: &ProcessCtx, inputs: &[&[f32]], outputs: &mut [&mut [f32]]) {
        match self.ramp {
            None => {
                let steady = Curve {
                    threshold_db: self.threshold_db,
                    ratio: self.ratio,
                    knee_db: self.knee_db,
                    makeup: self.makeup,
                    unity_at_or_under: self.threshold_amplitude,
                };
                let as_before_these_settings = self.filter.is_none()
                    && self.detector == Detector::Peak
                    && self.knee_db == 0.0
                    && self.makeup_db == 0.0;
                if as_before_these_settings {
                    self.run::<true>(inputs, outputs, |_| steady);
                } else {
                    self.run::<false>(inputs, outputs, |_| steady);
                }
            }
            Some(ramp) => {
                let frames = self.run::<false>(inputs, outputs, |frame| ramp.at(frame));
                self.ramp = Some(CurveRamp {
                    phase: ramp.phase.saturating_add(frames),
                    ..ramp
                });
            }
        }
    }

    fn reset(&mut self) {
        self.envelope = 0.0;
        self.cursor = 0;
        for channel in &mut self.delay {
            channel.fill(0.0);
        }
        if let Some(filter) = &mut self.filter {
            filter.reset();
        }
    }
    fn latency_samples(&self) -> u32 {
        self.latency
    }
    fn history_samples(&self) -> u32 {
        if self.ratio <= 1.0 {
            return 0;
        }
        crate::processor::settling_samples(f64::from(
            self.attack_coefficient.max(self.release_coefficient),
        ))
        .saturating_add(self.filter.as_ref().map_or(0, Processor::history_samples))
    }
    fn save_state(&self) -> StateBlob {
        let mut bytes = Vec::with_capacity(16 + self.delay.iter().map(Vec::len).sum::<usize>() * 4);
        bytes.extend_from_slice(&self.envelope.to_le_bytes());
        bytes.extend_from_slice(&(u64::try_from(self.cursor).unwrap_or(0)).to_le_bytes());
        bytes.extend_from_slice(&self.latency.to_le_bytes());
        for channel in &self.delay {
            for value in channel {
                bytes.extend_from_slice(&value.to_le_bytes());
            }
        }
        if let Some(filter) = &self.filter {
            bytes.extend_from_slice(filter.save_state().as_bytes());
        }
        StateBlob::new(bytes)
    }
    fn load_state(&mut self, state: &StateBlob) -> Result<(), StateError> {
        let delayed = 16 + self.delay.iter().map(Vec::len).sum::<usize>() * 4;
        let (bytes, filter_state) = state
            .as_bytes()
            .split_at_checked(delayed)
            .ok_or(StateError::Mismatch)?;
        let filter = match &self.filter {
            Some(filter) => {
                let mut loaded = filter.clone();
                loaded.load_state(&StateBlob::new(filter_state.to_vec()))?;
                Some(loaded)
            }
            None if filter_state.is_empty() => None,
            None => return Err(StateError::Mismatch),
        };
        let envelope = f32::from_le_bytes(bytes[0..4].try_into().expect("fixed range"));
        let cursor = usize::try_from(u64::from_le_bytes(
            bytes[4..12].try_into().expect("fixed range"),
        ))
        .ok();
        let latency = u32::from_le_bytes(bytes[12..16].try_into().expect("fixed range"));
        if latency != self.latency {
            return Err(StateError::Mismatch);
        }
        let values = bytes[16..]
            .as_chunks::<4>()
            .0
            .iter()
            .map(|word| f32::from_le_bytes(*word));
        if !envelope.is_finite()
            || envelope < 0.0
            || cursor.is_none_or(|value| value >= self.delay[0].len())
            || values.clone().any(|value| !value.is_finite())
        {
            return Err(StateError::Invalid);
        }
        self.envelope = envelope;
        self.cursor = cursor.unwrap_or(0);
        for (target, value) in self.delay.iter_mut().flatten().zip(values) {
            *target = value;
        }
        self.filter = filter;
        Ok(())
    }
}

pub(crate) fn finite(value: f32, fallback: f32) -> f32 {
    if value.is_finite() { value } else { fallback }
}
pub(crate) fn clamped_threshold(threshold_db: f32) -> f32 {
    finite(threshold_db, -12.0).clamp(-96.0, 0.0)
}
pub(crate) fn clamped_ratio(ratio: f32) -> f32 {
    finite(ratio, 4.0).clamp(1.0, MAX_RATIO)
}
fn clamped_knee(knee_db: f32) -> f32 {
    finite(knee_db, 0.0).clamp(0.0, MAX_KNEE_DB)
}
fn clamped_makeup(makeup_db: f32) -> f32 {
    finite(makeup_db, 0.0).clamp(-MAX_MAKEUP_DB, MAX_MAKEUP_DB)
}
fn threshold_amplitude(threshold_db: f32) -> f32 {
    // Rounded down slightly so the decibel comparison below still decides borderline cases.
    libm::exp10f(threshold_db / 20.0) * (1.0 - 1.0e-4)
}
pub(crate) fn positive(value: f32, fallback: f32) -> f32 {
    let value = finite(value, fallback);
    if value > 0.0 { value } else { fallback }
}