Skip to main content

audio_codec/
pcma.rs

1#[cfg(feature = "plc")]
2use super::plc::PitchConcealer;
3use super::{CodecError, Decoder, Encoder, Sample};
4#[cfg(feature = "plc")]
5use alloc::boxed::Box;
6
7const SEG_SHIFT: i16 = 4;
8const QUANT_MASK: i16 = 0x0F;
9const SEG_END: [i16; 8] = [0xFF, 0x1FF, 0x3FF, 0x7FF, 0xFFF, 0x1FFF, 0x3FFF, 0x7FFF];
10
11const fn search(val: i16, table: &[i16], size: usize) -> usize {
12    let mut i = 0;
13    while i < size {
14        if val <= table[i] {
15            return i;
16        }
17        i += 1;
18    }
19    size
20}
21
22const fn linear2alaw_algo(pcm_val: i16) -> u8 {
23    // Special case handling for small negative values [-8, -1]
24    if pcm_val < 0 && pcm_val >= -8 {
25        return 0xD5;
26    }
27
28    // Determine sign mask and prepare the positive sample value
29    let (mask, abs_val) = if pcm_val >= 0 {
30        (0xD5, pcm_val) // sign bit = 1
31    } else {
32        // Handle the edge case of -32768 (i16::MIN), which would overflow when negated
33        if pcm_val == i16::MIN {
34            (0x55, i16::MAX) // Use the maximum positive value
35        } else {
36            (0x55, -pcm_val - 8) // sign bit = 0
37        }
38    };
39
40    // Convert the scaled magnitude to segment number
41    let seg = search(abs_val, &SEG_END, 8);
42
43    // If out of range, return maximum value
44    if seg >= 8 {
45        return (0x7F ^ mask) as u8;
46    }
47
48    // Calculate the base value from segment
49    let aval = (seg as i16) << SEG_SHIFT;
50
51    // Combine the segment value with the quantization bits
52    let shift = if seg < 2 { 4 } else { seg as i16 + 3 };
53    let result = aval | ((abs_val >> shift) & QUANT_MASK);
54
55    // Apply the mask to set the sign bit
56    (result ^ mask) as u8
57}
58
59static ALAW_ENCODE_TABLE: [u8; 65536] = {
60    let mut table = [0; 65536];
61    let mut i = 0;
62    while i < 65536 {
63        let s = (i as i32 - 32768) as i16;
64        table[i] = linear2alaw_algo(s);
65        i += 1;
66    }
67    table
68};
69
70// A-law decode table (same as Go's alaw2lpcm)
71static ALAW_DECODE_TABLE: [i16; 256] = [
72    -5504, -5248, -6016, -5760, -4480, -4224, -4992, -4736, -7552, -7296, -8064, -7808, -6528,
73    -6272, -7040, -6784, -2752, -2624, -3008, -2880, -2240, -2112, -2496, -2368, -3776, -3648,
74    -4032, -3904, -3264, -3136, -3520, -3392, -22016, -20992, -24064, -23040, -17920, -16896,
75    -19968, -18944, -30208, -29184, -32256, -31232, -26112, -25088, -28160, -27136, -11008, -10496,
76    -12032, -11520, -8960, -8448, -9984, -9472, -15104, -14592, -16128, -15616, -13056, -12544,
77    -14080, -13568, -344, -328, -376, -360, -280, -264, -312, -296, -472, -456, -504, -488, -408,
78    -392, -440, -424, -88, -72, -120, -104, -24, -8, -56, -40, -216, -200, -248, -232, -152, -136,
79    -184, -168, -1376, -1312, -1504, -1440, -1120, -1056, -1248, -1184, -1888, -1824, -2016, -1952,
80    -1632, -1568, -1760, -1696, -688, -656, -752, -720, -560, -528, -624, -592, -944, -912, -1008,
81    -976, -816, -784, -880, -848, 5504, 5248, 6016, 5760, 4480, 4224, 4992, 4736, 7552, 7296, 8064,
82    7808, 6528, 6272, 7040, 6784, 2752, 2624, 3008, 2880, 2240, 2112, 2496, 2368, 3776, 3648, 4032,
83    3904, 3264, 3136, 3520, 3392, 22016, 20992, 24064, 23040, 17920, 16896, 19968, 18944, 30208,
84    29184, 32256, 31232, 26112, 25088, 28160, 27136, 11008, 10496, 12032, 11520, 8960, 8448, 9984,
85    9472, 15104, 14592, 16128, 15616, 13056, 12544, 14080, 13568, 344, 328, 376, 360, 280, 264,
86    312, 296, 472, 456, 504, 488, 408, 392, 440, 424, 88, 72, 120, 104, 24, 8, 56, 40, 216, 200,
87    248, 232, 152, 136, 184, 168, 1376, 1312, 1504, 1440, 1120, 1056, 1248, 1184, 1888, 1824, 2016,
88    1952, 1632, 1568, 1760, 1696, 688, 656, 752, 720, 560, 528, 624, 592, 944, 912, 1008, 976, 816,
89    784, 880, 848,
90];
91
92/// Decoder for A-law (PCMA) format
93pub struct PcmaDecoder {
94    /// Packet loss concealment, once enabled.
95    #[cfg(feature = "plc")]
96    plc: Option<Box<PitchConcealer>>,
97}
98
99impl PcmaDecoder {
100    /// Creates a new PcmaDecoder instance
101    pub fn new() -> Self {
102        Self {
103            #[cfg(feature = "plc")]
104            plc: None,
105        }
106    }
107}
108
109impl Default for PcmaDecoder {
110    fn default() -> Self {
111        Self::new()
112    }
113}
114
115impl Decoder for PcmaDecoder {
116    fn decode_into(&mut self, data: &[u8], out: &mut [Sample]) -> Result<usize, CodecError> {
117        if out.len() < data.len() {
118            return Err(CodecError::BufferTooSmall);
119        }
120        for (i, &sample) in data.iter().enumerate() {
121            out[i] = decode_a_law(sample);
122        }
123        #[cfg(feature = "plc")]
124        if let Some(plc) = &mut self.plc {
125            plc.on_decoded(&mut out[..data.len()]);
126        }
127        Ok(data.len())
128    }
129
130    #[cfg(feature = "plc")]
131    fn enable_concealment(&mut self) -> bool {
132        self.plc
133            .get_or_insert_with(|| Box::new(PitchConcealer::new(8000)));
134        true
135    }
136
137    /// Conceals with G.711 Appendix I style pitch repetition.
138    #[cfg(feature = "plc")]
139    fn conceal_into(&mut self, samples: usize, out: &mut [Sample]) -> Result<usize, CodecError> {
140        let Some(plc) = &mut self.plc else {
141            return Ok(0);
142        };
143        let out = out.get_mut(..samples).ok_or(CodecError::BufferTooSmall)?;
144        plc.conceal(out);
145        Ok(samples)
146    }
147
148    fn max_decode_samples(&self, n_bytes: usize) -> usize {
149        n_bytes
150    }
151
152    fn sample_rate(&self) -> u32 {
153        8000
154    }
155
156    fn channels(&self) -> u16 {
157        1
158    }
159}
160
161/// Decodes a single A-law encoded byte to a 16-bit PCM sample
162fn decode_a_law(a_law_sample: u8) -> i16 {
163    ALAW_DECODE_TABLE[a_law_sample as usize]
164}
165
166/// Encoder for A-law (PCMA) format
167#[derive(Default)]
168pub struct PcmaEncoder {}
169
170impl PcmaEncoder {
171    /// Creates a new PcmaEncoder instance
172    pub fn new() -> Self {
173        Self {}
174    }
175
176    /// Converts a linear 16-bit PCM sample to an A-law encoded byte using lookup table
177    fn linear2alaw(&self, sample: i16) -> u8 {
178        let index = (sample as i32 + 32768) as usize;
179        ALAW_ENCODE_TABLE[index]
180    }
181}
182
183impl Encoder for PcmaEncoder {
184    fn encode_into(&mut self, samples: &[Sample], out: &mut [u8]) -> Result<usize, CodecError> {
185        if out.len() < samples.len() {
186            return Err(CodecError::BufferTooSmall);
187        }
188        for (i, &sample) in samples.iter().enumerate() {
189            out[i] = self.linear2alaw(sample);
190        }
191        Ok(samples.len())
192    }
193
194    fn max_encode_bytes(&self, n_samples: usize) -> usize {
195        n_samples
196    }
197
198    fn sample_rate(&self) -> u32 {
199        8000
200    }
201
202    fn channels(&self) -> u16 {
203        1
204    }
205}