forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

aht.rs285 lines, 9.6 KiBHistoryRawDownload
1//! The adaptive hybrid transform of A/52 Annex E §3.4.
2//!
3//! AHT is E-AC-3's second transform stage: for a frame whose exponents never
4//! change, one bin's six block-mantissas are themselves DCT-coded, and the
5//! whole set arrives in the first block. That buys two quantizers the AC-3
6//! layer does not have — a six-dimensional vector quantizer for the coarse
7//! allocations and a gain-adaptive quantizer for the fine ones — so this module
8//! reads a channel's entire frame of mantissas at once and hands back the six
9//! blocks after inverting the DCT.
10
11use ec_core::{BitReader, Result};
12
13use crate::aht_tables::{GAQ_BITS, REMAP, VQ_BITS, vq_table};
14use crate::decode::COEFFS;
15use crate::mantissa::Dither;
16
17/// Blocks an AHT frame always has.
18pub(crate) const AHT_BLOCKS: usize = 6;
19
20/// One channel's mantissas for a whole frame: `[block * COEFFS + bin]`.
21pub(crate) type Frame = [f32];
22
23/// The `Gk` gain of a GAQ block (Table E3.3).
24fn gain_of(gaqmod: u32, mapped: u32) -> u32 {
25 match (gaqmod, mapped) {
26 (_, 0) => 1,
27 (1, _) | (3, 1) => 2,
28 _ => 4,
29 }
30}
31
32/// §3.4.4.2 remapping, `y = x + a*x + b`, with `a` and `b` as 16-bit fractions.
33fn remap(hebap: u8, gain: u32, x: f32) -> f32 {
34 let row = (hebap as usize).saturating_sub(8).min(11);
35 let column = match gain {
36 1 => 0,
37 2 => 1,
38 _ => 2,
39 };
40 let (a, b) = REMAP[row][column][usize::from(x < 0.0)];
41 x + x * (f32::from(a) / 32768.0) + f32::from(b) / 32768.0
42}
43
44/// One GAQ mantissa (§3.4.4.2 and Table E3.5).
45fn read_gaq(r: &mut BitReader<'_>, hebap: u8, gain: u32) -> Result<f32> {
46 let m = GAQ_BITS[(hebap as usize).min(19)];
47 if gain == 1 {
48 let code = r.read_signed(m)?;
49 return Ok(remap(hebap, 1, code as f32 / (1u32 << (m - 1)) as f32));
50 }
51 let small = if gain == 2 { m - 1 } else { m - 2 };
52 let code = r.read_signed(small)?;
53 // The full-scale negative symbol is the tag that says "large mantissa
54 // follows"; every other symbol is a small one, attenuated by 1/Gk.
55 if code == -(1i32 << (small - 1)) {
56 let large = if gain == 2 { m - 1 } else { m };
57 let value = r.read_signed(large)? as f32 / (1u32 << (large - 1)) as f32;
58 Ok(remap(hebap, gain, value))
59 } else {
60 Ok(code as f32 / (1u32 << (small - 1)) as f32 / gain as f32)
61 }
62}
63
64/// Read one AHT channel's whole frame of mantissas and invert the DCT.
65///
66/// `hebap` is the high-efficiency allocation for this channel, `range` its
67/// mantissa bins. `out` receives six blocks of `COEFFS` mantissas, exponents
68/// not yet applied — §3.4.5 inverts the DCT first.
69#[allow(clippy::too_many_arguments)]
70pub(crate) fn read_channel(
71 r: &mut BitReader<'_>,
72 hebap: &[u8],
73 range: (usize, usize),
74 dither: &mut Dither,
75 dither_on: bool,
76 out: &mut Frame,
77) -> Result<()> {
78 let (start, end) = range;
79 let gaqmod = r.read_bits(2)?;
80 let endbap = if gaqmod < 2 { 12 } else { 17 };
81
82 // §3.4.2: which bins carry a gain word, and how many gain sections that
83 // makes.
84 let active = hebap[start..end]
85 .iter()
86 .filter(|&&h| h > 7 && u32::from(h) < endbap)
87 .count();
88 let sections = match gaqmod {
89 0 => 0,
90 1 | 2 => active,
91 _ => active.div_ceil(3),
92 };
93 let mut gains = Vec::with_capacity(sections * 3);
94 for _ in 0..sections {
95 if gaqmod == 3 {
96 // Three 3-state gains in one 5-bit word, unpacked like exponents.
97 let word = r.read_bits(5)?.min(26);
98 gains.push(word / 9);
99 gains.push((word % 9) / 3);
100 gains.push((word % 9) % 3);
101 } else {
102 gains.push(r.read_bits(1)?);
103 }
104 }
105
106 let mut pre = [0.0f32; AHT_BLOCKS];
107 let mut next_gain = 0usize;
108 for bin in start..end {
109 let h = hebap[bin];
110 let mut zero_bits = false;
111 if h == 0 {
112 pre = [0.0; AHT_BLOCKS];
113 zero_bits = true;
114 } else if h <= 7 {
115 let index = r.read_bits(VQ_BITS[h as usize])? as usize;
116 let table = vq_table(h);
117 let vector = table[index.min(table.len() - 1)];
118 for (slot, v) in pre.iter_mut().zip(vector) {
119 *slot = f32::from(v) / 32768.0;
120 }
121 } else {
122 let gain = if gaqmod > 0 && u32::from(h) < endbap {
123 let mapped = gains.get(next_gain).copied().unwrap_or(0);
124 next_gain += 1;
125 gain_of(gaqmod, mapped)
126 } else {
127 1
128 };
129 for slot in &mut pre {
130 *slot = read_gaq(r, h, gain)?;
131 }
132 }
133
134 if zero_bits {
135 // A zero-bit AHT bin is the same silence AC-3 fills with dither.
136 for blk in 0..AHT_BLOCKS {
137 out[blk * COEFFS + bin] = if dither_on { dither.value() } else { 0.0 };
138 }
139 continue;
140 }
141 // §3.4.5: invert the six-point DCT across blocks.
142 for (blk, slot) in idct6(&pre).into_iter().enumerate() {
143 out[blk * COEFFS + bin] = slot;
144 }
145 }
146 Ok(())
147}
148
149/// The inverse of §3.4.5's DCT: six AHT coefficients into six block mantissas.
150fn idct6(x: &[f32; AHT_BLOCKS]) -> [f32; AHT_BLOCKS] {
151 // cos(j(2m+1)pi/12) for j, m in 0..6, with the 1/sqrt(2) weight on j = 0
152 // folded in. The leading factor is sqrt(2), not the 2 the standard's
153 // printed equation shows: measured against the oracle's decode of a real DDP
154 // stream, a factor of 2 makes every AHT channel exactly sqrt(2) too loud
155 // (per-frame RMS ratio 1.4142 across 3 649 frames). The radical is lost in
156 // the published equation's typesetting.
157 const COS: [[f32; AHT_BLOCKS]; AHT_BLOCKS] = cos_table();
158 let mut out = [0.0f32; AHT_BLOCKS];
159 for (m, slot) in out.iter_mut().enumerate() {
160 let mut acc = 0.0;
161 for (j, &v) in x.iter().enumerate() {
162 acc += v * COS[j][m];
163 }
164 *slot = std::f32::consts::SQRT_2 * acc;
165 }
166 out
167}
168
169/// Build the cosine table at compile time from a small polynomial-free form:
170/// the angles are multiples of 15 degrees, so every entry is one of six exact
171/// values.
172const fn cos_table() -> [[f32; AHT_BLOCKS]; AHT_BLOCKS] {
173 // cos(k * pi / 12) for k = 0..24, the only angles the transform uses.
174 use std::f32::consts::FRAC_1_SQRT_2;
175 const C: [f32; 25] = [
176 1.0,
177 0.965_925_8,
178 0.866_025_4,
179 FRAC_1_SQRT_2,
180 0.5,
181 0.258_819_04,
182 0.0,
183 -0.258_819_04,
184 -0.5,
185 -FRAC_1_SQRT_2,
186 -0.866_025_4,
187 -0.965_925_8,
188 -1.0,
189 -0.965_925_8,
190 -0.866_025_4,
191 -FRAC_1_SQRT_2,
192 -0.5,
193 -0.258_819_04,
194 0.0,
195 0.258_819_04,
196 0.5,
197 FRAC_1_SQRT_2,
198 0.866_025_4,
199 0.965_925_8,
200 1.0,
201 ];
202 let mut table = [[0.0f32; AHT_BLOCKS]; AHT_BLOCKS];
203 let mut j = 0;
204 while j < AHT_BLOCKS {
205 let mut m = 0;
206 while m < AHT_BLOCKS {
207 let k = (j * (2 * m + 1)) % 24;
208 let value = C[k];
209 // R_j: 1/sqrt(2) for the DC term, 1 otherwise.
210 table[j][m] = if j == 0 { value * FRAC_1_SQRT_2 } else { value };
211 m += 1;
212 }
213 j += 1;
214 }
215 table
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 #[test]
223 fn idct_of_a_dc_only_vector_is_flat() {
224 let mut x = [0.0f32; AHT_BLOCKS];
225 x[0] = 1.0;
226 let out = idct6(&x);
227 for v in out {
228 assert!((v - out[0]).abs() < 1e-5, "{out:?}");
229 }
230 assert!(out[0] > 0.0);
231 }
232
233 #[test]
234 fn idct_matches_the_direct_sum() {
235 // The table-driven transform against the standard's equation with the
236 // measured sqrt(2) scale, computed the slow way in f64.
237 let x = [0.3f32, -0.7, 0.1, 0.9, -0.2, 0.5];
238 let got = idct6(&x);
239 for (m, &g) in got.iter().enumerate() {
240 let mut acc = 0.0f64;
241 for (j, &v) in x.iter().enumerate() {
242 let r = if j == 0 { 1.0 / 2f64.sqrt() } else { 1.0 };
243 let angle = j as f64 * (2 * m + 1) as f64 * std::f64::consts::PI / 12.0;
244 acc += r * f64::from(v) * angle.cos();
245 }
246 assert!((f64::from(g) - 2f64.sqrt() * acc).abs() < 1e-5, "m = {m}");
247 }
248 }
249
250 #[test]
251 fn vq4_is_the_printed_table_shifted_by_one() {
252 // The correction measured against a real stream (see VQ4's comment):
253 // index k selects the row Table E4.4 prints at k + 1, and index 31
254 // selects silence. Pinned here so the table cannot drift back.
255 use crate::aht_tables::VQ4;
256 assert_eq!(VQ4[31], [0; 6]);
257 assert_eq!(VQ4[29], [-83, 278, 323, 55, -154, 232]);
258 assert_eq!(VQ4[0], [6636, -4593, 14173, -17297, -16523, 864]);
259 // Every other table is used exactly as printed.
260 assert_eq!(vq_table(3).len(), 16);
261 assert_eq!(vq_table(4).len(), 32);
262 assert_eq!(vq_table(7).len(), 512);
263 }
264
265 #[test]
266 fn gaq_gains_follow_table_e3_3() {
267 assert_eq!(gain_of(1, 0), 1);
268 assert_eq!(gain_of(1, 1), 2);
269 assert_eq!(gain_of(2, 1), 4);
270 assert_eq!(gain_of(3, 1), 2);
271 assert_eq!(gain_of(3, 2), 4);
272 }
273
274 #[test]
275 fn remap_reproduces_the_step_sizes_of_table_e3_5() {
276 // hebap 8, Gk = 1: seven points of step 2/(2^3 - 1) = 2/7.
277 let a = remap(8, 1, 1.0 / 4.0);
278 let b = remap(8, 1, 2.0 / 4.0);
279 assert!((b - a - 2.0 / 7.0).abs() < 1e-4, "{a} {b}");
280 // hebap 8, Gk = 2 large: four points of step 1/(2^2 - 1) = 1/3.
281 let a = remap(8, 2, 0.0);
282 let b = remap(8, 2, 0.5);
283 assert!((b - a - 1.0 / 3.0).abs() < 1e-4, "{a} {b}");
284 }
285}