forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mantissa.rs230 lines, 8.6 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/// Initial `state[8..64]` of ffmpeg's `av_lfg_init(_, 0)`. Each of the fourteen
9/// MD5 blocks hashes a 16-byte record: the seed word in bytes 0..4, the block
10/// index in byte 4, and whatever the previous digest left in bytes 5..16, since
11/// ffmpeg reuses one buffer in place. `state[0..8]` start at zero, as they do in
12/// ffmpeg's zeroed decoder context. Checked against libavutil's `av_lfg_init`.
13const LFG_SEED: [u32; 56] = [
14 0x3b376b5e, 0xf56be763, 0xcba2a7fc, 0x9751b2c7,
15 0x5b1fe69a, 0x860b05af, 0x2b2650ca, 0x92a97fb0,
16 0x7315e8eb, 0x8b6287a3, 0x2ddbd8b3, 0x1d098ca2,
17 0x6a65b478, 0xc9b22db4, 0x9637fbcf, 0xd4427934,
18 0xb390e2b5, 0x92a84d32, 0x2110b086, 0x25a9182f,
19 0x239295f1, 0xc6f846f7, 0x5c5b3a51, 0xe6a7ba34,
20 0xd6597325, 0xa537e3df, 0xcb80e534, 0xeaecf2dc,
21 0x9bbb6bd1, 0x2ea8bd11, 0x8c06ce60, 0x6859af1d,
22 0xf159f64e, 0xc213bd06, 0x2a5d7785, 0xe621dc54,
23 0xb8cb9a8e, 0xe6a491f8, 0x85d7df25, 0x917d9aee,
24 0xb156c513, 0x5bd929dd, 0xf6a9dab1, 0xc3ec5f2a,
25 0x5215230d, 0xe2b677d7, 0x701e36e7, 0x5405e2c7,
26 0xddcb3ae2, 0x95b866ea, 0x1eb13c9a, 0x346646c2,
27 0x8ba48526, 0xb325e9bf, 0x29f07d49, 0xc986cf38,
28];
29
30/// The pseudo-random source for `bap == 0` mantissas (§7.3.4) and for the
31/// Annex E noise.
32///
33/// The standard asks only for "any reasonably random sequence". This is the
34/// lagged-Fibonacci generator ffmpeg's AC-3 decoder draws from (`AVLFG`, seeded
35/// with 0 when the decoder starts and never reseeded), in the same order. A
36/// decode of a stream therefore reproduces ffmpeg's zero-bit noise sample for
37/// sample instead of differing from it by an independent noise sequence.
38#[derive(Debug, Clone)]
39pub struct Dither {
40 state: [u32; 64],
41 index: usize,
42}
43
44impl Default for Dither {
45 fn default() -> Self {
46 let mut state = [0u32; 64];
47 state[8..].copy_from_slice(&LFG_SEED);
48 Dither { state, index: 0 }
49 }
50}
51
52impl Dither {
53 /// Next dither value, uniform in ±0.707 (ffmpeg's mantissa scaled by 2^-23).
54 pub fn value(&mut self) -> f32 {
55 self.mantissa() as f32 / 8_388_608.0
56 }
57
58 /// Next value from a zero-mean, unit-variance source — what Annex E
59 /// §3.6.4.2.4 calls `noise()`. A uniform distribution on `[-1, 1]` has
60 /// variance 1/3, so it is scaled by `sqrt(3)`.
61 pub fn unit_variance(&mut self) -> f32 {
62 self.mantissa() as f32 / 5_931_008.0 * 1.732_050_8
63 }
64
65 /// ffmpeg's integer dither mantissa: `((x >> 8) * 181 >> 8) - 5931008`.
66 fn mantissa(&mut self) -> i32 {
67 let x = self.next_word();
68 let u = ((x >> 8) * 181) >> 8;
69 u as i32 - 5_931_008
70 }
71
72 /// `av_lfg_get`: `state[i] = state[i-24] + state[i-55]`, returning the new word.
73 fn next_word(&mut self) -> u32 {
74 let i = self.index & 63;
75 let v = self.state[(i + 40) & 63].wrapping_add(self.state[(i + 9) & 63]);
76 self.state[i] = v;
77 self.index = self.index.wrapping_add(1);
78 v
79 }
80}
81
82/// Reads one exponent set's mantissas, holding the two-and-three value groups
83/// that baps 1, 2 and 4 pack into a single code word.
84///
85/// A reader belongs to one channel's run of mantissas: the standard restarts
86/// grouping at each exponent set, so a partly consumed group is dropped when
87/// the next channel begins.
88#[derive(Debug, Clone, Copy, Default)]
89pub struct Mantissas {
90 group3: [f32; 3],
91 left3: usize,
92 group5: [f32; 3],
93 left5: usize,
94 group11: [f32; 2],
95 left11: usize,
96}
97
98impl Mantissas {
99 /// A reader with no group in flight.
100 pub fn new() -> Mantissas {
101 Mantissas::default()
102 }
103
104 /// One mantissa value in `[-1, 1)`, before the exponent is applied.
105 ///
106 /// `bap == 0` returns 0.0; the caller decides whether that bin gets dither,
107 /// because in the coupled range the decision belongs to the channel rather
108 /// than to the coupling channel the mantissa came from.
109 pub fn read(&mut self, r: &mut BitReader<'_>, bap: u8) -> Result<f32> {
110 Ok(match bap {
111 0 => 0.0,
112 1 => {
113 if self.left3 == 0 {
114 let code = r.read_bits(5)?.min(26);
115 let levels = QUANT_LEVELS[1];
116 self.group3 = [
117 symmetric_level(levels, code / 9),
118 symmetric_level(levels, (code % 9) / 3),
119 symmetric_level(levels, code % 3),
120 ];
121 self.left3 = 3;
122 }
123 self.left3 -= 1;
124 self.group3[2 - self.left3]
125 }
126 2 => {
127 if self.left5 == 0 {
128 let code = r.read_bits(7)?.min(124);
129 let levels = QUANT_LEVELS[2];
130 self.group5 = [
131 symmetric_level(levels, code / 25),
132 symmetric_level(levels, (code % 25) / 5),
133 symmetric_level(levels, code % 5),
134 ];
135 self.left5 = 3;
136 }
137 self.left5 -= 1;
138 self.group5[2 - self.left5]
139 }
140 4 => {
141 if self.left11 == 0 {
142 let code = r.read_bits(7)?.min(120);
143 let levels = QUANT_LEVELS[4];
144 self.group11 = [
145 symmetric_level(levels, code / 11),
146 symmetric_level(levels, code % 11),
147 ];
148 self.left11 = 2;
149 }
150 self.left11 -= 1;
151 self.group11[1 - self.left11]
152 }
153 3 | 5 => {
154 let bits = QNTZTAB[bap as usize];
155 let code = r.read_bits(bits)?;
156 symmetric_level(QUANT_LEVELS[bap as usize], code)
157 }
158 _ => {
159 // 6..=15: asymmetric two's complement, decimal point left of
160 // the MSB (§7.3.2).
161 let bits = QNTZTAB[(bap as usize).min(15)];
162 let value = r.read_signed(bits)?;
163 value as f32 / (1u32 << (bits - 1)) as f32
164 }
165 })
166 }
167}
168
169/// `2^-exponent`, the right shift §7.3 applies to every mantissa.
170pub fn scale(exponent: u8) -> f32 {
171 // Exponents are 0..=24, so a table lookup would buy nothing over the
172 // exponent arithmetic the compiler folds here.
173 f32::from_bits(127u32.wrapping_sub(u32::from(exponent)) << 23)
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179 use ec_core::BitWriter;
180
181 #[test]
182 fn grouped_quantizers_unpack_three_and_two_at_a_time() {
183 // One bap-1 group holding codes (2, 1, 0) => (+2/3, 0, -2/3), then one
184 // bap-4 group holding (10, 0) => (+10/11, -10/11).
185 let mut w = BitWriter::new();
186 w.write_bits(2 * 9 + 3, 5);
187 w.write_bits(10 * 11, 7);
188 let bytes = w.into_bytes();
189 let mut r = BitReader::new(&bytes);
190 let mut m = Mantissas::new();
191 let got: Vec<f32> = (0..3).map(|_| m.read(&mut r, 1).unwrap()).collect();
192 assert!((got[0] - 2.0 / 3.0).abs() < 1e-6);
193 assert!(got[1].abs() < 1e-6);
194 assert!((got[2] + 2.0 / 3.0).abs() < 1e-6);
195 let a = m.read(&mut r, 4).unwrap();
196 let b = m.read(&mut r, 4).unwrap();
197 assert!((a - 10.0 / 11.0).abs() < 1e-6);
198 assert!((b + 10.0 / 11.0).abs() < 1e-6);
199 }
200
201 #[test]
202 fn asymmetric_mantissas_span_minus_one_to_just_under_one() {
203 let mut w = BitWriter::new();
204 w.write_bits(0b100000, 6); // most negative 6-bit word
205 w.write_bits(0b011111, 6); // most positive
206 let bytes = w.into_bytes();
207 let mut r = BitReader::new(&bytes);
208 let mut m = Mantissas::new();
209 assert!((m.read(&mut r, 7).unwrap() + 1.0).abs() < 1e-6);
210 assert!((m.read(&mut r, 7).unwrap() - 31.0 / 32.0).abs() < 1e-6);
211 assert_eq!(m.read(&mut r, 0).unwrap(), 0.0);
212 }
213
214 #[test]
215 fn exponent_scale_is_a_power_of_two() {
216 assert_eq!(scale(0), 1.0);
217 assert_eq!(scale(1), 0.5);
218 assert_eq!(scale(24), 1.0 / 16_777_216.0);
219 }
220
221 #[test]
222 fn dither_stays_inside_its_stated_range_and_repeats() {
223 let mut d = Dither::default();
224 let first: Vec<f32> = (0..64).map(|_| d.value()).collect();
225 assert!(first.iter().all(|v| v.abs() <= 0.707));
226 assert!(first.iter().any(|v| v.abs() > 0.1));
227 let mut d2 = Dither::default();
228 assert_eq!(first, (0..64).map(|_| d2.value()).collect::<Vec<_>>());
229 }
230}