embedded_dsp/companding.rs
1//! Audio companding: the non-linear µ-law and "A"-law compression curves used by the ITU-T
2//! G.711 telephony standard to compress a wide-dynamic-range linear audio sample down to a
3//! lower bit depth with minimal perceptual loss (Steven W. Smith, "The Scientist and
4//! Engineer's Guide to DSP", Ch. 22, Eq. 22-1 / 22-2).
5//!
6//! All functions operate on samples normalized to `-1.0..=1.0`.
7
8#[allow(unused_imports)]
9use crate::math::FloatMath;
10
11const MU: f32 = 255.0;
12const A_LAW: f32 = 87.6;
13// Precomputed so the per-sample hot path only needs one transcendental call, not two.
14const LN_1P_MU: f32 = 5.545_177_5; // ln(1 + MU)
15const LN_A_LAW: f32 = 4.472_781; // ln(A_LAW)
16const A_LAW_DENOM: f32 = 1.0 + LN_A_LAW; // 1 + ln(A_LAW)
17
18#[inline(always)]
19fn sign(x: f32) -> f32 {
20 if x < 0.0 { -1.0 } else { 1.0 }
21}
22
23/// Compresses a normalized linear sample `x` (`-1.0..=1.0`) using µ255-law companding
24/// (Eq. 22-1), expanding resolution for small amplitudes at the expense of large ones.
25pub fn mu_law_compress_f32(x: f32) -> f32 {
26 let ax = x.abs();
27 sign(x) * (1.0 + MU * ax).ln() / LN_1P_MU
28}
29
30/// Expands a µ-law-compressed sample `y` (`-1.0..=1.0`) back to a normalized linear sample,
31/// inverting [`mu_law_compress_f32`].
32pub fn mu_law_expand_f32(y: f32) -> f32 {
33 let ay = y.abs();
34 sign(y) * ((1.0 + MU).powf(ay) - 1.0) / MU
35}
36
37/// Compresses a normalized linear sample `x` (`-1.0..=1.0`) using "A"-law companding
38/// (Eq. 22-2): a linear segment near zero, transitioning to a logarithmic curve.
39pub fn a_law_compress_f32(x: f32) -> f32 {
40 let ax = x.abs();
41 if ax < 1.0 / A_LAW {
42 sign(x) * (A_LAW * ax) / A_LAW_DENOM
43 } else {
44 sign(x) * (1.0 + (A_LAW * ax).ln()) / A_LAW_DENOM
45 }
46}
47
48/// Expands an "A"-law-compressed sample `y` (`-1.0..=1.0`) back to a normalized linear sample,
49/// inverting [`a_law_compress_f32`].
50pub fn a_law_expand_f32(y: f32) -> f32 {
51 let ay = y.abs();
52 if ay < 1.0 / A_LAW_DENOM {
53 sign(y) * ay * A_LAW_DENOM / A_LAW
54 } else {
55 sign(y) * (ay * A_LAW_DENOM - 1.0).exp() / A_LAW
56 }
57}