diff --git a/crates/ec-aac/src/sbr_payload.rs b/crates/ec-aac/src/sbr_payload.rs index 58fcd060..01c28216 100644 --- a/crates/ec-aac/src/sbr_payload.rs +++ b/crates/ec-aac/src/sbr_payload.rs @@ -77,20 +77,22 @@ struct Grid { } impl Grid { - fn new(num_env: usize, freq_res: Vec, t_env: Vec) -> Grid { + /// `pointer` is `bs_pointer` (0 for FIXFIX, which has no such field -- + /// the spec's own `bs_pointer == 0` case: the middle noise border is + /// `num_env >> 1`). Per ISO/IEC 14496-3 ยง4.6.18.3.3: `bs_pointer == 0` + /// selects `num_env >> 1`, `== 1` selects the last envelope border + /// (`num_env - 1`), otherwise `bs_pointer - 1`. + fn new(num_env: usize, freq_res: Vec, t_env: Vec, pointer: usize) -> Grid { let num_noise = if num_env == 1 { 1 } else { 2 }; let t_noise = if num_noise == 1 { vec![t_env[0], t_env[num_env]] } else { - let mid = (t_env[0] + t_env[num_env]) as f64 / 2.0; - let split = (1..num_env) - .min_by(|&a, &b| { - let da = (t_env[a] as f64 - mid).abs(); - let db = (t_env[b] as f64 - mid).abs(); - da.partial_cmp(&db).unwrap() - }) - .unwrap_or(1); - vec![t_env[0], t_env[split], t_env[num_env]] + let middle = match pointer { + 0 => num_env >> 1, + 1 => num_env - 1, + p => p - 1, + }; + vec![t_env[0], t_env[middle], t_env[num_env]] }; Grid { num_env, @@ -101,6 +103,12 @@ impl Grid { } } +/// Width of `bs_pointer`, which ranges `0..=num_env`: `ceil(log2(num_env+1))` +/// bits, equivalently the bit-length of `num_env` itself. +fn pointer_bits(num_env: usize) -> u32 { + (u32::BITS - (num_env as u32).leading_zeros()).max(1) +} + /// Per-channel state carried across frames, for delta-time (DT) envelope and /// noise coding whose first entry in a frame references the *previous* /// frame's last one. @@ -214,7 +222,7 @@ impl SbrParser { let t_env: Vec = (0..=num_env) .map(|i| (i as i64) * NUM_TIME_SLOTS / num_env as i64) .collect(); - Ok(Grid::new(num_env, vec![fr; num_env], t_env)) + Ok(Grid::new(num_env, vec![fr; num_env], t_env, 0)) } 1 | 2 => { // FIXVAR (1, trailing variable border) / VARFIX (2, leading variable border) @@ -230,10 +238,22 @@ impl SbrParser { for _ in 0..num_rel { rel.push(2 * i64::from(r.read_bits(2)?) + 2); } - let mut freq_res = Vec::with_capacity(num_env); + let pointer = r.read_bits(pointer_bits(num_env))? as usize; + // FIXVAR transmits bs_freq_res in reverse time order (the + // envelopes are numbered from the trailing variable border + // backwards); VARFIX transmits it forward. Confirmed against + // a reference decoder's own byte accounting on a non-uniform + // list, since a uniform one can't tell the orders apart + // (`scripts/aac-tables/sbrgrid_probe.py`). + let mut wire = Vec::with_capacity(num_env); for _ in 0..num_env { - freq_res.push(u8::from(r.read_bit()?)); + wire.push(u8::from(r.read_bit()?)); } + let freq_res = if frame_class == 1 { + wire.into_iter().rev().collect() + } else { + wire + }; let mut t = vec![0i64; num_env + 1]; if frame_class == 1 { let trail = NUM_TIME_SLOTS + var_bord; @@ -250,7 +270,7 @@ impl SbrParser { } t[num_env] = NUM_TIME_SLOTS; } - Ok(Grid::new(num_env, freq_res, t)) + Ok(Grid::new(num_env, freq_res, t, pointer)) } _ => { // VARVAR @@ -270,6 +290,7 @@ impl SbrParser { for _ in 0..num_rel1 { rel1.push(2 * i64::from(r.read_bits(2)?) + 2); } + let pointer = r.read_bits(pointer_bits(num_env))? as usize; let mut freq_res = Vec::with_capacity(num_env); for _ in 0..num_env { freq_res.push(u8::from(r.read_bit()?)); @@ -289,7 +310,7 @@ impl SbrParser { if t.windows(2).any(|w| w[0] >= w[1]) { return Err(Error::corrupt("sbr: non-monotone envelope time borders")); } - Ok(Grid::new(num_env, freq_res, t)) + Ok(Grid::new(num_env, freq_res, t, pointer)) } } } @@ -504,8 +525,26 @@ impl SbrParser { q_q.push(row); } - self.state[ch].last_env = e_q.last().cloned().unwrap_or_default(); - self.state[ch].last_noise = q_q.last().cloned().unwrap_or_default(); + // Containment, not the fix: a still-undiscovered desync could + // make a DT delta huge, and since a following frame's DT reads + // add onto this carried state, one corrupt cell would otherwise + // snowball unbounded across frames. Clamp to the raw field's own + // range (0..127 envelope, 0..31 noise) so corrupt input degrades + // that one cell instead of exploding the whole carried state. + self.state[ch].last_env = e_q + .last() + .cloned() + .unwrap_or_default() + .into_iter() + .map(|v| v.clamp(0, (1 << raw_env_width(balance, amp_res)) - 1)) + .collect(); + self.state[ch].last_noise = q_q + .last() + .cloned() + .unwrap_or_default() + .into_iter() + .map(|v| v.clamp(0, (1 << RAW_NOISE_WIDTH) - 1)) + .collect(); channels.push(SbrChannel { t_env: grids[ch].t_env.clone(), @@ -552,13 +591,13 @@ mod tests { // `_BITS` is the bit count the reference decoder's own accounting // measured for it, asserted below against `BitReader::bit_position()`. const FIXVAR_DF_BODY: &[u8] = &[ - 0x90, 0x31, 0xd8, 0xb2, 0xcc, 0x00, 0xbc, 0x78, 0xf0, 0x00, 0x00, + 0x90, 0x31, 0xd8, 0xb2, 0xcc, 0x00, 0x2f, 0x1e, 0x3c, 0x00, 0x00, ]; - const FIXVAR_DF_BITS: u64 = 82; - const VARFIX_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb5, 0x38, 0x0b, 0xc7, 0x80, 0x00]; - const VARFIX_DF_BITS: u64 = 71; - const VARVAR_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb6, 0xa8, 0x00, 0xbc, 0x78, 0x00, 0x00]; - const VARVAR_DF_BITS: u64 = 75; + const FIXVAR_DF_BITS: u64 = 84; + const VARFIX_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb5, 0x38, 0x02, 0xf1, 0xe0, 0x00, 0x00]; + const VARFIX_DF_BITS: u64 = 73; + const VARVAR_DF_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb6, 0xa8, 0x00, 0x2f, 0x1e, 0x00, 0x00]; + const VARVAR_DF_BITS: u64 = 77; const FIXFIX_DT_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb0, 0x95, 0x78, 0x00, 0x00]; const FIXFIX_DT_BITS: u64 = 57; const CPE_UNCOUPLED_BODY: &[u8] = &[0x90, 0x31, 0xd8, 0xb0, 0x00, 0x05, 0x78, 0x07, 0x80, 0x00]; diff --git a/scripts/aac-tables/sbrgrid_probe.py b/scripts/aac-tables/sbrgrid_probe.py new file mode 100644 index 00000000..f12108e5 --- /dev/null +++ b/scripts/aac-tables/sbrgrid_probe.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""One-shot probe: does the real decoder read a `bs_pointer` field in +FIXVAR sbr_grid(), and is bs_freq_res transmitted in reverse time order for +that class? Reuses the already-oracle-proven `sbr_bits_full`/`oracle_check` +machinery from sbrpayload_fixtures.py, swapping in a grid writer with a +non-uniform freq_res list and an EXPLICIT (not FILL) codeword for the one +Huffman slot the high-res envelope needs -- FILL's length is book-dependent +and not what we wrote, so byte prediction is only exact with an explicit +word (learned the hard way: FILL made every naive attempt here mismatch by +several bytes even for the untouched baseline). Not part of the pytest/cargo +run -- throwaway measurement, output pasted into the ledger. +""" +import os +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) + +import sbrtables as T +from sbrpayload_fixtures import one_band_header, sbr_bits_full, oracle_check + +cfg0, tables0 = one_band_header() +assert tables0["n_low"] == 1 and tables0["n_high"] == 2 and tables0["n_q"] == 1, tables0 + +ENV15_F_DELTA0 = T.as_bits(2, 0) # (length=2, code=0b00, delta=0) + + +def ptr_bits(num_env): + n = 1 + while (1 << n) < num_env + 1: + n += 1 + return n + + +def make_grid_writer(time_fr, pointer, reverse): + num_env = len(time_fr) + num_rel = num_env - 1 + + def write(s, grid_cfg): + s.w(1, 2) # frame_class = FIXVAR + s.w(1, 2) # var_bord + s.w(num_rel, 2) + for _ in range(num_rel): + s.w(1, 2) # rel_bord = 2*1+2 = 4 + if pointer: + s.w(0, ptr_bits(num_env)) + wire = list(reversed(time_fr)) if reverse else list(time_fr) + for fr in wire: + s.w(fr, 1) + return num_env, time_fr + + return write + + +def probe(oracle, label, time_fr, pointer, reverse): + import sbrpayload_fixtures as F + F.write_grid = make_grid_writer(time_fr, pointer, reverse) + cfg = dict(cfg0, df_env=[0] * 8, df_noise=[0, 0]) + ok, n = oracle_check(oracle, cfg, tables0, {}, [ENV15_F_DELTA0], label) + return ok, n + + +if __name__ == "__main__": + oracle = T.Oracle(8) + time_fr = [1, 0, 0, 0] # env0 high-res (needs the one Huffman slot) + for pointer in (False, True): + for reverse in (False, True): + label = f"fixvar_ptr{int(pointer)}_rev{int(reverse)}" + probe(oracle, label, time_fr, pointer, reverse) + oracle.save() diff --git a/scripts/aac-tables/sbrpayload_fixtures.py b/scripts/aac-tables/sbrpayload_fixtures.py index 0a969004..2b2f957c 100644 --- a/scripts/aac-tables/sbrpayload_fixtures.py +++ b/scripts/aac-tables/sbrpayload_fixtures.py @@ -25,17 +25,30 @@ RATE = T.SBR_RATE_FOR_SF[SF_INDEX] # --------------------------------------------------------------- grid writer +def ptr_bits(num_env): + """`ceil(log2(num_env+1))`: width of `bs_pointer`, which ranges `0..=num_env`.""" + n = 1 + while (1 << n) < num_env + 1: + n += 1 + return n + + def write_grid(s, grid_cfg): """Writes one `sbr_grid()`; returns `(num_env, freq_res_list)`. Field widths validated against the reference decoder's byte accounting in `gridcheck.py` (kept alongside this file): FIXVAR/VARFIX/VARVAR all use - `var_bord`(2 bits), `bs_num_rel`(2 bits), `bs_rel_bord`(2 bits, value - `2*n+2`) and one `bs_freq_res` bit per envelope, agreeing with the - reference parser's consumed byte count for every `num_rel` combination - whose total envelope count lands in `2..=5` (below or above that the - reference decoder takes a different, unmeasured path -- so the Rust - parser refuses those rather than guessing). + `var_bord`(2 bits), `bs_num_rel`(2 bits) and `bs_rel_bord`(2 bits, value + `2*n+2`), agreeing with the reference parser's consumed byte count for + every `num_rel` combination whose total envelope count lands in `2..=5` + (below or above that the reference decoder takes a different, unmeasured + path -- so the Rust parser refuses those rather than guessing). Between + the relative borders and `bs_freq_res` sits `bs_pointer` + (`ptr_bits(num_env)` bits) -- confirmed present by `sbrgrid_probe.py` + against a non-uniform freq_res list (a uniform one hides it entirely, + which is how earlier fixtures missed it). FIXVAR alone transmits + `bs_freq_res` in reverse time order (probed the same way); VARFIX/VARVAR + transmit it forward. """ fc = grid_cfg["frame_class"] s.w(fc, 2) @@ -52,8 +65,10 @@ def write_grid(s, grid_cfg): num_env = num_rel + 1 for b in grid_cfg["rel_bord"]: s.w(b, 2) + s.w(grid_cfg.get("pointer", 0), ptr_bits(num_env)) freq_res_list = grid_cfg["freq_res_list"] - for fr in freq_res_list: + wire = list(reversed(freq_res_list)) if fc == 1 else list(freq_res_list) + for fr in wire: s.w(fr, 1) return num_env, freq_res_list # VARVAR @@ -68,6 +83,7 @@ def write_grid(s, grid_cfg): s.w(b, 2) for b in grid_cfg["rel_bord1"]: s.w(b, 2) + s.w(grid_cfg.get("pointer", 0), ptr_bits(num_env)) freq_res_list = grid_cfg["freq_res_list"] for fr in freq_res_list: s.w(fr, 1)