forge
Explore
Log in

Don't you dare go Hollow

ec-av1: clip lossless chroma TUs and reset skip bands

Browse files at this commit

e72b9475ee379f70ac425af385a277ddb840121fAhmet Kaan GümüşParent: 08d6d41
crates/ec-av1/examples/decode_probe.rsmodified+5 -0
@@ -184,6 +184,11 @@ fn main() {
184184 ec_av1::decode::rect4_16_lossless_chroma_hits(),
185185 ec_av1::decode::rect4_16_intrabc_hits(),
186186 );
187+ println!(
188+ "loss64: chroma_edge_tu_clip={} skip_lossless_band_reset={}",
189+ ec_av1::decode::chroma_edge_tu_clip_hits(),
190+ ec_av1::decode::skip_lossless_band_reset_hits(),
191+ );
187192 // lane-t900 r12: chroma edge-filter neighbour answered from the mi-granular
188193 // uv_mode grid instead of the coarse one-slot-per-column map.
189194 println!(
crates/ec-av1/src/decode.rsmodified+82 -0
@@ -5019,6 +5019,15 @@ thread_local! {
50195019 /// lane-kf1200 r2: sub-8x8 chroma blocks that are `skip_txfm` AND
50205020 /// `UV_CFL_PRED` -- the arm that used to drop the CfL alpha entirely.
50215021 static SKIP_CFL_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5022+ /// lane-av1-loss64: chroma transform units the frame-edge clip skipped
5023+ /// (libaom `decode_reconstruct_tx`'s `max_blocks_wide/high` test) in
5024+ /// [`decode_block`]'s multi-transform-unit walk -- the units a lossless
5025+ /// block overhanging the frame does NOT code.
5026+ static CHROMA_EDGE_TU_CLIP_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
5027+ /// lane-av1-loss64: skipped lossless intrabc rect strips whose luma
5028+ /// entropy bands were zeroed per unit (libaom `av1_reset_entropy_context`,
5029+ /// decodemv.c:1262) instead of leaking the previous occupant's.
5030+ static SKIP_LOSSLESS_BAND_RESET_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
50225031 }
50235032
50245033 /// How many skipped sub-8x8 chroma blocks carried a CfL alpha (the shape
@@ -5027,6 +5036,26 @@ pub fn skip_cfl_hits() -> usize {
50275036 SKIP_CFL_HITS.with(|c| c.get())
50285037 }
50295038
5039+/// How many chroma transform units the frame-edge clip skipped in
5040+/// [`decode_block`]'s multi-transform-unit walk (lane-av1-loss64). Zero on a
5041+/// stream whose lossless blocks never overhang the frame -- a gate asserting
5042+/// the clip fired must see this nonzero.
5043+pub fn chroma_edge_tu_clip_hits() -> usize {
5044+ CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.get())
5045+}
5046+
5047+/// How many skipped lossless intrabc rect strips had their luma entropy
5048+/// bands zeroed per unit (lane-av1-loss64).
5049+pub fn skip_lossless_band_reset_hits() -> usize {
5050+ SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.get())
5051+}
5052+
5053+/// Gate-side reset for the two lane-av1-loss64 counters above.
5054+pub fn reset_loss64_hits() {
5055+ CHROMA_EDGE_TU_CLIP_HITS.with(|c| c.set(0));
5056+ SKIP_LOSSLESS_BAND_RESET_HITS.with(|c| c.set(0));
5057+}
5058+
50305059 /// How many 16x4/4x16 chroma pairs took a different `intra_edge_filter_type`
50315060 /// from the pair's base mi than the strip's own mi would have given.
50325061 pub fn rect4_16_uv_pair_filt_hits() -> usize {
@@ -12354,6 +12383,30 @@ fn decode_intrabc_owned_rect(
1235412383 push_mc_rect(0, px, py, side, bw, bh, Pred::Inline(&pred_y, side), &ZERO_RESIDUAL[..side * bh], fctx);
1235512384 push_mc_rect(1, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_u, cside), &ZERO_RESIDUAL[..cside * ch], fctx);
1235612385 push_mc_rect(2, px / 2, py / 2, cside, cw, ch, Pred::Inline(&pred_v, cside), &ZERO_RESIDUAL[..cside * ch], fctx);
12386+ if let Some(ls) = leaves.as_ref() {
12387+ // libaom `av1_reset_entropy_context` (`if (mbmi->skip_txfm)`,
12388+ // decodemv.c:1262 -> blockd.c:58): a SKIPPED block zeroes its
12389+ // whole entropy-band footprint. The non-skip arm below writes
12390+ // those bands per transform unit and the tail's
12391+ // `record_split_luma_rect_mi` writes chroma only, so without
12392+ // this walk a skipped strip whose `leaves` resolved (every
12393+ // lossless frame -- `read_block_tx_size_rect`'s lossless arm
12394+ // returns the 4x4 grid before it looks at `skip`) leaked the
12395+ // PREVIOUS occupant's luma bands into the next block's
12396+ // `txb_skip`/coefficient contexts (lane-av1-loss64: the skipped
12397+ // 8x16 intrabc strip at mi(48,66) of the 320x242 lossless sb128
12398+ // stream left a stale 7 in left[48] and mi(48,68)'s first
12399+ // transform unit read `txb_skip_ctx` 3 where aomdec reads 1).
12400+ hit!(SKIP_LOSSLESS_BAND_RESET_HITS);
12401+ for &(row, col, tw, th) in ls {
12402+ neighbours.record_mi_luma_rect(
12403+ (mi_r + row, mi_c + col),
12404+ tw,
12405+ th,
12406+ &ZERO_RESIDUAL[..tw * th],
12407+ );
12408+ }
12409+ }
1235712410 luma_grid = Grid::Zero(side * side);
1235812411 u_grid = Grid::Zero(cside * cside);
1235912412 v_grid = Grid::Zero(cside * cside);
@@ -15632,6 +15685,35 @@ fn decode_block(
1563215685 let mut pass_idx = 0usize;
1563315686 for cu_row in ch_row * cpc..(ch_row + 1) * cpc {
1563415687 for cu_col in ch_col * cpc..(ch_col + 1) * cpc {
15688+ // libaom `decode_reconstruct_tx`'s frame-edge clip
15689+ // (decodeframe.c:299, `blk_row >= max_blocks_high || blk_col
15690+ // >= max_blocks_wide` returns before ANY symbol is read): a
15691+ // transform unit whose 4x4 origin sits outside the frame's mi
15692+ // grid is not coded at all. The luma loop above carries the
15693+ // same clip; its absence here read `txb_skip` (+coeffs) for
15694+ // chroma units libaom never wrote -- the lossless 64x64 block
15695+ // at mi(48,0) of a 320x240 frame overhangs the bottom edge by
15696+ // 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units, not
15697+ // eight (lane-av1-loss64; 48 chroma units per plane in
15698+ // aomdec's EC_COEFF census vs the 64 this loop read).
15699+ // `max_block_wide/high` (av1_common_int.h:1565): the plane
15700+ // block's pixel span (4:2:0 halves the luma span, clamped to
15701+ // 4 by `set_plane_n4`) plus the negative overhang
15702+ // (`mb_to_*_edge` = `2 * overhang_mi` chroma px), in 4x4
15703+ // units.
15704+ let span_mi = side / MI;
15705+ let over_w_mi =
15706+ (2 * y.true_width.div_ceil(8)) as i32 - mi_c as i32 - span_mi as i32;
15707+ let over_h_mi =
15708+ (2 * y.true_height.div_ceil(8)) as i32 - mi_r as i32 - span_mi as i32;
15709+ let plane_px = ((span_mi * 2).max(4)) as i32;
15710+ let max_units_w = ((plane_px + 2 * over_w_mi.min(0)) >> 2).max(0) as usize;
15711+ let max_units_h = ((plane_px + 2 * over_h_mi.min(0)) >> 2).max(0) as usize;
15712+ let unit = chroma_tx / 4; // TU side in 4x4 chroma units
15713+ if cu_col * unit >= max_units_w || cu_row * unit >= max_units_h {
15714+ hit!(CHROMA_EDGE_TU_CLIP_HITS);
15715+ continue;
15716+ }
1563515717 // The chroma context arrays are indexed in LUMA mi, so this
1563615718 // unit's anchor is its own luma quadrant: `chroma_tx` chroma
1563715719 // pixels span `2 * chroma_tx` luma ones.
crates/ec-av1/src/stream.rsmodified+169 -0
@@ -5019,6 +5019,175 @@ pub(crate) mod tests {
50195019 eprintln!("{NAME}: {frames} frames sample-exact, intra128_lossless hits {hits}");
50205020 }
50215021
5022+ /// lane-av1-loss64: the generator for the two gates below -- a deterministic
5023+ /// 1-frame lossless superblock-128 aomenc stream of `testsrc2`. `extra`
5024+ /// flags land last (aomenc keeps the LAST occurrence of a repeated flag).
5025+ /// The recipe is the one lanes/av1rect14.report.md section 2 measured
5026+ /// (`--lossless=1 --sb-size=128 --enable-1to4-partitions=1`); the
5027+ /// `--min-partition-size` override is what steers the bottom superblock
5028+ /// row's RD into overhanging 64x64 `NONE` blocks (the shape the first fix
5029+ /// clips) or, at 8, keeps sub-8x8 partitions out of the second gate's
5030+ /// stream so the whole frame is decodable.
5031+ fn lossless_sb128_testsrc2(width: usize, height: usize, extra: &[&str]) -> Vec<u8> {
5032+ let mut ff = Command::new("ffmpeg");
5033+ let out = ff
5034+ .args(["-v", "error", "-f", "lavfi", "-i"])
5035+ .arg(format!("testsrc2=s={width}x{height}:r=25"))
5036+ .args(["-frames:v", "1", "-pix_fmt", "yuv420p", "-strict", "-1", "-f", "yuv4mpegpipe", "-"])
5037+ .stdin(Stdio::null())
5038+ .stdout(Stdio::piped())
5039+ .stderr(Stdio::piped())
5040+ .output()
5041+ .expect("ffmpeg failed to run");
5042+ assert!(out.status.success(), "ffmpeg failed for testsrc2 {width}x{height}");
5043+ let y4m = out.stdout;
5044+ let mut child = Command::new(aomenc_path())
5045+ .args(["--codec=av1", "--bit-depth=8", "--input-bit-depth=8"])
5046+ .args([
5047+ "--passes=1",
5048+ "--cpu-used=0",
5049+ "--lag-in-frames=0",
5050+ "--kf-max-dist=1",
5051+ "--limit=1",
5052+ "--threads=1",
5053+ "--tile-columns=0",
5054+ "--lossless=1",
5055+ "--sb-size=128",
5056+ "--enable-1to4-partitions=1",
5057+ ])
5058+ .args(extra)
5059+ .args(["--obu", "-o", "-", "-"])
5060+ .stdin(Stdio::piped())
5061+ .stdout(Stdio::piped())
5062+ .stderr(Stdio::piped())
5063+ .spawn()
5064+ .expect("aomenc failed to start");
5065+ child
5066+ .stdin
5067+ .take()
5068+ .expect("aomenc stdin")
5069+ .write_all(&y4m)
5070+ .expect("aomenc stdin write");
5071+ let out = child.wait_with_output().expect("aomenc failed to run");
5072+ assert!(out.status.success(), "aomenc failed: {}", String::from_utf8_lossy(&out.stderr));
5073+ out.stdout
5074+ }
5075+
5076+ /// lane-av1-loss64: a lossless superblock-128 frame whose intra blocks
5077+ /// overhang the bottom frame edge codes NO coefficient symbols for the
5078+ /// chroma transform units whose 4x4 origin sits outside the frame's mi
5079+ /// grid -- libaom `decode_reconstruct_tx` returns before any read
5080+ /// (`decodeframe.c:299`, `blk_row >= max_blocks_high || blk_col >=
5081+ /// max_blocks_wide`, the limits from `max_block_wide/high`,
5082+ /// av1_common_int.h:1565). The square multi-transform-unit chroma loop in
5083+ /// [`crate::decode`] carried no such clip (the luma loop had one) and read
5084+ /// `txb_skip`+coefficients for the phantom units: on the measured stream
5085+ /// the first lossless 64x64 `NONE` block, at mi(48,0), overhangs the
5086+ /// 240-px frame by 4 mi, so its 32x32 chroma codes SIX rows of 4x4 units,
5087+ /// not eight -- 32 phantom unit reads per plane desynced the tile and
5088+ /// every later symbol (including partition reads, which is what made
5089+ /// aomdec's zero-`value=8/9` census look like a partition-reader defect
5090+ /// in the rect14 review) decoded as garbage.
5091+ ///
5092+ /// Fail-pre-fix, measured on the ed12fe52 probe: both arms differ from
5093+ /// ffmpeg at byte 41120 (luma row 128 col 160, the first block decoded
5094+ /// after the phantom reads). The counter delta pins non-vacuity (class
5095+ /// `gate-blind-to-feature`): 96 clipped units on each arm.
5096+ #[test]
5097+ fn a_lossless_sb128_square_frame_clips_overhanging_chroma_tus() {
5098+ const NAME: &str = "a_lossless_sb128_square_frame_clips_overhanging_chroma_tus";
5099+ if !have_ffmpeg() {
5100+ eprintln!("SKIP {NAME}: no ffmpeg");
5101+ return;
5102+ }
5103+ // Arm 0 is the rect14 report's `loss320` recipe verbatim; arm 1 is its
5104+ // `lnone` companion (1:4 and rect partitions off) -- both coded the
5105+ // overhanging 64x64 blocks and both desynced at byte 41120 pre-fix.
5106+ let arms: [&[&str]; 2] = [
5107+ &["--min-partition-size=4"],
5108+ &["--min-partition-size=4", "--enable-1to4-partitions=0", "--enable-rect-partitions=0"],
5109+ ];
5110+ let mut clips_total = 0usize;
5111+ for (arm, extra) in arms.iter().enumerate() {
5112+ let stream = lossless_sb128_testsrc2(320, 240, extra);
5113+ crate::decode::reset_loss64_hits();
5114+ let ours = decode_stream(&stream)
5115+ .unwrap_or_else(|e| panic!("{NAME}: arm {arm} decodes: {e}"));
5116+ let clips = crate::decode::chroma_edge_tu_clip_hits();
5117+ assert!(
5118+ clips > 0,
5119+ "{NAME}: arm {arm} clipped NO overhanging chroma transform unit -- \
5120+ the fixed body was never reached (class gate-blind-to-feature)"
5121+ );
5122+ clips_total += clips;
5123+ let refs = ffmpeg_decode_sequence(&stream, 320, 240, 1);
5124+ assert_eq!(ours.len(), 1, "{NAME}: arm {arm} frame count");
5125+ for (plane, (g, r)) in [(&ours[0].y, &refs[0].y), (&ours[0].u, &refs[0].u), (&ours[0].v, &refs[0].v)]
5126+ .iter()
5127+ .enumerate()
5128+ {
5129+ let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
5130+ assert_eq!(bad, 0, "{NAME}: arm {arm} plane {plane}: {bad} samples differ from ffmpeg");
5131+ }
5132+ }
5133+ eprintln!("{NAME}: 2 arms full-frame exact, {clips_total} chroma units clipped");
5134+ }
5135+
5136+ /// lane-av1-loss64: a SKIPPED intrabc rect strip on a lossless frame
5137+ /// zeroes its whole entropy-band footprint (libaom
5138+ /// `av1_reset_entropy_context`, `if (mbmi->skip_txfm)` decodemv.c:1262 ->
5139+ /// blockd.c:58) instead of leaving the previous occupant's luma bands
5140+ /// standing. The skip arm of `decode_intrabc_owned_rect` never wrote the
5141+ /// luma bands: the lossless `read_block_tx_size_rect` resolves the 4x4
5142+ /// leaf list before it looks at `skip`, so the tail took the
5143+ /// per-transform-unit record path (chroma only) with no per-unit luma
5144+ /// writes ever run. The next block then read a STALE band: on the 320x242
5145+ /// `--min-partition-size=4` sibling of this stream the skipped 8x16
5146+ /// intrabc strip at mi(48,66) left a 7 in left[48] and mi(48,68)'s first
5147+ /// transform unit read `txb_skip_ctx` 3 where aomdec reads 1 (measured
5148+ /// `EC_ECDUMP` against the instrumented aomdec) -- a coefficient-walk
5149+ /// desync at byte 61712 with every mode symbol still matching.
5150+ ///
5151+ /// This stream is the same source at `--min-partition-size=8`, which
5152+ /// keeps sub-8x8 partitions out: post-fix it is full-frame exact. The
5153+ /// `--min-partition-size=4` sibling still is not -- its remaining
5154+ /// divergence is a sub-8x8 4x8-leaf chroma reconstruction defect with the
5155+ /// entropy ladder fully synced (first diff U(92,104), luma byte-exact),
5156+ /// deferred to the sub-8x8 lane family (lanes/av1loss64.report.md).
5157+ ///
5158+ /// Fail-pre-fix, measured on the ed12fe52 probe: differs at byte 41120
5159+ /// (the chroma-clip class, fixed in the same lane). Single-mutation on
5160+ /// the lane tree with ONLY this gate's walk reverted: differs at byte
5161+ /// 61712, the band-leak site.
5162+ #[test]
5163+ fn a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands() {
5164+ const NAME: &str = "a_skipped_lossless_intrabc_rect_strip_zeroes_its_entropy_bands";
5165+ if !have_ffmpeg() {
5166+ eprintln!("SKIP {NAME}: no ffmpeg");
5167+ return;
5168+ }
5169+ let stream = lossless_sb128_testsrc2(320, 242, &["--min-partition-size=8"]);
5170+ crate::decode::reset_loss64_hits();
5171+ let ours = decode_stream(&stream)
5172+ .unwrap_or_else(|e| panic!("{NAME}: decodes: {e}"));
5173+ let resets = crate::decode::skip_lossless_band_reset_hits();
5174+ assert!(
5175+ resets > 0,
5176+ "{NAME}: this stream coded NO skipped lossless intrabc rect strip -- \
5177+ the fixed body was never reached (class gate-blind-to-feature)"
5178+ );
5179+ let refs = ffmpeg_decode_sequence(&stream, 320, 242, 1);
5180+ assert_eq!(ours.len(), 1, "{NAME}: frame count");
5181+ for (plane, (g, r)) in [(&ours[0].y, &refs[0].y), (&ours[0].u, &refs[0].u), (&ours[0].v, &refs[0].v)]
5182+ .iter()
5183+ .enumerate()
5184+ {
5185+ let bad = g.iter().zip(r.iter()).filter(|(a, b)| a != b).count();
5186+ assert_eq!(bad, 0, "{NAME}: plane {plane}: {bad} samples differ from ffmpeg");
5187+ }
5188+ eprintln!("{NAME}: full-frame exact, {resets} band resets");
5189+ }
5190+
50225191 /// lane-dkey: the palette-neighbour-band gate. A palette-Y block's size and
50235192 /// colours used to stay standing in the mi-granular above/left bands after a
50245193 /// sub-8x8 group was decoded next to it -- the sub-8x8 readers published