forge
Explore
Log in

Don't you dare go Hollow

The missing bs_pointer field and FIXVAR's reversed freq_res

Browse files at this commit

7dabfff4ae18ed98b81348e930870aa9b28ba721Ahmet Kaan GümüşParent: 90930dd
  • fix
    • the missing bs_pointer field and FIXVAR's reversed freq_res
Show full message
fix(aac-sbr): the missing bs_pointer field and FIXVAR's reversed freq_res

FIXVAR/VARFIX/VARVAR sbr_grid() all carry a bs_pointer field (width
ceil(log2(num_env+1))) between the relative borders and bs_freq_res, which
this parser never read -- and FIXVAR alone transmits bs_freq_res in reverse
time order (envelopes are numbered from the trailing variable border
backwards). Confirmed against a reference decoder's own byte accounting on
a non-uniform freq_res list (scripts/aac-tables/sbrgrid_probe.py) -- a
uniform list hid both bugs, which is why the byte-exact fixtures never
caught them. The missing pointer field also explains the standing "VARVAR
num_env==3 reads one byte fewer" mystery: ptr_bits(3)=2 crosses a byte
boundary.

bs_pointer also drives the noise floor's middle time border (ISO/IEC
14496-3 Sec 4.6.18.3.3), which this parser was deriving with a
nearest-midpoint heuristic instead; Grid::new now follows the spec formula.

Adds a plausibility clamp on the carried DT state (last_env/last_noise) as
containment against any still-undiscovered desync, not a fix for one.

