Skip to main content

audio_codec/
pcmu.rs

1use super::{CodecError, Decoder, Encoder, Sample};
2
3const BIAS: i16 = 0x84;
4const CLIP: i16 = 32635;
5
6const fn linear2ulaw_algo(mut sample: i16) -> u8 {
7    // Clip the sample to prevent overflow
8    if sample > CLIP {
9        sample = CLIP;
10    } else if sample < -CLIP {
11        sample = -CLIP;
12    }
13
14    // Get the sample's sign and make it positive
15    let sign: i16 = if sample < 0 { 0x80 } else { 0x00 };
16    if sign == 0x80 {
17        sample = -sample;
18    }
19
20    // Add bias
21    sample += BIAS;
22
23    // Compute segment number and step size
24    let mut segment: i16 = 0;
25    let mut value = sample;
26    while value >= 256 {
27        segment += 1;
28        value >>= 1;
29    }
30
31    // Combine sign, segment, and quantization
32    let uval = if segment >= 8 {
33        0x7F ^ sign
34    } else {
35        // Standard G.711 µ-law complements the whole byte:
36        //   ulawbyte = ~(sign | (segment << 4) | mantissa)
37        // A previous version XOR'd with a partial mask
38        // (0xFF ^ (0xFF >> shift)), leaving the low bits un-complemented and
39        // producing non-standard codes for ~12% of inputs.
40        (sign | (segment << 4) | ((sample >> (segment + 3)) & 0x0F)) ^ 0xFF
41    };
42
43    uval as u8
44}
45
46static MULAW_ENCODE_TABLE: [u8; 65536] = {
47    let mut table = [0; 65536];
48    let mut i = 0;
49    while i < 65536 {
50        let s = (i as i32 - 32768) as i16;
51        table[i] = linear2ulaw_algo(s);
52        i += 1;
53    }
54    table
55};
56
57static MULAW_DECODE_TABLE: [i16; 256] = [
58    -32124, -31100, -30076, -29052, -28028, -27004, -25980, -24956, -23932, -22908, -21884, -20860,
59    -19836, -18812, -17788, -16764, -15996, -15484, -14972, -14460, -13948, -13436, -12924, -12412,
60    -11900, -11388, -10876, -10364, -9852, -9340, -8828, -8316, -7932, -7676, -7420, -7164, -6908,
61    -6652, -6396, -6140, -5884, -5628, -5372, -5116, -4860, -4604, -4348, -4092, -3900, -3772,
62    -3644, -3516, -3388, -3260, -3132, -3004, -2876, -2748, -2620, -2492, -2364, -2236, -2108,
63    -1980, -1884, -1820, -1756, -1692, -1628, -1564, -1500, -1436, -1372, -1308, -1244, -1180,
64    -1116, -1052, -988, -924, -876, -844, -812, -780, -748, -716, -684, -652, -620, -588, -556,
65    -524, -492, -460, -428, -396, -372, -356, -340, -324, -308, -292, -276, -260, -244, -228, -212,
66    -196, -180, -164, -148, -132, -120, -112, -104, -96, -88, -80, -72, -64, -56, -48, -40, -32,
67    -24, -16, -8, 0, 32124, 31100, 30076, 29052, 28028, 27004, 25980, 24956, 23932, 22908, 21884,
68    20860, 19836, 18812, 17788, 16764, 15996, 15484, 14972, 14460, 13948, 13436, 12924, 12412,
69    11900, 11388, 10876, 10364, 9852, 9340, 8828, 8316, 7932, 7676, 7420, 7164, 6908, 6652, 6396,
70    6140, 5884, 5628, 5372, 5116, 4860, 4604, 4348, 4092, 3900, 3772, 3644, 3516, 3388, 3260, 3132,
71    3004, 2876, 2748, 2620, 2492, 2364, 2236, 2108, 1980, 1884, 1820, 1756, 1692, 1628, 1564, 1500,
72    1436, 1372, 1308, 1244, 1180, 1116, 1052, 988, 924, 876, 844, 812, 780, 748, 716, 684, 652,
73    620, 588, 556, 524, 492, 460, 428, 396, 372, 356, 340, 324, 308, 292, 276, 260, 244, 228, 212,
74    196, 180, 164, 148, 132, 120, 112, 104, 96, 88, 80, 72, 64, 56, 48, 40, 32, 24, 16, 8, 0,
75];
76
77/// Decodes a single μ-law encoded byte to a 16-bit PCM sample
78fn decode_mu_law(mu_law_sample: u8) -> i16 {
79    MULAW_DECODE_TABLE[mu_law_sample as usize]
80}
81
82/// Decoder for μ-law (PCMU) format
83#[derive(Default)]
84pub struct PcmuDecoder {}
85
86impl PcmuDecoder {
87    /// Creates a new PcmuDecoder instance
88    pub fn new() -> Self {
89        Self {}
90    }
91}
92
93impl Decoder for PcmuDecoder {
94    fn decode_into(&mut self, data: &[u8], out: &mut [Sample]) -> Result<usize, CodecError> {
95        if out.len() < data.len() {
96            return Err(CodecError::BufferTooSmall);
97        }
98        for (i, &sample) in data.iter().enumerate() {
99            out[i] = decode_mu_law(sample);
100        }
101        Ok(data.len())
102    }
103
104    fn max_decode_samples(&self, n_bytes: usize) -> usize {
105        n_bytes
106    }
107
108    fn sample_rate(&self) -> u32 {
109        8000
110    }
111
112    fn channels(&self) -> u16 {
113        1
114    }
115}
116
117/// Encoder for μ-law (PCMU) format
118#[derive(Default)]
119pub struct PcmuEncoder {}
120
121impl PcmuEncoder {
122    /// Creates a new PcmuEncoder instance
123    pub fn new() -> Self {
124        Self {}
125    }
126
127    /// Converts a linear 16-bit PCM sample to a μ-law encoded byte using lookup table
128    fn linear2ulaw(&self, sample: i16) -> u8 {
129        let index = (sample as i32 + 32768) as usize;
130        MULAW_ENCODE_TABLE[index]
131    }
132}
133
134impl Encoder for PcmuEncoder {
135    fn encode_into(&mut self, samples: &[Sample], out: &mut [u8]) -> Result<usize, CodecError> {
136        if out.len() < samples.len() {
137            return Err(CodecError::BufferTooSmall);
138        }
139        for (i, &sample) in samples.iter().enumerate() {
140            out[i] = self.linear2ulaw(sample);
141        }
142        Ok(samples.len())
143    }
144
145    fn max_encode_bytes(&self, n_samples: usize) -> usize {
146        n_samples
147    }
148
149    fn sample_rate(&self) -> u32 {
150        8000
151    }
152
153    fn channels(&self) -> u16 {
154        1
155    }
156}