diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index be8f124f..58b0cd18 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -428,6 +428,20 @@ pub(crate) fn horz_vert_intra_hits() -> usize { HORZ_VERT_INTRA_HITS.with(|c| c.get()) } +// How many HORZ/VERT intra strips resolved a SPLIT luma transform +// (`tx_depth != 0`) and decoded it per transform unit (lane-rectsplit r1) -- +// the case every rect path here refused by name before, and the first +// refusal the user's ReelB extract (600s in) stops at. +thread_local! { + static RECT_SPLIT_TX_HITS: std::cell::Cell = + const { std::cell::Cell::new(0) }; +} + +/// Current value of [`RECT_SPLIT_TX_HITS`]. +pub(crate) fn rect_split_tx_hits() -> usize { + RECT_SPLIT_TX_HITS.with(|c| c.get()) +} + // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D` // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every // call on the current thread -- the same before/after counter pattern as @@ -2559,32 +2573,55 @@ impl Neighbours { mode: usize, uv_mode: usize, chroma_grids: [&[i32]; 2], + ) { + self.record_split_luma_rect(at, side, side, mode, uv_mode, chroma_grids); + } + + /// [`Self::record_split_luma`] with independent above (`w`)/left (`h`) + /// extents in pixels (lane-rectsplit r1), the same relationship + /// [`Self::record_rect`] has to [`Self::record`]: a HORZ/VERT strip whose + /// luma transform split into several square units needs exactly this + /// bookkeeping, at its own true rectangular extents. + fn record_split_luma_rect( + &mut self, + at: (usize, usize), + w: usize, + h: usize, + mode: usize, + uv_mode: usize, + chroma_grids: [&[i32]; 2], ) { let (r, c) = at; - for cell in 0..side / SUB { + for cell in 0..w / SUB { self.above_mode[c + cell] = mode; - self.left_mode[r + cell] = mode; self.above_uv_mode[c + cell] = uv_mode; + self.above_side[c + cell] = w; + } + for cell in 0..h / SUB { + self.left_mode[r + cell] = mode; self.left_uv_mode[r + cell] = uv_mode; - self.above_side[c + cell] = side; - self.left_side[r + cell] = side; + self.left_side[r + cell] = h; } let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); - let side_mi = side / MI; - for cell in 0..side_mi { - self.left_side_mi[mi_r + cell] = side; - self.above_side_mi[mi_c + cell] = side; + let (w_mi, h_mi) = (w / MI, h / MI); + for cell in 0..h_mi { + self.left_side_mi[mi_r + cell] = h; + } + for cell in 0..w_mi { + self.above_side_mi[mi_c + cell] = w; } let round_up_even = |n: usize| n.div_ceil(2) * 2; let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols)); for (plane_idx, grid) in chroma_grids.into_iter().enumerate() { let plane = plane_idx + 1; let state = neighbour_state(grid); - for cell in 0..side_mi { - if cell < side_mi.min(bound_h.saturating_sub(mi_r)) { + for cell in 0..h_mi { + if cell < h_mi.min(bound_h.saturating_sub(mi_r)) { self.left[mi_r + cell][plane] = state; } - if cell < side_mi.min(bound_w.saturating_sub(mi_c)) { + } + for cell in 0..w_mi { + if cell < w_mi.min(bound_w.saturating_sub(mi_c)) { self.above[mi_c + cell][plane] = state; } } @@ -3102,6 +3139,249 @@ fn cfl_ac_q3_rect(y: &PlaneBuf, px: usize, py: usize, bw: usize, bh: usize) -> V ac } +/// Everything a rect strip already read out of the stream before its luma +/// transform units are decoded -- [`decode_rect_split`]'s own mode bundle +/// (nine values that would otherwise be nine more parameters). +struct RectStripModes { + skip: bool, + mode: usize, + angle_delta_y: i32, + uv_predict_mode: usize, + angle_delta_uv: i32, + alpha: Option<(i32, i32)>, + filter_intra: Option, + smooth_neighbor: bool, + smooth_neighbor_uv: bool, +} + +/// Decodes the planes of one `bw`x`bh` HORZ/VERT intra strip whose luma +/// transform is SPLIT (`tx_depth != 0`) -- lane-rectsplit r1, the case every +/// rect path here refused by name until now ("per-unit rect prediction is not +/// ported"). +/// +/// `depth_to_tx_size` (libaom `blockd.h`) walks `sub_tx_size_map` `depth` +/// times from the block's own `max_txsize_rect_lookup` entry, and for a 2:1 +/// strip the very first step already lands on a SQUARE transform +/// (`sub_tx_size_map[TX_32X16] == TX_16X16`, `[TX_64X32] == TX_32X32`, and +/// every further step halves a square) -- so each unit is square and reads +/// through the ordinary square [`read_plane`]. What is genuinely rectangular +/// here is the *tiling* (`bw/tx` by `bh/tx` units, not `n` by `n` as +/// [`decode_block`]'s square split loop assumes) and the chroma plane, whose +/// own transform is `av1_get_max_uv_txsize` of the whole strip and is never +/// split by luma's depth. +/// +/// Each unit predicts off whatever the earlier units of this same block +/// already reconstructed (spec 5.11.36 `predict_and_reconstruct_intra_block` +/// inside `av1_foreach_transformed_block`, raster order), which is exactly +/// what predicting the whole strip in one shot got wrong. +#[allow(clippy::too_many_arguments)] +fn decode_rect_split( + dec: &mut SymbolDecoder, + cdfs: &mut Cdfs, + neighbours: &mut Neighbours, + at: (usize, usize), + bw: usize, + bh: usize, + tx: usize, + m: &RectStripModes, + y: &mut PlaneBuf, + u: &mut PlaneBuf, + v: &mut PlaneBuf, + base_q_idx: u8, + reduced_tx_set: bool, +) -> Result<()> { + let (r, c) = at; + let (px, py) = (c * SUB, r * SUB); + let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); + let (cpx, cpy) = (px / 2, py / 2); + let (chroma_w, chroma_h) = (bw / 2, bh / 2); + // The chroma transform is picked before any symbol is read, so an + // unsupported chroma shape refuses before this strip desyncs the tile. + let chroma: Option<(TxbSet, &[u16])> = match (chroma_w, chroma_h) { + (16, 8) => Some((TxbSet::ChromaRect16x8, &SCAN_16X8[..])), + (8, 16) => Some((TxbSet::ChromaRect16x8, &SCAN_8X16[..])), + (32, 16) => Some((TxbSet::ChromaRect32x16, &SCAN_32X16[..])), + (16, 32) => Some((TxbSet::ChromaRect32x16, &SCAN_16X32[..])), + _ => None, + }; + if !m.skip && chroma.is_none() { + return Err(unsupported( + "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", + )); + } + RECT_SPLIT_TX_HITS.with(|c| c.set(c.get() + 1)); + // LUMA: `bw/tx` x `bh/tx` square transform units, raster order. + let luma_set = txbset_for(tx, reduced_tx_set); + let luma_scan = default_scan(tx); + let zero_tu = vec![0i32; tx * tx]; + // The strip's OWN edge availability, the fallback for a transform unit + // whose top-right/bottom-left pixels fall outside the strip. + let block_reach = Reach::of_rect(bw, bh, px, py, y.width, y.height); + for tu_row in 0..bh / tx { + for tu_col in 0..bw / tx { + let tu_mi = (mi_r + tu_row * (tx / MI), mi_c + tu_col * (tx / MI)); + let (tu_px, tu_py) = (px + tu_col * tx, py + tu_row * tx); + let (col_off, row_off) = (tu_col * tx, tu_row * tx); + // `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a + // transform unit INSIDE a block, which is a different rule from + // the standalone-block table [`Reach::of`] applies -- and the + // reason a depth-2 superblock strip came out one sample off + // before this: `Reach::of(tx, ..)` answered as if the unit were + // its own block at that superblock position. + // * top-right: if the unit's right neighbour is still inside the + // strip the pixels are already reconstructed (`col_off + + // tx_wide < plane_bw`); otherwise only the strip's own top row + // of units can reach past it, through the block-level answer. + // * bottom-left: a unit that is not in the strip's left column + // has none (`col_off > 0` returns 0); inside the strip + // (`row_off + tx_high < plane_bh`) they are the left + // neighbour's, already reconstructed; the last row falls back + // to the block-level answer. + let tu_reach = Reach { + above_right: if col_off + tx < bw { + true + } else { + row_off == 0 && block_reach.above_right + }, + below_left: if col_off > 0 { + false + } else if row_off + tx < bh { + true + } else { + block_reach.below_left + }, + }; + if m.skip { + y.reconstruct( + tu_px, + tu_py, + tx, + m.mode, + m.angle_delta_y, + tu_reach, + &zero_tu, + None, + m.filter_intra, + m.smooth_neighbor, + ); + neighbours.record_mi_luma(tu_mi, tx, &zero_tu); + } else { + let tu_around = neighbours.around_mi(tu_mi, tx)[0]; + // This unit is smaller than the block it sits in, so + // `txb_skip_ctx` is the neighbour-magnitude table, not the + // lone-TU 0 (spec `get_txb_ctx_general`). + let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, tx / MI); + let tu_grid = read_plane( + dec, + cdfs, + luma_set, + &luma_scan, + 0, + tu_around, + m.mode, + m.mode, + m.angle_delta_y, + tu_reach, + y, + tu_px, + tu_py, + tx, + tx, + base_q_idx, + None, + m.filter_intra, + Some(tu_skip_ctx), + m.smooth_neighbor, + )?; + neighbours.record_mi_luma(tu_mi, tx, &tu_grid); + } + } + } + // CHROMA: one un-split rect transform for the whole strip. + let ac = m.alpha.map(|_| cfl_ac_q3_rect(y, px, py, bw, bh)); + let reach = block_reach; + let (u_grid, v_grid) = if m.skip { + let zero = vec![0i32; chroma_w * chroma_h]; + u.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, + m.alpha.zip(ac.as_deref()).map(|((au, _), ac)| (au, ac)), None, m.smooth_neighbor_uv, + ); + v.reconstruct_rect( + cpx, cpy, chroma_w, chroma_h, m.uv_predict_mode, m.angle_delta_uv, reach, &zero, + m.alpha.zip(ac.as_deref()).map(|((_, av), ac)| (av, ac)), None, m.smooth_neighbor_uv, + ); + (zero.clone(), zero) + } else { + let (chroma_set, chroma_scan) = chroma.expect("refused above when None"); + // `av1_get_ext_tx_set_type`: a chroma transform whose square-up size + // is TX_32X32 or bigger resolves to `EXT_TX_SET_DCTONLY` for intra, + // so only the 16x8/8x16 pair takes the mode-indexed default. + let default_tx = if chroma_w.max(chroma_h) >= 32 { + TxType::DctDct + } else { + default_intra_tx_type(m.uv_predict_mode as u8) + }; + let around = neighbours.around_rect(at, bw, bh); + let mut grids: Vec> = Vec::with_capacity(2); + for plane_idx in 1..=2 { + let skip_ctx = + usize::from(around[plane_idx].0) + usize::from(around[plane_idx].1); + let mut coding = cdfs.txb(chroma_set, m.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_idx].2), + default_tx, + )?; + let residual = dequant_and_inverse_typed_wh( + &levels, + chroma_w, + chroma_h, + crate::decode::bit_depth(), + CURRENT_Q_IDX.with(|c| c.get()), + plane_q_delta(plane_idx).0, + plane_q_delta(plane_idx).1, + tx_type, + ); + let cfl = m + .alpha + .zip(ac.as_deref()) + .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)); + let plane = if plane_idx == 1 { &mut *u } else { &mut *v }; + plane.reconstruct_rect( + cpx, + cpy, + chroma_w, + chroma_h, + m.uv_predict_mode, + m.angle_delta_uv, + reach, + &residual, + cfl, + None, + m.smooth_neighbor_uv, + ); + grids.push(levels); + } + let mut it = grids.into_iter(); + (it.next().unwrap(), it.next().unwrap()) + }; + neighbours.record_split_luma_rect(at, bw, bh, m.mode, m.uv_predict_mode, [&u_grid, &v_grid]); + neighbours.fill_skip_grid_rect((mi_r, mi_c), bw / MI, bh / MI, m.skip); + neighbours.fill_lf_grid_rect((mi_r, mi_c), bw / MI, bh / MI, tx as u8, tx as u8, 0); + if std::env::var_os("EC_AV1_TRACE").is_some() { + let (rng, _) = dec.debug_state(); + eprintln!( + "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} tx={tx} rng={rng}" + ); + } + Ok(()) +} + /// Decodes one true `bw`x`bh` `PARTITION_HORZ`/`PARTITION_VERT` intra strip /// (lane-intradisp r1, spec `decode_block` restricted to a 32x32 quadrant's /// two rect children). Only the `skip` case is supported: `skip`/`y_mode`/ @@ -3127,6 +3407,7 @@ fn decode_block_rect( allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, + reduced_tx_set: bool, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); @@ -3186,15 +3467,28 @@ fn decode_block_rect( }; if depth != 0 { TX_DEPTH_HITS.with(|c| c.set(c.get() + 1)); - // A split transform is predicted per transform unit, each taking its - // edges from the previous unit's reconstruction (the square path's own - // per-TU loop does exactly that). Predicting the whole strip in one - // shot would silently produce different pixels, so refuse by name - // until that loop is ported for rect strips. - return Err(unsupported( - "a HORZ/VERT intra strip with a split transform (per-unit rect \ - prediction is not ported)", - )); + // lane-rectsplit r1: a split transform is predicted and reconstructed + // per transform unit, each unit taking its edges from the previous + // unit's reconstruction inside this same strip (spec 5.11.36) -- + // [`decode_rect_split`]. `depth_to_tx_size` of a 2:1 strip is square + // from the first step on, so `bw.min(bh) >> (depth - 1)` names it. + let tx = bw.min(bh) >> (depth - 1); + let modes = RectStripModes { + skip, + mode, + angle_delta_y, + uv_predict_mode, + angle_delta_uv, + alpha, + filter_intra, + smooth_neighbor, + smooth_neighbor_uv, + }; + decode_rect_split( + dec, cdfs, neighbours, at, bw, bh, tx, &modes, y, u, v, base_q_idx, reduced_tx_set, + )?; + RECT_PARTITION_HITS.with(|c| c.set(c.get() + 1)); + return Ok(()); } let (tx_w, tx_h) = (bw, bh); let (cpx, cpy) = (px / 2, py / 2); @@ -3637,6 +3931,7 @@ fn decode_block_rect64( allow_screen_content_tools: bool, base_q_idx: u8, tx_select: bool, + reduced_tx_set: bool, ) -> Result<()> { let (r, c) = at; let (px, py) = (c * SUB, r * SUB); @@ -3687,12 +3982,31 @@ fn decode_block_rect64( let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI)); 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]) + // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`) + // counts `sub_tx_size_map` steps from the block's own max rect + // transform down to TX_4X4, minus one -- BLOCK_64X32's chain + // (TX_64X32 -> TX_32X32 -> TX_16X16 -> TX_8X8 -> TX_4X4) is four + // steps, so this level's category is 3 (the same one a 64x64 square + // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF + // here was a wrong-table read of a real symbol. + dec.symbol(&mut cdfs.tx_size_cat3[ctx]) } else { 0 }; if depth != 0 { TX_DEPTH_HITS.with(|c| c.set(c.get() + 1)); + // lane-rectsplit r1: [`decode_rect_split`] handles this shape too + // (`sub_tx_size_map[TX_64X32]` is `TX_32X32`, so a depth-1 unit here + // is a plain square 32x32) and its 32x32-level sibling arm in + // [`decode_block_rect`] is gated pixel-exact -- but at the SUPERBLOCK + // level the gate + // (`a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact`, + // `#[ignore]`d with its measurement) still comes out ONE sample off + // (seed 50, luma (171,56) ours 147 vs ffmpeg 148, inside a 64x32 + // strip whose transform resolved to depth 2 / TX_16X16). A refusal + // this lane could not lift is not a refusal it may silently ship + // wrong pixels past, so the named refusal stays until that gate is + // green. return Err(unsupported( "a superblock-level HORZ/VERT strip with a split transform (per-unit rect \ prediction is not ported)", @@ -6922,6 +7236,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; // Two 8x8 squares stacked on the // right, chained through @@ -7226,6 +7541,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect( &mut dec, @@ -7241,6 +7557,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } PARTITION_VERT => { @@ -7260,6 +7577,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect( &mut dec, @@ -7275,6 +7593,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } _ => { @@ -7301,6 +7620,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect64( &mut dec, @@ -7316,6 +7636,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } PARTITION_VERT => { @@ -7335,6 +7656,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; decode_block_rect64( &mut dec, @@ -7350,6 +7672,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs( allow_screen_content_tools, base_q_idx, tx_select, + reduced_tx_set, )?; } _ => { diff --git a/crates/ec-av1/src/refusal_inventory.rs b/crates/ec-av1/src/refusal_inventory.rs index fb771602..5c6a41a7 100644 --- a/crates/ec-av1/src/refusal_inventory.rs +++ b/crates/ec-av1/src/refusal_inventory.rs @@ -37,6 +37,7 @@ const REFUSALS: &[&str] = &[ "GLOBALMV (round 3)", "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)", "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)", + "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here", "a HORZ_A/HORZ_B/VERT_A partition below 16x16 (this decoder codes only the square arms, HORZ, VERT, VERT_B, and a clean split below 16x16)", "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", @@ -49,7 +50,6 @@ const REFUSALS: &[&str] = &[ "an INTER 32x32 partition type this decoder does not code (value={part32})", "a superblock-level partition type other than NONE or SPLIT (this decoder's intra tile path codes only those two at 64x64)", "a HORZ/VERT intra strip in a screen-content frame (palette syntax is consumed for square blocks only)", - "a HORZ/VERT intra strip with a split transform (per-unit rect prediction is not ported)", "a block that actually uses a palette (UV) -- reconstruction is out of scope", "a block that actually uses a palette (Y) -- reconstruction is out of scope", "a block that actually uses intrabc (this decoder never reconstructs one)", diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 8a2b0df0..02d269af 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -9333,6 +9333,351 @@ mod tests { ); } + /// lane-rectsplit r1 gate (a): a real `aomenc` key frame whose 32x32 + /// quadrants split HORZ/VERT into true 32x16/16x32 strips, with the + /// tx-size search left at aomenc's own default (ON) -- every sibling + /// recipe in this file pins `--enable-tx-size-search=0`, which is exactly + /// why the split-transform strip was never exercised. RD is then free to + /// give a strip a transform smaller than its own size, the case + /// [`crate::decode::decode_block_rect`] refused by name ("a HORZ/VERT + /// intra strip with a split transform (per-unit rect prediction is not + /// ported)") until this round ported the per-transform-unit predict-and- + /// reconstruct loop. Hard-asserts a nonzero `rect_split_tx_hits()` delta: + /// without it a stream that resolved every `tx_depth` to 0 would + /// pixel-match by construction and prove nothing. A decode error that is + /// not a named refusal, and any pixel mismatch, FAIL -- only a missing + /// tool skips. + #[test] + fn a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_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) = (192usize, 128usize); + let before = crate::decode::rect_split_tx_hits(); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let mut split_so_far = 0usize; + // Bounded sweep: see this gate's own doc for the seed-77 residue and + // why extending it is a diagnosis knob, not a pass/fail one. + let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(20); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, + // Desaturated (`hue=s=0`, the same guard + // `a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact` + // uses): with the tx-size search ON, a real chroma + // gradient hits a PRE-EXISTING chroma defect on the plain + // SQUARE path -- measured this round with + // `--enable-rect-partitions=0` on this very recipe, seed + // 42, U plane, i.e. with no rect strip in the stream at + // all. Flat chroma keeps that unrelated defect out of + // this gate (gate-recipe-confound class); it is open + // residue in lanes/rectsplit-r1.report.md, not fixed here. + "-vf", "hue=s=0", + "-pix_fmt", "yuv420p", "-f", + "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's + // own default (search ON) is the entire point of this gate. + 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", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=16", + "--max-partition-size=32", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=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; + assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + continue; + } + Ok(frames) => frames, + }; + let after = crate::decode::rect_split_tx_hits(); + eprintln!( + "{NAME}: seed {seed} decoded, split-tx strips this stream: {}", + after - before - split_so_far + ); + split_so_far = after - before; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); + if let Some(i) = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .position(|(a, b)| a != b) + { + eprintln!( + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + i % width, + i / width, + frames[0].y[i], + ffmpeg_frames[0].y[i] + ); + } + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + matched += 1; + } + let split_hits = crate::decode::rect_split_tx_hits() - before; + assert!( + matched > 0, + "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" + ); + assert!( + split_hits > 0, + "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \ + matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \ + this run" + ); + eprintln!( + "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ + rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts" + ); + } + + /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s + /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every + /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its + /// `--enable-tx-size-search=0` DROPPED: the 64x32/32x64 strips may then + /// carry a split transform, which [`crate::decode::decode_block_rect64`] + /// refused by name ("a superblock-level HORZ/VERT strip with a split + /// transform") until this round. Same hard `rect_split_tx_hits()` delta + /// assert as gate (a). + /// lane-rectsplit r1 MEASURED RED, `#[ignore]`d with its number (the + /// `rect64q` gate's own precedent): with the per-transform-unit port + /// wired at the superblock level, seed 50 decodes one sample off -- + /// luma (171, 56), ours 147 vs ffmpeg 148, inside the 64x32 strip at + /// mi=(8,32) whose transform resolved to depth 2 (TX_16X16). Seeds 42-49 + /// with depth-1 (TX_32X32) units were pixel-exact. The refusal in + /// `decode_block_rect64` was therefore RESTORED rather than lifted; run + /// this gate (`--ignored`) after any fix to that arm. + #[ignore = "lane-rectsplit r1: measured RED, seed 50 luma (171,56) off by one; refusal kept"] + #[test] + fn a_real_aomenc_stream_with_a_split_transform_superblock_strip_decodes_pixel_exact() { + const NAME: &str = "a_real_aomenc_stream_with_a_split_transform_superblock_strip_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) = (192usize, 128usize); + let before = crate::decode::rect_split_tx_hits(); + let mut named_refusals = 0u32; + let mut matched = 0u32; + let mut split_so_far = 0usize; + // Bounded sweep: see this gate's own doc for the seed-77 residue and + // why extending it is a diagnosis knob, not a pass/fail one. + let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(20); + for attempt in 0..n_attempts { + let seed = 42 + attempt; + let source = gradients_source(seed, width, height, "duration=0.04:rate=25"); + let y4m = Command::new("ffmpeg") + .args([ + "-v", "error", "-f", "lavfi", "-i", &source, + // Desaturated (`hue=s=0`, the same guard + // `a_real_aomenc_intra_stream_with_tx_select_decodes_pixel_exact` + // uses): with the tx-size search ON, a real chroma + // gradient hits a PRE-EXISTING chroma defect on the plain + // SQUARE path -- measured this round with + // `--enable-rect-partitions=0` on this very recipe, seed + // 42, U plane, i.e. with no rect strip in the stream at + // all. Flat chroma keeps that unrelated defect out of + // this gate (gate-recipe-confound class); it is open + // residue in lanes/rectsplit-r1.report.md, not fixed here. + "-vf", "hue=s=0", + "-pix_fmt", "yuv420p", "-f", + "yuv4mpegpipe", "-", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + assert!( + y4m.status.success(), + "ffmpeg fixture: {}", + String::from_utf8_lossy(&y4m.stderr) + ); + // NOTE: no `--enable-tx-size-search=0` here -- leaving aomenc's + // own default (search ON) is the entire point of this gate. + 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", + "--enable-rect-partitions=1", + "--enable-ab-partitions=0", + "--enable-1to4-partitions=0", + "--min-partition-size=32", + "--max-partition-size=64", + "--enable-restoration=0", + "--enable-palette=0", + "--deltaq-mode=0", + "--enable-filter-intra=0", + "--enable-cfl-intra=0", + "--enable-intrabc=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; + assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})"); + let frames = match decode_stream(&stream) { + Err(e) => { + let msg = e.to_string(); + assert!( + msg.contains("unsupported"), + "{NAME} failed outright, not a named refusal (seed {seed}): {msg}" + ); + named_refusals += 1; + continue; + } + Ok(frames) => frames, + }; + let after = crate::decode::rect_split_tx_hits(); + eprintln!( + "{NAME}: seed {seed} decoded, split-tx strips this stream: {}", + after - before - split_so_far + ); + split_so_far = after - before; + let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1); + assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})"); + if let Some(i) = frames[0] + .y + .iter() + .zip(&ffmpeg_frames[0].y) + .position(|(a, b)| a != b) + { + eprintln!( + "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}", + i % width, + i / width, + frames[0].y[i], + ffmpeg_frames[0].y[i] + ); + } + assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})"); + assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})"); + matched += 1; + } + let split_hits = crate::decode::rect_split_tx_hits() - before; + assert!( + matched > 0, + "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing" + ); + assert!( + split_hits > 0, + "{NAME}: zero HORZ/VERT strips resolved a split transform ({matched} pixel-exact \ + matches, {named_refusals} refusals out of {n_attempts}) -- gate proved nothing \ + this run" + ); + eprintln!( + "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \ + rect_split_tx_hits delta={split_hits} out of {n_attempts} attempts" + ); + } + /// lane-rect64q r1: same recipe as /// [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`] /// minus `--deltaq-mode=0` -- real aomenc's non-realtime default is