forge
Explore
Log in

Don't you dare go Hollow

Rect strips predict per transform unit

Browse files at this commit

aedec075655404504e1f12c459b2113a3905ad55Ahmet Kaan GümüşParent: b1f001a
  • feat
    • rect strips predict per transform unit
    • filter intra on a strip
Show full message
feat(av1): rect strips predict per transform unit; filter intra on a strip

lane-rectsplit r1 (continuing the WIP snapshot c5de1b6):
- decode_block_rect's split-transform arm decodes per transform unit
  (decode_rect_split), gated by
  a_real_aomenc_stream_with_a_split_transform_horz_vert_strip_decodes_pixel_exact
  (20/20 pixel-exact, rect_split_tx_hits > 0).
- predict_filter_intra takes bw x bh instead of one square side, so a
  use_filter_intra HORZ/VERT strip predicts instead of refusing; gated by
  a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact
  (--enable-filter-intra=1, cq 25, 40/40 pixel-exact, filter_intra_rect_hits=3).
- decode_leaf_rect (below 16x16) keeps both refusals, its split one renamed
  to name the size, and is listed in refusal_inventory.
- The superblock-level split-transform refusal stays: its gate is measured
  RED (seed 50, luma (171,56) off by one) and #[ignore]d with that number.
crates/ec-av1/src/decode.rsmodified+23 -9
@@ -442,6 +442,20 @@ pub(crate) fn rect_split_tx_hits() -> usize {
442442 RECT_SPLIT_TX_HITS.with(|c| c.get())
443443 }
444444
445+// How many HORZ/VERT intra strips actually predicted with filter intra
446+// (lane-rectsplit r1) -- the case `decode_block_rect` refused by name
447+// ("this decoder predicts square-only") until `predict_filter_intra` took
448+// `bw`x`bh`.
449+thread_local! {
450+ static FILTER_INTRA_RECT_HITS: std::cell::Cell<usize> =
451+ const { std::cell::Cell::new(0) };
452+}
453+
454+/// Current value of [`FILTER_INTRA_RECT_HITS`].
455+pub(crate) fn filter_intra_rect_hits() -> usize {
456+ FILTER_INTRA_RECT_HITS.with(|c| c.get())
457+}
458+
445459 // How many [`read_coeffs`] reads resolved a `tx_type` outside `TX_CLASS_2D`
446460 // (`V_DCT`/`H_DCT`, spec 5.11.39's `TxClass::Horiz`/`Vert`), across every
447461 // call on the current thread -- the same before/after counter pattern as
@@ -3436,15 +3450,13 @@ fn decode_block_rect(
34363450 // `uv_mode`, not the luma one.
34373451 let smooth_neighbor_uv =
34383452 is_smooth_mode(neighbours.above_uv_mode[c]) || is_smooth_mode(neighbours.left_uv_mode[r]);
3453+ // lane-rectsplit r1: `predict_filter_intra` now takes the block's own
3454+ // `bw`x`bh` (`av1_filter_intra_predictor_c` walks its 4x2 patches over a
3455+ // rectangle just as happily), so a `use_filter_intra` strip at this level
3456+ // predicts instead of refusing. The below-16x16 leaf arm
3457+ // (`decode_leaf_rect`) keeps the refusal: it has no gate of its own.
34393458 if filter_intra.is_some() {
3440- // `predict_filter_intra` (spec 7.11.2.3) is square-only in this
3441- // decoder (`assert_eq!(dst.len(), side*side)`) -- a real symbol was
3442- // already read above so the stream stays in sync, this only refuses
3443- // the *pixel* decode of a rare case (`use_filter_intra` on a rect
3444- // strip).
3445- return Err(unsupported(
3446- "filter intra on a HORZ/VERT strip (this decoder predicts square-only)",
3447- ));
3459+ FILTER_INTRA_RECT_HITS.with(|c| c.set(c.get() + 1));
34483460 }
34493461 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
34503462 DC_PRED
@@ -3830,7 +3842,7 @@ fn decode_leaf_rect(
38303842 };
38313843 if depth != 0 {
38323844 return Err(unsupported(
3833- "a HORZ/VERT intra strip with a split transform (per-unit rect \
3845+ "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect \
38343846 prediction is not ported)",
38353847 ));
38363848 }
@@ -4789,6 +4801,7 @@ impl PlaneBuf {
47894801 left.as_deref(),
47904802 corner,
47914803 bw,
4804+ bh,
47924805 &mut prediction,
47934806 );
47944807 } else {
@@ -4861,6 +4874,7 @@ impl PlaneBuf {
48614874 left.as_deref(),
48624875 corner,
48634876 side,
4877+ side,
48644878 &mut prediction,
48654879 );
48664880 } else {
crates/ec-av1/src/intra.rsmodified+26 -18
@@ -726,37 +726,45 @@ const FILTER_INTRA_SCALE_BITS: u32 = 4;
726726 /// though this mode itself never reaches past its own `side` samples of
727727 /// either edge.
728728 ///
729+/// `bw`x`bh` is the block, not necessarily square (lane-rectsplit r1):
730+/// `av1_filter_intra_predictor_c` walks the same 4x2 patches over a
731+/// rectangular block, and `av1_filter_intra_allowed_bsize` genuinely offers
732+/// this mode on every HORZ/VERT strip whose sides are both <= 32 (16x8,
733+/// 8x16, 32x16, 16x32, ...), which the square-only assert refused before.
734+///
729735 /// # Panics
730-/// Panics when `dst` is not `side * side` long, or `side` is not a multiple
731-/// of 4 (spec `av1_filter_intra_allowed_bsize` never offers this mode past
732-/// 32x32, and only on square blocks: 4, 8, 16 or 32).
736+/// Panics when `dst` is not `bw * bh` long, or `bw` is not a multiple of 4
737+/// or `bh` not a multiple of 2 (spec `av1_filter_intra_allowed_bsize` never
738+/// offers this mode past 32x32).
733739 pub fn predict_filter_intra(
734740 mode: usize,
735741 above: Option<&[u16]>,
736742 left: Option<&[u16]>,
737743 corner: Option<u16>,
738- side: usize,
744+ bw: usize,
745+ bh: usize,
739746 dst: &mut [u16],
740747 ) {
741- assert_eq!(dst.len(), side * side, "the destination is the block");
742- assert_eq!(side % 4, 0, "filter intra only offers 4/8/16/32");
743- let edges = Edges::build(above, left, corner, side, side);
748+ assert_eq!(dst.len(), bw * bh, "the destination is the block");
749+ assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
750+ assert_eq!(bh % 2, 0, "filter intra patches are 2 high");
751+ let edges = Edges::build(above, left, corner, bw, bh);
744752 let taps = &FILTER_INTRA_TAPS[mode];
745753 // A (side+1)-square buffer: row 0 / column 0 hold the corner and the
746754 // above/left edges, `buffer[r+1][c+1]` the block's own sample at (r, c).
747- let mut buffer = vec![0i32; (side + 1) * (side + 1)];
748- let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (side + 1) + c];
755+ let mut buffer = vec![0i32; (bh + 1) * (bw + 1)];
756+ let at = |buffer: &[i32], r: usize, c: usize| buffer[r * (bw + 1) + c];
749757 buffer[0] = edges.above(-1);
750- for c in 0..side {
758+ for c in 0..bw {
751759 buffer[c + 1] = edges.above(c as i32);
752760 }
753- for r in 0..side {
754- buffer[(r + 1) * (side + 1)] = edges.left(r as i32);
761+ for r in 0..bh {
762+ buffer[(r + 1) * (bw + 1)] = edges.left(r as i32);
755763 }
756764 let mut r = 1;
757- while r < side + 1 {
765+ while r < bh + 1 {
758766 let mut c = 1;
759- while c < side + 1 {
767+ while c < bw + 1 {
760768 let p0 = at(&buffer, r - 1, c - 1);
761769 let p1 = at(&buffer, r - 1, c);
762770 let p2 = at(&buffer, r - 1, c + 1);
@@ -769,16 +777,16 @@ pub fn predict_filter_intra(
769777 let (r_off, c_off) = (k >> 2, k & 3);
770778 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();
771779 let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max());
772- let idx = (r + r_off) * (side + 1) + c + c_off;
780+ let idx = (r + r_off) * (bw + 1) + c + c_off;
773781 buffer[idx] = value;
774782 }
775783 c += 4;
776784 }
777785 r += 2;
778786 }
779- for row in 0..side {
780- for col in 0..side {
781- dst[row * side + col] = at(&buffer, row + 1, col + 1) as u16;
787+ for row in 0..bh {
788+ for col in 0..bw {
789+ dst[row * bw + col] = at(&buffer, row + 1, col + 1) as u16;
782790 }
783791 }
784792 }
crates/ec-av1/src/refusal_inventory.rsmodified+1 -0
@@ -38,6 +38,7 @@ const REFUSALS: &[&str] = &[
3838 "a coded (non-skip) HORZ_B/VERT_B rect strip below 16x16 (this decoder ports only the skip case at this size)",
3939 "a coded (non-skip) HORZ/VERT rect strip below 16x16 (this decoder ports only the skip case at this size)",
4040 "a coded HORZ/VERT strip whose chroma transform has no rect coefficient tables here",
41+ "a HORZ/VERT intra strip below 16x16 with a split transform (per-unit rect prediction is not ported)",
4142 "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)",
4243 "a 16x16 block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
4344 "a 16x16 inter block whose true edge cuts through both axes needs a rectangular transform this decoder does not code yet",
crates/ec-av1/src/stream.rsmodified+198 -0
@@ -9504,6 +9504,204 @@ mod tests {
95049504 );
95059505 }
95069506
9507+ /// lane-rectsplit r1 gate (c): gate (a)'s recipe with
9508+ /// `--enable-filter-intra=1` (every sibling gate here pins it to 0), so
9509+ /// aomenc's RD is free to pick `use_filter_intra` on a 32x16/16x32 strip
9510+ /// -- the case [`crate::decode::decode_block_rect`] refused by name
9511+ /// ("filter intra on a HORZ/VERT strip (this decoder predicts
9512+ /// square-only)") until this round gave `predict_filter_intra` its own
9513+ /// `bw`x`bh`. Hard-asserts a nonzero `filter_intra_rect_hits()` delta:
9514+ /// a stream where RD never picked filter intra on a strip would
9515+ /// pixel-match by construction and prove nothing.
9516+ #[test]
9517+ fn a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact() {
9518+ const NAME: &str =
9519+ "a_real_aomenc_stream_with_filter_intra_on_a_horz_vert_strip_decodes_pixel_exact";
9520+ let _gate_lock = lock_gate_counters();
9521+ if !have_ffmpeg() {
9522+ eprintln!("SKIP {NAME}: no ffmpeg");
9523+ return;
9524+ }
9525+ if !have_aomenc() {
9526+ eprintln!("SKIP {NAME}: no aomenc at {}", aomenc_path().display());
9527+ return;
9528+ }
9529+ let (width, height) = (192usize, 128usize);
9530+ let before = crate::decode::filter_intra_rect_hits();
9531+ let rect_before = crate::decode::rect_partition_hits();
9532+ let fi_square_before = crate::decode::filter_intra_hits();
9533+ let mut named_refusals = 0u32;
9534+ let mut matched = 0u32;
9535+ let n_attempts: u32 = std::env::var("EC_RECTSPLIT_GATE_ATTEMPTS")
9536+ .ok()
9537+ .and_then(|s| s.parse().ok())
9538+ .unwrap_or(40);
9539+ for attempt in 0..n_attempts {
9540+ let seed = 42 + attempt;
9541+ // Diagnosis knob: which content makes RD pick a HORZ/VERT strip
9542+ // AND filter intra on it is a search (see this round's report).
9543+ let source = match std::env::var("EC_RECTSPLIT_SRC").unwrap_or_default().as_str() {
9544+ "bars" => format!("smptebars=size={width}x{height}:duration=0.04:rate=25"),
9545+ "src2" => format!("testsrc2=size={width}x{height}:duration=0.04:rate=25"),
9546+ _ => gradients_source(seed, width, height, "duration=0.04:rate=25"),
9547+ };
9548+ let y4m = Command::new("ffmpeg")
9549+ .args([
9550+ "-v", "error", "-f", "lavfi", "-i", &source,
9551+ // Same `hue=s=0` guard as gate (a): a real chroma gradient
9552+ // under the tx-size search hits a PRE-EXISTING square-path
9553+ // chroma defect that has nothing to do with this lane.
9554+ "-vf", "hue=s=0",
9555+ "-pix_fmt", "yuv420p", "-f", "yuv4mpegpipe", "-",
9556+ ])
9557+ .stdin(Stdio::null())
9558+ .stdout(Stdio::piped())
9559+ .stderr(Stdio::piped())
9560+ .output()
9561+ .expect("ffmpeg failed to run");
9562+ assert!(
9563+ y4m.status.success(),
9564+ "ffmpeg fixture: {}",
9565+ String::from_utf8_lossy(&y4m.stderr)
9566+ );
9567+ // Diagnosis knob only (default is the gate's pinned recipe):
9568+ // which `--cq-level` makes aomenc's RD reach for filter intra on
9569+ // a strip is a search, and the sweep that found this one is in
9570+ // lanes/rectsplit-r1.report.md.
9571+ let cq = format!(
9572+ "--cq-level={}",
9573+ // Pinned by the sweep in lanes/rectsplit-r1.report.md: at
9574+ // cq 45 aomenc's RD picks a strip 18 times in 100 seeds and
9575+ // filter intra on none of them; at cq 25 strips are common
9576+ // (130/100 seeds) and filter intra lands on one every ~13
9577+ // seeds.
9578+ std::env::var("EC_RECTSPLIT_CQ").unwrap_or_else(|_| "25".into())
9579+ );
9580+ let args: Vec<&str> = vec![
9581+ "--codec=av1",
9582+ "--passes=1",
9583+ "--end-usage=q",
9584+ &cq,
9585+ "--cpu-used=0",
9586+ "--threads=1",
9587+ "--row-mt=0",
9588+ "--sb-size=64",
9589+ "--enable-rect-partitions=1",
9590+ "--enable-ab-partitions=0",
9591+ "--enable-1to4-partitions=0",
9592+ "--min-partition-size=16",
9593+ "--max-partition-size=32",
9594+ "--enable-restoration=0",
9595+ "--enable-palette=0",
9596+ "--deltaq-mode=0",
9597+ // The point of this gate.
9598+ "--enable-filter-intra=1",
9599+ // The square filter-intra gate's own way of making RD reach
9600+ // for filter intra at all: with the directional/smooth/paeth
9601+ // competitors off, DC_PRED + filter intra is what is left
9602+ // (recipe borrowed from
9603+ // `a_real_aomenc_filter_intra_stream_decodes_pixel_exact`;
9604+ // without them 20/20 streams picked filter intra zero times
9605+ // on a strip -- measured this round).
9606+ "--enable-cfl-intra=0",
9607+ "--enable-intrabc=0",
9608+ "--obu",
9609+ "-o",
9610+ "-",
9611+ "-",
9612+ ];
9613+ // Diagnosis knob (default: every intra mode on): turning the
9614+ // directional/smooth/paeth competitors off is how the square
9615+ // filter-intra gate makes RD reach for filter intra, but with all
9616+ // four off aomenc stops picking rect partitions here entirely
9617+ // (rect strips=0, filter-intra blocks=28, measured this round),
9618+ // so the firing recipe is a search over subsets.
9619+ let mut args = args;
9620+ let off = std::env::var("EC_RECTSPLIT_OFF").unwrap_or_default();
9621+ for tool in off.split(',').filter(|t| !t.is_empty()) {
9622+ args.push(match tool {
9623+ "smooth" => "--enable-smooth-intra=0",
9624+ "paeth" => "--enable-paeth-intra=0",
9625+ "dir" => "--enable-directional-intra=0",
9626+ "angle" => "--enable-angle-delta=0",
9627+ other => panic!("unknown EC_RECTSPLIT_OFF entry {other}"),
9628+ });
9629+ }
9630+ let mut child = Command::new(aomenc_path())
9631+ .args(&args)
9632+ .stdin(Stdio::piped())
9633+ .stdout(Stdio::piped())
9634+ .stderr(Stdio::piped())
9635+ .spawn()
9636+ .expect("aomenc failed to start");
9637+ child
9638+ .stdin
9639+ .take()
9640+ .expect("aomenc stdin")
9641+ .write_all(&y4m.stdout)
9642+ .expect("writing y4m to aomenc");
9643+ let out = child.wait_with_output().expect("aomenc failed to run");
9644+ assert!(
9645+ out.status.success(),
9646+ "aomenc refused the fixture: {}",
9647+ String::from_utf8_lossy(&out.stderr)
9648+ );
9649+ let stream = out.stdout;
9650+ assert!(!stream.is_empty(), "{NAME}: aomenc wrote an empty stream (seed {seed})");
9651+ let frames = match decode_stream(&stream) {
9652+ Err(e) => {
9653+ let msg = e.to_string();
9654+ assert!(
9655+ msg.contains("unsupported"),
9656+ "{NAME} failed outright, not a named refusal (seed {seed}): {msg}"
9657+ );
9658+ named_refusals += 1;
9659+ continue;
9660+ }
9661+ Ok(frames) => frames,
9662+ };
9663+ let ffmpeg_frames = ffmpeg_decode_sequence(&stream, width, height, 1);
9664+ assert_eq!(frames.len(), 1, "{NAME}: expected one frame (seed {seed})");
9665+ if let Some(i) = frames[0]
9666+ .y
9667+ .iter()
9668+ .zip(&ffmpeg_frames[0].y)
9669+ .position(|(a, b)| a != b)
9670+ {
9671+ eprintln!(
9672+ "{NAME}: seed {seed} first luma mismatch at ({}, {}) ours={} ffmpeg={}",
9673+ i % width,
9674+ i / width,
9675+ frames[0].y[i],
9676+ ffmpeg_frames[0].y[i]
9677+ );
9678+ }
9679+ assert_eq!(frames[0].y, ffmpeg_frames[0].y, "{NAME}: luma vs ffmpeg (seed {seed})");
9680+ assert_eq!(frames[0].u, ffmpeg_frames[0].u, "{NAME}: U vs ffmpeg (seed {seed})");
9681+ assert_eq!(frames[0].v, ffmpeg_frames[0].v, "{NAME}: V vs ffmpeg (seed {seed})");
9682+ matched += 1;
9683+ }
9684+ let fi_hits = crate::decode::filter_intra_rect_hits() - before;
9685+ eprintln!(
9686+ "{NAME}: rect strips this run={}, filter-intra blocks (any shape)={}",
9687+ crate::decode::rect_partition_hits() - rect_before,
9688+ crate::decode::filter_intra_hits() - fi_square_before
9689+ );
9690+ assert!(
9691+ matched > 0,
9692+ "{NAME}: every attempt refused ({named_refusals} named refusals) -- gate decoded nothing"
9693+ );
9694+ assert!(
9695+ fi_hits > 0,
9696+ "{NAME}: no HORZ/VERT strip used filter intra ({matched} pixel-exact matches, \
9697+ {named_refusals} refusals out of {n_attempts}) -- gate proved nothing this run"
9698+ );
9699+ eprintln!(
9700+ "{NAME}: {matched} pixel-exact matches, {named_refusals} named refusals, \
9701+ filter_intra_rect_hits delta={fi_hits} out of {n_attempts} attempts"
9702+ );
9703+ }
9704+
95079705 /// lane-rectsplit r1 gate (b): [`a_real_aomenc_stream_with_a_superblock_level_horz_vert_partition_decodes_pixel_exact`]'s
95089706 /// own recipe (`--sb-size=64`, `--min/max-partition-size=32/64`, so every
95099707 /// SB-level decision is genuinely NONE/SPLIT/HORZ/VERT) with its