forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB5c8eff8Tahinli2 months ago2949 commits

bitalloc.rs348 lines, 11.5 KiBHistoryRawDownload
1//! The parametric bit allocation model of A/52 §7.2.2.
2//!
3//! This is the part of AC-3 that has no slack in it: the decoder recomputes,
4//! from the exponents alone, exactly how many bits the encoder spent on every
5//! mantissa. One wrong `bap` and the rest of the block is read at the wrong bit
6//! offset, so the seven steps below are transcribed step for step, integer for
7//! integer, from the standard's pseudo code.
8
9use crate::aht_tables::HEBAPTAB;
10use crate::tables::{
11 BAPTAB, BNDTAB, DBPBTAB, FASTDEC, FASTGAIN, FLOORTAB, HTH, LATAB, MASKTAB, SLOWDEC, SLOWGAIN,
12};
13
14/// The bit allocation parameters a block either sends (`baie`) or reuses.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
16pub struct BitAllocParams {
17 /// Slow decay code.
18 pub sdcycod: u8,
19 /// Fast decay code.
20 pub fdcycod: u8,
21 /// Slow gain code.
22 pub sgaincod: u8,
23 /// dB/bit code.
24 pub dbpbcod: u8,
25 /// Masking floor code.
26 pub floorcod: u8,
27}
28
29/// Delta bit allocation for one channel (§7.2.2.6): up to 8 segments of
30/// masking-curve adjustment. `nseg == 0` means "no adjustment", which is the
31/// state the standard asks decoders to initialise to every syncframe.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
33pub struct DeltaBa {
34 /// Number of active segments.
35 pub nseg: usize,
36 /// Band offset of each segment, relative to the previous segment's end.
37 pub offset: [u8; 8],
38 /// Band count of each segment.
39 pub length: [u8; 8],
40 /// Adjustment code of each segment.
41 pub delta: [u8; 8],
42}
43
44/// Which kind of channel the allocation is being run for; it selects the two
45/// special cases the standard carves out of the excitation function.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub enum Channel {
48 /// A full-bandwidth channel: starts at bin 0, runs the `lowcomp` path.
49 Fbw,
50 /// The LFE channel: like `Fbw`, but `calc_lowcomp` is skipped for its last
51 /// band (bin 6) because there is no band above it.
52 Lfe,
53 /// The coupling channel: starts high, and its leak state is initialised
54 /// from `cplfleak`/`cplsleak` rather than from the first bands.
55 Coupling {
56 /// `(cplfleak, cplsleak)` as sent, already shifted into leak units.
57 leak: (i32, i32),
58 },
59}
60
61/// One channel's inputs to the model.
62#[derive(Debug, Clone, Copy)]
63pub struct Allocation<'a> {
64 /// Sample rate code, indexing the hearing threshold table.
65 pub fscod: usize,
66 /// Parameters shared by every channel of the block.
67 pub params: BitAllocParams,
68 /// First and last-plus-one mantissa bin.
69 pub range: (usize, usize),
70 /// Fast gain code for this channel.
71 pub fgaincod: u8,
72 /// SNR offset, already combined from `csnroffst` and the channel's fine
73 /// offset: `(((csnroffst - 15) << 4) + fsnroffst) << 2`.
74 pub snroffset: i32,
75 /// Channel kind.
76 pub kind: Channel,
77 /// Delta bit allocation, when the block sent or is reusing some.
78 pub dba: Option<&'a DeltaBa>,
79 /// Emit Annex E's high-efficiency pointers (`hebaptab[]`, Table E3.1)
80 /// instead of `baptab[]`, which is what an AHT channel is allocated with
81 /// (§E3.4.3.1). Everything up to the final table lookup is identical.
82 pub high_efficiency: bool,
83}
84
85/// Log-domain addition of two PSD values (§7.2.2.3).
86fn logadd(a: i32, b: i32) -> i32 {
87 let c = a - b;
88 let address = ((c.abs() >> 1) as usize).min(255);
89 if c >= 0 {
90 a + LATAB[address]
91 } else {
92 b + LATAB[address]
93 }
94}
95
96/// `calc_lowcomp()` (§7.2.2.4).
97fn calc_lowcomp(a: i32, b0: i32, b1: i32, bin: usize) -> i32 {
98 if bin < 7 {
99 if b0 + 256 == b1 {
100 384
101 } else if b0 > b1 {
102 (a - 64).max(0)
103 } else {
104 a
105 }
106 } else if bin < 20 {
107 if b0 + 256 == b1 {
108 320
109 } else if b0 > b1 {
110 (a - 64).max(0)
111 } else {
112 a
113 }
114 } else {
115 (a - 128).max(0)
116 }
117}
118
119/// Run the seven steps for one channel, filling `bap[start..end]`.
120///
121/// `exps` is indexed by mantissa bin and holds the decoded 5-bit exponents.
122/// Everything outside `range` in `bap` is left alone.
123pub fn compute(alloc: &Allocation<'_>, exps: &[u8], bap: &mut [u8]) {
124 let (start, end) = alloc.range;
125 if start >= end {
126 return;
127 }
128 let sdecay = SLOWDEC[alloc.params.sdcycod as usize & 3];
129 let fdecay = FASTDEC[alloc.params.fdcycod as usize & 3];
130 let sgain = SLOWGAIN[alloc.params.sgaincod as usize & 3];
131 let dbknee = DBPBTAB[alloc.params.dbpbcod as usize & 3];
132 let floor = FLOORTAB[alloc.params.floorcod as usize & 7];
133 let fgain = FASTGAIN[alloc.fgaincod as usize & 7];
134 let snroffset = alloc.snroffset;
135
136 // Step: exponents into PSD.
137 let mut psd = [0i32; 256];
138 for bin in start..end {
139 psd[bin] = 3072 - (i32::from(exps[bin]) << 7);
140 }
141
142 // Step: PSD integration into 1/6-octave bands.
143 let mut bndpsd = [0i32; 50];
144 let mut j = start;
145 let mut k = MASKTAB[start];
146 loop {
147 let lastbin = BNDTAB[k + 1].min(end);
148 bndpsd[k] = psd[j];
149 j += 1;
150 while j < lastbin {
151 bndpsd[k] = logadd(bndpsd[k], psd[j]);
152 j += 1;
153 }
154 k += 1;
155 if end <= lastbin {
156 break;
157 }
158 }
159
160 // Step: excitation function.
161 let bndstrt = MASKTAB[start];
162 let bndend = MASKTAB[end - 1] + 1;
163 let mut excite = [0i32; 50];
164 let (mut fastleak, mut slowleak) = match alloc.kind {
165 Channel::Coupling { leak } => leak,
166 _ => (0, 0),
167 };
168 let begin = if bndstrt == 0 {
169 // fbw and lfe channels. The standard writes the LFE exception as
170 // `bndend != 7`; the LFE is the only channel that can end there, so
171 // the kind says it more plainly.
172 let is_lfe = alloc.kind == Channel::Lfe;
173 let mut lowcomp = 0;
174 lowcomp = calc_lowcomp(lowcomp, bndpsd[0], bndpsd[1], 0);
175 excite[0] = bndpsd[0] - fgain - lowcomp;
176 lowcomp = calc_lowcomp(lowcomp, bndpsd[1], bndpsd[2], 1);
177 excite[1] = bndpsd[1] - fgain - lowcomp;
178 let mut begin = 7;
179 for bin in 2..7 {
180 if !(is_lfe && bin == 6) {
181 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);
182 }
183 fastleak = bndpsd[bin] - fgain;
184 slowleak = bndpsd[bin] - sgain;
185 excite[bin] = fastleak - lowcomp;
186 if !(is_lfe && bin == 6) && bndpsd[bin] <= bndpsd[bin + 1] {
187 begin = bin + 1;
188 break;
189 }
190 }
191 for bin in begin..bndend.min(22) {
192 if !(is_lfe && bin == 6) {
193 lowcomp = calc_lowcomp(lowcomp, bndpsd[bin], bndpsd[bin + 1], bin);
194 }
195 fastleak = (fastleak - fdecay).max(bndpsd[bin] - fgain);
196 slowleak = (slowleak - sdecay).max(bndpsd[bin] - sgain);
197 excite[bin] = (fastleak - lowcomp).max(slowleak);
198 }
199 22
200 } else {
201 bndstrt
202 };
203 for bin in begin..bndend {
204 fastleak = (fastleak - fdecay).max(bndpsd[bin] - fgain);
205 slowleak = (slowleak - sdecay).max(bndpsd[bin] - sgain);
206 excite[bin] = fastleak.max(slowleak);
207 }
208
209 // Step: masking curve.
210 let mut mask = [0i32; 50];
211 for bin in bndstrt..bndend {
212 if bndpsd[bin] < dbknee {
213 excite[bin] += (dbknee - bndpsd[bin]) >> 2;
214 }
215 mask[bin] = excite[bin].max(HTH[alloc.fscod.min(2)][bin]);
216 }
217
218 // Step: delta bit allocation.
219 if let Some(dba) = alloc.dba {
220 let mut band = 0usize;
221 for seg in 0..dba.nseg {
222 band += usize::from(dba.offset[seg]);
223 let delta = if dba.delta[seg] >= 4 {
224 (i32::from(dba.delta[seg]) - 3) << 7
225 } else {
226 (i32::from(dba.delta[seg]) - 4) << 7
227 };
228 for _ in 0..dba.length[seg] {
229 if band >= 50 {
230 break;
231 }
232 mask[band] += delta;
233 band += 1;
234 }
235 }
236 }
237
238 // Step: bap from the gap between psd and the adjusted mask.
239 let mut i = start;
240 let mut j = MASKTAB[start];
241 loop {
242 let lastbin = BNDTAB[j + 1].min(end);
243 mask[j] -= snroffset;
244 mask[j] -= floor;
245 if mask[j] < 0 {
246 mask[j] = 0;
247 }
248 mask[j] &= 0x1fe0;
249 mask[j] += floor;
250 while i < lastbin {
251 let address = ((psd[i] - mask[j]) >> 5).clamp(0, 63) as usize;
252 bap[i] = if alloc.high_efficiency {
253 HEBAPTAB[address]
254 } else {
255 BAPTAB[address]
256 };
257 i += 1;
258 }
259 j += 1;
260 if end <= lastbin {
261 break;
262 }
263 }
264}
265
266#[cfg(test)]
267mod tests {
268 use super::*;
269
270 fn flat_alloc(snroffset: i32) -> Allocation<'static> {
271 Allocation {
272 fscod: 0,
273 params: BitAllocParams {
274 sdcycod: 2,
275 fdcycod: 1,
276 sgaincod: 1,
277 dbpbcod: 2,
278 floorcod: 4,
279 },
280 range: (0, 253),
281 fgaincod: 4,
282 snroffset,
283 kind: Channel::Fbw,
284 dba: None,
285 high_efficiency: false,
286 }
287 }
288
289 #[test]
290 fn louder_signal_and_bigger_snroffset_buy_more_bits() {
291 // A flat, loud spectrum against a flat, quiet one: every allocated
292 // pointer must be at least as large for the loud one, and raising the
293 // SNR offset must not reduce any pointer. Those two monotonicities are
294 // what the model exists to provide.
295 let loud = [2u8; 256];
296 let quiet = [20u8; 256];
297 let (mut a, mut b, mut c) = ([0u8; 256], [0u8; 256], [0u8; 256]);
298 compute(&flat_alloc(1000), &loud, &mut a);
299 compute(&flat_alloc(1000), &quiet, &mut b);
300 compute(&flat_alloc(1400), &quiet, &mut c);
301 for bin in 0..253 {
302 assert!(a[bin] >= b[bin], "bin {bin}: {} < {}", a[bin], b[bin]);
303 assert!(c[bin] >= b[bin], "bin {bin}: {} < {}", c[bin], b[bin]);
304 }
305 assert!(a.iter().any(|&v| v > 0));
306 }
307
308 #[test]
309 fn delta_bit_allocation_lowers_the_mask_where_it_points() {
310 // A quiet-ish flat spectrum with a modest SNR offset, so the affected
311 // bands are not already pinned at the top of baptab[].
312 let exps = [16u8; 256];
313 let (mut plain, mut with_dba) = ([0u8; 256], [0u8; 256]);
314 compute(&flat_alloc(0), &exps, &mut plain);
315 let dba = DeltaBa {
316 nseg: 1,
317 offset: [10, 0, 0, 0, 0, 0, 0, 0],
318 length: [4, 0, 0, 0, 0, 0, 0, 0],
319 // delta 0 => (0 - 4) << 7, a 4 x -6 dB mask reduction => more bits.
320 delta: [0, 0, 0, 0, 0, 0, 0, 0],
321 };
322 let mut alloc = flat_alloc(0);
323 alloc.dba = Some(&dba);
324 compute(&alloc, &exps, &mut with_dba);
325 for bin in BNDTAB[10]..BNDTAB[14] {
326 assert!(with_dba[bin] >= plain[bin], "bin {bin}");
327 }
328 assert!(
329 (BNDTAB[10]..BNDTAB[14]).any(|bin| with_dba[bin] > plain[bin]),
330 "the -6 dB segment bought no bits anywhere"
331 );
332 for bin in BNDTAB[14]..253 {
333 assert_eq!(with_dba[bin], plain[bin], "bin {bin}");
334 }
335 for bin in 0..BNDTAB[10] {
336 assert_eq!(with_dba[bin], plain[bin], "bin {bin}");
337 }
338 }
339
340 #[test]
341 fn all_zero_range_is_a_no_op() {
342 let mut bap = [7u8; 256];
343 let mut alloc = flat_alloc(0);
344 alloc.range = (37, 37);
345 compute(&alloc, &[5u8; 256], &mut bap);
346 assert!(bap.iter().all(|&v| v == 7));
347 }
348}