diff --git a/crates/ec-av1/src/decode.rs b/crates/ec-av1/src/decode.rs index 7a3f576d..b074f631 100644 --- a/crates/ec-av1/src/decode.rs +++ b/crates/ec-av1/src/decode.rs @@ -937,10 +937,17 @@ fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 { let base = fctx.current_q_idx.with(|c| c.get()); let seg_id = fctx.cur_segment_id.with(|c| c.get()) as usize; - match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) { + let q = match seg_feature(seg_id, SEG_LVL_ALT_Q, fctx) { Some(data) => (base + data).clamp(0, 255), None => base, + }; + // lane-d792: which SEGMENT a block's quantizer came out of, beside the + // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels + // already proven equal is a segment-id defect, not a quantizer one. + if crate::envflags::env_flag!("EC_DQCOEFF") { + eprintln!("OUR_Q base={base} seg={seg_id} q={q}"); } + q } /// The segment id recorded for one mi cell of the current frame's map. @@ -6652,6 +6659,19 @@ fn read_coeffs_rect( }; grid[pos] = if negative { -level } else { level }; } + // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the + // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose + // grids differ is a reader defect, one whose grids agree is a transform + // defect. + if crate::envflags::env_flag!("EC_DQCOEFF") { + let nz: Vec = grid + .iter() + .enumerate() + .filter(|&(_, &v)| v != 0) + .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w)) + .collect(); + eprintln!("OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}", nz.join(",")); + } Ok((Grid::Own(grid), tx_type)) } @@ -9712,7 +9732,12 @@ fn decode_rect_split( chroma_w, chroma_h, crate::decode::bit_depth(fctx), - fctx.current_q_idx.with(|c| c.get()), + // lane-d792: the BLOCK's quantizer index, i.e. the frame's + // own index PLUS this block's segment `SEG_LVL_ALT_Q` -- + // reading `current_q_idx` here dropped the segment feature + // that every other dequant site applies (class + // `parsed-then-discarded`). + block_q_idx(fctx), plane_q_delta(plane_idx, fctx).0, plane_q_delta(plane_idx, fctx).1, tx_type, @@ -11219,7 +11244,7 @@ fn decode_leaf_rect( luma_levels = l_levels; let luma_residual = dequant_and_inverse_typed_wh( &luma_levels, bw, bh, crate::decode::bit_depth(fctx), - fctx.current_q_idx.with(|c| c.get()), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, + block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, luma_tx_type, ); if let Some(b) = &palette_y_buf { set_palette_pred(b.clone(), fctx); @@ -11239,7 +11264,7 @@ fn decode_leaf_rect( u_levels = u_l; let u_residual = dequant_and_inverse_typed_wh( &u_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), - fctx.current_q_idx.with(|c| c.get()), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type, + block_q_idx(fctx), plane_q_delta(1, fctx).0, plane_q_delta(1, fctx).1, u_tx_type, ); if let Some((ub, _)) = &palette_uv_bufs { set_palette_pred(ub.clone(), fctx); @@ -11258,7 +11283,7 @@ fn decode_leaf_rect( v_levels = v_l; let v_residual = dequant_and_inverse_typed_wh( &v_levels, chroma_w, chroma_h, crate::decode::bit_depth(fctx), - fctx.current_q_idx.with(|c| c.get()), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type, + block_q_idx(fctx), plane_q_delta(2, fctx).0, plane_q_delta(2, fctx).1, v_tx_type, ); if let Some((_, vb)) = &palette_uv_bufs { set_palette_pred(vb.clone(), fctx); @@ -13658,6 +13683,17 @@ impl PlaneBuf<'_> { self.data.to_mut()[(y + row) * self.width + x + col] = sample; } } + // lane-d792: the RECONSTRUCTION rung beside `EC_PRED`'s prediction one + // -- a block whose prediction matches the oracle's but whose written + // samples do not is either a residual defect or a later overwrite, and + // only this print separates the two. + if crate::envflags::env_flag!("EC_PRED") { + let row0: Vec = + (0..bw.min(8)).map(|c| self.data[y * self.width + x + c]).collect(); + let col0: Vec = + (0..bh.min(8)).map(|r| self.data[(y + r) * self.width + x]).collect(); + eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}"); + } } /// Predicts under `mode` then adds `residual` (side*side, raster), @@ -16211,7 +16247,9 @@ fn decode_leaf_rect8( bw, bh, crate::decode::bit_depth(fctx), - fctx.current_q_idx.with(|q| q.get()), + // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at + // every other dequant site (class `parsed-then-discarded`). + block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, @@ -31123,7 +31161,9 @@ fn decode_intra_sub8_leaf( bw, bh, crate::decode::bit_depth(fctx), - fctx.current_q_idx.with(|q| q.get()), + // lane-d792 sweep: the block's segment `SEG_LVL_ALT_Q`, as at + // every other dequant site (class `parsed-then-discarded`). + block_q_idx(fctx), plane_q_delta(0, fctx).0, plane_q_delta(0, fctx).1, tx_type, diff --git a/crates/ec-av1/src/stream.rs b/crates/ec-av1/src/stream.rs index 0f11ae66..a3afba31 100644 --- a/crates/ec-av1/src/stream.rs +++ b/crates/ec-av1/src/stream.rs @@ -35173,4 +35173,180 @@ pub(crate) mod tests { ); } + + /// lane-d792: a frame whose height the superblock grid CUTS, decoded + /// against ffmpeg on every ladder point of BOTH reference encoders. + /// + /// WHY IT EXISTS: the reference encoders answer a straddling frame with + /// rectangular partitions in the cut superblock row -- the only place + /// these streams code a 16x8/8x4 transform unit at all -- and the rect + /// intra dequant path was reading the FRAME's quantizer index where every + /// square path reads the block's segment-adjusted one + /// (`SEG_LVL_ALT_Q`, class `parsed-then-discarded`). Every gate size + /// before this one was a whole number of superblocks, so no gate ever + /// decoded such a unit: the 1920x792 native BD arm's reference-decode + /// assertion was red on all four rav1e points and this is its small, + /// fast, encoder-independent form. + /// + /// 384x152 is 2 superblocks + 24 px (the 1920x792 straddle, film A's own + /// coded size) and 384x184 is 2 + 56 px (the 1920x1080 straddle), so both + /// the "less than half inside" and the "more than half inside" edge + /// superblock shapes are covered. + #[test] + fn a_straddling_frame_decodes_exactly_on_both_reference_encoders_ladders() { + const NAME: &str = "a_straddling_frame_decodes_exactly_on_both_reference_encoders_ladders"; + if !have_ffmpeg() { + eprintln!("SKIP {NAME}: no ffmpeg"); + return; + } + const FRAMES: usize = 4; + let mut checked = 0usize; + // The PINNED half of this gate. The generated rows below are the + // general regression; these two files are rav1e's own answer to a + // 384x152 crop of a REAL film (`speed=6`, quantizer 100 and 150, + // `-g 4`), which is the only recipe measured to turn on the + // activity segmentation whose `SEG_LVL_ALT_Q` the rect dequant path + // dropped -- a `testsrc2` or repo-fixture source codes one segment + // and passes this gate with the defect still in (both verified by + // reverting the fix under it). Bytes live in the shared `fixtures` + // directory, which is gitignored, so a missing file SKIPs. + for name in [ + "d792_straddle_rav1e_384x152_q100.obu", + "d792_straddle_rav1e_384x152_q150.obu", + ] { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures") + .join(name); + let Ok(stream) = std::fs::read(&path) else { + eprintln!("SKIP {NAME}: {name} missing"); + continue; + }; + let (w, h) = (384usize, 152usize); + let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES); + let got = decode_stream(&stream) + .unwrap_or_else(|e| panic!("{NAME}: {name} refused: {e}")); + assert_eq!(got.len(), want.len(), "{NAME}: {name} frame count"); + for (f, (o, r)) in got.iter().zip(&want).enumerate() { + for (plane, a, b) in [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] { + if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) { + let stride = if plane == "Y" { w } else { w / 2 }; + panic!( + "{NAME}: {name}, frame {f} plane {plane} sample ({}, {}): ours {} \ + vs ffmpeg {}", + i % stride, + i / stride, + a[i], + b[i], + ); + } + } + } + checked += 1; + } + for (w, h) in [(384usize, 152usize), (384, 184)] { + // REAL content, not colour bars (class `gate film rows are colour + // bars`): both encoders only turn segmentation on -- the feature + // this gate is about -- when the picture's activity varies, and + // `testsrc2` codes one segment, so a bars source passes this gate + // with the defect still in (verified by reverting the fix under + // it). + let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"); + if !clip.exists() { + eprintln!("SKIP {NAME}: {} missing", clip.display()); + return; + } + for (encoder, points) in [ + ("librav1e", ["50", "100", "150", "200"]), + ("libaom-av1", ["5", "20", "35", "45"]), + ] { + for point in points { + let mut args: Vec = + ["-v", "error", "-i", clip.to_str().expect("fixture path")] + .iter() + .map(|s| (*s).to_string()) + .collect(); + args.extend( + [ + "-frames:v", + &FRAMES.to_string(), + "-vf", + &format!("crop={w}:{h}:768:400"), + "-pix_fmt", + "yuv420p", + "-an", + ] + .iter() + .map(|s| (*s).to_string()), + ); + args.extend( + ["-threads", "1", "-g", &FRAMES.to_string(), "-c:v", encoder] + .iter() + .map(|s| (*s).to_string()), + ); + if encoder == "librav1e" { + args.push("-rav1e-params".into()); + args.push(format!( + "speed=6:quantizer={point}:tile_cols=1:tile_rows=1:threads=1" + )); + } else { + args.extend( + // `-aq-mode 1`: libaom's activity segmentation, + // i.e. `SEG_LVL_ALT_Q` -- the feature the rect + // dequant path used to drop. + ["-cpu-used", "6", "-b:v", "0", "-crf", point, "-aq-mode", "1"] + .iter() + .map(|s| (*s).to_string()), + ); + } + args.extend(["-f", "obu", "-"].iter().map(|s| (*s).to_string())); + let out = Command::new("ffmpeg") + .args(&args) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .expect("ffmpeg failed to run"); + if !out.status.success() { + eprintln!( + "SKIP {NAME}: ffmpeg cannot encode {w}x{h} with {encoder} ({})", + String::from_utf8_lossy(&out.stderr).lines().last().unwrap_or("") + ); + continue; + } + let stream = out.stdout; + let want = ffmpeg_decode_sequence(&stream, w, h, FRAMES); + let got = decode_stream(&stream).unwrap_or_else(|e| { + panic!("{NAME}: {encoder} {point} at {w}x{h} refused: {e}") + }); + assert_eq!( + got.len(), + want.len(), + "{NAME}: {encoder} {point} at {w}x{h} frame count" + ); + for (f, (o, r)) in got.iter().zip(&want).enumerate() { + for (plane, a, b) in + [("Y", &o.y, &r.y), ("U", &o.u, &r.u), ("V", &o.v, &r.v)] + { + if let Some(i) = a.iter().zip(b.iter()).position(|(x, y)| x != y) { + let stride = if plane == "Y" { w } else { w / 2 }; + panic!( + "{NAME}: {encoder} {point} at {w}x{h}, frame {f} plane \ + {plane} sample ({}, {}): ours {} vs ffmpeg {}", + i % stride, + i / stride, + a[i], + b[i], + ); + } + } + } + checked += 1; + } + } + } + assert!(checked > 0, "{NAME}: neither reference encoder was available"); + eprintln!("{NAME}: {checked} straddling reference points decoded sample-exact"); + } + } diff --git a/crates/ec-av1/src/transform.rs b/crates/ec-av1/src/transform.rs index 36bfdef9..34dbe3f5 100644 --- a/crates/ec-av1/src/transform.rs +++ b/crates/ec-av1/src/transform.rs @@ -1346,6 +1346,22 @@ pub fn dequant_and_inverse_typed_wh( DQ_SCRATCH.with(|cell| { let mut dq = cell.borrow_mut(); crate::quant::dequant_wh_into(levels, &mut dq, w, h, bit_depth, q_idx, dc_delta, ac_delta); + // lane-d792: the DEQUANTIZED grid, in row-major `(row/col)` pairs -- + // the twin of the oracle's `EC_DQCOEFF` rung (whose own layout is + // column-major `input[c * h + r]`), so a residual mismatch whose + // levels already agree is separable into dequant vs transform. + if crate::envflags::env_flag!("EC_DQCOEFF") { + let nz: Vec = dq + .iter() + .enumerate() + .filter(|&(_, &v)| v != 0) + .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w)) + .collect(); + eprintln!( + "OUR_DQ w={w} h={h} q={q_idx} dcd={dc_delta} acd={ac_delta} tx={tx_type:?} nz={}", + nz.join(",") + ); + } inverse_transform_2d_typed_wh(&dq, w, h, bit_depth, tx_type) }) } @@ -3105,3 +3121,38 @@ mod lossless_tx_tests { } } } + +#[cfg(test)] +mod d792_tests { + /// lane-d792: ONE 16x8 DCT_DCT inverse against libaom's own numbers. + /// + /// The dequantized grid below is `EC_DQCOEFF`'s dump of the first + /// TX_16X8 unit of `$HOME/.cache/d792/small/f100.obu` (a rav1e + /// `speed=6 quantizer=100` encode of a 384x152 crop, whose bottom + /// straddle is where the reference-ladder decode failures live), in + /// libaom's own column-major `input[c * h + r]` order; the expected + /// residual is `aomdec`'s reconstruction of that block minus its + /// prediction (the two decoders' predictions are byte-identical there, + /// checked with the oracle's `EC_PREDOUT8` rung). + #[test] + fn a_16x8_inverse_matches_libaoms_own_dqcoeff_and_residual() { + const H: usize = 8; + const W: usize = 16; + // (libaom index, dequantized value). + const NZ: [(usize, i32); 17] = [ + (0, 1554), (1, -1768), (2, 624), (3, -104), (9, 104), (10, -520), (11, 312), + (16, -104), (17, 104), (18, -104), (24, -104), (25, 104), (27, -104), (32, 208), + (33, -104), (35, -104), (40, 104), + ]; + let mut grid = vec![0i32; W * H]; + for (i, v) in NZ { + let (r, c) = (i % H, i / H); + grid[r * W + c] = v; + } + let out = super::inverse_transform_2d_typed_wh(&grid, W, H, 8, super::TxType::DctDct); + let col0: Vec = (0..H).map(|r| out[r * W]).collect(); + let row0: Vec = out[..8].to_vec(); + assert_eq!(col0, vec![-7, -2, 6, 17, 27, 34, 36, 37], "column 0"); + assert_eq!(row0, vec![-7, -7, -6, -5, -2, 0, 1, -1], "row 0"); + } +} diff --git a/lanes/d792.report.md b/lanes/d792.report.md new file mode 100644 index 00000000..98fd3776 --- /dev/null +++ b/lanes/d792.report.md @@ -0,0 +1,228 @@ +# lane-d792 — the reference-ladder decode failures on the 1920x792 (straddling) crop + +Working notes, kept current from the first commit. Streams and logs under +`$HOME/.cache/d792/` (`streams/`, `small/`, `stage/`). + +## Reproduction (standalone, without the 7-minute BD gate) + +12 frames of film A from `00:35:00`, `crop=1920:792:0:0` (film A IS coded +1920x792, so the gate's `EC_AV1_NATIVE_CROP=1920x792` is its whole frame), +encoded with the gate's own ladder recipes and decoded through +`examples/dump_yuv` vs `ffmpeg -pix_fmt yuv420p`: + +| point | our decode vs ffmpeg | +|---|---| +| libaom `-cpu-used 6 -crf 5/20/35/45` | **EXACT, all 4** | +| rav1e `speed=6 quantizer=50/100/150/200` | **DIFFERS, all 4, every frame** (4-6 k samples/frame, max abs 24) | + +So the chartered "libaom crf-5 Golomb refusal" does NOT reproduce at +046dbe0e on this source/recipe; only the rav1e ±1 class does. (Charter +premise re-checked, not assumed.) + +## Where the rav1e divergence lives + +All diffs sit in the LAST rows of the frame: luma rows 760..791 of 792, +chroma 382..395 of 396 — the bottom straddle (792 = 12*64 + 24). + +Stage bisect (our `EC_AV1_*_DUMP` vs the instrumented aomdec's twin dumps, +`$HOME/.cache/d792/stage/`), rav1e q150 frame 0: + +| stage | first differing row (luma) | +|---|---| +| pre-filter reconstruction | **769** | +| post-deblock | 766 | +| post-CDEF | 760 | +| final (post-LR) | 760 | + +So the loop filters only SPREAD it: the defect is in **reconstruction**, in +mi rows 192..197 — the 24 px the frame edge cuts off the last superblock row. + +## Small repro (fast iteration) + +`$HOME/.cache/d792/small/f100.obu`: 4 frames of film A cropped to +**384x152** (= 2*64 + 24 straddle), rav1e `speed=6 quantizer=100`. Our +pre-filter reconstruction differs from aomdec's in rows **144..151** only +(the last 8 rows), all columns; ~1800 luma samples on frame 0. + +## What is ruled OUT so far + +* **Parse (block level) is in sync**: `EC_TRACE_MODE_STEP` on both decoders + gives identical `mode`/`skip`/`uv_mode`/`angle_y`/`angle_uv` sequences for + the 1518 blocks of the 1920x792 key frame (the only surplus lines in ours + are intra-in-inter `y_mode` rungs aomdec names differently). +* **Intra prediction is byte-exact** at the first differing block. The + oracle was patched this round with an `EC_PREDOUT8` rung (8-bit predicted + block; the existing one was high-bitdepth only) and the block at + `mi_row=36 mi_col=0` of the small repro gives `sum=6959 + row0=82,74,65,56,50,47,46,45 col0=82,85,85,85,85,85,85,85` on BOTH sides. + Edge lengths agree too (`n_left = 8` for a 16-tall TU with 8 rows inside, + i.e. libaom's `AOMMIN(txhpx, yd + txhpx)` clip is already ours). +* Loop restoration's last-stripe substitution matches libaom's + `get_stripe_boundary_info` (`copy_below = 0` at the frame bottom). + +## Where it IS (open, in progress) + +The residual. `EC_TRACE_COEFF` on both decoders over the small repro: +`eob` sequences are IDENTICAL (514 transform units) but the symbol streams +below them are not — ours reads **extra `br` (base-range) symbols** and +fewer `sign`/`base` ones (aom 23085 base / 7966 sign / 3338 br; ours 23634 / +7715 / 3351). First divergence is an extra `br` at trace line ~22951 of +44647. Next: resolve that line to its transform unit and read the rule that +differs there. + +## Elimination chain (all measured on the 384x152 small repro, frame 0) + +The first differing sample is inside the luma block at `x=0 y=144`, a 16x8 +intra block in the bottom straddle (PARTITION_HORZ is forced there by the +frame edge). For that block: + +1. **Prediction: identical.** `OUR_PRED sum=6959 row0=[82,74,65,56,50,47,46,45] + col0=[82,85,85,85,85,85,85,85]` == the oracle's new `EC_PREDOUT8` line for + `mi_row=36 mi_col=4`(sic: `mi_col=0`), to the sample. +2. **Coefficient bitstream: in sync.** `EC_TRACE_COEFF`'s `all_zero` range + value agrees at ALL 750 transform units; `eob` agrees at all 514. +3. **Transform type: identical.** The oracle now prints the resolved + `txtype`/`txsize`; the 514-long sequence matches ours entry for entry. + All 19 TX_16X8 units are DCT_DCT. +4. **Transform unit shapes: identical.** Both decoders code 19 16x8, 27 8x4 + and 1 32x16 rectangular units (the oracle's new `EC_DQCOEFF` rung vs our + new `OUR_LEVELS` rung). +5. **Level grids: identical.** The first three 16x8 units' non-zero + (row/col, level) sets match the oracle's `EC_DQCOEFF` dump converted out + of libaom's column-major `input[c * h + r]` layout -- which also + re-verifies `SCAN_16X8` against `av1_default_scan_16x8`. +6. **The 16x8 inverse transform is correct.** New pin + `transform::d792_tests::a_16x8_inverse_matches_libaoms_own_dqcoeff_and_residual` + feeds our `inverse_transform_2d_typed_wh` libaom's own dequantized grid + and asserts libaom's own residual (`aomdec` reconstruction minus the + identical prediction): PASSES. +7. **The q index is frame-constant.** `aomdec`'s `current_base_qindex` is 127 + for all 1518 blocks of the 1920x792 key frame; no delta-q is in play. + +So the residual our decoder ADDS differs (ours `col0 = [-6,-3,4,13,21,26,28, +28]`, libaom's `[-7,-2,6,17,27,34,36,37]`, roughly a 0.77 factor) while the +levels, the shape, the type and the transform kernel all agree. The +remaining link is the DEQUANT step between them -- `dequant_and_inverse_typed_wh` +at the intra rect call sites (`decode.rs:9487/9543/9713/10826...`), where the +suspects are the `(w, h)` argument order (class `adjacent same-typed args`; +a transposed grid would weaken exactly the vertical response we see) and the +q index / DC-AC delta that site passes. + +## Instruments added this round + +* Oracle (`~/.cache/aom-oracle/src`, build2): `EC_PREDOUT8` on both 8-bit + prediction paths, `txtype=`/`txsize=` on the `tag=tx_type` rung, and + `EC_DQCOEFF` (the dequantized grid the inverse transform runs on). +* Ours: `OUR_RECON` (reconstructed row0/col0 beside `EC_PRED`'s prediction) + and `OUR_LEVELS` (a rect unit's level grid, `EC_DQCOEFF=1`). + +## NOT done this round (budget) + +* `deferred: the root cause and its fix -- the dequant link above is the one + unchecked step -- unblocked by dumping the dequantized grid at the rect + intra call site and diffing it against the oracle's EC_DQCOEFF line` +* `deferred: the libaom crf-5 "Golomb tail" refusal -- it does NOT reproduce + standalone at 046dbe0e (all four libaom points decode exact), so it needs + the gate arm itself re-run to confirm it is stale` +* `deferred: the synthetic straddling fixtures (384x152 / 384x184 gates), the + 1920x792 green arm, the suite and the workspace check -- they gate a fix + that does not exist yet` + +## ROOT CAUSE (round 2) — the rect intra dequant dropped the block's segment quantizer + +`OUR_DQ` (our new dequantized-grid rung) against the oracle's `EC_DQCOEFF` +for the same 16x8 unit: the level grids agree, but ours dequantizes with +`q = 75` where libaom uses the quantizer of q-index ~96 (dc 111 / ac 104 vs +our 82 / 82) -- the 0.77 residual factor exactly. + +`OUR_Q` (the segment rung) named it: frame 0 of the small repro has THREE +segments (`base = 75`; seg 0 -> 67, seg 1 -> 81, seg 2 -> 96 through +`SEG_LVL_ALT_Q`), and the rect intra path was dequantizing with +`fctx.current_q_idx` -- the FRAME's index -- instead of +[`block_q_idx`], which adds the block's own segment feature. Every square +path already used `block_q_idx`, which is why the defect was invisible until +a frame edge forced rectangular partitions: only the cut superblock row codes +16x8 / 8x4 units in these streams. + +**Class**: `parsed-then-discarded` -- the segmentation ALT_Q is parsed, +applied at 21 dequant sites, and dropped at 6 of them. (Sibling shape to +`override slot on one arm`: the rect ARM of a two-arm path missed the +adjustment its square twin had.) + +**Fix**: `block_q_idx(fctx)` at all six, in `crates/ec-av1/src/decode.rs` +(the split rect path's chroma, the 16x8/8x16 luma+chroma trio, and two +8x4/rect leaf sites at 16240 / 31147). + +**Sweep**: every `dequant_and_inverse*` call site in the decoder (27) now +takes either `block_q_idx` or a `TxParams::q_idx` that was itself built from +`block_q_idx`; `grep -n "current_q_idx" decode.rs` leaves only the frame-level +cell itself, `block_q_idx`'s own read of it and a `RECT64_QIDX_DRIFT_HITS` +counter. + +## Result + +* small repro `384x152` rav1e q100 and q150: **EXACT vs ffmpeg**, all frames. +* the whole 1920x792 reference ladder -- libaom crf 5/20/35/45 AND rav1e + quantizer 50/100/150/200, 12 frames each: **EXACT vs ffmpeg on every + point** (`$HOME/.cache/d792/streams`, decoded with `examples/dump_yuv`). + +## The gate, and what it took to make it see the defect + +`stream::tests::a_straddling_frame_decodes_exactly_on_both_reference_encoders_ladders` +(2.7 s) has two halves: + +* **Generated rows** -- 4 frames at 384x152 (2 SB + 24 px, the 1920x792 + straddle) and 384x184 (2 SB + 56 px, the 1080p straddle), through librav1e + (quantizer 50/100/150/200) and libaom (`-cpu-used 6 -crf 5/20/35/45 + -aq-mode 1`), each decoded by ffmpeg and by us and compared sample by + sample. +* **Pinned rows** -- `fixtures/d792_straddle_rav1e_384x152_q100.obu` and + `..._q150.obu`, rav1e's own answer to a 384x152 crop of a real film. + +That split is not decoration. **The generated rows alone do NOT catch this +defect**: with the fix reverted under them, first a `testsrc2` source and then +the repo's own `h264-1080p-23.976-8bit.mp4` fixture (which is colour bars, +per the standing note) both PASSED at all 16 points, because neither codes +more than one segment, and the defect only exists where `SEG_LVL_ALT_Q` does +(class `gate-blind-to-feature`). The pinned rows fail pre-fix at +`frame 0 plane Y sample (17, 140): ours 41 vs ffmpeg 42` and pass after, so +the gate's defect-catching power is measured, not assumed. + +## Verification + +| check | result | +|---|---| +| `cargo test -p ec-av1 --release --lib a_straddling_frame` | 18 straddling reference points sample-exact, 2.7 s | +| the same gate with the fix reverted | FAILED at `(17, 140)` of the pinned q100 row | +| the 1920x792 ladder, 12 frames, decoded standalone (`examples/dump_yuv` vs ffmpeg) | libaom crf 5/20/35/45 **EXACT**, rav1e quantizer 50/100/150/200 **EXACT** -- all 8 points, i.e. what `external_ladder`'s reference-decode assertion checks | +| `cargo check --workspace --all-targets -j4` | 0 errors; 0 `ec-av1` warnings (the 21 `ec-opus` missing-doc + 1 `ec-vorbis` dead-code ones are pre-existing) | + +## The 1920x792 arm itself (`EC_AV1_NATIVE_CROP=1920x792`, film A row) + +`cargo test -p ec-av1 --release --lib -- --ignored --exact +encode::tests::bd_rate_screen_native`, 494 s, log `$HOME/.cache/d792/native.log`: + +* **8 of the 9 failures are gone.** All four rav1e points now decode exactly; + the BD row itself is unchanged (`+22.5%` vs libaom, `-2.3%` vs rav1e, + 44.03/45.60/46.92/48.20 dB at 68847/109557/178345/426318 B -- lane-corner's + post-lift numbers to the digit). +* **One remains**, and it is NOT a straddle defect: + `libaom-av1 ["-cpu-used","6","-b:v","0","-crf","5"]: our decoder refused the + stream (a Golomb tail longer than this decoder reads)`. The same recipe run + standalone this round decoded EXACT, so libaom's crf-5 output is not + reproducible run-to-run here and the refusal is hit by some of its streams: + a coefficient-magnitude limit at the very lowest quantizer, not an edge + case of the frame geometry. + `deferred: the crf-5 Golomb-tail refusal -- read the refusal site's own + bound against libaom's read_golomb (which reads up to 20 bits + the level + bound), reproduce by looping the crf-5 encode until a refusing stream is + captured, pin that stream as a fixture -- it is lane-dgolomb's standing + debt and needs its own round` + +## Suite + +`cargo test -p ec-av1 --release` (detached, 893 s): **572 passed, 0 failed, +46 ignored**, RC=0 -- 570 before plus this lane's two (the 16x8 transform pin +and the straddle gate). The pin test +`the_encoders_own_streams_are_byte_identical_to_their_pins` is inside it, so +the 8562 / 33357 byte pins are unchanged.