Skip to main content

audio_codec/
g722.rs

1use super::{CodecError, Decoder, Encoder, Sample};
2
3#[cfg(feature = "std")]
4use super::PcmBuf;
5
6pub enum Bitrate {
7    Mode1_64000,
8    Mode2_56000,
9    Mode3_48000,
10}
11
12// Quantization decision thresholds used in the encoder
13const QUANT_DECISION_LEVEL: [i32; 32] = [
14    0, 35, 72, 110, 150, 190, 233, 276, 323, 370, 422, 473, 530, 587, 650, 714, 786, 858, 940,
15    1023, 1121, 1219, 1339, 1458, 1612, 1765, 1980, 2195, 2557, 2919, 0, 0,
16];
17
18// Negative quantization interval indices
19const QUANT_INDEX_NEG: [i32; 32] = [
20    0, 63, 62, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11,
21    10, 9, 8, 7, 6, 5, 4, 0,
22];
23
24// Positive quantization interval indices
25const QUANT_INDEX_POS: [i32; 32] = [
26    0, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39,
27    38, 37, 36, 35, 34, 33, 32, 0,
28];
29
30// Scale factor adaptation table for low band
31const SCALE_FACTOR_ADJUST_LOW: [i32; 8] = [-60, -30, 58, 172, 334, 538, 1198, 3042];
32
33// Mapping from 4 bits of low band code to 3 bits of logarithmic scale factor
34const LOG_SCALE_FACTOR_MAP: [i32; 16] = [0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 1, 0];
35
36// Inverse logarithmic base for computing the scale factor
37const INV_LOG_BASE: [i32; 32] = [
38    2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383, 2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834,
39    2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371, 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008,
40];
41
42// Quantizer multipliers for 4-bit low band
43const QUANT_MULT_LOW_4BIT: [i32; 16] = [
44    0, -20456, -12896, -8968, -6288, -4240, -2584, -1200, 20456, 12896, 8968, 6288, 4240, 2584,
45    1200, 0,
46];
47
48// Quantizer multipliers for 2-bit high band
49const QUANT_MULT_HIGH_2BIT: [i32; 4] = [-7408, -1616, 7408, 1616];
50
51// QMF filter coefficients for band splitting and reconstruction
52const QMF_FILTER_COEFS: [i32; 12] = [3, -11, 12, 32, -210, 951, 3876, -805, 362, -156, 53, -11];
53
54// Negative high band quantization indices
55const HIGH_QUANT_INDEX_NEG: [i32; 3] = [0, 1, 0];
56
57// Positive high band quantization indices
58const HIGH_QUANT_INDEX_POS: [i32; 3] = [0, 3, 2];
59
60// Scale factor adaptation table for high band
61const SCALE_FACTOR_ADJUST_HIGH: [i32; 3] = [0, -214, 798];
62
63// Mapping from 2 bits of high band code to 2 bits of logarithmic scale factor
64const HIGH_LOG_SCALE_MAP: [i32; 4] = [2, 1, 2, 1];
65
66// Quantizer multipliers for 5-bit quantization (56kbps mode)
67const QUANT_MULT_56K: [i32; 32] = [
68    -280, -280, -23352, -17560, -14120, -11664, -9752, -8184, -6864, -5712, -4696, -3784, -2960,
69    -2208, -1520, -880, 23352, 17560, 14120, 11664, 9752, 8184, 6864, 5712, 4696, 3784, 2960, 2208,
70    1520, 880, 280, -280,
71];
72
73// Quantizer multipliers for 6-bit quantization (64kbps mode)
74const QUANT_MULT_64K: [i32; 64] = [
75    -136, -136, -136, -136, -24808, -21904, -19008, -16704, -14984, -13512, -12280, -11192, -10232,
76    -9360, -8576, -7856, -7192, -6576, -6000, -5456, -4944, -4464, -4008, -3576, -3168, -2776,
77    -2400, -2032, -1688, -1360, -1040, -728, 24808, 21904, 19008, 16704, 14984, 13512, 12280,
78    11192, 10232, 9360, 8576, 7856, 7192, 6576, 6000, 5456, 4944, 4464, 4008, 3576, 3168, 2776,
79    2400, 2032, 1688, 1360, 1040, 728, 432, 136, -432, -136,
80];
81
82impl Bitrate {
83    fn bits_per_sample(&self) -> i32 {
84        match self {
85            Bitrate::Mode1_64000 => 8,
86            Bitrate::Mode2_56000 => 7,
87            Bitrate::Mode3_48000 => 6,
88        }
89    }
90}
91
92/// G.722 ADPCM band state structure used in the codec
93/// Each band (lower and upper) uses an independent state structure
94#[derive(Default)]
95struct G722Band {
96    /// Current signal prediction value (signal estimate)
97    signal_estimate: i32,
98    /// Pole filter output (result from IIR filter part)
99    pole_filter_output: i32,
100    /// Zero filter output (result from FIR filter part)
101    zero_filter_output: i32,
102    /// Reconstructed signal history [current, previous, previous-1]
103    reconstructed_signal: [i32; 3],
104    /// Pole filter coefficients [unused(0), a1, a2]
105    pole_coefficients: [i32; 3],
106    /// Temporary pole filter coefficients [unused(0), a1', a2']
107    pole_coefficients_temp: [i32; 3],
108    /// Partially reconstructed signal history [current, previous, previous-1]
109    partial_reconstructed: [i32; 3],
110    /// Difference signal history [current, previous, ..., previous-5]
111    difference_signal: [i32; 7],
112    /// Zero filter coefficients [unused(0), b1, b2, ..., b6]
113    zero_coefficients: [i32; 7],
114    /// Temporary zero filter coefficients [unused(0), b1', b2', ..., b6']
115    zero_coefficients_temp: [i32; 7],
116    /// Log scale factor (used for quantization and dequantization)
117    log_scale_factor: i32,
118    /// Quantizer step size (used for adaptive quantization)
119    quantizer_step_size: i32,
120}
121
122#[inline(always)]
123fn saturate(amp: i32) -> i32 {
124    amp.clamp(i16::MIN as i32, i16::MAX as i32)
125}
126
127/// Process Block 4 operations for G.722 ADPCM algorithm
128/// This function performs the predictor adaptation and reconstruction steps
129/// as defined in the G.722 standard
130#[inline]
131fn block4(band: &mut G722Band, d: i32) {
132    // Block 4, RECONS - Reconstruct the signal
133    band.difference_signal[0] = d;
134    band.reconstructed_signal[0] = saturate(band.signal_estimate + d);
135
136    // Block 4, PARREC - Partial reconstruction
137    let partial_rec0 = saturate(band.zero_filter_output + d);
138    band.partial_reconstructed[0] = partial_rec0;
139
140    // Block 4, UPPOL2 - Update second predictor coefficient
141    let s0 = partial_rec0 >> 15;
142    let s1 = band.partial_reconstructed[1] >> 15;
143    let s2 = band.partial_reconstructed[2] >> 15;
144
145    let a1_scaled = saturate(band.pole_coefficients[1] << 2);
146
147    let mut a2_update = if s0 == s1 { -a1_scaled } else { a1_scaled };
148    a2_update = a2_update.min(32767);
149
150    let mut a2_adj = a2_update >> 7;
151    a2_adj += if s0 == s2 { 128 } else { -128 };
152    a2_adj += (band.pole_coefficients[2] * 32512) >> 15;
153
154    band.pole_coefficients_temp[2] = a2_adj.clamp(-12288, 12288);
155
156    // Block 4, UPPOL1 - Update first predictor coefficient
157    let sign_factor = if s0 == s1 { 192 } else { -192 };
158    let leakage = (band.pole_coefficients[1] * 32640) >> 15;
159    band.pole_coefficients_temp[1] = saturate(sign_factor + leakage);
160
161    let limit = saturate(15360 - band.pole_coefficients_temp[2]);
162    band.pole_coefficients_temp[1] = band.pole_coefficients_temp[1].clamp(-limit, limit);
163
164    // Block 4, UPZERO - Update zero section (FIR) coefficients
165    let step_size = if d == 0 { 0 } else { 128 };
166    let sd = d >> 15;
167
168    {
169        macro_rules! update_zero {
170            ($i:expr) => {
171                let sz = band.difference_signal[$i] >> 15;
172                let adj = if sz == sd { step_size } else { -step_size };
173                let leakage = (band.zero_coefficients[$i] * 32640) >> 15;
174                band.zero_coefficients_temp[$i] = saturate(adj + leakage);
175            };
176        }
177        update_zero!(1);
178        update_zero!(2);
179        update_zero!(3);
180        update_zero!(4);
181        update_zero!(5);
182        update_zero!(6);
183    }
184
185    // Block 4, DELAYA - Delay updates for filter memory
186    band.difference_signal[6] = band.difference_signal[5];
187    band.difference_signal[5] = band.difference_signal[4];
188    band.difference_signal[4] = band.difference_signal[3];
189    band.difference_signal[3] = band.difference_signal[2];
190    band.difference_signal[2] = band.difference_signal[1];
191    band.difference_signal[1] = d;
192
193    band.zero_coefficients[1] = band.zero_coefficients_temp[1];
194    band.zero_coefficients[2] = band.zero_coefficients_temp[2];
195    band.zero_coefficients[3] = band.zero_coefficients_temp[3];
196    band.zero_coefficients[4] = band.zero_coefficients_temp[4];
197    band.zero_coefficients[5] = band.zero_coefficients_temp[5];
198    band.zero_coefficients[6] = band.zero_coefficients_temp[6];
199
200    band.reconstructed_signal[2] = band.reconstructed_signal[1];
201    band.reconstructed_signal[1] = band.reconstructed_signal[0];
202    band.partial_reconstructed[2] = band.partial_reconstructed[1];
203    band.partial_reconstructed[1] = partial_rec0;
204
205    band.pole_coefficients[1] = band.pole_coefficients_temp[1];
206    band.pole_coefficients[2] = band.pole_coefficients_temp[2];
207
208    // Block 4, FILTEP - Pole section (IIR) filtering
209    let r1_adj = saturate(band.reconstructed_signal[1] << 1);
210    let pole1 = (band.pole_coefficients[1] * r1_adj) >> 15;
211
212    let r2_adj = saturate(band.reconstructed_signal[2] << 1);
213    let pole2 = (band.pole_coefficients[2] * r2_adj) >> 15;
214
215    band.pole_filter_output = saturate(pole1 + pole2);
216
217    // Block 4, FILTEZ - Zero section (FIR) filtering
218    let mut zero_out = (band.zero_coefficients[1] * saturate(band.difference_signal[1] << 1)) >> 15;
219    zero_out += (band.zero_coefficients[2] * saturate(band.difference_signal[2] << 1)) >> 15;
220    zero_out += (band.zero_coefficients[3] * saturate(band.difference_signal[3] << 1)) >> 15;
221    zero_out += (band.zero_coefficients[4] * saturate(band.difference_signal[4] << 1)) >> 15;
222    zero_out += (band.zero_coefficients[5] * saturate(band.difference_signal[5] << 1)) >> 15;
223    zero_out += (band.zero_coefficients[6] * saturate(band.difference_signal[6] << 1)) >> 15;
224
225    band.zero_filter_output = saturate(zero_out);
226
227    // Block 4, PREDIC - Prediction
228    band.signal_estimate = saturate(band.pole_filter_output + band.zero_filter_output);
229}
230
231pub struct G722Encoder {
232    packed: bool,
233    eight_k: bool,
234    bits_per_sample: i32,
235    x: [i32; 24],
236    band: [G722Band; 2],
237    out_buffer: u32,
238    out_bits: i32,
239}
240
241pub struct G722Decoder {
242    packed: bool,
243    eight_k: bool,
244    bits_per_sample: i32,
245    x: [i32; 24],
246    band: [G722Band; 2],
247    in_buffer: u32,
248    in_bits: i32,
249}
250
251impl G722Encoder {
252    pub fn new() -> Self {
253        Self::with_options(Bitrate::Mode1_64000, false, false)
254    }
255
256    /// Creates an encoder with specified bitrate and options
257    pub fn with_options(rate: Bitrate, eight_k: bool, packed: bool) -> Self {
258        let mut encoder = Self {
259            packed,
260            eight_k,
261            bits_per_sample: rate.bits_per_sample(),
262            x: [0; 24],
263            band: [G722Band::default(), G722Band::default()],
264            out_buffer: 0,
265            out_bits: 0,
266        };
267
268        // Initialize band states with correct starting values
269        encoder.band[0].log_scale_factor = 32 << 2; // Initial det value for lower band
270        encoder.band[1].log_scale_factor = 8 << 2; // Initial det value for upper band
271
272        encoder
273    }
274
275    /// Encode 16-bit PCM samples into G.722 format
276    /// This function follows the G.722 standard algorithm exactly
277    fn g722_encode_into(&mut self, amp: &[i16], out: &mut [u8]) -> Result<usize, CodecError> {
278        // Cursor over `out`. We track a byte position plus a sub-byte bit
279        // buffer used only in packed mode. The cursor returns an error if
280        // `out` cannot accept another byte.
281        struct OutCursor<'a> {
282            buf: &'a mut [u8],
283            byte_pos: usize,
284            bit_buffer: u32,
285            bit_count: i32,
286        }
287        impl<'a> OutCursor<'a> {
288            #[inline]
289            fn push_byte(&mut self, b: u8) -> Result<(), CodecError> {
290                if self.byte_pos >= self.buf.len() {
291                    return Err(CodecError::BufferTooSmall);
292                }
293                self.buf[self.byte_pos] = b;
294                self.byte_pos += 1;
295                Ok(())
296            }
297        }
298
299        let packed = self.packed;
300        let bits_per_sample = self.bits_per_sample;
301        let mut cursor = OutCursor {
302            buf: out,
303            byte_pos: 0,
304            bit_buffer: self.out_buffer,
305            bit_count: self.out_bits,
306        };
307
308        // Helper closure: write one `bits_per_sample`-bit code.
309        let output_code = |code: i32, cursor: &mut OutCursor<'_>| -> Result<(), CodecError> {
310            if packed {
311                cursor.bit_buffer |= (code as u32) << cursor.bit_count;
312                cursor.bit_count += bits_per_sample;
313                if cursor.bit_count >= 8 {
314                    cursor.push_byte((cursor.bit_buffer & 0xFF) as u8)?;
315                    cursor.bit_count -= 8;
316                    cursor.bit_buffer >>= 8;
317                }
318            } else {
319                cursor.push_byte(code as u8)?;
320            }
321            Ok(())
322        };
323
324        let mut input_idx = 0usize;
325
326        if self.eight_k {
327            while input_idx < amp.len() {
328                // 8kHz mode - Just use input directly with scaling
329                let xlow = amp[input_idx] as i32 >> 1;
330                input_idx += 1;
331
332                // 8kHz mode - only low band matters
333                let code = self.encode_low_band(xlow, true);
334                output_code(code, &mut cursor)?;
335            }
336        } else {
337            // Process all input samples in 16kHz mode
338            // Use chunks_exact(2) for better performance and to avoid bound checks
339            let chunks = amp.chunks_exact(2);
340            let rem = chunks.remainder();
341
342            for chunk in chunks {
343                // Shuffle buffer down to make room for new samples
344                self.x.copy_within(2..24, 0);
345
346                // Add new samples to buffer
347                self.x[22] = chunk[0] as i32;
348                self.x[23] = chunk[1] as i32;
349
350                // Apply QMF filter to split input into bands
351                // Unrolled loop for 12 coefficients
352                let mut sumodd = self.x[0] * QMF_FILTER_COEFS[0];
353                sumodd += self.x[2] * QMF_FILTER_COEFS[1];
354                sumodd += self.x[4] * QMF_FILTER_COEFS[2];
355                sumodd += self.x[6] * QMF_FILTER_COEFS[3];
356                sumodd += self.x[8] * QMF_FILTER_COEFS[4];
357                sumodd += self.x[10] * QMF_FILTER_COEFS[5];
358                sumodd += self.x[12] * QMF_FILTER_COEFS[6];
359                sumodd += self.x[14] * QMF_FILTER_COEFS[7];
360                sumodd += self.x[16] * QMF_FILTER_COEFS[8];
361                sumodd += self.x[18] * QMF_FILTER_COEFS[9];
362                sumodd += self.x[20] * QMF_FILTER_COEFS[10];
363                sumodd += self.x[22] * QMF_FILTER_COEFS[11];
364
365                let mut sumeven = self.x[1] * QMF_FILTER_COEFS[11];
366                sumeven += self.x[3] * QMF_FILTER_COEFS[10];
367                sumeven += self.x[5] * QMF_FILTER_COEFS[9];
368                sumeven += self.x[7] * QMF_FILTER_COEFS[8];
369                sumeven += self.x[9] * QMF_FILTER_COEFS[7];
370                sumeven += self.x[11] * QMF_FILTER_COEFS[6];
371                sumeven += self.x[13] * QMF_FILTER_COEFS[5];
372                sumeven += self.x[15] * QMF_FILTER_COEFS[4];
373                sumeven += self.x[17] * QMF_FILTER_COEFS[3];
374                sumeven += self.x[19] * QMF_FILTER_COEFS[2];
375                sumeven += self.x[21] * QMF_FILTER_COEFS[1];
376                sumeven += self.x[23] * QMF_FILTER_COEFS[0];
377
378                // Scale filter outputs to get low and high bands
379                let xlow = (sumeven + sumodd) >> 14;
380                let xhigh = (sumeven - sumodd) >> 14;
381
382                // 16kHz mode - encode both bands
383                let ilow = self.encode_low_band(xlow, false);
384                let ihigh = self.encode_high_band(xhigh);
385                let code = (ihigh << 6 | ilow) >> (8 - self.bits_per_sample);
386
387                // Output the encoded code
388                output_code(code, &mut cursor)?;
389            }
390
391            if !rem.is_empty() {
392                self.x.copy_within(2..24, 0);
393                self.x[22] = rem[0] as i32;
394                self.x[23] = 0;
395                let mut sumodd = self.x[0] * QMF_FILTER_COEFS[0];
396                sumodd += self.x[2] * QMF_FILTER_COEFS[1];
397                sumodd += self.x[4] * QMF_FILTER_COEFS[2];
398                sumodd += self.x[6] * QMF_FILTER_COEFS[3];
399                sumodd += self.x[8] * QMF_FILTER_COEFS[4];
400                sumodd += self.x[10] * QMF_FILTER_COEFS[5];
401                sumodd += self.x[12] * QMF_FILTER_COEFS[6];
402                sumodd += self.x[14] * QMF_FILTER_COEFS[7];
403                sumodd += self.x[16] * QMF_FILTER_COEFS[8];
404                sumodd += self.x[18] * QMF_FILTER_COEFS[9];
405                sumodd += self.x[20] * QMF_FILTER_COEFS[10];
406                sumodd += self.x[22] * QMF_FILTER_COEFS[11];
407
408                let mut sumeven = self.x[1] * QMF_FILTER_COEFS[11];
409                sumeven += self.x[3] * QMF_FILTER_COEFS[10];
410                sumeven += self.x[5] * QMF_FILTER_COEFS[9];
411                sumeven += self.x[7] * QMF_FILTER_COEFS[8];
412                sumeven += self.x[9] * QMF_FILTER_COEFS[7];
413                sumeven += self.x[11] * QMF_FILTER_COEFS[6];
414                sumeven += self.x[13] * QMF_FILTER_COEFS[5];
415                sumeven += self.x[15] * QMF_FILTER_COEFS[4];
416                sumeven += self.x[17] * QMF_FILTER_COEFS[3];
417                sumeven += self.x[19] * QMF_FILTER_COEFS[2];
418                sumeven += self.x[21] * QMF_FILTER_COEFS[1];
419                sumeven += self.x[23] * QMF_FILTER_COEFS[0];
420
421                let xlow = (sumeven + sumodd) >> 14;
422                let xhigh = (sumeven - sumodd) >> 14;
423                let ilow = self.encode_low_band(xlow, false);
424                let ihigh = self.encode_high_band(xhigh);
425                let code = (ihigh << 6 | ilow) >> (8 - self.bits_per_sample);
426                output_code(code, &mut cursor)?;
427            }
428        }
429
430        // Handle any remaining bits in the output buffer
431        if self.packed && cursor.bit_count > 0 {
432            cursor.push_byte((cursor.bit_buffer & 0xFF) as u8)?;
433        }
434
435        // Persist bit buffer state for streaming across calls.
436        self.out_buffer = cursor.bit_buffer;
437        self.out_bits = cursor.bit_count;
438
439        Ok(cursor.byte_pos)
440    }
441
442    /// Encode low band sample and update state
443    /// Returns the encoded low band bits
444    #[inline]
445    fn encode_low_band(&mut self, xlow: i32, is_eight_k: bool) -> i32 {
446        // Block 1L, SUBTRA - Calculate difference signal
447        let el = saturate(xlow - self.band[0].signal_estimate);
448
449        // Block 1L, QUANTL - Quantize difference signal
450        let wd = el.abs().wrapping_sub((el >> 31) & 1);
451
452        // Find quantization interval using linear search (more predictable for audio)
453        let lsf = self.band[0].log_scale_factor;
454        let mut quantization_idx = 1;
455        while quantization_idx < 30 {
456            let decision_level = (QUANT_DECISION_LEVEL[quantization_idx] * lsf) >> 12;
457            if wd < decision_level {
458                break;
459            }
460            quantization_idx += 1;
461        }
462
463        // Select output bits based on sign
464        let ilow = if el < 0 {
465            QUANT_INDEX_NEG[quantization_idx]
466        } else {
467            QUANT_INDEX_POS[quantization_idx]
468        };
469
470        // Block 2L, INVQAL - Inverse quantize for prediction
471        let ril = ilow >> 2;
472        let wd2 = QUANT_MULT_LOW_4BIT[ril as usize];
473        let dlow = (self.band[0].log_scale_factor * wd2) >> 15;
474
475        // Block 3L, LOGSCL - Update scale factor
476        let il4 = LOG_SCALE_FACTOR_MAP[ril as usize];
477        let mut nb = (self.band[0].quantizer_step_size * 127) >> 7;
478        nb += SCALE_FACTOR_ADJUST_LOW[il4 as usize];
479        self.band[0].quantizer_step_size = nb.clamp(0, 18432);
480
481        // Block 3L, SCALEL - Compute new quantizer scale factor
482        let wd1 = self.band[0].quantizer_step_size >> 6 & 31;
483        let wd2 = 8 - (self.band[0].quantizer_step_size >> 11);
484        let wd3 = if wd2 < 0 {
485            INV_LOG_BASE[wd1 as usize] << -wd2
486        } else {
487            INV_LOG_BASE[wd1 as usize] >> wd2
488        };
489        self.band[0].log_scale_factor = wd3 << 2;
490
491        // Apply predictor adaptation (ADPCM core algorithm)
492        block4(&mut self.band[0], dlow);
493
494        // Return appropriate value based on mode
495        if is_eight_k {
496            ((0xc0 | ilow) >> 8) - self.bits_per_sample
497        } else {
498            ilow
499        }
500    }
501
502    /// Encode high band sample and update state
503    /// Returns the encoded high band bits
504    #[inline]
505    fn encode_high_band(&mut self, xhigh: i32) -> i32 {
506        // Block 1H, SUBTRA - Calculate difference signal
507        let eh = saturate(xhigh - self.band[1].signal_estimate);
508
509        // Block 1H, QUANTH - Quantize difference signal
510        let wd = if eh >= 0 { eh } else { -(eh + 1) };
511        let decision_level = (564 * self.band[1].log_scale_factor) >> 12;
512
513        // Determine quantization level for high band (2-bit)
514        let mih = if wd >= decision_level { 2 } else { 1 };
515        let ihigh = if eh < 0 {
516            HIGH_QUANT_INDEX_NEG[mih as usize]
517        } else {
518            HIGH_QUANT_INDEX_POS[mih as usize]
519        };
520
521        // Block 2H, INVQAH - Inverse quantize for prediction
522        let wd2 = QUANT_MULT_HIGH_2BIT[ihigh as usize];
523        let dhigh = (self.band[1].log_scale_factor * wd2) >> 15;
524
525        // Block 3H, LOGSCH - Update scale factor
526        let ih2 = HIGH_LOG_SCALE_MAP[ihigh as usize];
527        let mut nb = (self.band[1].quantizer_step_size * 127) >> 7;
528        nb += SCALE_FACTOR_ADJUST_HIGH[ih2 as usize];
529        self.band[1].quantizer_step_size = nb.clamp(0, 22528);
530
531        // Block 3H, SCALEH - Compute quantizer scale factor
532        let wd1 = self.band[1].quantizer_step_size >> 6 & 31;
533        let wd2 = 10 - (self.band[1].quantizer_step_size >> 11);
534        let wd3 = if wd2 < 0 {
535            INV_LOG_BASE[wd1 as usize] << -wd2
536        } else {
537            INV_LOG_BASE[wd1 as usize] >> wd2
538        };
539        self.band[1].log_scale_factor = wd3 << 2;
540
541        // Apply predictor adaptation (ADPCM core algorithm)
542        block4(&mut self.band[1], dhigh);
543
544        ihigh
545    }
546}
547
548impl G722Decoder {
549    pub fn new() -> Self {
550        Self::with_options(Bitrate::Mode1_64000, false, false)
551    }
552
553    pub fn with_options(rate: Bitrate, packed: bool, eight_k: bool) -> Self {
554        Self {
555            packed,
556            eight_k,
557            bits_per_sample: rate.bits_per_sample(),
558            x: Default::default(),
559            band: Default::default(),
560            in_buffer: 0,
561            in_bits: 0,
562        }
563    }
564
565    /// Extracts the next G.722 code from the input data stream
566    #[inline]
567    fn extract_code(&mut self, data: &[u8], idx: &mut usize) -> i32 {
568        if self.packed {
569            // When packed, bits are combined across bytes
570            if self.in_bits < self.bits_per_sample {
571                self.in_buffer |= (data[*idx] as u32) << self.in_bits;
572                *idx += 1;
573                self.in_bits += 8;
574            }
575            let code = (self.in_buffer & ((1 << self.bits_per_sample) - 1) as u32) as i32;
576            self.in_buffer >>= self.bits_per_sample;
577            self.in_bits -= self.bits_per_sample;
578            code
579        } else {
580            // Direct byte-based access when not packed
581            let code = data[*idx] as i32;
582            *idx += 1;
583            code
584        }
585    }
586
587    /// Parses the G.722 code into low-band word and high-band index based on bit rate
588    #[inline]
589    fn parse_code(&self, code: i32) -> (i32, i32, i32) {
590        // Returns (wd1, ihigh, wd2) tuple: low-band word, high-band index, and scaled value
591        match self.bits_per_sample {
592            7 => {
593                // 56 kbit/s mode
594                let wd1 = code & 0x1f;
595                let ihigh = (code >> 5) & 0x3;
596                let wd2 = QUANT_MULT_56K[wd1 as usize];
597                (wd1 >> 1, ihigh, wd2)
598            }
599            6 => {
600                // 48 kbit/s mode
601                let wd1 = code & 0xf;
602                let ihigh = (code >> 4) & 0x3;
603                let wd2 = QUANT_MULT_LOW_4BIT[wd1 as usize];
604                (wd1, ihigh, wd2)
605            }
606            _ => {
607                // 64 kbit/s mode (default)
608                let wd1 = code & 0x3f;
609                let ihigh = (code >> 6) & 0x3;
610                let wd2 = QUANT_MULT_64K[wd1 as usize];
611                (wd1 >> 2, ihigh, wd2)
612            }
613        }
614    }
615
616    /// Process the low band component of the G.722 stream
617    #[inline]
618    fn process_low_band(&mut self, wd1: i32, wd2: i32) -> i32 {
619        // Block 5L, LOW BAND INVQBL - Inverse quantization for low band
620        let dequant = (self.band[0].log_scale_factor * wd2) >> 15;
621
622        // Block 5L, RECONS - Reconstruction of low band signal
623        let rlow = self.band[0].signal_estimate + dequant;
624
625        // Block 6L, LIMIT - Limiting to valid range
626        let rlow = rlow.clamp(-16384, 16383);
627
628        // Block 2L, INVQAL - Inverse adaptive quantizer for prediction
629        let wd2 = QUANT_MULT_LOW_4BIT[wd1 as usize];
630        let dlowt = (self.band[0].log_scale_factor * wd2) >> 15;
631
632        // Block 3L, LOGSCL - Compute log scale factor
633        let wd2 = LOG_SCALE_FACTOR_MAP[wd1 as usize];
634        let mut wd1 = (self.band[0].quantizer_step_size * 127) >> 7;
635        wd1 += SCALE_FACTOR_ADJUST_LOW[wd2 as usize];
636        self.band[0].quantizer_step_size = wd1.clamp(0, 18432);
637
638        // Block 3L, SCALEL - Compute quantizer scale factor
639        let wd1 = (self.band[0].quantizer_step_size >> 6) & 31;
640        let wd2 = 8 - (self.band[0].quantizer_step_size >> 11);
641        let wd3 = if wd2 < 0 {
642            INV_LOG_BASE[wd1 as usize] << -wd2
643        } else {
644            INV_LOG_BASE[wd1 as usize] >> wd2
645        };
646        self.band[0].log_scale_factor = wd3 << 2;
647
648        // Apply predictor adaptation
649        block4(&mut self.band[0], dlowt);
650
651        rlow
652    }
653
654    /// Process the high band component of the G.722 stream
655    #[inline]
656    fn process_high_band(&mut self, ihigh: i32) -> i32 {
657        // Block 2H, INVQAH - Inverse quantizer for high band
658        let wd2 = QUANT_MULT_HIGH_2BIT[ihigh as usize];
659        let dhigh = (self.band[1].log_scale_factor * wd2) >> 15;
660
661        // Block 5H, RECONS - Reconstruction of high band signal
662        let rhigh = dhigh + self.band[1].signal_estimate;
663
664        // Block 6H, LIMIT - Limiting to valid range
665        let rhigh = rhigh.clamp(-16384, 16383);
666
667        // Block 2H, INVQAH - Adaptation logic
668        let wd2 = HIGH_LOG_SCALE_MAP[ihigh as usize];
669        let mut wd1 = (self.band[1].quantizer_step_size * 127) >> 7;
670        wd1 += SCALE_FACTOR_ADJUST_HIGH[wd2 as usize];
671        self.band[1].quantizer_step_size = wd1.clamp(0, 22528);
672
673        // Block 3H, SCALEH - Compute quantizer scale factor
674        let wd1 = (self.band[1].quantizer_step_size >> 6) & 31;
675        let wd2 = 10 - (self.band[1].quantizer_step_size >> 11);
676        let wd3 = if wd2 < 0 {
677            INV_LOG_BASE[wd1 as usize] << -wd2
678        } else {
679            INV_LOG_BASE[wd1 as usize] >> wd2
680        };
681        self.band[1].log_scale_factor = wd3 << 2;
682
683        // Apply predictor adaptation
684        block4(&mut self.band[1], dhigh);
685
686        rhigh
687    }
688
689    /// Apply QMF synthesis filter to combine low and high band signals
690    #[inline]
691    fn apply_qmf_synthesis(&mut self, rlow: i32, rhigh: i32) -> [i16; 2] {
692        // Shift filter state
693        self.x.copy_within(2..24, 0);
694
695        // Set new filter state values
696        self.x[22] = rlow + rhigh;
697        self.x[23] = rlow - rhigh;
698
699        // Apply QMF synthesis filter (unrolled loop for 12 coefficients)
700        let mut xout2 = self.x[0] * QMF_FILTER_COEFS[0];
701        xout2 += self.x[2] * QMF_FILTER_COEFS[1];
702        xout2 += self.x[4] * QMF_FILTER_COEFS[2];
703        xout2 += self.x[6] * QMF_FILTER_COEFS[3];
704        xout2 += self.x[8] * QMF_FILTER_COEFS[4];
705        xout2 += self.x[10] * QMF_FILTER_COEFS[5];
706        xout2 += self.x[12] * QMF_FILTER_COEFS[6];
707        xout2 += self.x[14] * QMF_FILTER_COEFS[7];
708        xout2 += self.x[16] * QMF_FILTER_COEFS[8];
709        xout2 += self.x[18] * QMF_FILTER_COEFS[9];
710        xout2 += self.x[20] * QMF_FILTER_COEFS[10];
711        xout2 += self.x[22] * QMF_FILTER_COEFS[11];
712
713        let mut xout1 = self.x[1] * QMF_FILTER_COEFS[11];
714        xout1 += self.x[3] * QMF_FILTER_COEFS[10];
715        xout1 += self.x[5] * QMF_FILTER_COEFS[9];
716        xout1 += self.x[7] * QMF_FILTER_COEFS[8];
717        xout1 += self.x[9] * QMF_FILTER_COEFS[7];
718        xout1 += self.x[11] * QMF_FILTER_COEFS[6];
719        xout1 += self.x[13] * QMF_FILTER_COEFS[5];
720        xout1 += self.x[15] * QMF_FILTER_COEFS[4];
721        xout1 += self.x[17] * QMF_FILTER_COEFS[3];
722        xout1 += self.x[19] * QMF_FILTER_COEFS[2];
723        xout1 += self.x[21] * QMF_FILTER_COEFS[1];
724        xout1 += self.x[23] * QMF_FILTER_COEFS[0];
725
726        // Return reconstructed samples with proper scaling
727        [saturate(xout1 >> 11) as i16, saturate(xout2 >> 11) as i16]
728    }
729
730    /// Decodes a G.722 frame into the caller-provided buffer.
731    ///
732    /// Returns the number of samples written to `out`. Returns
733    /// [`CodecError::BufferTooSmall`] if `out` cannot accept all decoded
734    /// samples.
735    pub fn decode_frame_into(
736        &mut self,
737        data: &[u8],
738        out: &mut [Sample],
739    ) -> Result<usize, CodecError> {
740        let mut written = 0usize;
741        let mut idx = 0usize;
742
743        if self.eight_k {
744            while idx < data.len() {
745                let code = self.extract_code(data, &mut idx);
746                let (wd1, _, wd2) = self.parse_code(code);
747                let rlow = self.process_low_band(wd1, wd2);
748                if written >= out.len() {
749                    return Err(CodecError::BufferTooSmall);
750                }
751                out[written] = (rlow << 1) as i16;
752                written += 1;
753            }
754        } else {
755            while idx < data.len() {
756                let code = self.extract_code(data, &mut idx);
757                let (wd1, ihigh, wd2) = self.parse_code(code);
758                let rlow = self.process_low_band(wd1, wd2);
759                let rhigh = self.process_high_band(ihigh);
760                let pcm = self.apply_qmf_synthesis(rlow, rhigh);
761                if out.len() < written + 2 {
762                    return Err(CodecError::BufferTooSmall);
763                }
764                out[written] = pcm[0];
765                out[written + 1] = pcm[1];
766                written += 2;
767            }
768        }
769        Ok(written)
770    }
771
772    /// Decodes a G.722 frame into a freshly-allocated `Vec`.
773    ///
774    /// Only available with the `std` feature.
775    #[cfg(feature = "std")]
776    pub fn decode_frame(&mut self, data: &[u8]) -> PcmBuf {
777        let max = self.max_decode_samples(data.len());
778        let mut out = vec![0i16; max];
779        match self.decode_frame_into(data, &mut out) {
780            Ok(n) => {
781                out.truncate(n);
782                out
783            }
784            Err(_) => Vec::new(),
785        }
786    }
787}
788
789impl Default for G722Encoder {
790    fn default() -> Self {
791        Self::new()
792    }
793}
794
795impl Default for G722Decoder {
796    fn default() -> Self {
797        Self::new()
798    }
799}
800
801impl Encoder for G722Encoder {
802    fn encode_into(&mut self, samples: &[Sample], out: &mut [u8]) -> Result<usize, CodecError> {
803        self.g722_encode_into(samples, out)
804    }
805
806    fn max_encode_bytes(&self, n_samples: usize) -> usize {
807        // Non-packed: one byte per 16kHz code. 8kHz mode emits one byte per
808        // sample. Use the larger bound so the caller always allocates enough.
809        if self.eight_k {
810            n_samples + 1
811        } else {
812            n_samples / 2 + 1
813        }
814    }
815
816    fn sample_rate(&self) -> u32 {
817        16000 // G.722 encoding sample rate is 16kHz
818    }
819
820    fn channels(&self) -> u16 {
821        1 // G.722 is mono encoding
822    }
823}
824
825impl Decoder for G722Decoder {
826    fn decode_into(&mut self, data: &[u8], out: &mut [Sample]) -> Result<usize, CodecError> {
827        self.decode_frame_into(data, out)
828    }
829
830    fn max_decode_samples(&self, n_bytes: usize) -> usize {
831        // 16kHz mode: 2 samples per byte. 8kHz mode: 1 sample per byte.
832        // Use the larger bound so callers always size the buffer adequately.
833        if self.eight_k { n_bytes } else { n_bytes * 2 }
834    }
835
836    fn sample_rate(&self) -> u32 {
837        16000
838    }
839
840    fn channels(&self) -> u16 {
841        1
842    }
843}