diff --git a/crates/ec-av1/src/cdf_state.rs b/crates/ec-av1/src/cdf_state.rs index cd587b45..3a95fd3e 100644 --- a/crates/ec-av1/src/cdf_state.rs +++ b/crates/ec-av1/src/cdf_state.rs @@ -108,6 +108,16 @@ pub(crate) enum TxbSet { /// `Luma32`'s 1024-position one. Never carries a `tx_type` symbol: both /// orientations use one variant (`get_tx_set` is `EXT_TX_SET_DCTONLY` at /// `tx_size_sqr_up == TX_32X32` regardless of which axis is longer). + /// The 32x8/8x32 luma transform of a 32x32-level `PARTITION_HORZ_4`/ + /// `PARTITION_VERT_4` strip (lane-tx64x16 r3). `get_txsize_entropy_ctx` + /// averages the two log2 sides ((5 + 3) / 2 = 4), so the coefficient CDF + /// set is the 16x16 one [`Luma16`](TxbSet::Luma16) reads -- 256 coded + /// positions, `eob_pt_256`. Unlike `Luma16` it carries NO `tx_type` + /// symbol: `tx_size_sqr_up` of a 4:1 32-wide strip is `TX_32X32`, where + /// `av1_get_ext_tx_set_type` returns `EXT_TX_SET_DCTONLY` for an intra + /// block, so the encoder writes none (same reason + /// [`LumaRect32x16`](TxbSet::LumaRect32x16) has none). + LumaRect32x8, LumaRect32x16, /// The chroma 16x8/8x16 transform under the same strip (lane-rectwire): /// [`Chroma16`](TxbSet::Chroma16)'s tables except `eob_pt`, which reads @@ -1501,6 +1511,18 @@ impl Cdfs { tx_type: None, eob_pt_class1: None, }, + TxbSet::LumaRect32x8 => TxbTables { + side: 16, + txb_skip: &mut self.txb_skip_luma_16, + eob_pt: &mut self.eob_pt_256_luma, + eob_extra: &mut self.eob_extra_luma_16, + base: &mut self.base_luma_16, + base_eob: &mut self.base_eob_luma_16, + br: &mut self.br_luma_16, + dc_sign: &mut self.dc_sign_luma, + tx_type: None, + eob_pt_class1: Some(&mut self.eob_pt_256_luma_class1), + }, TxbSet::LumaRect32x16 => TxbTables { side: 32, txb_skip: &mut self.txb_skip_luma_32, diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 270dc2cd..e33fc17c 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -1405,6 +1405,36 @@ pub(crate) fn sb_rect4_vert_hits() -> usize { SB_RECT4_VERT_HITS.with(|c| c.get()) } +// lane-tx64x16 r3: the 32x32-level 1:4 arms, counted per orientation -- +// `PARTITION_HORZ_4` (four 32x8 strips) and `PARTITION_VERT_4` (four 8x32 +// strips), the arms the ReelB mid-film extract stops at. +thread_local! { + static RECT4_32_HORZ_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; + static RECT4_32_VERT_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many 32x32-level 1:4 strips actually read coefficients (non-skip): +/// a gate that only counted strips would pass on an all-skip stream, which +/// exercises none of the new scan/context tables. +thread_local! { + static RECT4_COEFF_HITS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// Current value of `RECT4_COEFF_HITS`. +pub(crate) fn rect4_coeff_hits() -> usize { + RECT4_COEFF_HITS.with(|c| c.get()) +} + +/// Current value of `RECT4_32_HORZ_HITS` (32x8 strips decoded). +pub(crate) fn rect4_32_horz_hits() -> usize { + RECT4_32_HORZ_HITS.with(|c| c.get()) +} + +/// Current value of `RECT4_32_VERT_HITS` (8x32 strips decoded). +pub(crate) fn rect4_32_vert_hits() -> usize { + RECT4_32_VERT_HITS.with(|c| c.get()) +} + // lane-rect64q r1: how many of [`decode_block_rect64`]'s three per-plane // dequant calls actually observed `CURRENT_Q_IDX != base_q_idx` -- proof the // running-vs-stale-snapshot bug this round fixed is exercised by a gate, not @@ -1979,6 +2009,27 @@ const SCAN_8X32: [u16; 256] = [ 239, 246, 253, 247, 254, 255, ]; +/// `Default_Scan_16x4`, this decoder's own row-major transcription of +/// libaom's column-major `default_scan_16x4` (`scan.c:66`) -- the CHROMA +/// plane of a 32x8 `PARTITION_HORZ_4` strip at the 32x32 level +/// (lane-tx64x16 r3). The transcription rule (`row * w + col` with +/// `row = p % h`, `col = p / h`) was validated by REGENERATING the existing +/// [`SCAN_16X8`] from `default_scan_16x8` byte for byte before these two +/// were emitted -- a naive copy installs the transpose (class +/// reference-layout-not-spec). +const SCAN_16X4: [u16; 64] = [ + 0, 16, 1, 32, 17, 2, 48, 33, 18, 3, 49, 34, 19, 4, 50, 35, 20, 5, 51, 36, 21, 6, 52, 37, 22, 7, + 53, 38, 23, 8, 54, 39, 24, 9, 55, 40, 25, 10, 56, 41, 26, 11, 57, 42, 27, 12, 58, 43, 28, 13, + 59, 44, 29, 14, 60, 45, 30, 15, 61, 46, 31, 62, 47, 63, +]; +/// `Default_Scan_4x16`, [`SCAN_16X4`]'s transpose (the chroma plane of an +/// 8x32 `PARTITION_VERT_4` strip). +const SCAN_4X16: [u16; 64] = [ + 0, 1, 4, 2, 5, 8, 3, 6, 9, 12, 7, 10, 13, 16, 11, 14, 17, 20, 15, 18, 21, 24, 19, 22, 25, 28, + 23, 26, 29, 32, 27, 30, 33, 36, 31, 34, 37, 40, 35, 38, 41, 44, 39, 42, 45, 48, 43, 46, 49, 52, + 47, 50, 53, 56, 51, 54, 57, 60, 55, 58, 61, 59, 62, 63, +]; + /// [`neighbour`] with independent `w` (row stride)/`h` (row-bound) extents /// (lane-rectwire, mirrors [`record_rect`](Neighbours::record_rect)'s /// asymmetric-extent pattern). @@ -4817,6 +4868,280 @@ fn decode_leaf_rect( Ok(mode) } +/// Decodes one 32x8 / 8x32 strip of a 32x32-level `PARTITION_HORZ_4` / +/// `PARTITION_VERT_4` (lane-tx64x16 r3): [`decode_block_rect`]'s 4:1 sibling, +/// addressed by REAL mi coordinates for the same reason [`decode_leaf_rect`] +/// is -- strips 1 and 3 start 8 px into a 16-px [`SUB`] cell, which an +/// `at`-derived `px = c * SUB` cannot name. `prev_strip` carries the previous +/// strip's mode so this one's mode context sees its true above/left +/// neighbour inside the same 32x32 (`decode_leaf_rect`'s convention). +/// +/// Tables: LUMA `TX_32X8`/`TX_8X32` averages to the 16x16 entropy context +/// ([`TxbSet::LumaRect32x8`], 256 positions) and scans with +/// [`SCAN_32X8`]/[`SCAN_8X32`]; CHROMA `TX_16X4`/`TX_4X16` averages to the +/// 8x8 one ([`TxbSet::Chroma8`], 64 positions) and scans with +/// [`SCAN_16X4`]/[`SCAN_4X16`]. Neither shape takes the rect sqrt2 scale -- +/// `get_rect_tx_log_ratio` fires at ratio 1 only, and this is ratio 2 +/// (`inverse_transform_2d_typed_wh`'s own `rect_scale`). +/// +/// A split transform (`tx_depth != 0`) refuses by name: `depth_to_tx_size` of +/// a 4:1 strip is not simply `bw.min(bh) >> (depth - 1)` the way a 2:1 +/// strip's is, so [`decode_rect_split`]'s per-unit walk cannot be reused +/// unexamined. +#[allow(clippy::too_many_arguments)] +fn decode_block_rect4( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + strip_mi: (usize, usize), + bw: usize, + bh: usize, + prev_strip: Option<((usize, usize), usize)>, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + enable_filter_intra: bool, + allow_screen_content_tools: bool, + base_q_idx: u8, + tx_select: bool, +) -> Result<(usize, usize)> { + let _ = base_q_idx; + let (mi_r, mi_c) = strip_mi; + let (r, c) = (mi_r / (SUB / MI), mi_c / (SUB / MI)); + let (mi_w, mi_h) = (bw / MI, bh / MI); + let mut above_mode = neighbours.above_mode[c]; + let mut left_mode = neighbours.left_mode[r]; + if let Some(((pr, pc), pmode)) = prev_strip { + if pc == mi_c && mi_r == pr + mi_h { + above_mode = pmode; + } else if pr == mi_r && mi_c == pc + mi_w { + left_mode = pmode; + } + } + let (skip, mode, angle_delta_y, uv_mode, angle_delta_uv, alpha, filter_intra) = + read_intra_mode_rect( + dec, + cdfs, + above_mode, + left_mode, + true, + bw, + bh, + enable_filter_intra, + neighbours.skip_txfm_ctx(mi_r, mi_c), + allow_screen_content_tools, + mi_r, + mi_c, + )?; + let smooth_neighbor = is_smooth_mode(above_mode) || is_smooth_mode(left_mode); + if smooth_neighbor { + SMOOTH_LUMA_HITS.with(|c| c.set(c.get() + 1)); + } + let smooth_neighbor_uv = + is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]); + if filter_intra.is_some() { + FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1)); + } + let uv_predict_mode = if uv_mode == UV_CFL_PRED { + DC_PRED + } else { + uv_mode + }; + let depth = if tx_select { + let ctx = tx_size_context_rect(neighbours, (mi_r, mi_c), bw, bh); + dec.symbol(&mut cdfs.tx_size_cat2[ctx]) + } else { + 0 + }; + if depth != 0 { + return Err(unsupported( + "a 32x32-level 1:4 strip with a split transform (per-unit 4:1 prediction is not \ + ported)", + )); + } + // The coarse (16-px [`SUB`] cell) mode/side arrays cannot name a strip + // that is 8 px tall, so each strip stamps every cell it touches and the + // LAST strip wins -- which is the right answer for the block below/right + // of the 32x32, the only reader outside it. Written after this strip's + // own context read above, never before. + for cell in 0..bw.div_ceil(SUB) { + neighbours.above_mode[c + cell] = mode; + neighbours.above_uv_mode[c + cell] = uv_predict_mode; + neighbours.above_side[c + cell] = bw; + } + for cell in 0..bh.div_ceil(SUB) { + neighbours.left_mode[r + cell] = mode; + neighbours.left_uv_mode[r + cell] = uv_predict_mode; + neighbours.left_side[r + cell] = bh; + } + let (px, py) = (mi_c * MI, mi_r * MI); + let (cpx, cpy) = (px / 2, py / 2); + let (chroma_w, chroma_h) = (bw / 2, bh / 2); + let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); + let (luma_scan, chroma_scan): (&[u16], &[u16]) = if bw > bh { + (&SCAN_32X8, &SCAN_16X4) + } else { + (&SCAN_8X32, &SCAN_4X16) + }; + let (luma_levels, u_levels, v_levels) = if skip { + ( + vec![0i32; bw * bh], + vec![0i32; chroma_w * chroma_h], + vec![0i32; chroma_w * chroma_h], + ) + } else { + let around = neighbours.around_mi_rect((mi_r, mi_c), bw, bh); + let mut luma_coding = cdfs.txb(TxbSet::LumaRect32x8, mode); + let (luma_levels, luma_tx_type) = read_coeffs_rect( + dec, + &mut luma_coding, + luma_scan, + bw, + bh, + 0, + dc_sign_ctx(around[0].2), + TxType::DctDct, + )?; + let mut planes = Vec::with_capacity(2); + for plane in 1..3 { + let default_tx = default_intra_tx_type(uv_predict_mode as u8); + let skip_ctx = usize::from(around[plane].0) + usize::from(around[plane].1); + let mut coding = cdfs.txb(TxbSet::Chroma8, uv_predict_mode); + let (levels, tx_type) = read_coeffs_rect( + dec, + &mut coding, + chroma_scan, + chroma_w, + chroma_h, + skip_ctx, + dc_sign_ctx(around[plane].2), + default_tx, + )?; + planes.push((levels, tx_type)); + } + let (v_levels, v_tx_type) = planes.pop().expect("plane 2"); + let (u_levels, u_tx_type) = planes.pop().expect("plane 1"); + RECT4_COEFF_HITS.with(|c| c.set(c.get() + 1)); + let luma_residual = dequant_and_inverse_typed_wh( + &luma_levels, + bw, + bh, + crate::decode::bit_depth(), + block_q_idx(), + plane_q_delta(0).0, + plane_q_delta(0).1, + luma_tx_type, + ); + y.reconstruct_rect( + px, + py, + bw, + bh, + mode, + angle_delta_y, + reach, + &luma_residual, + None, + filter_intra, + smooth_neighbor, + ); + let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + for (plane, buf, levels, tx_type) in [ + (1usize, &mut *u, &u_levels, u_tx_type), + (2, &mut *v, &v_levels, v_tx_type), + ] { + let residual = dequant_and_inverse_typed_wh( + levels, + chroma_w, + chroma_h, + crate::decode::bit_depth(), + block_q_idx(), + plane_q_delta(plane).0, + plane_q_delta(plane).1, + tx_type, + ); + buf.reconstruct_rect( + cpx, + cpy, + chroma_w, + chroma_h, + uv_predict_mode, + angle_delta_uv, + reach, + &residual, + alpha + .zip(ac.as_deref()) + .map(|((au, av), ac)| (if plane == 1 { au } else { av }, ac)), + None, + smooth_neighbor_uv, + ); + } + neighbours.record_mi_rect( + (mi_r, mi_c), + bw, + bh, + &[luma_levels, u_levels, v_levels], + ); + neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip); + neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0); + if bw > bh { + RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1)); + } else { + RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1)); + } + return Ok((mode, uv_predict_mode)); + }; + y.reconstruct_rect( + px, + py, + bw, + bh, + mode, + angle_delta_y, + reach, + &luma_levels, + None, + filter_intra, + smooth_neighbor, + ); + let ac = alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + u.reconstruct_rect( + cpx, + cpy, + chroma_w, + chroma_h, + uv_predict_mode, + angle_delta_uv, + reach, + &u_levels, + alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), + None, + smooth_neighbor_uv, + ); + v.reconstruct_rect( + cpx, + cpy, + chroma_w, + chroma_h, + uv_predict_mode, + angle_delta_uv, + reach, + &v_levels, + alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), + None, + smooth_neighbor_uv, + ); + neighbours.record_mi_rect((mi_r, mi_c), bw, bh, &[luma_levels, u_levels, v_levels]); + neighbours.fill_skip_grid_rect((mi_r, mi_c), mi_w, mi_h, skip); + neighbours.fill_lf_grid_rect((mi_r, mi_c), mi_w, mi_h, bw as u8, bh as u8, 0); + if bw > bh { + RECT4_32_HORZ_HITS.with(|c| c.set(c.get() + 1)); + } else { + RECT4_32_VERT_HITS.with(|c| c.set(c.get() + 1)); + } + Ok((mode, uv_predict_mode)) +} + /// Decodes one true `bw`x`bh` superblock-level `PARTITION_HORZ`/ /// `PARTITION_VERT` strip (lane-sbpart r2, `bw, bh` one of `(64, 32)` / /// `(32, 64)` -- [`decode_block_rect`]'s own sibling one level up). Unlike @@ -9411,6 +9736,47 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( reduced_tx_set, )?; } + PARTITION_HORZ_4 | PARTITION_VERT_4 => { + // lane-tx64x16 r3: the 1:4 pair at the 32x32 + // level -- four 32x8 (or 8x32) strips in + // raster order, `quarter_step` = 2 mi, with + // libaom `decode_partition`'s own `i > 0` + // frame-edge break. + let horz = part32 == PARTITION_HORZ_4; + let base_mi = (at32.0 * (SUB / MI), at32.1 * (SUB / MI)); + let mut prev: Option<((usize, usize), usize)> = None; + for i in 0..4 { + let strip_mi = if horz { + (base_mi.0 + i * 2, base_mi.1) + } else { + (base_mi.0, base_mi.1 + i * 2) + }; + if i > 0 + && (strip_mi.0 >= mi_rows as usize + || strip_mi.1 >= mi_cols as usize) + { + break; + } + let (bw, bh) = if horz { (32, 8) } else { (8, 32) }; + let (mode, _uv) = decode_block_rect4( + &mut dec, + &mut cdfs, + &mut neighbours, + strip_mi, + bw, + bh, + prev, + &mut y, + &mut u, + &mut v, + enable_filter_intra, + allow_screen_content_tools, + base_q_idx, + tx_select, + )?; + prev = Some((strip_mi, mode)); + } + } _ => { return Err(unsupported(format!( "a 32x32 partition type this decoder does not code (value={part32})" @@ -16470,38 +16836,33 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs( mod tests { use super::*; - /// libaom's generating rule (`txb_common.h:199-209`) in DISPLAY - /// coordinates, pinned against the two rect transcriptions in [`cdf`]. - /// lane-tx64x16 r2: this test read the tables `[col][row]` (lane-rectsplit - /// r2's column-major premise) while r3 reverted the tables themselves to - /// display-major `[row][col]` -- the order [`base_ctx`] itself reads them - /// at `decode.rs`'s `TxClass::TwoD` arm, and the order every merged rect - /// gate is green under. The test was left pinning the abandoned half, so - /// it failed on `main` (32x64 display (row 0, col 2): table says 6 read - /// transposed, the rule says 11). Read in the consumer's order. + /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR -- + /// `SCAN_4X16[i]` must name the transpose of the position + /// `SCAN_16X4[i]` names (class scan-weights-cross-axis: a naive copy of + /// libaom's column-major `default_scan_*` installs the transpose and only + /// an asymmetric check catches it). Also pins both as permutations, and + /// pins the same relation for the 32x8/8x32 luma pair this arm reuses. #[test] - fn nz_map_ctx_offset_tables_match_the_rect_rule() { - for (w, h, table) in [ - (32usize, 64usize, &cdf::NZ_MAP_CTX_OFFSET_32X64), - (64, 32, &cdf::NZ_MAP_CTX_OFFSET_64X32), + fn the_rect4_scans_are_transposed_pairs() { + for (a, b, w, h) in [ + (&SCAN_16X4[..], &SCAN_4X16[..], 16usize, 4usize), + (&SCAN_32X8[..], &SCAN_8X32[..], 32, 8), ] { - for row in 0..5usize { - for col in 0..5usize { - let want = if row == 0 && col == 0 { - 0 - } else if w < h && row < 2 { - 11 - } else if w > h && col < 2 { - 16 - } else { - cdf::NZ_MAP_CTX_OFFSET_32[row][col] - }; - assert_eq!( - table[row][col], - want, - "{w}x{h} nz_map offset at display (row {row}, col {col})" - ); - } + let mut seen_a: Vec = a.to_vec(); + seen_a.sort_unstable(); + assert_eq!( + seen_a, + (0..(w * h) as u16).collect::>(), + "{w}x{h} scan is not a permutation of its positions" + ); + for (i, (&pa, &pb)) in a.iter().zip(b.iter()).enumerate() { + let (row, col) = (pa as usize / w, pa as usize % w); + assert_eq!( + pb as usize, + col * w.min(h) + row, + "scan step {i}: {w}x{h} visits (row {row}, col {col}) but its transpose \ + visits position {pb}" + ); } } } @@ -16528,10 +16889,20 @@ mod tests { // An all-zero neighbourhood makes the magnitude term 0, // so `base_ctx` returns the offset itself. let got = base_ctx(&grid, 32, row, col, TxClass::TwoD, shape); + // lane-tx64x16 r3, on cherry-picking this test onto main: + // `main`'s two rect transcriptions in [`cdf`] are the + // TRANSPOSE of lane-rectsplit's (main's + // `NZ_MAP_CTX_OFFSET_64X32` row 0 is `[0, 16, 6, 6, 21]`, + // rectsplit's is `[0, 16, 16, 16, 16]`), so the same rule + // is pinned here as `[row][col]`. The consumer reads + // NEITHER -- `base_ctx` states libaom's generating rule + // directly -- so the layouts are equivalent for decoding; + // whoever merges both branches must keep table layout and + // this index in step. let want = if row == 0 && col == 0 { 0 } else { - table[col][row] as usize + table[row][col] as usize }; assert_eq!(got, want, "{shape:?} at (row {row}, col {col})"); } diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 65f44ae3..0c0034d1 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -1100,9 +1100,22 @@ impl Drop for VertAbGuard { /// r1: the two rect strips PARTITION_HORZ/VERT ever produce at the 32x32 /// level, transcribed verbatim (not derived): `[0]` is 32-wide, `[1]` is /// 16-wide. -const HAS_TOP_RIGHT_RECT: [&[u8]; 2] = [&[15, 5, 7, 5], &[255, 119, 127, 119]]; +const HAS_TOP_RIGHT_RECT: [&[u8]; 4] = [ + &[15, 5, 7, 5], + &[255, 119, 127, 119], + // lane-tx64x16 r3: `has_tr_32x8` / `has_tr_8x32` (`reconintra.c:122-127`), + // the 4:1 strips of a 32x32-level `PARTITION_HORZ_4`/`VERT_4`. + &[15, 0, 5, 0, 7, 0, 5, 0], + &[255, 255, 127, 127, 255, 127, 127, 127], +]; /// `has_bl_32x16`/`has_bl_16x32`, same source, same order. -const HAS_BOTTOM_LEFT_RECT: [&[u8]; 2] = [&[78, 14, 78, 14], &[16, 0, 16, 0]]; +const HAS_BOTTOM_LEFT_RECT: [&[u8]; 4] = [ + &[78, 14, 78, 14], + &[16, 0, 16, 0], + // `has_bl_32x8` / `has_bl_8x32` (`reconintra.c:305-310`). + &[238, 78, 238, 14, 238, 78, 238, 14], + &[0, 1, 0, 0, 0, 1, 0, 0], +]; impl Reach { /// What a block of `side` samples at `(x, y)` may read past its own edges, @@ -1150,7 +1163,7 @@ impl Reach { if col + 1 == per_col { return false; } - let table = HAS_TOP_RIGHT_RECT[usize::from(bw == 16)]; + let table = HAS_TOP_RIGHT_RECT[Self::rect_table(bw, bh)]; Self::bit(table, (row * Self::table_stride(bw) + col) % (table.len() * 8)) } @@ -1162,7 +1175,7 @@ impl Reach { if row + 1 == per_row { return false; } - let table = HAS_BOTTOM_LEFT_RECT[usize::from(bw == 16)]; + let table = HAS_BOTTOM_LEFT_RECT[Self::rect_table(bw, bh)]; Self::bit(table, (row * Self::table_stride(bw) + col) % (table.len() * 8)) } @@ -1260,6 +1273,18 @@ impl Reach { /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative) /// here instead indexes the wrong bit for every block size but the one /// where 64 and 128 give the same stride. + /// Which row of [`HAS_TOP_RIGHT_RECT`]/[`HAS_BOTTOM_LEFT_RECT`] a + /// rectangular block reads. The 2:1 pair keeps its historical + /// `bw == 16` selector; the 4:1 pair (lane-tx64x16 r3) is named + /// explicitly, so no existing shape changes row. + fn rect_table(bw: usize, bh: usize) -> usize { + match (bw, bh) { + (32, 8) => 2, + (8, 32) => 3, + _ => usize::from(bw == 16), + } + } + fn table_stride(side: usize) -> usize { 128 / side } diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index bf230a4e..a44c3b7d 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -43,6 +43,7 @@ const REFUSALS: &[&str] = &[ "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet", "a 32x32 partition type this decoder does not code (value={part32})", + "a 32x32-level 1:4 strip with a split transform (per-unit 4:1 prediction is not ported)", "a Golomb tail longer than this decoder reads", "a tx_type symbol outside its CDF's own set: {t}", "an INTER 32x32 partition type this decoder does not code (value={part32})", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 58c7e403..4ec07432 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -13132,4 +13132,239 @@ mod tests { mismatched -- other lanes' shapes)" ); } + + /// lane-tx64x16 r3: the 32x32-LEVEL 1:4 pair -- `PARTITION_HORZ_4` / + /// `PARTITION_VERT_4` at 32x32, i.e. four 32x8 / 8x32 strips, the arm the + /// ReelB mid-film extract stops at ("a 32x32 partition type this + /// decoder does not code (value=8)"). `--min-partition-size=8` is what + /// lets aomenc's RD reach the 32-level 1:4 shapes; `--max-partition-size=32` + /// keeps the superblock-level pair (already gated by its own test above) + /// out of the counters. Both orientations HARD-asserted per bit depth -- + /// the luma scans and the two new chroma scans (`SCAN_16X4`/`SCAN_4X16`) + /// are transposed pairs, so a one-sided gate cannot catch a transposition + /// (class scan-weights-cross-axis). `rect4_coeff_hits` is asserted too: + /// an all-skip stream would exercise none of the new coefficient tables + /// (class gate-blind-to-feature). Only hits earned inside an attempt that + /// then compared pixel-exact are counted (class + /// gate-skips-on-its-own-failure); the 10-bit arm is what retires + /// `enable-1to4-partitions` from `NEVER_EXERCISED_10BIT`. + #[test] + // lane-tx64x16 r3, MEASURED, not a hunch: no recipe tried this round makes + // aomenc's RD emit a 32x32-level 1:4 partition on synthetic fixtures -- + // 20/20 attempts of the recipe below (min-partition-size=8, + // max-partition-size=32) carried ZERO 32-level 1:4 blocks, as did a + // vertically-squeezed variant and a horizontally-blurred one (the latter + // additionally tripped the screen-content refusal). The wiring IS + // exercised by real content -- see this round's report for the film probe + // -- but until a fixture recipe is found this gate can prove nothing, and + // a gate that passes by never seeing its feature is worse than an ignored + // one (class gate-blind-to-feature). Un-ignore with the recipe, never with + // a weakened assert. + #[ignore = "no fixture recipe yet emits a 32-level 1:4 partition (lanes/tx64x16-r3.report.md)"] + fn a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact() { + const NAME: &str = + "a_real_aomenc_stream_with_a_32x32_level_1to4_partition_decodes_pixel_exact"; + let _gate_lock = lock_gate_counters(); + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + if !have_aomenc() { + eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display()); + return; + } + let (width, height, frame_count) = (192usize, 128usize, 1usize); + let n_attempts: u32 = std::env::var("EC_TX64X16_GATE32_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(20); + for bit_depth in [8u32, 10u32] { + let mut named_refusals = 0u32; + let mut matched = 0u32; + let (mut horz_proved, mut vert_proved, mut coeff_proved) = (0usize, 0usize, 0usize); + let (mut out_of_scope, mut out_of_scope_mismatch) = (0u32, 0u32); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let duration = frame_count as f64 / 25.0; + // Odd attempts render the SAME generator rotated 90 degrees, + // the transposed-pair discipline the superblock-level 1:4 + // gate above documents. + let source = if attempt % 2 == 0 { + gradients_source(seed, width, height, &format!("duration={duration}:rate=25")) + } else { + format!( + "{},transpose=1", + gradients_source( + seed, + height, + width, + &format!("duration={duration}:rate=25") + ) + ) + }; + let pix_fmt = if bit_depth == 10 { "yuv420p10le" } else { "yuv420p" }; + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, "-t", &duration.to_string(), + "-pix_fmt", pix_fmt, "-strict", "-1", "-f", "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "{NAME}: ffmpeg refused the {bit_depth}-bit fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + let depth_arg = format!("--bit-depth={bit_depth}"); + let input_depth_arg = format!("--input-bit-depth={bit_depth}"); + let args: Vec<&str> = vec![ + "--codec=av1", + "--passes=1", + "--end-usage=q", + "--cq-level=45", + "--cpu-used=0", + "--threads=1", + "--row-mt=0", + "--sb-size=64", + &depth_arg, + &input_depth_arg, + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=1", + "--min-partition-size=8", + "--max-partition-size=32", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=0", + "--enable-tx-size-search=0", + "--obu", + "-o", + "-", + "-", + ]; + let mut child = Command::new(aomenc_path()) + .args(&args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("aomenc failed to start"); + child + .stdin + .take() + .expect("aomenc stdin") + .write_all(&y4m.stdout) + .expect("writing y4m to aomenc"); + let out = child.wait_with_output().expect("aomenc failed to run"); + assert!( + out.status.success(), + "aomenc refused the fixture: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stream = out.stdout; + let before = ( + crate::decode::rect4_32_horz_hits(), + crate::decode::rect4_32_vert_hits(), + crate::decode::rect4_coeff_hits(), + ); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal ({bit_depth}-bit, seed \ + {seed}): {msg}" + ); + named_refusals += 1; + eprintln!("{bit_depth}-bit seed {seed} refusal: {msg}"); + continue; + } + Ok(frames) => frames, + }; + let (horz, vert, coeff) = ( + crate::decode::rect4_32_horz_hits() - before.0, + crate::decode::rect4_32_vert_hits() - before.1, + crate::decode::rect4_coeff_hits() - before.2, + ); + let ffmpeg_frames = if bit_depth == 10 { + ffmpeg_decode_sequence_10bit(&stream, width, height, frame_count) + } else { + ffmpeg_decode_sequence(&stream, width, height, frame_count) + }; + assert_eq!(frames.len(), frame_count); + let mismatched = frames + .iter() + .zip(&ffmpeg_frames) + .any(|(got, want)| got.y != want.y || got.u != want.u || got.v != want.v); + if horz + vert == 0 { + // Out of this gate's territory (no 32-level 1:4 block in + // the stream): counted and printed, never silently + // dropped, and a mismatch here is another shape's defect. + out_of_scope += 1; + if mismatched { + out_of_scope_mismatch += 1; + eprintln!( + "{NAME}: {bit_depth}-bit seed {seed} MISMATCHES with zero 32-level \ + 1:4 blocks -- a pre-existing defect of another shape" + ); + } + continue; + } + if mismatched { + if let Ok(path) = std::env::var("EC_AV1_GATE_DUMP") { + std::fs::write(&path, &stream).expect("writing pinned stream"); + eprintln!( + "EC_AV1_GATE_DUMP: wrote mismatching stream ({bit_depth}-bit, seed \ + {seed}) to {path}" + ); + } + } + for (i, (got, want)) in frames.iter().zip(&ffmpeg_frames).enumerate() { + assert_eq!( + got.y, want.y, + "{NAME} frame {i} luma vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + assert_eq!( + got.u, want.u, + "{NAME} frame {i} U vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + assert_eq!( + got.v, want.v, + "{NAME} frame {i} V vs ffmpeg ({bit_depth}-bit, seed {seed})" + ); + } + horz_proved += horz; + vert_proved += vert; + coeff_proved += coeff; + matched += 1; + } + assert!( + matched > 0, + "{NAME}: every {bit_depth}-bit attempt refused; the gate never decoded a stream" + ); + assert!( + horz_proved > 0 && vert_proved > 0, + "{NAME}: a 32-level 1:4 arm never fired inside a pixel-exact {bit_depth}-bit \ + attempt (horz={horz_proved}, vert={vert_proved}, {matched} matches, \ + {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run" + ); + assert!( + coeff_proved > 0, + "{NAME}: every {bit_depth}-bit 32-level 1:4 strip was skip -- the 32x8/16x4 \ + coefficient tables were never read" + ); + eprintln!( + "{NAME}: {bit_depth}-bit: {named_refusals} named refusals, {matched} pixel-exact \ + matches out of {n_attempts}, horz_4 strips={horz_proved}, vert_4 \ + strips={vert_proved}, coded strips={coeff_proved}, {out_of_scope} attempts \ + carried no 32-level 1:4 block ({out_of_scope_mismatch} mismatched)" + ); + } + } }