forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

mantissa.rs184 lines, 6.7 KiBHistoryRawDownload
1//! Mantissa unpacking (A/52 §7.3), including the grouped quantizers and the
2//! dither the standard puts in place of zero-bit mantissas.
3
4use ec_core::{BitReader, Result};
5
6use crate::tables::{QNTZTAB, QUANT_LEVELS, symmetric_level};
7
8/// The pseudo-random source for `bap == 0` mantissas (§7.3.4).
9///
10/// The standard asks only for "any reasonably random sequence" scaled to a
11/// uniform distribution between ±0.707, so this is the classic 16-bit LFSR the
12/// AC-3 reference decoder uses. It is deterministic, which is what makes a
13/// decode reproducible from one run to the next.
14#[derive(Debug, Clone, Copy, Default)]
15pub struct Dither(u32);
16
17impl Dither {
18 /// Next dither value, uniform in ±0.707.
19 pub fn value(&mut self) -> f32 {
20 self.uniform() * 0.707
21 }
22
23 /// Next value from a zero-mean, unit-variance source — what Annex E
24 /// §3.6.4.2.4 calls `noise()`. A uniform distribution on `[-1, 1)` has
25 /// variance 1/3, so it is scaled by `sqrt(3)`.
26 pub fn unit_variance(&mut self) -> f32 {
27 self.uniform() * 1.732_050_8
28 }
29
30 fn uniform(&mut self) -> f32 {
31 self.0 = self.0.wrapping_mul(25173).wrapping_add(13849) & 0xffff;
32 f32::from(self.0 as u16 as i16) * (1.0 / 32768.0)
33 }
34}
35
36/// Reads one exponent set's mantissas, holding the two-and-three value groups
37/// that baps 1, 2 and 4 pack into a single code word.
38///
39/// A reader belongs to one channel's run of mantissas: the standard restarts
40/// grouping at each exponent set, so a partly consumed group is dropped when
41/// the next channel begins.
42#[derive(Debug, Clone, Copy, Default)]
43pub struct Mantissas {
44 group3: [f32; 3],
45 left3: usize,
46 group5: [f32; 3],
47 left5: usize,
48 group11: [f32; 2],
49 left11: usize,
50}
51
52impl Mantissas {
53 /// A reader with no group in flight.
54 pub fn new() -> Mantissas {
55 Mantissas::default()
56 }
57
58 /// One mantissa value in `[-1, 1)`, before the exponent is applied.
59 ///
60 /// `bap == 0` returns 0.0; the caller decides whether that bin gets dither,
61 /// because in the coupled range the decision belongs to the channel rather
62 /// than to the coupling channel the mantissa came from.
63 pub fn read(&mut self, r: &mut BitReader<'_>, bap: u8) -> Result<f32> {
64 Ok(match bap {
65 0 => 0.0,
66 1 => {
67 if self.left3 == 0 {
68 let code = r.read_bits(5)?.min(26);
69 let levels = QUANT_LEVELS[1];
70 self.group3 = [
71 symmetric_level(levels, code / 9),
72 symmetric_level(levels, (code % 9) / 3),
73 symmetric_level(levels, code % 3),
74 ];
75 self.left3 = 3;
76 }
77 self.left3 -= 1;
78 self.group3[2 - self.left3]
79 }
80 2 => {
81 if self.left5 == 0 {
82 let code = r.read_bits(7)?.min(124);
83 let levels = QUANT_LEVELS[2];
84 self.group5 = [
85 symmetric_level(levels, code / 25),
86 symmetric_level(levels, (code % 25) / 5),
87 symmetric_level(levels, code % 5),
88 ];
89 self.left5 = 3;
90 }
91 self.left5 -= 1;
92 self.group5[2 - self.left5]
93 }
94 4 => {
95 if self.left11 == 0 {
96 let code = r.read_bits(7)?.min(120);
97 let levels = QUANT_LEVELS[4];
98 self.group11 = [
99 symmetric_level(levels, code / 11),
100 symmetric_level(levels, code % 11),
101 ];
102 self.left11 = 2;
103 }
104 self.left11 -= 1;
105 self.group11[1 - self.left11]
106 }
107 3 | 5 => {
108 let bits = QNTZTAB[bap as usize];
109 let code = r.read_bits(bits)?;
110 symmetric_level(QUANT_LEVELS[bap as usize], code)
111 }
112 _ => {
113 // 6..=15: asymmetric two's complement, decimal point left of
114 // the MSB (§7.3.2).
115 let bits = QNTZTAB[(bap as usize).min(15)];
116 let value = r.read_signed(bits)?;
117 value as f32 / (1u32 << (bits - 1)) as f32
118 }
119 })
120 }
121}
122
123/// `2^-exponent`, the right shift §7.3 applies to every mantissa.
124pub fn scale(exponent: u8) -> f32 {
125 // Exponents are 0..=24, so a table lookup would buy nothing over the
126 // exponent arithmetic the compiler folds here.
127 f32::from_bits(127u32.wrapping_sub(u32::from(exponent)) << 23)
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133 use ec_core::BitWriter;
134
135 #[test]
136 fn grouped_quantizers_unpack_three_and_two_at_a_time() {
137 // One bap-1 group holding codes (2, 1, 0) => (+2/3, 0, -2/3), then one
138 // bap-4 group holding (10, 0) => (+10/11, -10/11).
139 let mut w = BitWriter::new();
140 w.write_bits(2 * 9 + 3, 5);
141 w.write_bits(10 * 11, 7);
142 let bytes = w.into_bytes();
143 let mut r = BitReader::new(&bytes);
144 let mut m = Mantissas::new();
145 let got: Vec<f32> = (0..3).map(|_| m.read(&mut r, 1).unwrap()).collect();
146 assert!((got[0] - 2.0 / 3.0).abs() < 1e-6);
147 assert!(got[1].abs() < 1e-6);
148 assert!((got[2] + 2.0 / 3.0).abs() < 1e-6);
149 let a = m.read(&mut r, 4).unwrap();
150 let b = m.read(&mut r, 4).unwrap();
151 assert!((a - 10.0 / 11.0).abs() < 1e-6);
152 assert!((b + 10.0 / 11.0).abs() < 1e-6);
153 }
154
155 #[test]
156 fn asymmetric_mantissas_span_minus_one_to_just_under_one() {
157 let mut w = BitWriter::new();
158 w.write_bits(0b100000, 6); // most negative 6-bit word
159 w.write_bits(0b011111, 6); // most positive
160 let bytes = w.into_bytes();
161 let mut r = BitReader::new(&bytes);
162 let mut m = Mantissas::new();
163 assert!((m.read(&mut r, 7).unwrap() + 1.0).abs() < 1e-6);
164 assert!((m.read(&mut r, 7).unwrap() - 31.0 / 32.0).abs() < 1e-6);
165 assert_eq!(m.read(&mut r, 0).unwrap(), 0.0);
166 }
167
168 #[test]
169 fn exponent_scale_is_a_power_of_two() {
170 assert_eq!(scale(0), 1.0);
171 assert_eq!(scale(1), 0.5);
172 assert_eq!(scale(24), 1.0 / 16_777_216.0);
173 }
174
175 #[test]
176 fn dither_stays_inside_its_stated_range_and_repeats() {
177 let mut d = Dither::default();
178 let first: Vec<f32> = (0..64).map(|_| d.value()).collect();
179 assert!(first.iter().all(|v| v.abs() <= 0.707));
180 assert!(first.iter().any(|v| v.abs() > 0.1));
181 let mut d2 = Dither::default();
182 assert_eq!(first, (0..64).map(|_| d2.value()).collect::<Vec<_>>());
183 }
184}