lc3_codec/encoder/
residual_spectrum.rs

1use crate::common::complex::Scaler;
2use bitvec::prelude::*;
3use core::iter::Take;
4
5pub struct ResidualBitsEncoder {
6    // NOTE: there can be no more than `ne` residual bits (400 lines)
7    // This can be confirmed by looking at the algorithm in encode
8    // 400 bits / 8 bits per byte = 50 bytes
9    res_bits: BitArray<[u8; 50], Lsb0>,
10}
11
12pub struct ResidualBits<'a> {
13    inner: Take<bitvec::slice::Iter<'a, u8, LocalBits>>,
14}
15
16impl<'a> Iterator for ResidualBits<'a> {
17    type Item = bool;
18
19    fn next(&mut self) -> Option<Self::Item> {
20        self.inner.next().map(|x| *x)
21    }
22}
23
24impl Default for ResidualBitsEncoder {
25    fn default() -> Self {
26        Self {
27            res_bits: BitArray::new([0; 50]),
28        }
29    }
30}
31
32impl ResidualBitsEncoder {
33    pub fn encode(
34        &mut self,
35        nbits_spec: usize,
36        nbits_spec_trunc: usize,
37        ne: usize,
38        gg: Scaler,
39        tns_xf: &[Scaler],
40        spec_quant_xq: &[i16],
41    ) -> ResidualBits {
42        let nbits_residual_max = nbits_spec as i32 - nbits_spec_trunc as i32 + 4;
43        let nbits_residual_max = 0.max(nbits_residual_max) as usize;
44        let mut nbits_residual = 0;
45
46        if nbits_residual_max > 0 {
47            for (tns, spec_quant) in tns_xf[..ne].iter().zip(spec_quant_xq[..ne].iter()) {
48                if nbits_residual >= nbits_residual_max {
49                    break;
50                }
51
52                if *spec_quant != 0 {
53                    let res_bit = *tns >= *spec_quant as Scaler * gg as Scaler;
54                    self.res_bits.set(nbits_residual, res_bit);
55                    nbits_residual += 1;
56                }
57            }
58        }
59
60        let inner = self.res_bits.as_bitslice().iter().take(nbits_residual);
61        ResidualBits { inner }
62    }
63}