Regenerates the FIXVAR/VARFIX/VARVAR fixtures from the corrected wire
format (all still oracle-verified byte-exact).
crates/ec-aac/src/sbr_payload.rsmodified+62 -23
@@ -77,20 +77,22 @@ struct Grid {
7777 }
7878
7979 impl Grid {
80- fn new(num_env: usize, freq_res: Vec<u8>, t_env: Vec<i64>) -> Grid {
80+ /// `pointer` is `bs_pointer` (0 for FIXFIX, which has no such field --
81+ /// the spec's own `bs_pointer == 0` case: the middle noise border is
82+ /// `num_env >> 1`). Per ISO/IEC 14496-3 §4.6.18.3.3: `bs_pointer == 0`
83+ /// selects `num_env >> 1`, `== 1` selects the last envelope border
84+ /// (`num_env - 1`), otherwise `bs_pointer - 1`.
85+ fn new(num_env: usize, freq_res: Vec<u8>, t_env: Vec<i64>, pointer: usize) -> Grid {
8186 let num_noise = if num_env == 1 { 1 } else { 2 };
8287 let t_noise = if num_noise == 1 {
8388 vec![t_env[0], t_env[num_env]]
8489 } else {
85- let mid = (t_env[0] + t_env[num_env]) as f64 / 2.0;
86- let split = (1..num_env)
87- .min_by(|&a, &b| {
88- let da = (t_env[a] as f64 - mid).abs();
89- let db = (t_env[b] as f64 - mid).abs();
90- da.partial_cmp(&db).unwrap()
91- })
92- .unwrap_or(1);
93- vec![t_env[0], t_env[split], t_env[num_env]]
90+ let middle = match pointer {
91+ 0 => num_env >> 1,
92+ 1 => num_env - 1,
93+ p => p - 1,
94+ };
95+ vec![t_env[0], t_env[middle], t_env[num_env]]
9496 };
9597 Grid {
9698 num_env,
@@ -101,6 +103,12 @@ impl Grid {
101103 }
102104 }
103105
106+/// Width of `bs_pointer`, which ranges `0..=num_env`: `ceil(log2(num_env+1))`
107+/// bits, equivalently the bit-length of `num_env` itself.
108+fn pointer_bits(num_env: usize) -> u32 {
109+ (u32::BITS - (num_env as u32).leading_zeros()).max(1)
110+}
111+
104112 /// Per-channel state carried across frames, for delta-time (DT) envelope and
105113 /// noise coding whose first entry in a frame references the *previous*
106114 /// frame's last one.
@@ -214,7 +222,7 @@ impl SbrParser {
214222 let t_env: Vec<i64> = (0..=num_env)
215223 .map(|i| (i as i64) * NUM_TIME_SLOTS / num_env as i64)
216224 .collect();
217- Ok(Grid::new(num_env, vec![fr; num_env], t_env))
225+ Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0))
218226 }
219227 1 | 2 => {
220228 // FIXVAR (1, trailing variable border) / VARFIX (2, leading variable border)
@@ -230,10 +238,22 @@ impl SbrParser {
230238 for _ in 0..num_rel {
231239 rel.push(2 * i64::from(r.read_bits(2)?) + 2);
232240 }
233- let mut freq_res = Vec::with_capacity(num_env);
241+ let pointer = r.read_bits(pointer_bits(num_env))? as usize;
242+ // FIXVAR transmits bs_freq_res in reverse time order (the
243+ // envelopes are numbered from the trailing variable border
244+ // backwards); VARFIX transmits it forward. Confirmed against
245+ // a reference decoder's own byte accounting on a non-uniform
246+ // list, since a uniform one can't tell the orders apart
247+ // (`scripts/aac-tables/sbrgrid_probe.py`).
248+ let mut wire = Vec::with_capacity(num_env);
234249 for _ in 0..num_env {
235- freq_res.push(u8::from(r.read_bit()?));
250+ wire.push(u8::from(r.read_bit()?));
236251 }
252+ let freq_res = if frame_class == 1 {
253+ wire.into_iter().rev().collect()
254+ } else {
255+ wire
256+ };
237257 let mut t = vec![0i64; num_env + 1];
238258 if frame_class == 1 {
239259 let trail = NUM_TIME_SLOTS + var_bord;
@@ -250,7 +270,7 @@ impl SbrParser {
250270 }
251271 t[num_env] = NUM_TIME_SLOTS;
252272 }
253- Ok(Grid::new(num_env, freq_res, t))
273+ Ok(Grid::new(num_env, freq_res, t, pointer))
254274 }
255275 _ => {
256276 // VARVAR
@@ -270,6 +290,7 @@ impl SbrParser {
270290 for _ in 0..num_rel1 {
271291 rel1.push(2 * i64::from(r.read_bits(2)?) + 2);
272292 }
293+ let pointer = r.read_bits(pointer_bits(num_env))? as usize;
273294 let mut freq_res = Vec::with_capacity(num_env);
274295 for _ in 0..num_env {
275296 freq_res.push(u8::from(r.read_bit()?));
@@ -289,7 +310,7 @@ impl SbrParser {
289310 if t.windows(2).any(|w| w[0] >= w[1]) {
290311 return Err(Error::corrupt("sbr: non-monotone envelope time borders"));
291312 }
292- Ok(Grid::new(num_env, freq_res, t))
313+ Ok(Grid::new(num_env, freq_res, t, pointer))
293314 }
294315 }
295316 }
@@ -504,8 +525,26 @@ impl SbrParser {
504525 q_q.push(row);
505526 }
506527
507- self.state[ch].last_env = e_q.last().cloned().unwrap_or_default();
508- self.state[ch].last_noise = q_q.last().cloned().unwrap_or_default();
528+ // Containment, not the fix: a still-undiscovered desync could
529+ // make a DT delta huge, and since a following frame's DT reads
530+ // add onto this carried state, one corrupt cell would otherwise
531+ // snowball unbounded across frames. Clamp to the raw field's own
532+ // range (0..127 envelope, 0..31 noise) so corrupt input degrades
533+ // that one cell instead of exploding the whole carried state.
534+ self.state[ch].last_env = e_q
535+ .last()
536+ .cloned()
537+ .unwrap_or_default()
538+ .into_iter()
539+ .map(|v| v.clamp(0, (1 << raw_env_width(balance, amp_res)) - 1))
540+ .collect();
541+ self.state[ch].last_noise = q_q
542+ .last()
543+ .cloned()
544+ .unwrap_or_default()
545+ .into_iter()
546+ .map(|v| v.clamp(0, (1 << RAW_NOISE_WIDTH) - 1))
547+ .collect();
509548
510549 channels.push(SbrChannel {
511550 t_env: grids[ch].t_env.clone(),
@@ -552,13 +591,13 @@ mod tests {
552591 // `_BITS` is the bit count the reference decoder's own accounting
553592 // measured for it, asserted below against `BitReader::bit_position()`.
554593 const FIXVAR_DF_BODY: &[u8] = &[
555- 0x90, 0x31, 0xd8, 0xb2, 0xcc, 0x00, 0xbc, 0x78, 0xf0, 0x00, 0x00,
594+ 0x90, 0x31, 0xd8, 0xb2, 0xcc, 0x00, 0x2f, 0x1e, 0x3c, 0x00, 0x00,
556595 ];
557- const FIXVAR_DF_BITS: u64 = 82;
558- const VARFIX_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb5, 0x38, 0x0b, 0xc7, 0x80, 0x00];
559- const VARFIX_DF_BITS: u64 = 71;
560- const VARVAR_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb6, 0xa8, 0x00, 0xbc, 0x78, 0x00, 0x00];
561- const VARVAR_DF_BITS: u64 = 75;
596+ const FIXVAR_DF_BITS: u64 = 84;
597+ const VARFIX_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb5, 0x38, 0x02, 0xf1, 0xe0, 0x00, 0x00];
598+ const VARFIX_DF_BITS: u64 = 73;
599+ const VARVAR_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb6, 0xa8, 0x00, 0x2f, 0x1e, 0x00, 0x00];
600+ const VARVAR_DF_BITS: u64 = 77;
562601 const FIXFIX_DT_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb0, 0x95, 0x78, 0x00, 0x00];
563602 const FIXFIX_DT_BITS: u64 = 57;
564603 const CPE_UNCOUPLED_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb0, 0x00, 0x05, 0x78, 0x07, 0x80, 0x00];
scripts/aac-tables/sbrgrid_probe.pyadded+70 -0
@@ -0,0 +1,70 @@
1+#!/usr/bin/env python3
2+"""One-shot probe: does the real decoder read a `bs_pointer` field in
3+FIXVAR sbr_grid(), and is bs_freq_res transmitted in reverse time order for
4+that class? Reuses the already-oracle-proven `sbr_bits_full`/`oracle_check`
5+machinery from sbrpayload_fixtures.py, swapping in a grid writer with a
6+non-uniform freq_res list and an EXPLICIT (not FILL) codeword for the one
7+Huffman slot the high-res envelope needs -- FILL's length is book-dependent
8+and not what we wrote, so byte prediction is only exact with an explicit
9+word (learned the hard way: FILL made every naive attempt here mismatch by
10+several bytes even for the untouched baseline). Not part of the pytest/cargo
11+run -- throwaway measurement, output pasted into the ledger.
12+"""
13+import os
14+import sys
15+
16+HERE = os.path.dirname(os.path.abspath(__file__))
17+sys.path.insert(0, HERE)
18+
19+import sbrtables as T
20+from sbrpayload_fixtures import one_band_header, sbr_bits_full, oracle_check
21+
22+cfg0, tables0 = one_band_header()
23+assert tables0["n_low"] == 1 and tables0["n_high"] == 2 and tables0["n_q"] == 1, tables0
24+
25+ENV15_F_DELTA0 = T.as_bits(2, 0) # (length=2, code=0b00, delta=0)
26+
27+
28+def ptr_bits(num_env):
29+ n = 1
30+ while (1 << n) < num_env + 1:
31+ n += 1
32+ return n
33+
34+
35+def make_grid_writer(time_fr, pointer, reverse):
36+ num_env = len(time_fr)
37+ num_rel = num_env - 1
38+
39+ def write(s, grid_cfg):
40+ s.w(1, 2) # frame_class = FIXVAR
41+ s.w(1, 2) # var_bord
42+ s.w(num_rel, 2)
43+ for _ in range(num_rel):
44+ s.w(1, 2) # rel_bord = 2*1+2 = 4
45+ if pointer:
46+ s.w(0, ptr_bits(num_env))
47+ wire = list(reversed(time_fr)) if reverse else list(time_fr)
48+ for fr in wire:
49+ s.w(fr, 1)
50+ return num_env, time_fr
51+
52+ return write
53+
54+
55+def probe(oracle, label, time_fr, pointer, reverse):
56+ import sbrpayload_fixtures as F
57+ F.write_grid = make_grid_writer(time_fr, pointer, reverse)
58+ cfg = dict(cfg0, df_env=[0] * 8, df_noise=[0, 0])
59+ ok, n = oracle_check(oracle, cfg, tables0, {}, [ENV15_F_DELTA0], label)
60+ return ok, n
61+
62+
63+if __name__ == "__main__":
64+ oracle = T.Oracle(8)
65+ time_fr = [1, 0, 0, 0] # env0 high-res (needs the one Huffman slot)
66+ for pointer in (False, True):
67+ for reverse in (False, True):
68+ label = f"fixvar_ptr{int(pointer)}_rev{int(reverse)}"
69+ probe(oracle, label, time_fr, pointer, reverse)
70+ oracle.save()
scripts/aac-tables/sbrpayload_fixtures.pymodified+23 -7
@@ -25,17 +25,30 @@ RATE = T.SBR_RATE_FOR_SF[SF_INDEX]
2525
2626 # --------------------------------------------------------------- grid writer
2727
28+def ptr_bits(num_env):
29+ """`ceil(log2(num_env+1))`: width of `bs_pointer`, which ranges `0..=num_env`."""
30+ n = 1
31+ while (1 << n) < num_env + 1:
32+ n += 1
33+ return n
34+
35+
2836 def write_grid(s, grid_cfg):
2937 """Writes one `sbr_grid()`; returns `(num_env, freq_res_list)`.
3038
3139 Field widths validated against the reference decoder's byte accounting in
3240 `gridcheck.py` (kept alongside this file): FIXVAR/VARFIX/VARVAR all use
33- `var_bord`(2 bits), `bs_num_rel`(2 bits), `bs_rel_bord`(2 bits, value
34- `2*n+2`) and one `bs_freq_res` bit per envelope, agreeing with the
35- reference parser's consumed byte count for every `num_rel` combination
36- whose total envelope count lands in `2..=5` (below or above that the
37- reference decoder takes a different, unmeasured path -- so the Rust
38- parser refuses those rather than guessing).
41+ `var_bord`(2 bits), `bs_num_rel`(2 bits) and `bs_rel_bord`(2 bits, value
42+ `2*n+2`), agreeing with the reference parser's consumed byte count for
43+ every `num_rel` combination whose total envelope count lands in `2..=5`
44+ (below or above that the reference decoder takes a different, unmeasured
45+ path -- so the Rust parser refuses those rather than guessing). Between
46+ the relative borders and `bs_freq_res` sits `bs_pointer`
47+ (`ptr_bits(num_env)` bits) -- confirmed present by `sbrgrid_probe.py`
48+ against a non-uniform freq_res list (a uniform one hides it entirely,
49+ which is how earlier fixtures missed it). FIXVAR alone transmits
50+ `bs_freq_res` in reverse time order (probed the same way); VARFIX/VARVAR
51+ transmit it forward.
3952 """
4053 fc = grid_cfg["frame_class"]
4154 s.w(fc, 2)
@@ -52,8 +65,10 @@ def write_grid(s, grid_cfg):
5265 num_env = num_rel + 1
5366 for b in grid_cfg["rel_bord"]:
5467 s.w(b, 2)
68+ s.w(grid_cfg.get("pointer", 0), ptr_bits(num_env))
5569 freq_res_list = grid_cfg["freq_res_list"]
56- for fr in freq_res_list:
70+ wire = list(reversed(freq_res_list)) if fc == 1 else list(freq_res_list)
71+ for fr in wire:
5772 s.w(fr, 1)
5873 return num_env, freq_res_list
5974 # VARVAR
@@ -68,6 +83,7 @@ def write_grid(s, grid_cfg):
6883 s.w(b, 2)
6984 for b in grid_cfg["rel_bord1"]:
7085 s.w(b, 2)
86+ s.w(grid_cfg.get("pointer", 0), ptr_bits(num_env))
7187 freq_res_list = grid_cfg["freq_res_list"]
7288 for fr in freq_res_list:
7389 s.w(fr, 1)