forge
Explore
Log in

Don't you dare go Hollow

U3: ec-av1 scaffolding: drop EC_SYMR and EC_* trace/probe gates in decode and stream, dead counter helpers and unused params, ignored probe/sweep/wall tests, stale test-only witnesses; cargo fmt on touched files (HEAD was not fmt-clean, so churn is in these 39 files). Output bits unchanged: unset env branches kept only. cargo check -p ec-av1 --all-targets clean, no warnings

Browse files at this commit

421435250c2f1313f118bc7f62d65f260d093aaaAhmet Kaan GümüşParent: b4eb44d

39 changed files +6989 -12565

crates/ec-av1/src/decode/block.rsmodified+6 -410
@@ -41,41 +41,16 @@ pub(super) fn read_intra_mode(
4141 Option<PaletteY>,
4242 Option<PaletteUv>,
4343 )> {
44- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
4544 // lane-tiny r2: EC_ISTEP-format trace (same "name=... val=... rng=..."
4645 // shape the oracle's own `ec_read_intra_frame_mode_info_impl` prints
4746 // under `EC_TRACE_MODE_STEP`) so a range ladder can be diffed line for
4847 // line against the instrumented aomdec, not just `tell()`.
49- crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
50- let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
51- if ec_istep {
52- // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
53- // (decodemv.c:818), printed at the same point: before the first
54- // mode-info symbol of the block, so a cross-decoder range ladder can
55- // be keyed on the BLOCK, not just on the symbol sequence.
56- eprintln!(
57- "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sq side={side} rng={}",
58- dec.debug_state().0
59- );
60- }
6148 macro_rules! istep {
62- ($name:literal, $val:expr) => {
63- if ec_istep {
64- let (rng, _) = dec.debug_state();
65- eprintln!(
66- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
67- $name, $val
68- );
69- }
70- };
49+ ($name:literal, $val:expr) => {};
7150 }
7251 // lane-sbrect10 r1: `is_cfl_allowed`'s <=32 bound, enforced at the single
7352 // point every square caller routes through (see `read_intra_mode_rect`).
74- let cfl = if cfl && side > 32 {
75- false
76- } else {
77- cfl
78- };
53+ let cfl = if cfl && side > 32 { false } else { cfl };
7954 // spec 5.11.6 `intra_frame_mode_info`: `intra_segment_id` is read BEFORE
8055 // `skip` when `SegIdPreSkip`, and after it otherwise.
8156 let (seg_w_mi, seg_h_mi) = (side / 4, side / 4);
@@ -83,13 +58,6 @@ pub(super) fn read_intra_mode(
8358 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
8459 }
8560 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
86- if trace {
87- eprintln!(
88- "TRACE skip value={} rng={}",
89- skip as i32,
90- dec.debug_state().0
91- );
92- }
9361 istep!("skip", skip as i32);
9462 if !seg_id_pre_skip(fctx) {
9563 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
@@ -116,21 +84,8 @@ pub(super) fn read_intra_mode(
11684 // that merely allows (but never uses) intrabc.
11785 if allow_intrabc {
11886 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
119- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
120- eprintln!(
121- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
122- u8::from(use_intrabc),
123- dec.debug_state().0
124- );
125- }
126- if trace {
127- eprintln!("TRACE use_intrabc value={}", use_intrabc as i32);
128- }
12987 if use_intrabc {
13088 let dv = read_intrabc_dv(dec, cdfs, mi_r, mi_c, (side / MI, side / MI), fctx);
131- if trace {
132- eprintln!("TRACE intrabc dv={dv:?}");
133- }
13489 fctx.intrabc_dv.with(|c| c.set(Some(dv)));
13590 // spec 5.11.13 / libaom `read_intra_frame_mode_info` returns the
13691 // moment `is_intrabc_block`: no y/uv mode, angle delta, palette,
@@ -143,21 +98,9 @@ pub(super) fn read_intra_mode(
14398 let above_ctx = INTRA_MODE_CTX[above_mode];
14499 let left_ctx = INTRA_MODE_CTX[left_mode];
145100 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
146- if trace {
147- eprintln!(
148- "TRACE y_mode ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
149- dec.debug_state().0
150- );
151- }
152101 istep!("mode", mode as i32);
153102 let angle_delta_y = if (V_PRED..=D67_PRED).contains(&mode) {
154103 let delta = read_angle_delta(dec, &mut cdfs.angle_delta[mode - V_PRED]);
155- if trace {
156- eprintln!(
157- "TRACE angle_delta value={}",
158- delta + ANGLE_DELTA_ZERO as i32
159- );
160- }
161104 delta
162105 } else {
163106 0
@@ -172,18 +115,10 @@ pub(super) fn read_intra_mode(
172115 let uv_mode = if !has_chroma {
173116 DC_PRED
174117 } else if cfl {
175- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
176118 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
177119 } else {
178- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
179120 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
180121 };
181- if trace {
182- eprintln!(
183- "TRACE uv_mode cfl={cfl} y_mode={mode} value={uv_mode} rng={}",
184- dec.debug_state().0
185- );
186- }
187122 istep!("uv_mode", uv_mode as i32);
188123 let alpha = if cfl && uv_mode == UV_CFL_PRED {
189124 Some(read_cfl_alphas(dec, cdfs))
@@ -235,32 +170,11 @@ pub(super) fn read_intra_mode(
235170 let mut palette_uv_pending: Option<(usize, [u16; 8], [u16; 8])> = None;
236171 if allow_screen_content_tools && let Some(bsize_ctx) = palette_bsize_ctx(side) {
237172 let (mode_ctx, cache) = palette.unwrap_or((0, &[]));
238- if mode == DC_PRED && trace {
239- let (rng, _) = dec.debug_state();
240- eprintln!(
241- "TRACE pre_palette_y_mode bsize_ctx={bsize_ctx} mode_ctx={mode_ctx} rng={rng}"
242- );
243- }
244173 let use_palette_y =
245174 mode == DC_PRED && dec.symbol(&mut cdfs.palette_y_mode[bsize_ctx][mode_ctx]) != 0;
246- if mode == DC_PRED && trace {
247- let (rng, _) = dec.debug_state();
248- eprintln!(
249- "TRACE palette_y_mode value={} rng={rng}",
250- use_palette_y as i32
251- );
252- }
253175 if use_palette_y {
254176 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
255- if trace {
256- let (rng, _) = dec.debug_state();
257- eprintln!("TRACE palette_y_size n={n} rng={rng}");
258- }
259177 let colors = read_palette_colors_y(dec, n, cache, fctx);
260- if trace {
261- let (rng, _) = dec.debug_state();
262- eprintln!("TRACE palette_y_colors colors={:?} rng={rng}", &colors[..n]);
263- }
264178 palette_y_pending = Some((n, colors));
265179 }
266180 // `read_palette_mode_info`'s UV half (decodemv.c:588): read
@@ -304,19 +218,9 @@ pub(super) fn read_intra_mode(
304218 && let Some(class) = filter_intra_size_class(side)
305219 {
306220 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
307- if trace {
308- eprintln!(
309- "TRACE use_filter_intra side={side} rng={} value={}",
310- dec.debug_state().0,
311- use_filter_intra as i32
312- );
313- }
314221 istep!("use_filter_intra", use_filter_intra as i32);
315222 if use_filter_intra {
316223 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
317- if trace {
318- eprintln!("TRACE filter_intra_mode value={fi_mode}");
319- }
320224 istep!("filter_intra_mode", fi_mode as i32);
321225 filter_intra = Some(fi_mode);
322226 }
@@ -332,9 +236,6 @@ pub(super) fn read_intra_mode(
332236 palette_onscreen(mi_r, mi_c, side, side, fctx),
333237 false,
334238 );
335- if trace {
336- eprintln!("TRACE palette_y size={n} colors={:?}", &colors[..n]);
337- }
338239 PaletteY {
339240 size: n,
340241 colors,
@@ -361,13 +262,6 @@ pub(super) fn read_intra_mode(
361262 on,
362263 true,
363264 );
364- if trace {
365- eprintln!(
366- "TRACE palette_uv size={n} u_colors={:?} v_colors={:?}",
367- &u_colors[..n],
368- &v_colors[..n]
369- );
370- }
371265 PaletteUv {
372266 size: n,
373267 u_colors,
@@ -493,9 +387,6 @@ pub(crate) fn cfl_ac_q3_at(
493387 bh: usize,
494388 sample: impl Fn(usize, usize) -> i32,
495389 ) -> Vec<i32> {
496- if crate::envflags::env_flag!("EC_HALVSWEEP") {
497- eprintln!("EC_HALV cfl_ac_q3_at px={px} py={py} bw={bw} bh={bh}");
498- }
499390 let (cw, ch) = (bw / 2, bh / 2);
500391 let mut ac = vec![0i32; cw * ch];
501392 let mut sum = 0i32;
@@ -600,12 +491,6 @@ pub fn take_pad_unwritten_samples() -> usize {
600491 PAD_UNWRITTEN_SAMPLES.swap(0, std::sync::atomic::Ordering::SeqCst)
601492 }
602493
603-/// The largest value reconstruction can produce, `(1 << 12) - 1`: the highest
604-/// bit depth this decoder carries is 12. A sentinel at or below this could be
605-/// a LEGAL sample, which would make the whole census vacuous -- every
606-/// unwritten sample would look like an ordinary one.
607-pub(super) const MAX_LEGAL_SAMPLE: u16 = 4095;
608-
609494 /// The value [`fresh_plane`] fills with when the sentinel is on.
610495 ///
611496 /// [`PLANE_SENTINEL`] unless `EC_AV1_PLANE_SENTINEL` names a different one in
@@ -623,24 +508,7 @@ pub(super) const MAX_LEGAL_SAMPLE: u16 = 4095;
623508 /// [`census_unwritten_grained`] counts the same value. The fill and the census
624509 /// must agree on both the value and the predicate, or a "0" means nothing.
625510 pub(crate) fn plane_poison() -> u16 {
626- static V: std::sync::LazyLock<u16> = std::sync::LazyLock::new(|| {
627- let Ok(raw) = crate::envflags::var("EC_AV1_PLANE_SENTINEL") else {
628- return PLANE_SENTINEL;
629- };
630- let t = raw.trim();
631- if t.is_empty() || t == "1" {
632- return PLANE_SENTINEL;
633- }
634- let hex = t
635- .strip_prefix("0x")
636- .or_else(|| t.strip_prefix("0X"))
637- .unwrap_or(t);
638- match u16::from_str_radix(hex, 16) {
639- Ok(v) if v > MAX_LEGAL_SAMPLE => v,
640- _ => PLANE_SENTINEL,
641- }
642- });
643- *V
511+ PLANE_SENTINEL
644512 }
645513
646514 thread_local! {
@@ -652,8 +520,7 @@ thread_local! {
652520 /// Whether freshly allocated planes are [`PLANE_SENTINEL`]-filled.
653521 /// `pub(crate)` for the same reason as [`plane_poison`].
654522 pub(crate) fn plane_sentinel_on() -> bool {
655- crate::envflags::env_flag!("EC_AV1_PLANE_SENTINEL")
656- || PLANE_SENTINEL_ON.with(std::cell::Cell::get)
523+ PLANE_SENTINEL_ON.with(std::cell::Cell::get)
657524 }
658525
659526 /// lane-av1unwritten: whether a subsize has a chroma PLANE BLOCK at this
@@ -834,19 +701,6 @@ pub(super) fn refuse_invalid_subsize(
834701 // records, per CALL SITE and per partition value, how often the guard was
835702 // reached and how often it fired, so a site that never sees an offending
836703 // value is visible instead of assumed covered.
837- if crate::envflags::env_flag!("EC_AV1_SUBSIZE_GUARD_TRACE") {
838- note_subsize_guard(
839- std::panic::Location::caller(),
840- bsize,
841- part,
842- chroma_plane_block_codable(
843- partition_subsize_dims(bsize, part).0,
844- partition_subsize_dims(bsize, part).1,
845- ss_x(fctx),
846- ss_y(fctx),
847- ),
848- );
849- }
850704 let (bw, bh) = partition_subsize_dims(bsize, part);
851705 if chroma_plane_block_codable(bw, bh, ss_x(fctx), ss_y(fctx)) {
852706 Ok(())
@@ -864,21 +718,6 @@ pub(super) static SUBSIZE_ARM: std::sync::LazyLock<
864718 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize), usize>>,
865719 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));
866720
867-#[track_caller]
868-pub(crate) fn note_subsize_arm(part: usize, codable: bool) {
869- if !crate::envflags::env_flag!("EC_AV1_SUBSIZE_ARM_TRACE") {
870- return;
871- }
872- let site = std::panic::Location::caller();
873- let key = (
874- format!("{}:{}", site.file(), site.line()).leak() as &'static str,
875- part * 2 + usize::from(codable),
876- );
877- if let Ok(mut m) = SUBSIZE_ARM.lock() {
878- *m.entry(key).or_insert(0) += 1;
879- }
880-}
881-
882721 /// Prints and clears the [`note_subsize_arm`] table.
883722 pub fn dump_subsize_arm_scan() {
884723 let Ok(mut m) = SUBSIZE_ARM.lock() else {
@@ -901,23 +740,6 @@ pub(super) static SUBSIZE_GUARD: std::sync::LazyLock<
901740 std::sync::Mutex<std::collections::BTreeMap<(&'static str, usize, usize, bool), usize>>,
902741 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(Default::default()));
903742
904-fn note_subsize_guard(
905- site: &'static std::panic::Location<'static>,
906- bsize: (usize, usize),
907- part: usize,
908- codable: bool,
909-) {
910- let key = (
911- format!("{}:{}", site.file(), site.line()).leak() as &'static str,
912- bsize.0 * 256 + bsize.1,
913- part,
914- codable,
915- );
916- if let Ok(mut m) = SUBSIZE_GUARD.lock() {
917- *m.entry(key).or_insert(0) += 1;
918- }
919-}
920-
921743 /// Prints and clears the [`refuse_invalid_subsize`] table: one line per
922744 /// (site, block, partition value) with the times reached and whether the guard
923745 /// fired. `decode_probe` calls this at exit.
@@ -1064,52 +886,6 @@ pub(super) struct PlaneBuf<'a> {
1064886 pub(super) plane: u8,
1065887 }
1066888
1067-/// One entry per `MV_REFERENCE_FRAME` (index 0/1 unused -- `NONE`/
1068-/// `INTRA_FRAME`/`LAST_FRAME` all resolve elsewhere), `Some` when this
1069-/// frame's own `ref_frame_idx` names a DPB slot that has a picture in it
1070-/// (lane-av1refs: the same "empty slot" case `GOLDEN_FRAME` already
1071-/// refused by name, now generic across `LAST2`/`LAST3`/`GOLDEN`/`BWDREF`/
1072-/// `ALTREF2`/`ALTREF`).
1073-// lane-av1pixprobe: env-gated one-sample write probe -- `EC_AV1_PIXPROBE=x,y`
1074-// prints one PIXWRITE line per reconstruction store landing on that sample,
1075-// naming the store site, the value it replaces and the one it leaves. Re-anchored
1076-// from `lane-av1-ibcwrite` @ 25f5c729 onto the main-shape sites (the two mc stores
1077-// now live in `reconstruct_mc_rect`).
1078-pub(super) static PIXPROBE_ON: std::sync::LazyLock<bool> =
1079- std::sync::LazyLock::new(|| std::env::var_os("EC_AV1_PIXPROBE").is_some());
1080-
1081-pub(super) static PIXPROBE: std::sync::LazyLock<Option<(usize, usize)>> =
1082- std::sync::LazyLock::new(|| {
1083- crate::envflags::var("EC_AV1_PIXPROBE").ok().and_then(|v| {
1084- let (x, y) = v.split_once(',')?;
1085- Some((
1086- x.trim().parse::<usize>().ok()?,
1087- y.trim().parse::<usize>().ok()?,
1088- ))
1089- })
1090- });
1091-
1092-#[inline]
1093-// Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
1094-#[allow(clippy::too_many_arguments)]
1095-pub(super) fn pix_write(
1096- site: &str,
1097- bx: usize,
1098- by: usize,
1099- bside: usize,
1100- x: usize,
1101- y: usize,
1102- prev: u16,
1103- val: u16,
1104-) {
1105- if *PIXPROBE_ON && Some((x, y)) == *PIXPROBE {
1106- eprintln!(
1107- "PIXWRITE {site} block=({bx},{by})+{bside} px=({x},{y}) prev={prev} val={val} at {}",
1108- std::panic::Location::caller()
1109- );
1110- }
1111-}
1112-
1113889 impl PlaneBuf<'_> {
1114890 /// Sets this plane's own tile pixel origin ([`Self::tile_x0`]/
1115891 /// [`Self::tile_y0`]) before that tile's own superblock walk. `x0`/`y0`
@@ -1229,18 +1005,6 @@ impl PlaneBuf<'_> {
12291005 buf
12301006 } else {
12311007 let (above, left, corner) = self.edges_rect(x, y, bw, bh, reach);
1232- if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
1233- eprintln!(
1234- "EDGES x={x} y={y} bw={bw} bh={bh} mode={mode} above={:?} left_len={:?} left0={:?} corner={corner:?} tx0={} ty0={} truew={} trueh={}",
1235- above.as_ref().map(|a| (a.len(), a[0])),
1236- left.as_ref().map(|l| l.len()),
1237- left.as_ref().map(|l| l[0]),
1238- self.tile_x0,
1239- self.tile_y0,
1240- self.true_width,
1241- self.true_height
1242- );
1243- }
12441008 let mut prediction = vec![0u16; bw * bh];
12451009 if let Some(fi_mode) = filter_intra {
12461010 crate::intra::predict_filter_intra(
@@ -1273,25 +1037,7 @@ impl PlaneBuf<'_> {
12731037 };
12741038 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
12751039 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
1276- if crate::envflags::env_flag!("EC_PRED") {
1277- let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
1278- let row0: Vec<u16> = prediction[..bw.min(8)].to_vec();
1279- let col0: Vec<u16> = (0..bh.min(8)).map(|r| prediction[r * bw]).collect();
1280- eprintln!(
1281- "@{} OUR_PRED x={x} y={y} plane={} bw={bw} bh={bh} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
1282- std::panic::Location::caller(),
1283- recon_plane(),
1284- i32::from(smooth_neighbor)
1285- );
1286- }
12871040 let residual = dense_residual(residual, bw * bh);
1288- if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
1289- let res0: Vec<i32> = residual[..bw.min(8)].to_vec();
1290- let pred0: Vec<u16> = prediction[..bw.min(8)].to_vec();
1291- eprintln!(
1292- "DBG192 rect x={x} y={y} bw={bw} bh={bh} mode={mode} pred0={pred0:?} res0={res0:?}"
1293- );
1294- }
12951041 for row in 0..bh {
12961042 // Same bottom/right frame-edge clip as [`Self::reconstruct`]'s
12971043 // (lane-sb128c r8) -- a 64x128 block at the right edge of a frame
@@ -1312,16 +1058,6 @@ impl PlaneBuf<'_> {
13121058 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));
13131059 }
13141060 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
1315- pix_write(
1316- "reconstruct_rect",
1317- x,
1318- y,
1319- bw,
1320- x + col,
1321- y + row,
1322- self.data[(y + row) * self.width + x + col],
1323- sample,
1324- );
13251061 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
13261062 }
13271063 }
@@ -1329,15 +1065,6 @@ impl PlaneBuf<'_> {
13291065 // -- a block whose prediction matches the oracle's but whose written
13301066 // samples do not is either a residual defect or a later overwrite, and
13311067 // only this print separates the two.
1332- if crate::envflags::env_flag!("EC_PRED") {
1333- let row0: Vec<u16> = (0..bw.min(8))
1334- .map(|c| self.data[y * self.width + x + c])
1335- .collect();
1336- let col0: Vec<u16> = (0..bh.min(8))
1337- .map(|r| self.data[(y + r) * self.width + x])
1338- .collect();
1339- eprintln!("OUR_RECON x={x} y={y} bw={bw} bh={bh} row0={row0:?} col0={col0:?}");
1340- }
13411068 }
13421069
13431070 /// Predicts under `mode` then adds `residual` (side*side, raster),
@@ -1384,13 +1111,6 @@ impl PlaneBuf<'_> {
13841111 buf
13851112 } else {
13861113 let (above, left, corner) = self.edges(x, y, side, reach);
1387- if crate::envflags::env_flag!("EC_DEBUG_EDGES") {
1388- eprintln!(
1389- "EDGES_SQ x={x} y={y} side={side} mode={mode} above={:?} left={:?} corner={corner:?}",
1390- above.as_deref(),
1391- left.as_deref(),
1392- );
1393- }
13941114 let mut prediction = vec![0u16; side * side];
13951115 if let Some(fi_mode) = filter_intra {
13961116 crate::intra::predict_filter_intra(
@@ -1430,26 +1150,7 @@ impl PlaneBuf<'_> {
14301150 };
14311151 // lane-hgkf r2: per-TU prediction trace, the twin of aomdec's
14321152 // EC_PRED/EC_PREDND rungs (x/y are this plane's pixel origin).
1433- if crate::envflags::env_flag!("EC_PRED") {
1434- let sum: i64 = prediction.iter().map(|&v| i64::from(v)).sum();
1435- let row0: Vec<u16> = prediction[..side.min(8)].to_vec();
1436- let col0: Vec<u16> = (0..side.min(8)).map(|r| prediction[r * side]).collect();
1437- eprintln!(
1438- "@{} OUR_PRED x={x} y={y} plane={} side={side} side={side} mode={mode} ad={angle_delta} ft={} sum={sum} row0={row0:?} col0={col0:?}",
1439- std::panic::Location::caller(),
1440- recon_plane(),
1441- i32::from(smooth_neighbor)
1442- );
1443- }
14441153 let residual = dense_residual(residual, side * side);
1445- if crate::envflags::env_flag!("EC_DBG192") && y == 168 && (x == 224 || x == 232) {
1446- let res0: Vec<i32> = residual[..side.min(8)].to_vec();
1447- let pred0: Vec<u16> = prediction[..side.min(8)].to_vec();
1448- eprintln!(
1449- "DBG192 sq x={x} y={y} side={side} mode={mode} cfl={} pred0={pred0:?} res0={res0:?}",
1450- cfl.is_some()
1451- );
1452- }
14531154 for row in 0..side {
14541155 // lane-sb128c r8: libaom's frame buffer is superblock
14551156 // aligned; ours is padded to 32 (`block_grid`), so a 64x64
@@ -1475,16 +1176,6 @@ impl PlaneBuf<'_> {
14751176 base = (base + cfl_scaled(alpha_q3, ac)).clamp(0, sample_max(fctx));
14761177 }
14771178 let sample = (base + residual[idx]).clamp(0, sample_max(fctx)) as u16;
1478- pix_write(
1479- "reconstruct",
1480- x,
1481- y,
1482- side,
1483- x + col,
1484- y + row,
1485- self.data[(y + row) * self.width + x + col],
1486- sample,
1487- );
14881179 self.data.to_mut()[(y + row) * self.width + x + col] = sample;
14891180 }
14901181 }
@@ -1501,9 +1192,6 @@ pub(super) fn read_plane(
15011192 scan: &[u16],
15021193 plane_idx: usize,
15031194 around: (bool, bool, i32),
1504- // The block's own luma mode — [`crate::tile::write_block_planes`] passes
1505- // it for every plane's `txb` lookup (it is what an intra transform type's
1506- // CDF is indexed by, spec 9.3), never the plane's own predicted mode.
15071195 tx_mode: usize,
15081196 predict_mode: usize,
15091197 angle_delta: i32,
@@ -1515,17 +1203,9 @@ pub(super) fn read_plane(
15151203 cy: usize,
15161204 side: usize,
15171205 tx_side: usize,
1518- base_q_idx: u8,
15191206 cfl: Option<(i32, CflSrc)>,
15201207 filter_intra: Option<usize>,
1521- // Only meaningful for `plane_idx == 0`: `Some` when this transform unit is
1522- // smaller than its own block (spec `get_txb_ctx_general`'s
1523- // `plane_bsize != tx_size` branch), carrying the already-looked-up
1524- // `SKIP_CONTEXTS` value; `None` everywhere else (a lone luma TU, or any
1525- // chroma plane), where `txb_skip_ctx` is 0 or the usual OR-of-neighbours
1526- // formula below.
15271208 luma_skip_ctx: Option<usize>,
1528- // See [`PlaneBuf::reconstruct`]'s own doc: caller's neighbour-smooth check.
15291209 smooth_neighbor: bool,
15301210 fctx: &crate::decode::FrameCtx,
15311211 ) -> Result<Grid> {
@@ -1562,12 +1242,6 @@ pub(super) fn read_plane(
15621242 // labelling its unit `plane=0`, and a sweep reading a second-luma-unit
15631243 // phantom out of that label (class `rung-mislabels-plane`). Diagnostic
15641244 // only: no gate asserts decode behaviour off this line.
1565- if crate::envflags::env_flag!("EC_TRACE_MODE") {
1566- eprintln!(
1567- "OUR_MODE plane={plane_idx} x={x} y={cy} side={side} mode={predict_mode} \
1568- ad={angle_delta} fi={filter_intra:?} reach={reach:?}"
1569- );
1570- }
15711245 let tx_mode = if plane_idx == 0 {
15721246 fi_tx_row(tx_mode, filter_intra)
15731247 } else {
@@ -1642,7 +1316,6 @@ pub(super) fn read_plane(
16421316 default_tx_type,
16431317 None,
16441318 )?;
1645- note_chroma_class1(plane_idx, tx_type);
16461319 if plane_idx == 0 {
16471320 fctx.luma_tx_type.with(|c| c.set(tx_type));
16481321 }
@@ -1669,13 +1342,6 @@ pub(super) fn read_plane(
16691342 stride: 0,
16701343 lossless: lossless(fctx),
16711344 };
1672- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1673- let residual = tx.run(&levels);
1674- eprintln!(
1675- "TRACE dequant plane={plane_idx} base_q_idx={base_q_idx} tx_type={tx_type:?} side={side} levels={:?} residual={residual:?}",
1676- &*levels,
1677- );
1678- }
16791345 push_intra_tx(
16801346 y,
16811347 u,
@@ -1842,7 +1508,6 @@ pub(super) fn read_rect_chroma_unit(
18421508 usize::from(around.0) + usize::from(around.1) + chroma_skip_offset.unwrap_or(0),
18431509 dc_sign_ctx(around.2),
18441510 default_tx,
1845- plane_idx,
18461511 )?;
18471512 let residual = dequant_and_inverse_typed_wh(
18481513 &levels,
@@ -1912,7 +1577,6 @@ pub(super) fn decode_block(
19121577 let (palette_ctx, palette_cache) = neighbours.palette_ctx_and_cache(at);
19131578 let palette_uv_cache = neighbours.palette_uv_cache(at);
19141579 let (nb_above_mode, nb_left_mode) = neighbours.modes_above_left(r, c);
1915- let at_tile_left = c == neighbours.tile_col0_mi / (SUB / MI);
19161580 let (
19171581 skip,
19181582 mode,
@@ -2010,12 +1674,6 @@ pub(super) fn decode_block(
20101674 let smooth_neighbor = is_smooth_mode(nb_above_mode) || is_smooth_mode(nb_left_mode);
20111675 let smooth_neighbor_uv =
20121676 neighbours.smooth_uv_neighbour(r * (SUB / MI), c * (SUB / MI), r, c, fctx);
2013- if crate::envflags::env_flag!("EC_AV1_TRACE") {
2014- eprintln!(
2015- "TRACE block px={px} py={py} side={side} mode={mode} uv_mode={uv_mode} \
2016- angle_delta_uv={angle_delta_uv}"
2017- );
2018- }
20191677 let (mi_r, mi_c) = (r * (SUB / MI), c * (SUB / MI));
20201678 // `TxMode::Select`'s `tx_depth` (spec 5.11.16): read for every intra
20211679 // block, skipped or not. `logical_tx` is what the loop filter's edge
@@ -2085,14 +1743,7 @@ pub(super) fn decode_block(
20851743 .iter()
20861744 .all(|l| (l.2, l.3) == (f.2, f.3) && l.2 == l.3)
20871745 });
2088- if !uniform {
2089- if crate::envflags::env_flag!("EC_AV1_IBCVTX_DEBUG") {
2090- eprintln!(
2091- "IBCVTX mixed intrabc tree mi=({mi_r},{mi_c}) side={side} \
2092- dv={intrabc_dv:?} leaves={leaves:?}"
2093- );
2094- }
2095- }
1746+ if !uniform {}
20961747 Some(leaves)
20971748 } else {
20981749 None
@@ -2280,11 +1931,6 @@ pub(super) fn decode_block(
22801931 tu_row * logical_tx,
22811932 logical_tx,
22821933 reach,
2283- px,
2284- py,
2285- y.width,
2286- y.height,
2287- fctx,
22881934 );
22891935 push_intra(
22901936 y,
@@ -2349,11 +1995,6 @@ pub(super) fn decode_block(
23491995 luma_span_x,
23501996 luma_span_y,
23511997 reach,
2352- px,
2353- py,
2354- y.width,
2355- y.height,
2356- fctx,
23571998 )
23581999 };
23592000 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
@@ -2451,14 +2092,6 @@ pub(super) fn decode_block(
24512092 // side`, so only 4:2:2 changes.
24522093 let u_grid = vec![0i32; chroma_side * chroma_height];
24532094 let v_grid = vec![0i32; chroma_side * chroma_height];
2454- // The measured arm, not a proxy: how many samples this block's
2455- // chroma bookkeeping grid is SHORT of its own plane block. The
2456- // square form this lane removed is `chroma_side * chroma_side`,
2457- // which at 4:2:2 is half the plane block; restoring it makes this
2458- // non-zero on every 4:2:2 skip block, and the witness gate asserts
2459- // the total stayed 0.
2460- let plane_block = chroma_side * chroma_height;
2461- let short = plane_block.saturating_sub(u_grid.len());
24622095 neighbours.record(
24632096 at,
24642097 side,
@@ -2494,7 +2127,6 @@ pub(super) fn decode_block(
24942127 py,
24952128 side,
24962129 coeff_tx_side,
2497- base_q_idx,
24982130 None,
24992131 filter_intra,
25002132 None,
@@ -2547,19 +2179,12 @@ pub(super) fn decode_block(
25472179 cpy,
25482180 chroma_side,
25492181 chroma_tx,
2550- base_q_idx,
25512182 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
25522183 None,
25532184 None,
25542185 smooth_neighbor_uv,
25552186 fctx,
25562187 )?;
2557- if crate::envflags::env_flag!("EC_AV1_TRACE") {
2558- eprintln!(
2559- "TRACE u-write cpx={cpx} cpy={cpy} chroma_side={chroma_side} row0={:?}",
2560- &u.data[cpy * u.width + cpx..][..chroma_side]
2561- );
2562- }
25632188 if let Some((_, vb)) = &palette_uv_bufs {
25642189 set_palette_pred(vb.clone(), fctx);
25652190 }
@@ -2581,7 +2206,6 @@ pub(super) fn decode_block(
25812206 cpy,
25822207 chroma_side,
25832208 chroma_tx,
2584- base_q_idx,
25852209 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
25862210 None,
25872211 None,
@@ -2679,11 +2303,6 @@ pub(super) fn decode_block(
26792303 luma_span_x,
26802304 luma_span_y,
26812305 reach,
2682- px,
2683- py,
2684- y.width,
2685- y.height,
2686- fctx,
26872306 );
26882307 let (cu_x, cu_y) = (cpx + cu_col * chroma_tx, cpy + cu_row * chroma_tx_h);
26892308 if let Some((ub, vb)) = &palette_uv_bufs {
@@ -2718,7 +2337,6 @@ pub(super) fn decode_block(
27182337 cu_y,
27192338 chroma_tx,
27202339 chroma_tx,
2721- base_q_idx,
27222340 alpha
27232341 .zip(ac)
27242342 .map(|((au, av), ac)| (if plane_pass == 1 { au } else { av }, ac)),
@@ -2852,10 +2470,7 @@ pub(super) fn decode_block(
28522470 // top-right 8x8 unit of a 16x16 D203 block bottom-left
28532471 // pixels libaom refuses outright (`col_off > 0`), which is
28542472 // the diagonal wedge seed 46 reconstructed wrong.
2855- let tu_reach = tu_reach(
2856- side, side, tu_off_x, tu_off_y, tu_tx, reach, px, py, y.width, y.height,
2857- fctx,
2858- );
2473+ let tu_reach = tu_reach(side, side, tu_off_x, tu_off_y, tu_tx, reach);
28592474 // This transform unit's own bsize (`tu_tx`) is smaller
28602475 // than the block it sits in (`side`), so `txb_skip_ctx` is
28612476 // the neighbour-magnitude table, not the lone-TU 0 (spec
@@ -2905,26 +2520,13 @@ pub(super) fn decode_block(
29052520 tu_px,
29062521 tu_py,
29072522 tu_tx,
2908- // The unit's own COEFFICIENT grid, half its side at
2909- // TX_64X64 (a 64-point transform codes nothing past 32);
2910- // identical to `tu_tx` at every smaller size
2911- // (lane-sb128b r1).
29122523 if tu_tx == 64 { 32 } else { tu_tx },
2913- base_q_idx,
29142524 None,
29152525 filter_intra,
29162526 Some(tu_skip_ctx),
29172527 smooth_neighbor,
29182528 fctx,
29192529 )?;
2920- if crate::envflags::env_flag!("EC_AV1_TRACE") {
2921- eprintln!(
2922- "TRACE tu_bitpos mi=({},{}) tell={}",
2923- tu_mi.0,
2924- tu_mi.1,
2925- dec.debug_bitpos()
2926- );
2927- }
29282530 neighbours.record_mi_luma(tu_mi, tu_tx, &tu_grid);
29292531 if first_leaf_tx.is_none() {
29302532 first_leaf_tx = Some(fctx.luma_tx_type.with(std::cell::Cell::get));
@@ -3036,11 +2638,6 @@ pub(super) fn decode_block(
30362638 luma_span_x,
30372639 luma_span_y,
30382640 reach,
3039- px,
3040- py,
3041- y.width,
3042- y.height,
3043- fctx,
30442641 )
30452642 };
30462643 let (cu_x, cu_y) =
@@ -3078,7 +2675,6 @@ pub(super) fn decode_block(
30782675 cu_y,
30792676 chroma_tx,
30802677 chroma_tx,
3081- base_q_idx,
30822678 alpha.zip(ac).map(|((au, av), ac)| {
30832679 (if plane_pass == 1 { au } else { av }, ac)
30842680 }),
crates/ec-av1/src/decode/coeffs.rsmodified+74 -541
@@ -2,70 +2,6 @@
22
33 use super::*;
44
5-/// lane-coefread: the per-coefficient trace sites, one `#[cold]` call each.
6-/// `eprintln!` builds its `fmt::Arguments` on the stack AT THE CALL SITE, so
7-/// nine of them inside the base/sign loops pinned nine sets of values in the
8-/// hot loop's frame (the annotated profile was full of `mov ...(%rsp)` spill
9-/// traffic). Out of line, the loop keeps its values in registers and the
10-/// trace output is character-for-character what it was.
11-#[cold]
12-#[inline(never)]
13-fn trace_base_eob(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
14- eprintln!(
15- "TRACE base_eob scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}"
16- );
17-}
18-
19-#[cold]
20-#[inline(never)]
21-fn trace_base(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, v: i32) {
22- eprintln!("TRACE base scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={v}");
23-}
24-
25-#[cold]
26-#[inline(never)]
27-fn trace_br(scan_idx: usize, pos: usize, row: usize, col: usize, ctx: usize, k: i32) {
28- eprintln!("TRACE br scan_idx={scan_idx} pos={pos} row={row} col={col} ctx={ctx} value={k}");
29-}
30-
31-#[cold]
32-#[inline(never)]
33-fn coeff_step_base(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, v: i32) {
34- let (rng, _) = dec.debug_state();
35- eprintln!("EC_COEFF_STEP tag=base c={scan_idx} pos={apos} ctx={ctx} level={v} rng={rng}");
36-}
37-
38-#[cold]
39-#[inline(never)]
40-fn coeff_step_br(dec: &SymbolDecoder, scan_idx: usize, apos: usize, ctx: usize, k: i32) {
41- let (rng, _) = dec.debug_state();
42- eprintln!("EC_COEFF_STEP tag=br c={scan_idx} pos={apos} ctx={ctx} k={k} rng={rng}");
43-}
44-
45-#[cold]
46-#[inline(never)]
47-fn coeff_step_sign(dec: &SymbolDecoder, c: usize, negative: bool) {
48- let (rng, _) = dec.debug_state();
49- eprintln!(
50- "EC_COEFF_STEP tag=sign c={c} sign={} rng={rng}",
51- negative as i32
52- );
53-}
54-
55-#[cold]
56-#[inline(never)]
57-fn coeff_step_post_golomb(dec: &SymbolDecoder, c: usize, level: i32) {
58- let (rng, _) = dec.debug_state();
59- eprintln!("EC_COEFF_STEP tag=post_golomb c={c} level={level} rng={rng}");
60-}
61-
62-#[cold]
63-#[inline(never)]
64-fn coeff_step_base_eob_level(dec: &SymbolDecoder, level: i32) {
65- let (rng, _) = dec.debug_state();
66- eprintln!("EC_COEFF_STEP tag=base_eob level={level} rng={rng}");
67-}
68-
695 // lane-ibc444c: see `read_coeffs_rect`'s `#[track_caller]`.
706 #[track_caller]
717 pub(super) fn read_coeffs(
@@ -88,65 +24,11 @@ pub(super) fn read_coeffs(
8824 // caller's block genuinely is `side` x `side`.
8925 rect_shape: Option<(usize, usize)>,
9026 ) -> Result<(Grid, TxType)> {
91- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
9227 let side = coding.side;
93- let (census_w, census_h) = rect_shape.unwrap_or((side, side));
94- if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
95- let (range, value) = dec.debug_state();
96- eprintln!("EC_AV1_STATE_BEFORE_TXBSKIP range={range} value={value}");
97- }
98- if crate::envflags::env_flag!("EC_ECDUMP_IN") {
99- let (range, value) = dec.debug_state();
100- let bit = dec.debug_bitpos();
101- eprintln!(
102- "EC_ECDUMP_IN side={side} ctx={skip_ctx} dcctx={sign_ctx} ECIN=({value},{range},{bit})"
103- );
104- }
105- let dbg_txbskip = if coeff_trace_on() {
106- coding.txb_skip[skip_ctx]
107- } else {
108- [0; 3]
109- };
110- let sq_bit = if coeff_trace_on() {
111- dec.debug_bitpos()
112- } else {
113- 0
114- };
11528 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
11629 // lane-ibc444c: this reader logs an `all_zero` step even for a read that
11730 // consumes ZERO bits, so `post_bit == bit` means "no symbol was read" --
11831 // filter on it before pairing anything against the oracle.
119- if crate::envflags::env_flag!("EC_IBCTX") {
120- eprintln!(
121- "EC_IBCTX2 side={} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={sq_bit} at {}",
122- coding.side,
123- std::panic::Location::caller(),
124- );
125- }
126- if coeff_trace_on() {
127- let (rng, _) = dec.debug_state();
128- eprintln!(
129- "EC_COEFF_STEP tag=all_zero side={} ctx={skip_ctx} dcctx={sign_ctx} cdf={dbg_txbskip:?} all_zero={} rng={rng} bit={sq_bit} post_bit={}",
130- coding.side,
131- all_zero as i32,
132- dec.debug_bitpos()
133- );
134- }
135- if crate::envflags::env_flag!("EC_AV1_TELL") {
136- eprintln!(
137- "TELL label=post_txb_skip ctx={skip_ctx} all_zero={} tell={} range={}",
138- all_zero as u8,
139- dec.debug_bitpos(),
140- dec.debug_state().0
141- );
142- }
143- if trace {
144- eprintln!("TRACE all_zero ctx={skip_ctx} value={}", all_zero as i32);
145- }
146- if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
147- let (range, value) = dec.debug_state();
148- eprintln!("EC_AV1_STATE_AFTER_TXBSKIP range={range} value={value}");
149- }
15032 if all_zero {
15133 return Ok((Grid::Zero(side * side), TxType::DctDct));
15234 }
@@ -162,22 +44,7 @@ pub(super) fn read_coeffs(
16244 // share their symbol order with (`Tx_Type_Inter_Inv_Set3`'s two
16345 // members are a prefix of `Tx_Type_Intra_Inv_Set2`'s five).
16446 let len = tx_type_cdf.len();
165- if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") && len == 3 {
166- eprintln!("EC_AV1_TXTYPE32_CDF {tx_type_cdf:?}");
167- }
168- crate::msac::SymbolDecoder::set_symr_cdf("tx_type");
16947 let t = dec.symbol(tx_type_cdf);
170- if coeff_trace_on() {
171- let (rng, _) = dec.debug_state();
172- eprintln!("EC_COEFF_STEP tag=tx_type len={len} rng={rng}");
173- }
174- if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
175- let (range, value) = dec.debug_state();
176- eprintln!("EC_AV1_STATE_AFTER_TXTYPE range={range} value={value}");
177- }
178- if trace {
179- eprintln!("TRACE tx_type value={t} len={len}");
180- }
18148 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
18249 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
18350 })?;
@@ -185,19 +52,6 @@ pub(super) fn read_coeffs(
18552
18653 let class = TxClass::of(tx_type);
18754 let eob = read_eob(dec, coding, class);
188- if trace {
189- eprintln!("TRACE eob value={eob}");
190- }
191- let ec_trace_coeff = coeff_trace_on();
192- if ec_trace_coeff {
193- let (rng, _) = dec.debug_state();
194- let cls = match class {
195- TxClass::TwoD => "2d",
196- TxClass::Horiz => "horiz",
197- TxClass::Vert => "vert",
198- };
199- eprintln!("EC_COEFF_STEP tag=eob eob={eob} tx={tx_type:?} class={cls} rng={rng}");
200- }
20155 let class_scan;
20256 let scan: &[u16] = if class == TxClass::TwoD {
20357 scan
@@ -238,9 +92,6 @@ pub(super) fn read_coeffs(
23892 let level = if scan_idx == eob - 1 {
23993 let ctx = eob_coeff_ctx(scan_idx, side * side);
24094 let v = dec.symbol(&mut coding.base_eob[ctx]) as i32 + 1;
241- if trace {
242- trace_base_eob(scan_idx, pos, row, col, ctx, v);
243- }
24495 v
24596 } else {
24697 let ctx = if class == TxClass::TwoD && rect_shape.is_none() {
@@ -254,14 +105,6 @@ pub(super) fn read_coeffs(
254105 base_ctx(levels, stride, row, col, class, rect_shape)
255106 };
256107 let v = dec.symbol(&mut coding.base[ctx]) as i32;
257- if ec_trace_coeff {
258- // `pos` in libaom's column-major `coeff_idx` convention, so
259- // the ladder lines up with instrumented `aomdec`.
260- coeff_step_base(dec, scan_idx, col * side + row, ctx, v);
261- }
262- if trace {
263- trace_base(scan_idx, pos, row, col, ctx, v);
264- }
265108 v
266109 };
267110 let level = if level > NUM_BASE_LEVELS {
@@ -282,16 +125,6 @@ pub(super) fn read_coeffs(
282125 let mut sent = 0;
283126 loop {
284127 let k = dec.symbol(&mut coding.br[ctx]) as i32;
285- if ec_trace_coeff {
286- // lane-leaf8tx r3: the `br` rung was missing from THIS
287- // path's trace, so the cross-decoder range ladder was
288- // blind to every base-range symbol and mis-reported the
289- // first divergence (class [[gate-blind-to-feature]]).
290- coeff_step_br(dec, scan_idx, col * side + row, ctx, k);
291- }
292- if trace {
293- trace_br(scan_idx, pos, row, col, ctx, k);
294- }
295128 level += k;
296129 sent += BR_STEP;
297130 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
@@ -302,9 +135,6 @@ pub(super) fn read_coeffs(
302135 } else {
303136 level
304137 };
305- if ec_trace_coeff && scan_idx == eob - 1 {
306- coeff_step_base_eob_level(dec, level);
307- }
308138 // Every coded level here is a magnitude in `0..=15` (base <= 3 plus
309139 // at most `COEFF_BASE_RANGE` from the `br` loop; the Golomb tail is
310140 // added in the sign pass below, straight into `grid`), so the context
@@ -317,10 +147,6 @@ pub(super) fn read_coeffs(
317147 nz_n += 1;
318148 }
319149 }
320- if ec_trace_coeff {
321- let (rng, _) = dec.debug_state();
322- eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
323- }
324150
325151 for &packed in nz_buf[..nz_n].iter().rev() {
326152 let c = (packed >> 4) as usize;
@@ -328,28 +154,16 @@ pub(super) fn read_coeffs(
328154 let level = (packed & 15) as i32;
329155 let negative = if pos == 0 {
330156 let v = dec.symbol(&mut coding.dc_sign[sign_ctx]) == 1;
331- if trace {
332- eprintln!("TRACE dc_sign ctx={sign_ctx} value={}", v as i32);
333- }
334157 v
335158 } else {
336159 dec.literal(1) == 1
337160 };
338- if ec_trace_coeff {
339- coeff_step_sign(dec, c, negative);
340- }
341161 let level = if level > MAX_BR_LEVEL {
342162 let g = read_golomb(dec)?;
343- if trace {
344- eprintln!("TRACE golomb pos={pos} value={g}");
345- }
346163 level + g as i32
347164 } else {
348165 level
349166 };
350- if ec_trace_coeff {
351- coeff_step_post_golomb(dec, c, level);
352- }
353167 grid[pos] = if negative { -level } else { level };
354168 }
355169 Ok((Grid::Own(grid), tx_type))
@@ -379,38 +193,8 @@ pub(super) fn read_coeffs_rect(
379193 skip_ctx: usize,
380194 sign_ctx: usize,
381195 default_tx_type: TxType,
382- // lane-av1chrtx: the plane this unit belongs to (0 luma, 1 U, 2 V) --
383- // printed by the two `EC_COEFF_STEP` traces below, which hardcoded
384- // `plane=0` and so mis-attributed a CHROMA read as a luma one in two
385- // independent lane reports.
386- plane: usize,
387196 ) -> Result<(Grid, TxType)> {
388- let rect_trace = coeff_trace_on();
389- let ibctx_on = crate::envflags::env_flag!("EC_IBCTX");
390- let entry_bit = if ibctx_on { dec.debug_bitpos() } else { 0 };
391- let entry_rng = dec.debug_state().0;
392197 let all_zero = dec.symbol(&mut coding.txb_skip[skip_ctx]) == 1;
393- if rect_trace {
394- eprintln!(
395- "EC_COEFF_STEP tag=all_zero plane={plane} ctx={skip_ctx} entry={entry_rng} all_zero={} rng={} bit={entry_bit} post_bit={}",
396- all_zero as i32,
397- dec.debug_state().0,
398- dec.debug_bitpos()
399- );
400- }
401- if ibctx_on {
402- // lane-ibc444c. `bit`/`post_bit` are the STREAM POSITION, not the coder
403- // range: the only collision-free key for pairing this unit against the
404- // oracle's `EC_ECDUMP_IN`. And `post_bit != bit` is how a caller tells
405- // a real symbol read from a 0-bit one -- the SQUARE reader logs a step
406- // either way, which is exactly the artifact that made an earlier
407- // round of this lane claim a false exactness.
408- eprintln!(
409- "EC_IBCTX w={w} h={h} skip_ctx={skip_ctx} sign_ctx={sign_ctx} bit={entry_bit} post_bit={} at {}",
410- dec.debug_bitpos(),
411- std::panic::Location::caller(),
412- );
413- }
414198 if all_zero {
415199 return Ok((Grid::Zero(w * h), TxType::DctDct));
416200 }
@@ -428,21 +212,9 @@ pub(super) fn read_coeffs_rect(
428212 tx_type = tx_type_from_symbol(len, t).ok_or_else(|| {
429213 unsupported(format!("a tx_type symbol outside its CDF's own set: {t}"))
430214 })?;
431- if rect_trace {
432- eprintln!(
433- "EC_COEFF_STEP tag=tx_type plane={plane} rng={}",
434- dec.debug_state().0
435- );
436- }
437215 }
438216 let class = TxClass::of(tx_type);
439217 let eob = read_eob(dec, coding, class);
440- if rect_trace {
441- eprintln!(
442- "EC_COEFF_STEP tag=eob eob={eob} rng={}",
443- dec.debug_state().0
444- );
445- }
446218 let class_scan;
447219 let scan: &[u16] = if class == TxClass::TwoD {
448220 scan
@@ -514,12 +286,6 @@ pub(super) fn read_coeffs_rect(
514286 base_ctx_rect(levels, stride, w, h, row, col, class)
515287 };
516288 let v = dec.symbol(&mut coding.base[ctx]) as i32;
517- if rect_trace {
518- eprintln!(
519- "EC_COEFF_STEP tag=base c={scan_idx} pos={pos} ctx={ctx} level={v} rng={}",
520- dec.debug_state().0
521- );
522- }
523289 v
524290 };
525291 let level = if level > NUM_BASE_LEVELS {
@@ -540,12 +306,6 @@ pub(super) fn read_coeffs_rect(
540306 let mut sent = 0;
541307 loop {
542308 let k = dec.symbol(&mut coding.br[ctx]) as i32;
543- if rect_trace {
544- eprintln!(
545- "EC_COEFF_STEP tag=br c={scan_idx} pos={pos} ctx={ctx} k={k} rng={}",
546- dec.debug_state().0
547- );
548- }
549309 level += k;
550310 sent += BR_STEP;
551311 if k < BR_STEP || sent >= COEFF_BASE_RANGE {
@@ -562,19 +322,6 @@ pub(super) fn read_coeffs_rect(
562322 nz_buf[nz_n] = ((scan_idx as u16) << 4) | level as u16;
563323 nz_n += 1;
564324 }
565- if rect_trace && scan_idx == eob - 1 {
566- // the oracle's `tag=base_eob`: POST-br level, POST-br rng, with the
567- // same `get_lower_levels_ctx_eob` ctx (the same `eob_coeff_ctx`).
568- let ctx = eob_coeff_ctx(scan_idx, w * h);
569- let (rng, _) = dec.debug_state();
570- eprintln!(
571- "EC_COEFF_STEP tag=base_eob c={scan_idx} pos={pos} ctx={ctx} level={level} rng={rng}"
572- );
573- }
574- }
575- if rect_trace {
576- let (rng, _) = dec.debug_state();
577- eprintln!("EC_COEFF_STEP tag=after_bases rng={rng}");
578325 }
579326 for &packed in nz_buf[..nz_n].iter().rev() {
580327 let pos = scan[(packed >> 4) as usize] as usize;
@@ -584,51 +331,18 @@ pub(super) fn read_coeffs_rect(
584331 } else {
585332 dec.literal(1) == 1
586333 };
587- if rect_trace {
588- let (rng, _) = dec.debug_state();
589- eprintln!(
590- "EC_COEFF_STEP tag=sign_rect pos={pos} sign={} dcctx={sign_ctx} rng={rng}",
591- u8::from(negative)
592- );
593- }
594334 let level = if level > MAX_BR_LEVEL {
595335 let g = read_golomb(dec)?;
596336 level + g as i32
597337 } else {
598338 level
599339 };
600- if rect_trace {
601- // lane-av1oddheightfork2: the twin of the square reader's
602- // `coeff_step_post_golomb`. The oracle's `EC_COEFF_STEP
603- // tag=post_golomb` (decodetxb.c, after read_golomb) fires for a RECT
604- // unit exactly as it does for a square one, but this reader had no
605- // rung for it, so every rect unit's ladder was one step short and
606- // the pairing had to guess whether a golomb had been read. This
607- // rung reads no bits: it prints the state after the read it labels.
608- let (rng, _) = dec.debug_state();
609- eprintln!(
610- "EC_COEFF_STEP tag=post_golomb c={} pos={pos} level={level} rng={rng}",
611- (packed >> 4)
612- );
613- }
614340 grid[pos] = if negative { -level } else { level };
615341 }
616342 // lane-d792: the rect unit's LEVEL grid in row-major (w) order, the
617343 // twin of the oracle's `EC_DQCOEFF` rung -- a residual mismatch whose
618344 // grids differ is a reader defect, one whose grids agree is a transform
619345 // defect.
620- if crate::envflags::env_flag!("EC_DQCOEFF") {
621- let nz: Vec<String> = grid
622- .iter()
623- .enumerate()
624- .filter(|&(_, &v)| v != 0)
625- .map(|(i, &v)| format!("{}/{}:{v}", i / w, i % w))
626- .collect();
627- eprintln!(
628- "OUR_LEVELS w={w} h={h} eob={eob} tx={tx_type:?} nz={}",
629- nz.join(",")
630- );
631- }
632346 Ok((Grid::Own(grid), tx_type))
633347 }
634348
@@ -660,25 +374,11 @@ pub(super) fn read_chroma_coeffs_rect(
660374 sign_ctx: usize,
661375 default_tx_type: TxType,
662376 fctx: &crate::decode::FrameCtx,
663- // lane-av1chrtx: the plane index, threaded to `read_coeffs_rect`'s
664- // `EC_COEFF_STEP` traces (they used to print a hardcoded `plane=0`, so a
665- // V-plane read was indistinguishable from a luma one in the log).
666- plane: usize,
667377 ) -> Result<(Grid, TxType)> {
668378 if mono(fctx) {
669379 return Ok((Grid::Zero(w * h), TxType::DctDct));
670380 }
671- read_coeffs_rect(
672- dec,
673- coding,
674- scan,
675- w,
676- h,
677- skip_ctx,
678- sign_ctx,
679- default_tx_type,
680- plane,
681- )
381+ read_coeffs_rect(dec, coding, scan, w, h, skip_ctx, sign_ctx, default_tx_type)
682382 }
683383
684384 /// What one coded block leaves behind for the blocks that read it as a
@@ -1175,7 +875,13 @@ impl Neighbours {
1175875 /// [`SUB`]-grid cell it covers on both the above and left edges --
1176876 /// mirrors [`Self::record_rect`]'s loop shape, square-only (this lane's
1177877 /// call sites are all square blocks).
1178- pub(super) fn record_palette_y(&mut self, at: (usize, usize), side: usize, size: usize, colors: [u16; 8]) {
878+ pub(super) fn record_palette_y(
879+ &mut self,
880+ at: (usize, usize),
881+ side: usize,
882+ size: usize,
883+ colors: [u16; 8],
884+ ) {
1179885 self.record_palette_y_rect(
1180886 (at.0 * (SUB / MI), at.1 * (SUB / MI)),
1181887 side,
@@ -1198,9 +904,6 @@ impl Neighbours {
1198904 colors: [u16; 8],
1199905 ) {
1200906 let (r, c) = mi;
1201- if crate::envflags::env_flag!("EC_PALPUB") {
1202- eprintln!("EC_PALPUB yrect mi={r},{c} bw={w} bh={h} y={size}");
1203- }
1204907 // lane-kf900 r6: mi (4px) granularity, libaom's own -- `palette_size`
1205908 // lives per mi cell in `MB_MODE_INFO`, and `xd->left_mbmi` is the mi
1206909 // cell immediately left of the block, not its 16px [`SUB`] cell. The
@@ -1575,11 +1278,6 @@ impl Neighbours {
15751278 // TX_32X32 -- independent of this block's luma `tx_depth`.
15761279 let uv_tx_w = ((w_mi * MI) >> ss_x(fctx)).clamp(4, 32) as u8;
15771280 let uv_tx_h = ((h_mi * MI) >> ss_y(fctx)).clamp(4, 32) as u8;
1578- if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
1579- eprintln!(
1580- "EC_LFGRID mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}"
1581- );
1582- }
15831281 let cur = fctx.current_delta_lf.with(|c| c.get());
15841282 let snapshot: [i8; 4] = if fctx.delta_lf_multi.with(|c| c.get()) {
15851283 std::array::from_fn(|i| cur[i].clamp(-63, 63) as i8)
@@ -1668,11 +1366,6 @@ impl Neighbours {
16681366 tx_h_px: u8,
16691367 ) {
16701368 let (mi_r, mi_c) = at_mi;
1671- if crate::envflags::env_flag!("EC_TXGRID_TRACE") {
1672- eprintln!(
1673- "EC_LFLEAF mi_row={mi_r} mi_col={mi_c} w_mi={w_mi} h_mi={h_mi} tx_px={tx_px} tx_h_px={tx_h_px}"
1674- );
1675- }
16761369 for rr in 0..h_mi {
16771370 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
16781371 fill_span(&mut self.tx_grid, start, w_mi, tx_px);
@@ -1689,7 +1382,13 @@ impl Neighbours {
16891382 }
16901383
16911384 /// [`Self::fill_skip_grid`] with independent row/col extents (lane-partitions r1).
1692- pub(super) fn fill_skip_grid_rect(&mut self, at_mi: (usize, usize), w_mi: usize, h_mi: usize, skip: bool) {
1385+ pub(super) fn fill_skip_grid_rect(
1386+ &mut self,
1387+ at_mi: (usize, usize),
1388+ w_mi: usize,
1389+ h_mi: usize,
1390+ skip: bool,
1391+ ) {
16931392 let (mi_r, mi_c) = at_mi;
16941393 for rr in 0..h_mi {
16951394 let start = (mi_r + rr) * self.skip_grid_cols_mi + mi_c;
@@ -1842,7 +1541,8 @@ impl Neighbours {
18421541 /// "no neighbour"). `ref_frame` is `-1` for an intra block, else the
18431542 /// `1..=7` reference it coded (lane-av1refs's `single_ref_p*_ctx` needs
18441543 /// the real value, not just `is_inter`).
1845- #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1544+ #[allow(dead_code)]
1545+ // read only from the `#[cfg(test)]` gates
18461546 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
18471547 #[allow(clippy::too_many_arguments)]
18481548 pub(super) fn record_inter(
@@ -2051,7 +1751,11 @@ impl Neighbours {
20511751
20521752 /// [`Self::around`] taking the block's position directly in 4x4 mode-info
20531753 /// units, for the same reason [`Self::record_mi`] does.
2054- pub(super) fn around_mi(&self, (mi_r, mi_c): (usize, usize), side: usize) -> [(bool, bool, i32); 3] {
1754+ pub(super) fn around_mi(
1755+ &self,
1756+ (mi_r, mi_c): (usize, usize),
1757+ side: usize,
1758+ ) -> [(bool, bool, i32); 3] {
20551759 let side_mi = side / MI;
20561760 // One pass over the cells accumulating all three planes, not one pass
20571761 // per plane: the three planes of a cell live in the same
@@ -2116,45 +1820,18 @@ impl Neighbours {
21161820 o.2 += dc_vote(left[plane].dc);
21171821 }
21181822 }
2119- if crate::envflags::env_flag!("EC_DCDUMP") {
2120- // lane-av1422mi24: same dump [`Self::around_mi_rect`] prints, so
2121- // a rerouted 4:2:2 chroma gather stays visible under EC_DCDUMP=1.
2122- // The above rows are the SAMPLED (every-second) cells.
2123- for (plane, o) in out.iter().enumerate() {
2124- let vote = o.2;
2125- let ab: Vec<String> = (0..above_mi)
2126- .step_by(2)
2127- .map(|k| {
2128- format!(
2129- "{:?}/{}",
2130- self.above[mi_c + k][plane].dc,
2131- self.above[mi_c + k][plane].level
2132- )
2133- })
2134- .collect();
2135- let lf: Vec<String> = (0..left_mi)
2136- .map(|k| {
2137- format!(
2138- "{:?}/{}",
2139- self.left[mi_r + k][plane].dc,
2140- self.left[mi_r + k][plane].level
2141- )
2142- })
2143- .collect();
2144- eprintln!(
2145- "EC_DCDUMP422 mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
2146- ab.join(","),
2147- lf.join(",")
2148- );
2149- }
2150- }
21511823 out
21521824 }
21531825
21541826 /// [`Self::around`] with independent above (`w`)/left (`h`) extents, in
21551827 /// pixels -- lane-rectwire, mirrors [`Self::record_rect`]'s asymmetric
21561828 /// extent pattern for a true rectangular strip's own coefficient context.
2157- pub(super) fn around_rect(&self, (r, c): (usize, usize), w: usize, h: usize) -> [(bool, bool, i32); 3] {
1829+ pub(super) fn around_rect(
1830+ &self,
1831+ (r, c): (usize, usize),
1832+ w: usize,
1833+ h: usize,
1834+ ) -> [(bool, bool, i32); 3] {
21581835 self.around_mi_rect((r * (SUB / MI), c * (SUB / MI)), w, h)
21591836 }
21601837
@@ -2185,34 +1862,6 @@ impl Neighbours {
21851862 o.2 += dc_vote(left[plane].dc);
21861863 }
21871864 }
2188- if crate::envflags::env_flag!("EC_DCDUMP") {
2189- for (plane, o) in out.iter().enumerate() {
2190- let vote = o.2;
2191- let ab: Vec<String> = (0..above_mi)
2192- .map(|k| {
2193- format!(
2194- "{:?}/{}",
2195- self.above[mi_c + k][plane].dc,
2196- self.above[mi_c + k][plane].level
2197- )
2198- })
2199- .collect();
2200- let lf: Vec<String> = (0..left_mi)
2201- .map(|k| {
2202- format!(
2203- "{:?}/{}",
2204- self.left[mi_r + k][plane].dc,
2205- self.left[mi_r + k][plane].level
2206- )
2207- })
2208- .collect();
2209- eprintln!(
2210- "EC_DCDUMP mi=({mi_r},{mi_c}) plane={plane} wh=({w},{h}) vote={vote} above=[{}] left=[{}]",
2211- ab.join(","),
2212- lf.join(",")
2213- );
2214- }
2215- }
22161865 out
22171866 }
22181867
@@ -2230,8 +1879,12 @@ impl Neighbours {
22301879 /// [`Self::luma_skip_ctx`] with the unit's own width and height in mi
22311880 /// units (lane-rectsplitx r1) -- `get_txb_ctx_general` ORs the above
22321881 /// context over `tx_size_wide` and the left one over `tx_size_high`.
2233- pub(super) fn luma_skip_ctx_rect(&self, (mi_r, mi_c): (usize, usize), w_mi: usize, h_mi: usize) -> usize {
2234- let side_mi = w_mi;
1882+ pub(super) fn luma_skip_ctx_rect(
1883+ &self,
1884+ (mi_r, mi_c): (usize, usize),
1885+ w_mi: usize,
1886+ h_mi: usize,
1887+ ) -> usize {
22351888 let above_mi = w_mi.min(self.mi_cols.saturating_sub(mi_c));
22361889 let left_mi = h_mi.min(self.mi_rows.saturating_sub(mi_r));
22371890 let mut top = 0u8;
@@ -2243,12 +1896,6 @@ impl Neighbours {
22431896 left |= self.left[mi_r + cell][0].level;
22441897 }
22451898 let ctx = SKIP_CONTEXTS[(top as usize).min(4)][(left as usize).min(4)];
2246- if crate::envflags::env_flag!("EC_AV1_TRACE") {
2247- eprintln!(
2248- "TRACE luma_skip_ctx mi=({mi_r},{mi_c}) side_mi={side_mi} top={top} left={left} ctx={ctx} band={:?}",
2249- self.left.iter().map(|e| e[0].level).collect::<Vec<_>>()
2250- );
2251- }
22521899 ctx
22531900 }
22541901
@@ -2283,7 +1930,14 @@ impl Neighbours {
22831930 /// block to the right reads via `mi(row, col-1)`). Only sub-8x8 leaves
22841931 /// read these back, and only when the recorded position is exactly their
22851932 /// own neighbour -- see [`Self::sub8_mode_col`]'s doc.
2286- pub(super) fn record_mode_mi(&mut self, mi_r: usize, mi_c: usize, mi_w: usize, mi_h: usize, mode: usize) {
1933+ pub(super) fn record_mode_mi(
1934+ &mut self,
1935+ mi_r: usize,
1936+ mi_c: usize,
1937+ mi_w: usize,
1938+ mi_h: usize,
1939+ mode: usize,
1940+ ) {
22871941 let (last_r, last_c) = ((mi_r + mi_h - 1) as u16, (mi_c + mi_w - 1) as u16);
22881942 let mode = mode as u8;
22891943 for cell in 0..mi_w {
@@ -2361,9 +2015,6 @@ impl Neighbours {
23612015 for row in mi_r..=last_r {
23622016 fill_span(&mut self.uv_owner, row * stride + mi_c, n, owner);
23632017 }
2364- if crate::envflags::env_flag!("EC_LEFTSSY") {
2365- eprintln!("EC_LEAF mi=({mi_r},{mi_c}) wh=({mi_w},{mi_h}) uv_mode={uv_mode}");
2366- }
23672018 }
23682019
23692020 /// Whether either mi-exact chroma neighbour of the block at `(mi_r, mi_c)`
@@ -2457,8 +2108,7 @@ impl Neighbours {
24572108 let have_left = mi_c > self.tile_col0_mi;
24582109 if self.tile_row0_mi > 0 && !have_above && self.above_uv_mode[c] != DC_PRED
24592110 || self.tile_col0_mi > 0 && !have_left && self.left_uv_mode[r] != DC_PRED
2460- {
2461- }
2111+ {}
24622112 // The mi grid is libaom's own read; the two maps below stay as the
24632113 // fallback for cells no block has written (see [`Self::uv_mode_grid`]).
24642114 let cell = |grid: &Vec<u8>, row: usize, col: usize| -> Option<usize> {
@@ -2550,7 +2200,6 @@ impl Neighbours {
25502200 // The pre-lane read, kept as the counter's own-row arm: it is what
25512201 // this decoder answered before the `+ss_y` term landed, and
25522202 // comparing against it is what proves the term is load-bearing.
2553- let own_row = read_left(mi_r);
25542203 // lane-av1leftwit: the geometry the `+ss_y` term needs. The two
25552204 // cells are one left mi column apart, so they are two different
25562205 // blocks exactly when the left neighbour is 1 mi tall or shorter.
@@ -2567,19 +2216,7 @@ impl Neighbours {
25672216 .copied()
25682217 .filter(|o| o & 0xff00_0000 == epoch)
25692218 .unwrap_or(0);
2570- if own != 0 && down != 0 && own != down {
2571- if crate::envflags::env_flag!("EC_LEFTSSY") {
2572- eprintln!(
2573- "EC_LEFTSSY epoch={} mi=({mi_r},{mi_c}) left_col={col} \
2574- owners=({},{})->({},{}) modes={own_row}/{left}",
2575- epoch >> 24,
2576- own >> 12 & 0xfff,
2577- own & 0xfff,
2578- down >> 12 & 0xfff,
2579- down & 0xfff,
2580- );
2581- }
2582- }
2219+ if own != 0 && down != 0 && own != down {}
25832220 }
25842221 if have_above && cell(&self.uv_mode_grid, mi_r - 1, mi_c).is_some_and(|m| {
25852222 !matches!(self.uv_mode_col.get(mi_c), Some(&(row, cm)) if usize::from(row) == mi_r - 1 && usize::from(cm) == m)
@@ -2592,8 +2229,7 @@ impl Neighbours {
25922229 // have been filtered at the wrong strength by the coarse map alone.
25932230 if (is_smooth_mode(self.above_uv_mode[c]) && !is_smooth_mode(above))
25942231 || (is_smooth_mode(self.left_uv_mode[r]) && !is_smooth_mode(left))
2595- {
2596- }
2232+ {}
25972233 is_smooth_mode(above) || is_smooth_mode(left)
25982234 }
25992235
@@ -2648,14 +2284,12 @@ impl Neighbours {
26482284 self.modes_above_left_mi(mi_r, mi_c, (self.above_mode[c], self.left_mode[r]));
26492285 if (is_smooth_mode(self.above_mode[c]) && !is_smooth_mode(above))
26502286 || (is_smooth_mode(self.left_mode[r]) && !is_smooth_mode(left))
2651- {
2652- }
2287+ {}
26532288 // A neighbour the coarse band offered where the tile edge makes it
26542289 // unavailable -- must never happen (see `MODE_TILE_EDGE_COARSE_LEAKS`).
26552290 if (mi_r <= self.tile_row0_mi && self.above_mode[c] != DC_PRED)
26562291 || (mi_c <= self.tile_col0_mi && self.left_mode[r] != DC_PRED)
2657- {
2658- }
2292+ {}
26592293 (above, left)
26602294 }
26612295
@@ -2755,16 +2389,16 @@ impl Neighbours {
27552389
27562390 /// [`Self::record_mi`] with independent above (`w`)/left (`h`) extents,
27572391 /// in pixels (lane-partitions r1, mirroring [`Self::record_rect`]).
2758- pub(super) fn record_mi_rect(&mut self, at_mi: (usize, usize), w: usize, h: usize, grids: &[&[i32]; 3]) {
2392+ pub(super) fn record_mi_rect(
2393+ &mut self,
2394+ at_mi: (usize, usize),
2395+ w: usize,
2396+ h: usize,
2397+ grids: &[&[i32]; 3],
2398+ ) {
27592399 let (mi_r, mi_c) = at_mi;
27602400 let states: [Neighbour; 3] = std::array::from_fn(|plane| neighbour_state(grids[plane]));
27612401 let (w_mi, h_mi) = (w / MI, h / MI);
2762- if crate::envflags::env_flag!("EC_ECPUB") {
2763- eprintln!(
2764- "EC_ECPUB blk mi=({mi_r},{mi_c}) wh=({w},{h}) lvl={}",
2765- states[0].level
2766- );
2767- }
27682402 fill_span(&mut self.left_side_mi, mi_r, h_mi, h as u8);
27692403 fill_span(&mut self.above_side_mi, mi_c, w_mi, w as u8);
27702404 // A chroma 4x4 unit straddling the true luma edge is still whole in
@@ -2856,19 +2490,11 @@ impl Neighbours {
28562490 let (step_x, step_y) = (w_px / MI, h_px / MI);
28572491 // the flags read the CALLER's origin, before the shadowing align below
28582492 let (row_mid, col_mid) = (mi_r & (step_y - 1) != 0, mi_c & (step_x - 1) != 0);
2859- if row_mid || col_mid {
2860- }
2493+ if row_mid || col_mid {}
28612494 let (mi_r, mi_c) = (mi_r & !(step_y - 1), mi_c & !(step_x - 1));
28622495 let round_up_even = |n: usize| n.div_ceil(2) * 2;
28632496 let (bound_h, bound_w) = (round_up_even(self.mi_rows), round_up_even(self.mi_cols));
28642497 let state = neighbour_state(grid);
2865- if crate::envflags::env_flag!("EC_CHROMA_PUB") {
2866- eprintln!(
2867- "EC_CHROMA_PUB plane={plane} mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={} dc={}",
2868- state.level,
2869- state.dc.map_or(-1, i32::from)
2870- );
2871- }
28722498 for cell in 0..(h_px / MI).min(bound_h.saturating_sub(mi_r)) {
28732499 self.left[mi_r + cell][plane] = state;
28742500 }
@@ -2888,12 +2514,6 @@ impl Neighbours {
28882514 grid: &[i32],
28892515 ) {
28902516 let state = neighbour_state(grid);
2891- if crate::envflags::env_flag!("EC_ECPUB") {
2892- eprintln!(
2893- "EC_ECPUB tu mi=({mi_r},{mi_c}) wh=({w_px},{h_px}) lvl={}",
2894- state.level
2895- );
2896- }
28972517 for cell in 0..h_px / MI {
28982518 if mi_r + cell < self.mi_rows {
28992519 self.left[mi_r + cell][0] = state;
@@ -3484,18 +3104,9 @@ pub(super) fn decode_color_index_map_wh(
34843104 on: (usize, usize),
34853105 uv: bool,
34863106 ) -> Vec<u8> {
3487- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
34883107 let (on_bw, on_bh) = (on.0.clamp(1, bw), on.1.clamp(1, bh));
34893108 let mut map = vec![0u8; bw * bh];
3490- if trace {
3491- let (rng, _) = dec.debug_state();
3492- eprintln!("EC_PAL row=0 col=0 ctx=-1 n={n} rng={rng}");
3493- }
34943109 map[0] = read_uniform(dec, n) as u8;
3495- if trace {
3496- let (rng, _) = dec.debug_state();
3497- eprintln!("EC_PAL_VAL row=0 col=0 color_idx={} rng={rng}", map[0]);
3498- }
34993110 for i in 1..(on_bw + on_bh - 1) {
35003111 let j_hi = i.min(on_bw - 1);
35013112 let j_lo = i.saturating_sub(on_bh - 1);
@@ -3503,28 +3114,12 @@ pub(super) fn decode_color_index_map_wh(
35033114 let row = i - j;
35043115 let col = j;
35053116 let (ctx, color_order) = palette_color_index_context(&map, bw, row, col, n);
3506- if trace {
3507- let (rng, _) = dec.debug_state();
3508- let row_cdf = if uv {
3509- &cdfs.palette_uv_color_index[n - 2][ctx]
3510- } else {
3511- &cdfs.palette_y_color_index[n - 2][ctx]
3512- };
3513- eprintln!(
3514- "EC_PAL row={row} col={col} ctx={ctx} n={n} cdf0={} cnt={} rng={rng}",
3515- row_cdf[0], row_cdf[n]
3516- );
3517- }
35183117 let symbol = if uv {
35193118 dec.symbol(&mut cdfs.palette_uv_color_index[n - 2][ctx][..=n])
35203119 } else {
35213120 dec.symbol(&mut cdfs.palette_y_color_index[n - 2][ctx][..=n])
35223121 };
35233122 map[row * bw + col] = color_order[symbol];
3524- if trace {
3525- let (rng, _) = dec.debug_state();
3526- eprintln!("EC_PAL_VAL row={row} col={col} color_idx={symbol} rng={rng}");
3527- }
35283123 }
35293124 }
35303125 palette_replicate(&mut map, bw, bh, on);
@@ -3592,9 +3187,6 @@ pub(super) fn apply_deblock(
35923187 ) {
35933188 // lane-part32 r2 debug rung, env-gated: bisecting a widespread pixel
35943189 // mismatch between the raw reconstruction and post-filter output.
3595- if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_DEBLOCK") {
3596- return;
3597- }
35983190 if lf.level[0] != 0 || lf.level[1] != 0 {
35993191 deblock_plane(y, 0, lf, n, frame_width, frame_height, fctx);
36003192 }
@@ -3684,7 +3276,6 @@ pub(super) fn tx_size_context_txfm_rect(
36843276 (mi_r, mi_c): (usize, usize),
36853277 own_w: usize,
36863278 own_h: usize,
3687- fctx: &crate::decode::FrameCtx,
36883279 ) -> usize {
36893280 // `max_txsize_rect_lookup[bsize]` tops out at TX_64X64: no transform is
36903281 // wider or taller than 64, so a block with a 128 side resolves against 64
@@ -3734,30 +3325,7 @@ pub(super) fn tx_size_context_txfm_rect(
37343325 };
37353326 if band_above != (has_above && usize::from(above) != 0)
37363327 || band_left != (has_left && usize::from(left) != 0)
3737- {
3738- }
3739- }
3740- if crate::envflags::env_flag!("EC_TXCTX") {
3741- eprintln!(
3742- "EC_TXCTX mi={mi_r},{mi_c} own={own_w}x{own_h} ha={has_above} hl={has_left} \
3743- intra_only={} above_txfm={} left_txfm={} above_inter={} left_inter={} \
3744- above_side={} left_side={} above={above} left={left} \
3745- | cell_inter ab={} lb={} ab_side={} lb_side={}",
3746- fctx.intra_only.with(std::cell::Cell::get),
3747- n.above_txfm[mi_c],
3748- n.left_txfm[mi_r],
3749- n.above_inter[mi_c],
3750- n.left_inter[mi_r],
3751- n.above_side_mi[mi_c],
3752- n.left_side_mi[mi_r],
3753- // lane-av1txctxband: the per-CELL terms this read now uses, next to
3754- // the per-column bands it used to use, so a divergence names which
3755- // of the two disagreed.
3756- if has_above { n.inter_at(mi_r - 1, mi_c) } else { false },
3757- if has_left { n.inter_at(mi_r, mi_c - 1) } else { false },
3758- if has_above { n.blk_side_at(mi_r - 1, mi_c).0 } else { 0 },
3759- if has_left { n.blk_side_at(mi_r, mi_c - 1).1 } else { 0 },
3760- );
3328+ {}
37613329 }
37623330 let ctx = match (has_above, has_left) {
37633331 (true, true) => usize::from(above) + usize::from(left),
@@ -3765,10 +3333,6 @@ pub(super) fn tx_size_context_txfm_rect(
37653333 (false, true) => usize::from(left),
37663334 (false, false) => 0,
37673335 };
3768- {
3769- let stale = usize::from(has_above && tx_px_at(n, false, mi_r - 1, mi_c) as usize >= own_w)
3770- + usize::from(has_left && tx_h_px_at(n, false, mi_r, mi_c - 1) as usize >= own_h);
3771- }
37723336 ctx
37733337 }
37743338
@@ -3778,7 +3342,11 @@ pub(super) fn tx_size_context_txfm_rect(
37783342 /// override above fired on the wrong neighbour -- the first divergence of the
37793343 /// 10-bit gate's stream was exactly this (`tx_depth` ctx 0 where libaom has 1,
37803344 /// at the intra block right of an inter one).
3781-pub(super) fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize), side: usize) -> usize {
3345+pub(super) fn tx_size_context_txfm(
3346+ n: &Neighbours,
3347+ (mi_r, mi_c): (usize, usize),
3348+ side: usize,
3349+) -> usize {
37823350 let has_above = mi_r > n.tile_row0_mi;
37833351 let has_left = mi_c > n.tile_col0_mi;
37843352 let mut above = usize::from(n.above_txfm[mi_c]) >= side;
@@ -3821,25 +3389,7 @@ pub(super) fn tx_size_context_txfm(n: &Neighbours, (mi_r, mi_c): (usize, usize),
38213389 };
38223390 if band_above != (has_above && usize::from(above) != 0)
38233391 || band_left != (has_left && usize::from(left) != 0)
3824- {
3825- }
3826- }
3827- if crate::envflags::env_flag!("EC_TXCTX") {
3828- eprintln!(
3829- "EC_TXCTX mi={mi_r},{mi_c} own={side} ha={has_above} hl={has_left} \
3830- above_txfm={} left_txfm={} above_inter={} left_inter={} above_side={} left_side={} \
3831- above={above} left={left} | cell_inter ab={} lb={} ab_side={} lb_side={}",
3832- n.above_txfm[mi_c],
3833- n.left_txfm[mi_r],
3834- n.above_inter[mi_c],
3835- n.left_inter[mi_r],
3836- n.above_side_mi[mi_c],
3837- n.left_side_mi[mi_r],
3838- if has_above { n.inter_at(mi_r - 1, mi_c) } else { false },
3839- if has_left { n.inter_at(mi_r, mi_c - 1) } else { false },
3840- if has_above { n.blk_side_at(mi_r - 1, mi_c).0 } else { 0 },
3841- if has_left { n.blk_side_at(mi_r, mi_c - 1).1 } else { 0 },
3842- );
3392+ {}
38433393 }
38443394 match (has_above, has_left) {
38453395 (true, true) => usize::from(above) + usize::from(left),
@@ -3886,13 +3436,6 @@ pub(super) fn read_tx_size(
38863436 64 => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
38873437 _ => unreachable!("decode_block/decode_leaf8 only call this at 8/16/32/64/128"),
38883438 };
3889- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
3890- let (rng, _) = dec.debug_state();
3891- let (mi_r, mi_c) = at_mi;
3892- eprintln!(
3893- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={depth} ctx={ctx} rng={rng}"
3894- );
3895- }
38963439 max_tx >> depth
38973440 }
38983441
@@ -3902,7 +3445,12 @@ pub(super) fn read_tx_size(
39023445 /// the two neighbour terms (whether the transform last written above/left of
39033446 /// this unit is narrower/shorter than the unit itself).
39043447 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3905-pub(super) fn txfm_partition_ctx(above_px: u8, left_px: u8, blk_max_px: usize, tx_px: usize) -> usize {
3448+pub(super) fn txfm_partition_ctx(
3449+ above_px: u8,
3450+ left_px: u8,
3451+ blk_max_px: usize,
3452+ tx_px: usize,
3453+) -> usize {
39063454 txfm_partition_ctx_rect(above_px, left_px, blk_max_px, tx_px, tx_px)
39073455 }
39083456
@@ -3935,7 +3483,12 @@ pub(crate) fn txfm_partition_ctx_rect(
39353483 /// resolves, every mi cell its *parent* unit (`txb_px`) spans records the
39363484 /// resolved transform's own size.
39373485 #[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3938-pub(super) fn txfm_partition_update(n: &mut Neighbours, at_mi: (usize, usize), tx_px: usize, txb_px: usize) {
3486+pub(super) fn txfm_partition_update(
3487+ n: &mut Neighbours,
3488+ at_mi: (usize, usize),
3489+ tx_px: usize,
3490+ txb_px: usize,
3491+) {
39393492 txfm_partition_update_rect(n, at_mi, (tx_px, tx_px), (txb_px, txb_px));
39403493 }
39413494
@@ -4005,12 +3558,6 @@ pub(super) fn txfm_partition_update_rect(
40053558 (tx_w, tx_h): (usize, usize),
40063559 (txb_w, txb_h): (usize, usize),
40073560 ) {
4008- if crate::envflags::env_flag!("EC_TXUPD") {
4009- eprintln!(
4010- "EC_TXUPD rect mi=({},{}) tx=({tx_w},{tx_h}) txb=({txb_w},{txb_h})",
4011- mi_r, mi_c
4012- );
4013- }
40143561 for i in 0..txb_h / MI {
40153562 if let Some(cell) = n.left_txfm.get_mut(mi_r + i) {
40163563 *cell = tx_h as u8;
@@ -4034,11 +3581,6 @@ pub(super) fn set_txfm_ctxs(
40343581 h_mi: usize,
40353582 skip_inter: bool,
40363583 ) {
4037- if crate::envflags::env_flag!("EC_TXUPD") {
4038- eprintln!(
4039- "EC_TXUPD ctxs mi=({mi_r},{mi_c}) tx={tx_px} wh=({w_mi},{h_mi}) skip_inter={skip_inter}"
4040- );
4041- }
40423584 let bw = if skip_inter { w_mi * MI } else { tx_px };
40433585 let bh = if skip_inter { h_mi * MI } else { tx_px };
40443586 for i in 0..w_mi {
@@ -4308,15 +3850,6 @@ pub(super) fn read_var_tx_size(
43083850 tx_h,
43093851 );
43103852 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
4311- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
4312- let (rng, _) = dec.debug_state();
4313- eprintln!(
4314- "EC_ISTEP mi_row={} mi_col={} name=txfm_split val={} ctx={ctx} rng={rng}",
4315- unit.0,
4316- unit.1,
4317- u8::from(split)
4318- );
4319- }
43203853 if !split {
43213854 out.push((blk_row, blk_col, tx_w, tx_h));
43223855 txfm_partition_update_rect(n, unit, (tx_w, tx_h), (tx_w, tx_h));
crates/ec-av1/src/decode/deblock.rsmodified+33 -49
@@ -1,7 +1,7 @@
11 //! Deblocking filters: the edge filters, the deblock plane drivers, the filter-replay capture and the pooled plane scratch. Moved out of `decode/mod.rs` (av1split D12); the items are unchanged apart from visibility.
22
3-use archmage::SimdToken;
43 use super::*;
4+use archmage::SimdToken;
55
66 /// `update_sharpness`'s per-level `(blimit, limit, hev_thr)` triple.
77 fn deblock_thresholds(level: i32, sharpness: u8) -> (i32, i32, i32) {
@@ -463,12 +463,6 @@ pub(super) fn deblock_plane_span(
463463 plane.true_height.min(ch),
464464 plane.width,
465465 );
466- if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") {
467- eprintln!(
468- "DEBLOCK plane={plane_idx} tw={tw} th={th} stride={stride} true={}x{} crop={cw}x{ch}",
469- plane.true_width, plane.true_height
470- );
471- }
472466 // lane-perf8: both passes iterate the edge's OWN direction innermost, so
473467 // 4 consecutive 4-sample groups (16 lines) can go through one AVX2
474468 // kernel. The swap is order-preserving: a filtered group overlaps only
@@ -523,20 +517,20 @@ pub(super) fn deblock_plane_span(
523517 std::array::from_fn(|k| edge_params(&vctx, x0, y0 + 4 * k));
524518 if let Some((len, level)) = ps[0]
525519 && ps.iter().all(|p| *p == ps[0])
526- && filter_edge16(
527- mine,
528- (y0 - y_lo) * stride + x0,
529- stride,
530- true,
531- len,
532- level,
533- lf.sharpness,
534- fctx,
535- )
536- {
537- y0 += 16;
538- continue;
539- }
520+ && filter_edge16(
521+ mine,
522+ (y0 - y_lo) * stride + x0,
523+ stride,
524+ true,
525+ len,
526+ level,
527+ lf.sharpness,
528+ fctx,
529+ )
530+ {
531+ y0 += 16;
532+ continue;
533+ }
540534 for (k, p) in ps.iter().enumerate() {
541535 if let Some((len, level)) = *p {
542536 filter_edge(
@@ -555,9 +549,6 @@ pub(super) fn deblock_plane_span(
555549 continue;
556550 }
557551 if let Some((len, level)) = edge_params(&vctx, x0, y0) {
558- if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE_V") && plane_idx == 0 {
559- eprintln!("VEDGE x0={x0} y0={y0} len={len} level={level}");
560- }
561552 filter_edge(
562553 mine,
563554 (y0 - y_lo) * stride + x0,
@@ -637,20 +628,20 @@ pub(super) fn deblock_plane_span(
637628 std::array::from_fn(|k| edge_params(&hctx, x0 + 4 * k, y0));
638629 if let Some((len, level)) = ps[0]
639630 && ps.iter().all(|p| *p == ps[0])
640- && filter_edge16(
641- px,
642- (y0 - r_lo) * w + (x0 - x_lo),
643- w,
644- false,
645- len,
646- level,
647- lf.sharpness,
648- fctx,
649- )
650- {
651- x0 += 16;
652- continue;
653- }
631+ && filter_edge16(
632+ px,
633+ (y0 - r_lo) * w + (x0 - x_lo),
634+ w,
635+ false,
636+ len,
637+ level,
638+ lf.sharpness,
639+ fctx,
640+ )
641+ {
642+ x0 += 16;
643+ continue;
644+ }
654645 for (k, p) in ps.iter().enumerate() {
655646 if let Some((len, level)) = *p {
656647 filter_edge(
@@ -669,15 +660,6 @@ pub(super) fn deblock_plane_span(
669660 continue;
670661 }
671662 if let Some((len, level)) = edge_params(&hctx, x0, y0) {
672- if crate::envflags::env_flag!("EC_AV1_DEBLOCK_TRACE")
673- && plane_idx == 0
674- && x0 == 44
675- {
676- eprintln!(
677- "HEDGE x0={x0} y0={y0} len={len} level={level} sharpness={}",
678- lf.sharpness
679- );
680- }
681663 filter_edge(
682664 px,
683665 (y0 - r_lo) * w + (x0 - x_lo),
@@ -716,7 +698,8 @@ pub(super) fn deblock_plane_span(
716698 /// every pool thread the decode ever created. One shared pool with a hard
717699 /// entry cap bounds the retention at [`SCRATCH_CAP`] buffers no matter how
718700 /// many threads cycle through it; anything over the cap is freed.
719-pub(super) static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> = std::sync::Mutex::new(Vec::new());
701+pub(super) static PLANE_SCRATCH: std::sync::Mutex<Vec<Vec<u16>>> =
702+ std::sync::Mutex::new(Vec::new());
720703
721704 /// Most buffers the shared pool keeps. ~3 whole-plane sets per in-flight 4K
722705 /// frame at the shipped `EC_AV1_THREADS` ceiling; the frames actually in
@@ -877,7 +860,8 @@ pub(crate) fn arm_filter_replay() {
877860 /// can hold the replay against the decode it stands in for
878861 /// (`encoder::tests::filter_replay_codes_the_same_stream_as_a_full_decode`).
879862 #[cfg(test)]
880-pub(super) static REPLAY_DISABLED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
863+pub(super) static REPLAY_DISABLED: std::sync::atomic::AtomicBool =
864+ std::sync::atomic::AtomicBool::new(false);
881865
882866 #[cfg(test)]
883867 pub(crate) fn set_filter_replay_disabled(off: bool) {
crates/ec-av1/src/decode/frame_tile.rsmodified+8 -174
@@ -435,7 +435,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
435435 plane: 0,
436436 };
437437 let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx));
438- note_frame_chroma_alloc((width, height), (cw, ch), (ss_x(fctx), ss_y(fctx)));
439438 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));
440439 let mut u = PlaneBuf {
441440 data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),
@@ -545,13 +544,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
545544 // lane-comppin r9: tile-entry range, the earliest point comparable
546545 // against aomdec's own `r->ec.rng` right after `aom_reader_init` -- the
547546 // first ladder rung before any symbol (partition or otherwise) is read.
548- if crate::envflags::env_flag!("EC_AV1_TELL") {
549- eprintln!(
550- "TELL label=tile_init tell={} range={}",
551- dec.debug_bitpos(),
552- dec.debug_state().0
553- );
554- }
555547 neighbours.start_tile(mi_row0 as usize, mi_col0 as usize, mi_col1 as usize, fctx);
556548 y.set_tile_origin(
557549 mi_col0 as usize * 4,
@@ -1071,16 +1063,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
10711063 // instead of silently decoding as SPLIT and desyncing.
10721064 let part64 = match (has_cols, has_rows) {
10731065 (true, true) => {
1074- let pre_rng = dec.debug_state().0;
1075- if crate::envflags::env_flag!("EC_TRACE_PART") {
1076- eprintln!(
1077- "EC_PART mi_row={} mi_col={} bsize=12 ctx={} rng={}",
1078- sb_r as usize * SB_MI as usize,
1079- sb_c as usize * SB_MI as usize,
1080- sb_ctx,
1081- dec.debug_state().0
1082- );
1083- }
10841066 let p = dec.symbol(&mut cdfs.partition_w64[sb_ctx]);
10851067 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be
10861068 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`
@@ -1089,33 +1071,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
10891071 // arm -- VERT, VERT_A / VERT_B, HORZ_4 and VERT_4 -- and the HORZ siblings
10901072 // keep decoding because the helper is exact, not a heuristic. inter-frame 64x64 level; `p` is the symbol.
10911073
1092- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1093- eprintln!(
1094- "TRACE partition_w64 mi=({},{}) ctx={sb_ctx} value={p} pre_rng={pre_rng}",
1095- sb_r * SB_MI,
1096- sb_c * SB_MI
1097- );
1098- }
10991074 p
11001075 }
11011076 (true, false) => {
11021077 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
11031078 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT
11041079 // (libaom `ec_read_partition_impl`).
1105- if crate::envflags::env_flag!("EC_TRACE_PART") {
1106- eprintln!(
1107- "EC_PARTG mi_row={} mi_col={} bsize=12 ctx={} rng={}",
1108- sb_r as usize * SB_MI as usize,
1109- sb_c as usize * SB_MI as usize,
1110- sb_ctx,
1111- dec.debug_state().0
1112- );
1113- }
1114- if bump_edge32_bit(
1115- 4,
1116- dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)),
1117- ) == 1
1118- {
1080+ if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], VERT_ALIKE)) == 1 {
11191081 PARTITION_SPLIT
11201082 } else {
11211083 PARTITION_HORZ
@@ -1125,20 +1087,13 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
11251087 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
11261088 // bit IS the partition -- 0 means PARTITION_VERT, only 1 means SPLIT
11271089 // (libaom `ec_read_partition_impl`).
1128- if bump_edge32_bit(
1129- 4,
1130- dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)),
1131- ) == 1
1132- {
1090+ if dec.symbol_fixed(&gather(&cdfs.partition_w64[sb_ctx], HORZ_ALIKE)) == 1 {
11331091 PARTITION_SPLIT
11341092 } else {
11351093 PARTITION_VERT
11361094 }
11371095 }
1138- (false, false) => {
1139- bump_edge_both_cut(2);
1140- PARTITION_SPLIT
1141- }
1096+ (false, false) => PARTITION_SPLIT,
11421097 };
11431098 // lane-av1unwritten r7: the symbol is RESOLVED (a full CDF
11441099 // read or an edge `gather`) and about to be dispatched, so the
@@ -1205,15 +1160,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
12051160 PARTITION_HORZ | PARTITION_VERT | PARTITION_HORZ_4 | PARTITION_VERT_4
12061161 ) {
12071162 // lane-av1unwritten r6: arm census.
1208- note_subsize_arm(
1209- part64,
1210- chroma_plane_block_codable(
1211- partition_subsize_dims((64, 64), part64).0,
1212- partition_subsize_dims((64, 64), part64).1,
1213- ss_x(fctx),
1214- ss_y(fctx),
1215- ),
1216- );
12171163 // lane-inter4 r1: the superblock-level rect + 1:4 pairs as
12181164 // inter blocks -- two 64x32 / 32x64 strips, or four 64x16 /
12191165 // 16x64 ones. Each piece keeps `side = SB` for every
@@ -1267,9 +1213,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
12671213 bw,
12681214 bh
12691215 );
1270- if !four && i == 0 && ((horz && !has_rows) || (!horz && !has_cols)) {
1271- bump_inter_edge_strip(if horz { 0 } else { 1 });
1272- }
1216+ if !four && i == 0 && ((horz && !has_rows) || (!horz && !has_cols)) {}
12731217 }
12741218 continue;
12751219 }
@@ -1402,14 +1346,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
14021346 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
14031347 );
14041348 let part32 = if has_cols32 && has_rows32 {
1405- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1406- eprintln!(
1407- "TRACE part32_pre mi=({},{}) rng={}",
1408- r32 * BLOCK_MI,
1409- c32 * BLOCK_MI,
1410- dec.debug_state().0
1411- );
1412- }
14131349 // lane-av1tilerows: this rung printed the RAW 32-grid
14141350 // index (`r32`, `c32`) into its `mi_row=`/`mi_col=`
14151351 // fields — a factor of `BLOCK_MI` (8) off — while the
@@ -1420,23 +1356,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
14201356 // against libaom's per-level `EC_PART_VAL` dump, which
14211357 // is the only way to locate a partition-walk
14221358 // divergence. Behaviour-free: env-gated print only.
1423- if crate::envflags::env_flag!("EC_TRACE_PART") {
1424- eprintln!(
1425- "EC_PART mi_row={} mi_col={} bsize=9 ctx={} rng={}",
1426- r32 * BLOCK_MI,
1427- c32 * BLOCK_MI,
1428- ctx32,
1429- dec.debug_state().0
1430- );
1431- }
14321359 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
1433- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1434- eprintln!(
1435- "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p}",
1436- r32 * BLOCK_MI,
1437- c32 * BLOCK_MI
1438- );
1439- }
14401360 p
14411361 } else {
14421362 match (has_cols32, has_rows32) {
@@ -1444,21 +1364,11 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
14441364 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
14451365 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT
14461366 // (libaom `ec_read_partition_impl`).
1447- if crate::envflags::env_flag!("EC_TRACE_PART") {
1448- eprintln!(
1449- "EC_PARTG mi_row={} mi_col={} bsize=9 ctx={} rng={}",
1450- r32 as usize * BLOCK_MI as usize,
1451- c32 as usize * BLOCK_MI as usize,
1452- ctx32,
1453- dec.debug_state().0
1454- );
1455- }
14561367 if {
14571368 let b = dec.symbol_fixed(&gather(
14581369 &cdfs.partition_w32[ctx32],
14591370 VERT_ALIKE,
14601371 ));
1461- bump_edge32(b.min(1));
14621372 b
14631373 } == 1
14641374 {
@@ -1476,7 +1386,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
14761386 &cdfs.partition_w32[ctx32],
14771387 HORZ_ALIKE,
14781388 ));
1479- bump_edge32(b.min(1));
14801389 b
14811390 } == 1
14821391 {
@@ -1485,10 +1394,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
14851394 PARTITION_VERT
14861395 }
14871396 }
1488- _ => {
1489- bump_edge_both_cut(1);
1490- PARTITION_SPLIT
1491- }
1397+ _ => PARTITION_SPLIT,
14921398 }
14931399 };
14941400 // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or
@@ -1571,24 +1477,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
15711477 // inter leaves through the very same loop the
15721478 // straddling case has always used.
15731479 let part16 = if has_cols16 && has_rows16 {
1574- if crate::envflags::env_flag!("EC_TRACE_PART") {
1575- eprintln!(
1576- "EC_PART mi_row={} mi_col={} bsize=6 ctx={} rng={}",
1577- (sr * SUB_MI as usize),
1578- (sc * SUB_MI as usize),
1579- ctx16,
1580- dec.debug_state().0
1581- );
1582- }
15831480 let p = dec.symbol(&mut cdfs.partition_w16[ctx16]);
1584- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1585- let (rng, _) = dec.debug_state();
1586- eprintln!(
1587- "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={p} rng={rng}",
1588- sr as u32 * SUB_MI,
1589- sc as u32 * SUB_MI
1590- );
1591- }
15921481 p
15931482 } else if !has_cols16 && !has_rows16 {
15941483 // lane-edgeboth r1: both axes cut by the true
@@ -1596,22 +1485,12 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
15961485 // forces PARTITION_SPLIT and reads NO symbol;
15971486 // the leaf loop below already drops the
15981487 // out-of-frame quadrants.
1599- bump_edge_both_cut(0);
16001488 PARTITION_SPLIT
16011489 } else {
16021490 if has_cols16 {
16031491 // lane-golomb r1 (class `parsed-then-discarded`): the gathered
16041492 // bit IS the partition -- 0 means PARTITION_HORZ, only 1 means SPLIT
16051493 // (libaom `ec_read_partition_impl`).
1606- if crate::envflags::env_flag!("EC_TRACE_PART") {
1607- eprintln!(
1608- "EC_PARTG mi_row={} mi_col={} bsize=6 ctx={} rng={}",
1609- sr * SUB_MI as usize,
1610- sc * SUB_MI as usize,
1611- ctx16,
1612- dec.debug_state().0
1613- );
1614- }
16151494 if dec.symbol_fixed(&gather(
16161495 &cdfs.partition_w16[ctx16],
16171496 VERT_ALIKE,
@@ -1726,7 +1605,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
17261605 && (piece_mi.0 >= mi_rows as usize
17271606 || piece_mi.1 >= mi_cols as usize)
17281607 {
1729- bump_inter_edge_strip(if horz { 4 } else { 5 });
17301608 break;
17311609 }
17321610 decode_inter_block(
@@ -1819,7 +1697,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
18191697 // block_size_high >= 16, blockd.h) both hold
18201698 // and the leaf/strip decoders' own gates
18211699 // apply unchanged.
1822- bump_ab16_inter(part16 - PARTITION_HORZ_A);
18231700 let _vert_guard = if part16 == PARTITION_VERT_A
18241701 || part16 == PARTITION_VERT_B
18251702 {
@@ -2019,8 +1896,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
20191896 refpix
20201897 .dims(rf)
20211898 .is_some_and(|(w, _)| w != frame_width as usize)
2022- }) {
2023- }
1899+ }) {}
20241900 let mut prev_leaves: Vec<(
20251901 (usize, usize),
20261902 bool,
@@ -2031,16 +1907,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
20311907 for (mr, mc) in leaf_positions {
20321908 let leaf_mi = (mr as usize, mc as usize);
20331909 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
2034- if crate::envflags::env_flag!("EC_TRACE_PART") {
2035- eprintln!(
2036- "EC_PART mi_row={} mi_col={} bsize=3 ctx={} rng={}",
2037- leaf_mi.0,
2038- leaf_mi.1,
2039- leaf_ctx,
2040- dec.debug_state().0
2041- );
2042- }
2043- let ec_dbg_pre = dec.debug_state().0;
20441910 let part8 = dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
20451911 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be
20461912 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`
@@ -2050,13 +1916,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
20501916 // keep decoding because the helper is exact, not a heuristic. inter-frame 8x8 level.
20511917 refuse_invalid_subsize((8, 8), part8, fctx)?;
20521918
2053- if std::env::var_os("EC_DBG_SUB8").is_some() {
2054- let ec_dbg_post = dec.debug_state().0;
2055- eprintln!(
2056- "EC_DBG b8 mi=({},{}) ctx={leaf_ctx} val={part8} pre={ec_dbg_pre} post={ec_dbg_post}",
2057- leaf_mi.0, leaf_mi.1
2058- );
2059- }
20601919 if part8 == PARTITION_SPLIT {
20611920 // lane-intersub8: four BLOCK_4X4 inter
20621921 // sub-blocks, chroma once per 8x8.
@@ -2090,15 +1949,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
20901949 // lane-av1unwritten r6: arm census -- an
20911950 // 8x8-level VERT selects BLOCK_4X8, which
20921951 // is INVALID at 4:2:2.
2093- note_subsize_arm(
2094- part8,
2095- chroma_plane_block_codable(
2096- partition_subsize_dims((8, 8), part8).0,
2097- partition_subsize_dims((8, 8), part8).1,
2098- ss_x(fctx),
2099- ss_y(fctx),
2100- ),
2101- );
21021952 if part8 == PARTITION_VERT || part8 == PARTITION_HORZ {
21031953 // lane-intersub8 r3/r4/r5: two
21041954 // BLOCK_8X4 (HORZ) / BLOCK_4X8 (VERT)
@@ -2440,9 +2290,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
24402290 (frame_width as usize, frame_height as usize),
24412291 fctx,
24422292 )?;
2443- if !has_rows32 {
2444- bump_edge32(2);
2445- }
2293+ if !has_rows32 {}
24462294 // lane-golomb r2: at the frame edge only the first half of the
24472295 // strip is coded (libaom `decode_partition` guards the second
24482296 // with the same has_rows32 test that made this partition non-square).
@@ -2495,7 +2343,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
24952343 fctx,
24962344 )?;
24972345 } else {
2498- bump_inter_edge_strip(2);
24992346 }
25002347 }
25012348 PARTITION_VERT => {
@@ -2546,9 +2393,7 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
25462393 (frame_width as usize, frame_height as usize),
25472394 fctx,
25482395 )?;
2549- if !has_cols32 {
2550- bump_edge32(3);
2551- }
2396+ if !has_cols32 {}
25522397 // lane-golomb r2: at the frame edge only the first half of the
25532398 // strip is coded (libaom `decode_partition` guards the second
25542399 // with the same has_cols32 test that made this partition non-square).
@@ -2601,7 +2446,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
26012446 fctx,
26022447 )?;
26032448 } else {
2604- bump_inter_edge_strip(3);
26052449 }
26062450 }
26072451 PARTITION_HORZ_A => {
@@ -3144,16 +2988,6 @@ pub(crate) fn decode_inter_frame_tile_with_cdfs(
31442988 );
31452989 }
31462990
3147- // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
3148- if crate::envflags::env_flag!("EC_OBMC")
3149- || crate::envflags::env_flag!("EC_TRACE_MODE")
3150- || crate::envflags::env_flag!("EC_PRED")
3151- {
3152- eprintln!(
3153- "EC_PICT idx={}",
3154- PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
3155- );
3156- }
31572991 // lane-av1fwd: the encoder scores ~25 filter candidates against this
31582992 // same coded tile ([`FilterReplay`]). Capture the reconstruction here,
31592993 // before either filter has touched it -- but only on the shape whose
crates/ec-av1/src/decode/inter_block.rsmodified+37 -239
@@ -123,8 +123,6 @@ pub(super) fn decode_inter_block(
123123 // Round 27: the per-read trace is the only instrument that reaches the inter
124124 // path (the coefficient rungs stop well before the frame-3 divergence),
125125 // so publish the phase and the block's mi for every read it makes.
126- crate::msac::SymbolDecoder::set_symr_phase("inter");
127- crate::msac::SymbolDecoder::set_symr_mi(at.0 as i64, at.1 as i64);
128126 // lane-inter4 r1: `at` is in MI units (4 px) so a 32-level 1:4 strip can
129127 // name an 8-px offset; `(r, c)` stays the enclosing 16-px cell for the
130128 // few 16-px-granular uses below.
@@ -232,30 +230,12 @@ pub(super) fn decode_inter_block(
232230 // bails per PLANE at `block_width < 8 || block_height < 8` -- on the
233231 // block's own dims, never on the square prediction buffer this reader
234232 // allocates.
235- if crate::envflags::env_flag!("EC_MC_TRACE") {
236- eprintln!("EC_IB px={px} py={py} side={side} w={write_w} h={write_h}");
237- }
238233
239- if crate::envflags::env_flag!("EC_AV1_TELL") {
240- eprintln!(
241- "TELL mi_row={} mi_col={} label=block_entry side={side} tell={} range={}",
242- rmi,
243- cmi,
244- dec.debug_bitpos(),
245- dec.debug_state().0
246- );
247- }
248234 let skip_mode_ctx =
249235 usize::from(neighbours.above_skip_mode[cmi]) + usize::from(neighbours.left_skip_mode[rmi]);
250236 // lane-comppin r3: skip_mode desync isolation -- dump ctx + the pre-read
251237 // MSAC tell so it can be diffed against an equivalent hook in libaom's
252238 // own `read_skip_mode`/`av1_get_skip_mode_context`.
253- if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") {
254- eprintln!(
255- "EC_SKIPMODE r={r} c={c} ctx={skip_mode_ctx} skip_mode_present={skip_mode_present} tell_before={}",
256- dec.debug_bitpos()
257- );
258- }
259239 // spec 5.11.5 `inter_frame_mode_info`: `inter_segment_id(1)` before
260240 // `skip_mode`/`skip`, `inter_segment_id(0)` after them.
261241 let (seg_mi_r, seg_mi_c) = (rmi, cmi);
@@ -269,12 +249,6 @@ pub(super) fn decode_inter_block(
269249 let comp_allowed = write_w.min(write_h) >= 8;
270250 let skip_mode =
271251 skip_mode_present && comp_allowed && dec.symbol(&mut cdfs.skip_mode[skip_mode_ctx]) == 1;
272- if crate::envflags::env_flag!("EC_AV1_SKIPMODE_DUMP") {
273- eprintln!(
274- "EC_SKIPMODE r={r} c={c} result={skip_mode} tell_after={}",
275- dec.debug_bitpos()
276- );
277- }
278252
279253 let skip_ctx = usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
280254 let skip = skip_mode || dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
@@ -299,16 +273,6 @@ pub(super) fn decode_inter_block(
299273 // chunk). An INTRA block at that size inside an inter frame takes the
300274 // intra tail below, which still codes one whole-block chroma unit and one
301275 // `read_tx_size` at 128 -- refuse by name instead of mis-decoding it.
302- if crate::envflags::env_flag!("EC_TRACE_MODE") {
303- eprintln!(
304- "EC_MODE mi_row={} mi_col={} rng={} is_inter={} skip={} side={side}",
305- rmi,
306- cmi,
307- dec.debug_state().0,
308- u8::from(is_inter),
309- u8::from(skip)
310- );
311- }
312276 // lane-warp r5: see `reject_residual` -- a square-block decode of a
313277 // HORZ_B strip is symbol-exact only for `skip` (no residual, no
314278 // motion_mode/warp symbol). lane-intrarect r1 MOVED this gate from just
@@ -328,26 +292,10 @@ pub(super) fn decode_inter_block(
328292 && !rect_inter_residual_supported(write_w, write_h)
329293 && (is_inter || (write_w == side && write_h == side))
330294 {
331- if crate::envflags::env_flag!("EC_RECTRES") {
332- eprintln!(
333- "EC_RECTRES w={write_w} h={write_h} side={side} skip={} is_inter={} mi_row={rmi} mi_col={cmi}",
334- u8::from(skip),
335- u8::from(is_inter)
336- );
337- }
338295 return Err(unsupported(
339296 "a non-skip rectangular (HORZ/VERT/HORZ_B) strip needs rectangular residual coding",
340297 ));
341298 }
342- if crate::envflags::env_flag!("EC_AV1_TELL") {
343- eprintln!(
344- "TELL mi_row={} mi_col={} label=post_is_inter skip_mode={skip_mode} skip={skip} is_inter={is_inter} tell={} range={}",
345- rmi,
346- cmi,
347- dec.debug_bitpos(),
348- dec.debug_state().0
349- );
350- }
351299
352300 let mode_for_tx;
353301 let uv_predict_mode;
@@ -407,12 +355,6 @@ pub(super) fn decode_inter_block(
407355 uni: neighbours.left_ref1[rmi]
408356 .is_some_and(|r1| is_uni_comp_ref(neighbours.left_ref[rmi], r1)),
409357 });
410- if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") {
411- eprintln!(
412- "EC_PRECOMP r={r} c={c} skip_mode={skip_mode} skip={skip} reference_select={reference_select} tell={}",
413- dec.debug_bitpos()
414- );
415- }
416358 let is_compound = skip_mode
417359 || (reference_select
418360 // `is_comp_ref_allowed` (blockd.h:65) gates the
@@ -494,22 +436,6 @@ pub(super) fn decode_inter_block(
494436 ),
495437 fctx,
496438 );
497- if crate::envflags::env_flag!("EC_TRACE_MODE") {
498- eprintln!(
499- "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={} ref0={ref0} ref1={ref1} mv0=({},{}) stack={} rng={}",
500- compound_mode + 17,
501- mv0.0,
502- mv0.1,
503- comp_stack.entries.len(),
504- dec.debug_state().0
505- );
506- for (i, e) in comp_stack.entries.iter().enumerate() {
507- eprintln!(
508- "EC_STACK mi_row={mi_row} mi_col={mi_col} i={i} this=({},{}) comp=({},{}) w={}",
509- e.mv0.0, e.mv0.1, e.mv1.0, e.mv1.1, e.weight
510- );
511- }
512- }
513439 let is_globalmv = compound_mode == 6; // GLOBAL_GLOBALMV
514440 // be non-TRANSLATION (IDENTITY counts) for the compound block's
515441 // interp-filter read to be suppressed.
@@ -545,10 +471,8 @@ pub(super) fn decode_inter_block(
545471 // all, so its number was an upper bound dressed up as an
546472 // engagement figure.
547473 if mi_row < mi_rows as usize / 2 {
548- if is_globalmv {
549- }
550- if is_global_mv0 || is_global_mv1 {
551- }
474+ if is_globalmv {}
475+ if is_global_mv0 || is_global_mv1 {}
552476 }
553477 // libaom `av1_init_warp_params` + `allow_warp`'s
554478 // `global_warp_allowed` branch, run once per reference for a
@@ -658,17 +582,10 @@ pub(super) fn decode_inter_block(
658582 && enable_masked_compound
659583 && is_any_masked_compound_used_here(write_w, write_h)
660584 {
661- crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx");
662585 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
663586 } else {
664587 0
665588 };
666- if crate::envflags::env_flag!("EC_TRACE_MODE") {
667- eprintln!(
668- "EC_CGI mi_row={rmi} mi_col={cmi} ctx={group_ctx} val={comp_group_idx} rng={}",
669- dec.debug_state().0
670- );
671- }
672589 // lane-maskcomp r2 / lane-wedge r3: `Some(mask_type)` for a
673590 // `COMPOUND_DIFFWTD` block, `Some(mask)` (wedge codebook lookup)
674591 // for a `COMPOUND_WEDGE` block -- exactly one of the two is set
@@ -932,14 +849,7 @@ pub(super) fn decode_inter_block(
932849 ref_order_hints[(ref0 - LAST_FRAME) as usize],
933850 ref_order_hints[(ref1 - LAST_FRAME) as usize],
934851 );
935- crate::msac::SymbolDecoder::set_symr_cdf("compound_idx");
936852 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
937- if crate::envflags::env_flag!("EC_TRACE_MODE") {
938- eprintln!(
939- "EC_CIDX mi_row={rmi} mi_col={cmi} ctx={idx_ctx} val={idx} rng={}",
940- dec.debug_state().0
941- );
942- }
943853 if idx == 1 {
944854 (8, 8, 1u8)
945855 } else {
@@ -955,16 +865,6 @@ pub(super) fn decode_inter_block(
955865 (8, 8, 1u8)
956866 };
957867 compound_ctx = Some((ref1, comp_group_idx as u8, compound_idx));
958- if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") {
959- eprintln!(
960- "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize={side} mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}",
961- mv0.0,
962- mv0.1,
963- mv1.0,
964- mv1.1,
965- dec.debug_bitpos()
966- );
967- }
968868
969869 // spec 5.11.19/libaom `decodemv.c` 1575: `read_mb_interp_filter`
970870 // comes AFTER `read_compound_type` (the `comp_group_idx`/
@@ -1377,7 +1277,23 @@ pub(super) fn decode_inter_block(
13771277 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
13781278 let (sy, su, sv) = if pred_deferred(refpix) {
13791279 push_pred(build);
1380- (Pred::Cur { plane: 0, stride: side, off: 0 }, Pred::Cur { plane: 1, stride: chroma_stride, off: 0 }, Pred::Cur { plane: 2, stride: chroma_stride, off: 0 })
1280+ (
1281+ Pred::Cur {
1282+ plane: 0,
1283+ stride: side,
1284+ off: 0,
1285+ },
1286+ Pred::Cur {
1287+ plane: 1,
1288+ stride: chroma_stride,
1289+ off: 0,
1290+ },
1291+ Pred::Cur {
1292+ plane: 2,
1293+ stride: chroma_stride,
1294+ off: 0,
1295+ },
1296+ )
13811297 } else {
13821298 let mut built: [Vec<u16>; 3] = Default::default();
13831299 build(y, u, v, refpix, fctx, &mut built);
@@ -2120,14 +2036,6 @@ pub(super) fn decode_inter_block(
21202036 neighbours.left_ref1[rmi],
21212037 );
21222038 ref_frame_for_lf = ref_frame;
2123- if crate::envflags::env_flag!("EC_AV1_TELL") {
2124- let (mi_row, mi_col) = (rmi, cmi);
2125- eprintln!(
2126- "TELL mi_row={mi_row} mi_col={mi_col} label=post_ref_frame ref={ref_frame} tell={} range={}",
2127- dec.debug_bitpos(),
2128- dec.debug_state().0
2129- );
2130- }
21312039 // round 4-9 (lane-av1golden..lane-av1golden7): GOLDEN_FRAME's own
21322040 // stacked defects (lf_level ref/mode-delta forwarding, the
21332041 // switchable_interp ref-frame ctx gate, and a film-grain synthesis
@@ -2192,7 +2100,6 @@ pub(super) fn decode_inter_block(
21922100 // lane-interbis r1: which single-ref mode this block resolved to,
21932101 // in the oracle's own numbering (NEARESTMV=13 .. NEWMV=16), for
21942102 // the `EC_MODE_VAL` value ladder below.
2195- let mut dbg_mode = 16u32;
21962103 let (mv, is_new_mv) = if !not_new {
21972104 // NEWMV (spec 5.11.24's `read_drl_idx`, `RefMvIdx` starting at 0):
21982105 // read at most two `drl_mode` bits, one per stack entry past the
@@ -2226,11 +2133,9 @@ pub(super) fn decode_inter_block(
22262133 let mv = if !not_zero {
22272134 // GLOBALMV: `gm_get_motion_vector` (spec 7.10.2.1), already
22282135 // computed at this block's own position in `gm_table`.
2229- dbg_mode = 15;
22302136 gm_table[(ref_frame - LAST_FRAME) as usize]
22312137 } else {
22322138 let nearest = dec.symbol(&mut cdfs.ref_mv[stack.ref_mv_ctx]) == 0;
2233- dbg_mode = if nearest { 13 } else { 14 };
22342139 if nearest {
22352140 stack.nearest_mv
22362141 } else {
@@ -2252,21 +2157,6 @@ pub(super) fn decode_inter_block(
22522157 };
22532158 (mv, false)
22542159 };
2255- if crate::envflags::env_flag!("EC_TRACE_MODE") {
2256- for (i, e) in stack.entries.iter().enumerate() {
2257- eprintln!(
2258- "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
2259- e.mv.0, e.mv.1, e.weight
2260- );
2261- }
2262- eprintln!(
2263- "EC_MODE_VAL mi_row={mi_row} mi_col={mi_col} mode={dbg_mode} ref0={ref_frame} ref1=-1 mv0=({},{}) stack={} rng={}",
2264- mv.0,
2265- mv.1,
2266- stack.entries.len(),
2267- dec.debug_state().0
2268- );
2269- }
22702160 // lane-gm r2: the two libaom predicates single-ref GLOBALMV
22712161 // blocks need -- `is_global_mv_block` (blockd.h:421-429, mode
22722162 // GLOBAL* AND model > TRANSLATION AND min(bw,bh) >= 8px, gating
@@ -2279,13 +2169,6 @@ pub(super) fn decode_inter_block(
22792169 let is_global_mv_block = is_globalmv && gm_model as u8 > 1 && min_bw_bh4 >= 2;
22802170 let gm_nontrans =
22812171 is_globalmv && gm_model != ec_av1_syntax::WarpModel::Translation && min_bw_bh4 >= 2;
2282- if crate::envflags::env_flag!("EC_AV1_TELL") {
2283- eprintln!(
2284- "TELL mi_row={mi_row} mi_col={mi_col} label=post_assign_mv tell={} range={}",
2285- dec.debug_bitpos(),
2286- dec.debug_state().0
2287- );
2288- }
22892172 // lane-sb128 r4: `interintra` (spec 5.11.24; libaom
22902173 // `decodemv.c` read_inter_block_mode_info ~1490-1510), placed
22912174 // right after `assign_mv` and before `read_motion_mode` below --
@@ -2315,7 +2198,6 @@ pub(super) fn decode_inter_block(
23152198 // TRUE footprint -- a 16x8 strip is group 1, a 32x16 strip
23162199 // group 2, not their square `side`'s 2/3.
23172200 let bsize_group = size_group_wh(write_w, write_h);
2318- crate::msac::SymbolDecoder::set_symr_cdf("interintra");
23192201 let interintra = dec.symbol(&mut cdfs.interintra[bsize_group]) == 1;
23202202 if interintra {
23212203 // lane-interintra r1 (decodemv.c 1540-1555): interintra_mode,
@@ -2354,13 +2236,6 @@ pub(super) fn decode_inter_block(
23542236 super::wave::finish_tile(fctx, refpix, [&mut *y, &mut *u, &mut *v]);
23552237 }
23562238 }
2357- if crate::envflags::env_flag!("EC_AV1_TELL") {
2358- eprintln!(
2359- "TELL mi_row={mi_row} mi_col={mi_col} label=post_interintra tell={} range={}",
2360- dec.debug_bitpos(),
2361- dec.debug_state().0
2362- );
2363- }
23642239 // lane-motionmode round 1: `read_motion_mode` (spec 5.11.24;
23652240 // libaom `decodemv.c` read_inter_block_mode_info, ~1520-1528),
23662241 // placed right after MV assignment and before the switchable
@@ -2403,20 +2278,6 @@ pub(super) fn decode_inter_block(
24032278 // as aomdec's `EC_ISTEP2 name=motion_mode` -- an eligibility
24042279 // mismatch is otherwise invisible (a skipped symbol prints
24052280 // nothing).
2406- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
2407- eprintln!(
2408- "EC_MM mi_row={mi_row} mi_col={mi_col} w={write_w} h={write_h} elig={} \
2409- ab={} lf={} sw={} skipmode={} ii={} gmb={} rng={}",
2410- motion_mode_eligible as u8,
2411- overlappable_above(grid, mi_row, mi_col, bw4, mi_cols as usize, 1).len(),
2412- overlappable_left(grid, mi_row, mi_col, bh4, mi_rows as usize, 1).len(),
2413- switchable_motion_mode as u8,
2414- skip_mode as u8,
2415- interintra_mode.is_some() as u8,
2416- is_global_mv_block as u8,
2417- dec.debug_state().0,
2418- );
2419- }
24202281 let mut obmc_selected = false;
24212282 // lane-warp round 2: `Some` when motion_mode == WARPED_CAUSAL
24222283 // *and* the local warp estimate is valid (`!wm_params.invalid`,
@@ -2485,7 +2346,6 @@ pub(super) fn decode_inter_block(
24852346 let warp_eligible =
24862347 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
24872348 if warp_eligible {
2488- crate::msac::SymbolDecoder::set_symr_cdf("motion_mode");
24892349 let mode = dec.symbol(&mut cdfs.motion_mode[bsize_idx]);
24902350 match mode {
24912351 0 => {}
@@ -2505,18 +2365,6 @@ pub(super) fn decode_inter_block(
25052365 ref_frame,
25062366 fctx,
25072367 );
2508- if crate::envflags::env_flag!("EC_WARP_DEBUG") {
2509- eprintln!(
2510- "EC_WARP_DEBUG findSamples mi_row={mi_row} mi_col={mi_col} bsize={side} num_proj_ref={}",
2511- samples.len()
2512- );
2513- for (i, s) in samples.iter().enumerate() {
2514- eprintln!(
2515- "EC_WARP_DEBUG sample[{i}] pts={:?} pts_inref={:?}",
2516- s.pts1, s.pts2
2517- );
2518- }
2519- }
25202368 if samples.len() > 1 {
25212369 crate::warp::select_samples(
25222370 mv,
@@ -2537,21 +2385,6 @@ pub(super) fn decode_inter_block(
25372385 mi_row as i32,
25382386 mi_col as i32,
25392387 );
2540- if crate::envflags::env_flag!("EC_WARP_DEBUG") {
2541- eprintln!(
2542- "EC_WARP_DEBUG projection mi_row={mi_row} mi_col={mi_col} num_proj_ref(final)={} mv=({},{}) params={:?}",
2543- samples.len(),
2544- mv.0,
2545- mv.1,
2546- warp_params
2547- );
2548- for (i, s) in samples.iter().enumerate() {
2549- eprintln!(
2550- "EC_WARP_DEBUG sample_used[{i}] pts={:?} pts_inref={:?}",
2551- s.pts1, s.pts2
2552- );
2553- }
2554- }
25552388 }
25562389 }
25572390 } else {
@@ -2561,18 +2394,6 @@ pub(super) fn decode_inter_block(
25612394 // motion_mode vs 2-symbol obmc) and the range after -- the
25622395 // two give the same value with a different narrowing (class
25632396 // wrong-alphabet-same-value).
2564- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
2565- eprintln!(
2566- "EC_MM2 mi_row={mi_row} mi_col={mi_col} row={bsize_idx} warp_elig={} \
2567- scaled={} fimv={} obmc={} warped={} rng={}",
2568- warp_eligible as u8,
2569- ref_is_scaled as u8,
2570- force_integer_mv as u8,
2571- obmc_selected as u8,
2572- warped_selected as u8,
2573- dec.debug_state().0,
2574- );
2575- }
25762397 }
25772398 // lane-gm r4: `allow_warp`'s `global_warp_allowed` branch
25782399 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
@@ -2604,14 +2425,6 @@ pub(super) fn decode_inter_block(
26042425 // (`warp::warp_round_0`, 5 at 12 bits) and the six-frame 12-bit
26052426 // warp stream decodes byte-exact vs ffmpeg
26062427 // (`a_12bit_warped_motion_stream_decodes_pixel_exact`).
2607- if crate::envflags::env_flag!("EC_AV1_TELL") {
2608- eprintln!(
2609- "TELL mi_row={mi_row} mi_col={mi_col} label=post_motion_mode eligible={} tell={} range={}",
2610- motion_mode_eligible as u8,
2611- dec.debug_bitpos(),
2612- dec.debug_state().0
2613- );
2614- }
26152428 // spec `get_ref_filter_type`: a neighbour's own filter only feeds
26162429 // this block's switchable_interp context when that neighbour coded
26172430 // the SAME reference frame this block is about to read -- a
@@ -2649,26 +2462,6 @@ pub(super) fn decode_inter_block(
26492462 );
26502463 block_filter = resolved_filter;
26512464 globalmv_for_lf = is_globalmv;
2652- if crate::envflags::env_flag!("EC_AV1_TELL") {
2653- eprintln!(
2654- "TELL mi_row={mi_row} mi_col={mi_col} label=post_interp_filter tell={} range={}",
2655- dec.debug_bitpos(),
2656- dec.debug_state().0
2657- );
2658- }
2659- if crate::envflags::env_flag!("EC_AV1_TRACE") {
2660- eprintln!(
2661- "EC_TRACE mi_row={mi_row} mi_col={mi_col} skip={} is_inter=1 mv=({},{}) is_new_mv={is_new_mv} bsize={side} ref={ref_frame} filter={:?} motion_mode_eligible={} obmc_selected={} warped={} tell={}",
2662- skip as u8,
2663- mv.0,
2664- mv.1,
2665- block_filter,
2666- motion_mode_eligible as u8,
2667- obmc_selected as u8,
2668- warp_params.is_some() as u8,
2669- dec.debug_bitpos()
2670- );
2671- }
26722465 // lane-rect r2: see the compound path's matching comment above --
26732466 // `grid` must be stamped with the block's true bh4/bw4 span, not
26742467 // a square `bw4`x`bw4` guess.
@@ -3076,7 +2869,23 @@ pub(super) fn decode_inter_block(
30762869 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
30772870 let (sy, su, sv) = if pred_deferred(refpix) {
30782871 push_pred(build);
3079- (Pred::Cur { plane: 0, stride: side, off: 0 }, Pred::Cur { plane: 1, stride: chroma_stride, off: 0 }, Pred::Cur { plane: 2, stride: chroma_stride, off: 0 })
2872+ (
2873+ Pred::Cur {
2874+ plane: 0,
2875+ stride: side,
2876+ off: 0,
2877+ },
2878+ Pred::Cur {
2879+ plane: 1,
2880+ stride: chroma_stride,
2881+ off: 0,
2882+ },
2883+ Pred::Cur {
2884+ plane: 2,
2885+ stride: chroma_stride,
2886+ off: 0,
2887+ },
2888+ )
30802889 } else {
30812890 let mut built: [Vec<u16>; 3] = Default::default();
30822891 build(y, u, v, refpix, fctx, &mut built);
@@ -3241,9 +3050,7 @@ pub(super) fn decode_inter_block(
32413050 // extent is the strip's own. Counted so a 4:4:4 1:4-strip
32423051 // gate can prove it exercised this route (a 4:2:0 stream
32433052 // of the same content reads 0).
3244- Some(_) if ss_x(fctx) == 0 => {
3245- around
3246- }
3053+ Some(_) if ss_x(fctx) == 0 => around,
32473054 Some(s) if s.has_chroma => {
32483055 let (pw, ph) = if s.horz {
32493056 if ss_y(fctx) == 0 { (16, 4) } else { (16, 8) }
@@ -3945,15 +3752,6 @@ pub(super) fn decode_inter_block(
39453752 // equivalent post-content point (added at the matching call site)
39463753 // narrows the ladder to this block's own tail instead of the next
39473754 // block's partition read.
3948- if crate::envflags::env_flag!("EC_AV1_TELL") {
3949- eprintln!(
3950- "TELL mi_row={} mi_col={} label=block_end tell={} range={}",
3951- rmi,
3952- cmi,
3953- dec.debug_bitpos(),
3954- dec.debug_state().0
3955- );
3956- }
39573755 // lane-inter16ab r2: the pair's chroma coefficient context spans BOTH
39583756 // strips (mirroring the intra `decode_rect4_16` path), and the even
39593757 // strip's own record wrote empty chroma state over those cells -- this
crates/ec-av1/src/decode/inter_block8.rsmodified+34 -143
@@ -160,8 +160,6 @@ pub(super) fn decode_inter_block8(
160160 // entry sets the same label from ITS `at`, which is a different block --
161161 // publishing from here is what makes the EC_SYMR mi trustworthy on the
162162 // inter path, which is what round 22 got wrong by assuming it was not.
163- crate::msac::SymbolDecoder::set_symr_phase("inter8");
164- crate::msac::SymbolDecoder::set_symr_mi(leaf_mi.0 as i64, leaf_mi.1 as i64);
165163 const LAST_FRAME: i8 = 1;
166164 // lane-gmaffine r2: the leaf's OWN switchable-filter symbols, handed back
167165 // so the caller stamps them into `Neighbours` instead of the `[3, 3]`
@@ -261,14 +259,6 @@ pub(super) fn decode_inter_block8(
261259 // lane-inter8 r1: mirrors the oracle's `EC_MODE` (instrument rung 4,
262260 // `read_inter_block_mode_info`) so an 8x8 leaf's mode-info range ladder
263261 // diffs line for line against a real aomdec.
264- if crate::envflags::env_flag!("EC_TRACE_MODE") {
265- eprintln!(
266- "EC_MODE mi_row={} mi_col={} rng={}",
267- leaf_mi.0,
268- leaf_mi.1,
269- dec.debug_state().0
270- );
271- }
272262
273263 let mode_for_tx;
274264 // lane-uv8 r1: this leaf's chroma prediction mode (`get_uv_mode` of the
@@ -379,18 +369,6 @@ pub(super) fn decode_inter_block8(
379369 comp_stack.ref_mv_ctx,
380370 )
381371 };
382- if crate::envflags::env_flag!("EC_TRACE_MODE") {
383- eprintln!(
384- "EC_LEAFMODE mi_row={} mi_col={} cmode={} stack={} newmv_ctx={} refmv_ctx={} rng={}",
385- leaf_mi.0,
386- leaf_mi.1,
387- compound_mode + 17,
388- comp_stack.entries.len(),
389- comp_stack.new_mv_ctx,
390- comp_stack.ref_mv_ctx,
391- dec.debug_state().0
392- );
393- }
394372 let (mv0, mv1) = assign_compound_mv(
395373 dec,
396374 cdfs,
@@ -409,19 +387,6 @@ pub(super) fn decode_inter_block8(
409387 // lane-inter8 r3: byte-format-identical to the oracle's
410388 // rung-4 `EC_MODE_VAL`, so the leaf's mode+mv VALUE ladder
411389 // diffs line for line against a real aomdec.
412- if crate::envflags::env_flag!("EC_TRACE_MODE") {
413- eprintln!(
414- "EC_MODE_VAL mi_row={} mi_col={} mode={} ref0={} ref1={} mv0=({},{}) rng={}",
415- leaf_mi.0,
416- leaf_mi.1,
417- compound_mode + 17,
418- ref0,
419- ref1,
420- mv0.0,
421- mv0.1,
422- dec.debug_state().0
423- );
424- }
425390
426391 // spec 5.11.25: same gating [`decode_inter_block`]'s own
427392 // compound arm uses, keyed off `outer_at`'s [`SUB`]-grid
@@ -432,7 +397,6 @@ pub(super) fn decode_inter_block8(
432397 && enable_masked_compound
433398 && is_any_masked_compound_used_here(SIDE, SIDE)
434399 {
435- crate::msac::SymbolDecoder::set_symr_cdf("comp_group_idx");
436400 dec.symbol(&mut cdfs.comp_group_idx[group_ctx])
437401 } else {
438402 0
@@ -485,7 +449,6 @@ pub(super) fn decode_inter_block8(
485449 ref_order_hints[(ref0 - LAST_FRAME) as usize],
486450 ref_order_hints[(ref1 - LAST_FRAME) as usize],
487451 );
488- crate::msac::SymbolDecoder::set_symr_cdf("compound_idx");
489452 let idx = dec.symbol(&mut cdfs.compound_idx[idx_ctx]);
490453 if idx == 1 {
491454 (8, 8, 1u8)
@@ -502,16 +465,6 @@ pub(super) fn decode_inter_block8(
502465 (8, 8, 1u8)
503466 };
504467 compound_ctx8 = Some((ref0, ref1, comp_group_idx as u8, compound_idx));
505- if crate::envflags::env_flag!("EC_AV1_COMPIDX_DUMP") {
506- eprintln!(
507- "EC_COMPIDX mi_row={mi_row} mi_col={mi_col} bsize=8 mode={compound_mode} mv0=({},{}) mv1=({},{}) ref0={ref0} ref1={ref1} comp_group_idx={comp_group_idx} compound_idx={compound_idx} tell={}",
508- mv0.0,
509- mv0.1,
510- mv1.0,
511- mv1.1,
512- dec.debug_bitpos()
513- );
514- }
515468
516469 // lane-interp3 r1: `read_mb_interp_filter` (libaom
517470 // `decodemv.c` 1575, the tail of
@@ -981,7 +934,23 @@ pub(super) fn decode_inter_block8(
981934 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
982935 let (sy, su, sv) = if pred_deferred(refpix) {
983936 push_pred(build);
984- (Pred::Cur { plane: 0, stride: SIDE, off: 0 }, Pred::Cur { plane: 1, stride: chroma_w, off: 0 }, Pred::Cur { plane: 2, stride: chroma_w, off: 0 })
937+ (
938+ Pred::Cur {
939+ plane: 0,
940+ stride: SIDE,
941+ off: 0,
942+ },
943+ Pred::Cur {
944+ plane: 1,
945+ stride: chroma_w,
946+ off: 0,
947+ },
948+ Pred::Cur {
949+ plane: 2,
950+ stride: chroma_w,
951+ off: 0,
952+ },
953+ )
985954 } else {
986955 let mut built: [Vec<u16>; 3] = Default::default();
987956 build(y, u, v, refpix, fctx, &mut built);
@@ -1380,14 +1349,6 @@ pub(super) fn decode_inter_block8(
13801349 // lane-interp3 r2: same per-entry EC_STACK ladder
13811350 // [`decode_inter_block`]'s single-ref arm prints, so this leaf's stack
13821351 // diffs line for line against the oracle's.
1383- if crate::envflags::env_flag!("EC_TRACE_MODE") {
1384- for (i, e) in stack.entries.iter().enumerate() {
1385- eprintln!(
1386- "EC_STACK mi_row={mi_row} mi_col={mi_col} ref={ref_frame} i={i} this=({},{}) comp=(0,0) w={}",
1387- e.mv.0, e.mv.1, e.weight
1388- );
1389- }
1390- }
13911352
13921353 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
13931354 let mut is_globalmv = false;
@@ -1448,7 +1409,6 @@ pub(super) fn decode_inter_block8(
14481409 let mut interintra_mode: Option<u8> = None;
14491410 let mut wedge_mask: Option<(&'static [u8], usize)> = None;
14501411 if enable_interintra_compound && !skip_mode {
1451- crate::msac::SymbolDecoder::set_symr_cdf("interintra");
14521412 let interintra = dec.symbol(&mut cdfs.interintra[SIZE_GROUP_8]) == 1;
14531413 if interintra {
14541414 // lane-interintra r1: same read pair as the 16/32 site;
@@ -1543,14 +1503,7 @@ pub(super) fn decode_inter_block8(
15431503 let ref_is_scaled = !scale_of((ref_width, ref_height), frame_size).is_unscaled();
15441504 let warp_eligible =
15451505 allow_warped_motion && !ref_is_scaled && !force_integer_mv && proj_ok;
1546- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
1547- eprintln!(
1548- "EC_MM8 mi_row={mi_row} mi_col={mi_col} proj={} warp_elig={} awm={}",
1549- proj_ok as u8, warp_eligible as u8, allow_warped_motion as u8
1550- );
1551- }
15521506 if warp_eligible {
1553- crate::msac::SymbolDecoder::set_symr_cdf("motion_mode");
15541507 let mode = dec.symbol(&mut cdfs.motion_mode[0]);
15551508 match mode {
15561509 0 => {}
@@ -1630,17 +1583,6 @@ pub(super) fn decode_inter_block8(
16301583 false,
16311584 );
16321585 leaf_filter_syms = resolved_filter;
1633- if crate::envflags::env_flag!("EC_TRACE_MODE") {
1634- eprintln!(
1635- "EC_MODE_VAL8 mi_row={} mi_col={} newmv={is_new_mv} globalmv={is_globalmv} ref0={ref_frame} mv0=({},{}) stack={} rng={}",
1636- leaf_mi.0,
1637- leaf_mi.1,
1638- mv.0,
1639- mv.1,
1640- stack.entries.len(),
1641- dec.debug_state().0
1642- );
1643- }
16441586 // lane-gmaffine r1: `allow_warp`'s `global_warp_allowed` branch
16451587 // (`reconinter.c:33-55`), gated INDEPENDENTLY of `motion_mode` --
16461588 // see [`decode_inter_block`]'s own copy. A local WARPED_CAUSAL model
@@ -1654,14 +1596,6 @@ pub(super) fn decode_inter_block8(
16541596 // `warp_params` set here; the 12-bit refusal that stood here is
16551597 // lifted with the same witness (`warp::warp_round_0` moved the
16561598 // filter's shifts; the same stream decodes byte-exact vs ffmpeg).
1657- if crate::envflags::env_flag!("EC_TRACE_MODE") {
1658- eprintln!(
1659- "EC_WARP8 mi_row={} mi_col={} warp={} globalblk={is_global_mv_block}",
1660- leaf_mi.0,
1661- leaf_mi.1,
1662- warp_params.is_some(),
1663- );
1664- }
16651599 grid.fill_rect(
16661600 mi_row,
16671601 mi_col,
@@ -1901,7 +1835,23 @@ pub(super) fn decode_inter_block8(
19011835 let (pred_y, pred_u, pred_v): (Vec<u16>, Vec<u16>, Vec<u16>);
19021836 let (sy, su, sv) = if pred_deferred(refpix) {
19031837 push_pred(build);
1904- (Pred::Cur { plane: 0, stride: SIDE, off: 0 }, Pred::Cur { plane: 1, stride: chroma_w, off: 0 }, Pred::Cur { plane: 2, stride: chroma_w, off: 0 })
1838+ (
1839+ Pred::Cur {
1840+ plane: 0,
1841+ stride: SIDE,
1842+ off: 0,
1843+ },
1844+ Pred::Cur {
1845+ plane: 1,
1846+ stride: chroma_w,
1847+ off: 0,
1848+ },
1849+ Pred::Cur {
1850+ plane: 2,
1851+ stride: chroma_w,
1852+ off: 0,
1853+ },
1854+ )
19051855 } else {
19061856 // The interintra predictor reads this block's own above/left
19071857 // edges, which are already written at this point.
@@ -2123,7 +2073,6 @@ pub(super) fn decode_inter_block8(
21232073 }
21242074 }
21252075 } else {
2126- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
21272076 let mode = dec.symbol(&mut cdfs.y_mode[SIZE_GROUP_8]);
21282077 if mode >= 13 {
21292078 return Err(unsupported(
@@ -2172,21 +2121,10 @@ pub(super) fn decode_inter_block8(
21722121 let uv_mode = if !has_chroma {
21732122 DC_PRED
21742123 } else if cfl_allowed_px(SIDE, SIDE, fctx) {
2175- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
21762124 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
21772125 } else {
2178- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
21792126 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
21802127 };
2181- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
2182- eprintln!(
2183- "EC_ISTEP8 mi_row={} mi_col={} name=modes y={mode} uv={uv_mode} fi_enabled={} rng={}",
2184- leaf_mi.0,
2185- leaf_mi.1,
2186- fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
2187- dec.debug_state().0
2188- );
2189- }
21902128 let alpha = if has_chroma && uv_mode == UV_CFL_PRED {
21912129 Some(read_cfl_alphas(dec, cdfs))
21922130 } else {
@@ -2238,16 +2176,6 @@ pub(super) fn decode_inter_block8(
22382176 let use_palette_uv = has_chroma
22392177 && uv_mode == DC_PRED
22402178 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
2241- if crate::envflags::env_flag!("EC_PALSYN") {
2242- eprintln!(
2243- "EC_PALSYN leaf8 mi={},{} bw=8 bh=8 mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
2244- leaf_mi.0,
2245- leaf_mi.1,
2246- palette_y_pending.map_or(0, |(n, _)| n),
2247- u8::from(use_palette_uv),
2248- dec.debug_state().0
2249- );
2250- }
22512179 if use_palette_uv {
22522180 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
22532181 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
@@ -2267,7 +2195,6 @@ pub(super) fn decode_inter_block8(
22672195 // prints `use_filter_intra` for an intra block inside an INTER frame
22682196 // and nothing else, so this leaf needs the same two lines for a
22692197 // range-ladder diff against it.
2270- let ec_istep8 = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
22712198 if mode == DC_PRED
22722199 && fctx.enable_filter_intra_inter.with(std::cell::Cell::get)
22732200 // `av1_filter_intra_allowed` (reconintra.h:77) excludes a
@@ -2276,25 +2203,8 @@ pub(super) fn decode_inter_block8(
22762203 && let Some(class) = filter_intra_size_class(SIDE)
22772204 {
22782205 let use_fi = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
2279- if ec_istep8 {
2280- eprintln!(
2281- "EC_ISTEP mi_row={} mi_col={} name=use_filter_intra val={} rng={}",
2282- leaf_mi.0,
2283- leaf_mi.1,
2284- u8::from(use_fi),
2285- dec.debug_state().0
2286- );
2287- }
22882206 if use_fi {
22892207 let fi = dec.symbol(&mut cdfs.filter_intra_mode);
2290- if ec_istep8 {
2291- eprintln!(
2292- "EC_ISTEP mi_row={} mi_col={} name=filter_intra_mode val={fi} rng={}",
2293- leaf_mi.0,
2294- leaf_mi.1,
2295- dec.debug_state().0
2296- );
2297- }
22982208 filter_intra = Some(fi);
22992209 }
23002210 }
@@ -2448,10 +2358,6 @@ pub(super) fn decode_inter_block8(
24482358 read_plane(
24492359 dec,
24502360 cdfs,
2451- // Intra 4x4 luma: seven-type
2452- // `EXT_TX_SET_DTT4_IDTX_1DDCT` unless reduced, whose
2453- // CDF row is the intra dir (`fi_tx_row` inside
2454- // `read_plane` maps a filter-intra block's).
24552361 txbset_for(tx_px, reduced_tx_set),
24562362 default_scan(tx_px),
24572363 0,
@@ -2467,7 +2373,6 @@ pub(super) fn decode_inter_block8(
24672373 tu_py,
24682374 tx_px,
24692375 tx_px,
2470- base_q_idx,
24712376 None,
24722377 filter_intra,
24732378 Some(tu_skip_ctx),
@@ -2566,14 +2471,6 @@ pub(super) fn decode_inter_block8(
25662471 read_plane(
25672472 dec,
25682473 cdfs,
2569- // lane-uv8 r3: an intra leaf inside an inter frame is
2570- // `is_inter == 0` in `av1_get_ext_tx_set_type`, so its 8x8
2571- // luma reads the INTRA set -- seven-type
2572- // `EXT_TX_SET_DTT4_IDTX_1DDCT` when `reduced_tx_set == 0`,
2573- // five-type `EXT_TX_SET_DTT4_IDTX` when it is 1. Hardcoding
2574- // the reduced set read the wrong ALPHABET (class
2575- // [[wrong-alphabet-same-value]]) and desynced at the leaf's
2576- // first `tx_type`.
25772474 txbset_for(8, reduced_tx_set),
25782475 scan8,
25792476 0,
@@ -2589,7 +2486,6 @@ pub(super) fn decode_inter_block8(
25892486 py,
25902487 SIDE,
25912488 TX8,
2592- base_q_idx,
25932489 None,
25942490 filter_intra,
25952491 None,
@@ -2636,7 +2532,6 @@ pub(super) fn decode_inter_block8(
26362532 cdfs,
26372533 neighbours,
26382534 leaf_mi,
2639- (px, py),
26402535 (cpx, cpy),
26412536 SIDE,
26422537 (chroma_w, chroma_h),
@@ -2644,13 +2539,11 @@ pub(super) fn decode_inter_block8(
26442539 (chroma_w, chroma_h),
26452540 chroma_w,
26462541 reach,
2647- (y.width, y.height),
26482542 mode,
26492543 uv_predict_mode,
26502544 angle_delta_uv,
26512545 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
26522546 smooth_neighbor_uv,
2653- base_q_idx,
26542547 &mut uo,
26552548 &mut vo,
26562549 fctx,
@@ -2713,7 +2606,6 @@ pub(super) fn decode_inter_block8(
27132606 cpy,
27142607 chroma_w,
27152608 chroma_tx,
2716- base_q_idx,
27172609 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
27182610 None,
27192611 None,
@@ -2767,7 +2659,6 @@ pub(super) fn decode_inter_block8(
27672659 cpy,
27682660 chroma_w,
27692661 chroma_tx,
2770- base_q_idx,
27712662 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
27722663 None,
27732664 None,
crates/ec-av1/src/decode/inter_ctx.rsmodified+5 -328
@@ -64,31 +64,13 @@ pub(super) fn resolve_interp_filter(
6464 // `h_kind`/`v_kind` argument order, which is why this function returns
6565 // `(h, v, ..)` but reads `dir0` (`v`) before `dir1` (`h`).
6666 let ctx0 = switchable_interp_ctx(above[0], left[0], 0, is_compound);
67- if crate::envflags::env_flag!("EC_AV1_IFDBG") {
68- eprintln!(
69- "IFDBG dir=0 ctx={ctx0} above={above:?} left={left:?} cdf={:?}",
70- &cdfs.switchable_interp[ctx0][..3]
71- );
72- }
7367 let sym0 = dec.symbol(&mut cdfs.switchable_interp[ctx0]) as u8;
7468 let sym1 = if enable_dual_filter {
7569 let ctx1 = switchable_interp_ctx(above[1], left[1], 1, is_compound);
76- if crate::envflags::env_flag!("EC_AV1_IFDBG") {
77- eprintln!(
78- "IFDBG dir=1 ctx={ctx1} above={above:?} left={left:?} cdf={:?} sym0={sym0}",
79- &cdfs.switchable_interp[ctx1][..3]
80- );
81- }
8270 dec.symbol(&mut cdfs.switchable_interp[ctx1]) as u8
8371 } else {
8472 sym0
8573 };
86- if crate::envflags::env_flag!("EC_TRACE_MODE") {
87- eprintln!(
88- "EC_IF ctx0={ctx0} above={above:?} left={left:?} sym0={sym0} sym1={sym1} rng={}",
89- dec.debug_state().0
90- );
91- }
9274 (
9375 mc::InterpFilterKind::from_switchable_symbol(sym1 as usize),
9476 mc::InterpFilterKind::from_switchable_symbol(sym0 as usize),
@@ -293,13 +275,6 @@ pub(super) fn read_intrabc_dv(
293275 true,
294276 fctx,
295277 );
296- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
297- let (rng, _) = dec.debug_state();
298- eprintln!(
299- "EC_DV mi_row={mi_r} mi_col={mi_c} dv_col={} dv_row={} rng={rng}",
300- dv.1, dv.0
301- );
302- }
303278 dv
304279 }
305280
@@ -331,7 +306,6 @@ impl PlaneBuf<'_> {
331306 &mut self,
332307 x: usize,
333308 y: usize,
334- plane: usize,
335309 side: usize,
336310 w: usize,
337311 h: usize,
@@ -359,13 +333,6 @@ impl PlaneBuf<'_> {
359333 // prediction is byte-identical to the oracle's and whose committed
360334 // samples are not can only be a DIFFERENT WRITE -- and this is the
361335 // only write path with no rung of its own.
362- if crate::envflags::env_flag!("EC_MCWR") {
363- eprintln!(
364- "EC_MCWR x={x} y={y} side={side} w={w} h={h} empty_res={} at {}",
365- residual.is_empty(),
366- std::panic::Location::caller()
367- );
368- }
369336 // lane-av1444altref r2: EC_CPRED, the picture-independent twin of the
370337 // oracle's rung of the same name (aomdec's
371338 // `dec_build_inter_predictor`). This is the ONE site every inter
@@ -376,33 +343,6 @@ impl PlaneBuf<'_> {
376343 // pictures, so a rung line alone is ambiguous, but a geometry whose
377344 // samples differ by at most 1 is a unique match (any wrong pairing
378345 // differs by tens).
379- // Env: EC_CPRED="x:y" (plane-absolute origin; -1 for either = any).
380- if let Ok(spec) = crate::envflags::var("EC_CPRED") {
381- let (fx, fy): (i64, i64) = spec
382- .split_once(':')
383- .and_then(|(a, b)| Some((a.trim().parse().ok()?, b.trim().parse().ok()?)))
384- .unwrap_or((-1, -1));
385- let hit = (fx < 0 || fx == x as i64) && (fy < 0 || fy == y as i64);
386- if hit {
387- // `PREFILT_PICTURE_IDX` is bumped once per frame just AFTER
388- // that frame's last block, so it still reads this frame's own
389- // decode-order index here -- the same numbering the oracle's
390- // `aom_ec_pict_idx` and the `.fN` prefilter dumps use.
391- let pict = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst);
392- eprintln!(
393- "OUR_CPRED pict={pict} plane={plane} x={x} y={y} w={w} h={h} side={side}"
394- );
395- for row in 0..h {
396- let src = &prediction[row * side..row * side + w];
397- let mut line = String::with_capacity(w * 4);
398- for v in src {
399- line.push(' ');
400- line.push_str(&v.to_string());
401- }
402- eprintln!("OUR_CPROW{row}:{line}");
403- }
404- }
405- }
406346 // lane-recoparse: an all-zero residual (60% of the units) is a plain
407347 // prediction copy -- the same arithmetic with `r == 0`, without
408348 // reading `side * h` zeros out of [`ZERO_RESIDUAL`].
@@ -412,9 +352,8 @@ impl PlaneBuf<'_> {
412352 let dst = (y + row) * self.width + x;
413353 let pred = &prediction[src..src + w];
414354 let out = &mut self.data.to_mut()[dst..dst + w];
415- for (col, (o, &p)) in out.iter_mut().zip(pred).enumerate() {
355+ for (o, &p) in out.iter_mut().zip(pred) {
416356 let v = i32::from(p).clamp(0, max) as u16;
417- pix_write("mc_copy", x, y, w, x + col, y + row, *o, v);
418357 *o = v;
419358 }
420359 }
@@ -427,9 +366,8 @@ impl PlaneBuf<'_> {
427366 let pred = &prediction[src..src + w];
428367 let res = &residual[src..src + w];
429368 let out = &mut self.data.to_mut()[dst..dst + w];
430- for (col, ((o, &p), &r)) in out.iter_mut().zip(pred).zip(res).enumerate() {
369+ for ((o, &p), &r) in out.iter_mut().zip(pred).zip(res) {
431370 let v = (i32::from(p) + r).clamp(0, max) as u16;
432- pix_write("mc_add", x, y, w, x + col, y + row, *o, v);
433371 *o = v;
434372 }
435373 }
@@ -521,12 +459,6 @@ pub(super) fn read_inter_plane(
521459 default_tx_type,
522460 None,
523461 )?;
524- note_chroma_class1(plane_idx, tx_type);
525- if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
526- eprintln!(
527- "OUR_TXTYPE plane={plane_idx} x={x} y={cy} side={side} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}"
528- );
529- }
530462 // lane-inter8 r1: a 64-point transform covers the whole 64x64 area but
531463 // codes only its top-left 32x32 of frequencies (spec 5.11.40) -- the
532464 // caller hands the 32-point `scan` there, and the coded corner goes into
@@ -572,7 +504,6 @@ pub(super) fn read_intra_chroma_lossless(
572504 cdfs: &mut Cdfs,
573505 neighbours: &mut Neighbours,
574506 at_mi: (usize, usize),
575- (px, py): (usize, usize),
576507 (cpx, cpy): (usize, usize),
577508 side: usize,
578509 (blk_w, blk_h): (usize, usize),
@@ -580,13 +511,11 @@ pub(super) fn read_intra_chroma_lossless(
580511 (reg_w, reg_h): (usize, usize),
581512 stride: usize,
582513 reach: Reach,
583- (frame_w, frame_h): (usize, usize),
584514 mode: usize,
585515 uv_predict_mode: usize,
586516 angle_delta_uv: i32,
587517 palette_uv_bufs: Option<(&[u16], &[u16])>,
588518 smooth_neighbor_uv: bool,
589- base_q_idx: u8,
590519 u_out: &mut Vec<i32>,
591520 v_out: &mut Vec<i32>,
592521 fctx: &crate::decode::FrameCtx,
@@ -629,11 +558,6 @@ pub(super) fn read_intra_chroma_lossless(
629558 4 << ss_x(fctx),
630559 4 << ss_y(fctx),
631560 reach,
632- px,
633- py,
634- frame_w,
635- frame_h,
636- fctx,
637561 );
638562 if let Some((ub, vb)) = palette_uv_bufs {
639563 let buf = if plane_idx == 1 { ub } else { vb };
@@ -657,7 +581,6 @@ pub(super) fn read_intra_chroma_lossless(
657581 cpy + oy,
658582 4,
659583 4,
660- base_q_idx,
661584 None,
662585 None,
663586 offset,
@@ -778,7 +701,6 @@ pub(super) fn read_inter_chroma_lossless(
778701 // lane-av1h5: a plane block above 64 is the 128-root class, whose chroma
779702 // libaom walks one 64x64 mu chunk at a time. Counted so a gate can pin
780703 // the walk/unit totals exactly rather than as a floor on wrong output.
781- let counted_128 = blk_w > 64 || blk_h > 64;
782704 for plane_idx in 1..3 {
783705 for rr in 0..reg_h / 4 {
784706 for cc in 0..reg_w / 4 {
@@ -1001,8 +923,7 @@ pub(super) fn read_single_ref(
1001923 if p4 == 1 { LAST2_FRAME } else { LAST_FRAME }
1002924 }
1003925 };
1004- if ref_frame != LAST_FRAME {
1005- }
926+ if ref_frame != LAST_FRAME {}
1006927 ref_frame
1007928 }
1008929
@@ -1042,9 +963,8 @@ pub(crate) struct RefPix<'p> {
1042963 #[derive(Clone)]
1043964 pub(crate) struct SharedRefs {
1044965 pub(crate) dims: [Option<(usize, usize)>; 8],
1045- pub(crate) wait: std::sync::Arc<
1046- dyn Fn() -> Result<[Option<std::sync::Arc<Picture>>; 8]> + Send + Sync,
1047- >,
966+ pub(crate) wait:
967+ std::sync::Arc<dyn Fn() -> Result<[Option<std::sync::Arc<Picture>>; 8]> + Send + Sync>,
1048968 }
1049969
1050970 /// Where a [`RefPix`] gets its pictures: already in hand, or behind a wait
@@ -1179,12 +1099,6 @@ impl<'p> RefPix<'p> {
11791099 /// (lane-defer8).
11801100 pub(super) fn ref_dims(ref_frame: i8, refpix: &RefPix<'_>) -> Result<(usize, usize)> {
11811101 refpix.dims(ref_frame).ok_or_else(|| {
1182- if crate::envflags::env_flag!("EC_AV1_REFPROBE") {
1183- eprintln!(
1184- "EC_REFPROBE missing ref {ref_frame}\n{}",
1185- std::backtrace::Backtrace::force_capture()
1186- );
1187- }
11881102 // lane-hdrlossless: libaom errors on the same stream
11891103 // (`decodeframe.c:5027`: `if (cm->ref_frame_map[ref] == NULL)
11901104 // aom_internal_error(... AOM_CODEC_CORRUPT_FRAME, "Inter frame
@@ -1475,23 +1389,6 @@ pub(crate) fn has_overlappable_neighbour(
14751389 || !overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, 1).is_empty()
14761390 }
14771391
1478-/// The warp-sample gather's own `has_top_right` probe (libaom `av1_findSamples`
1479-/// calls the same `mvref_common.c` function the MV stack does). lane-sb128 r2:
1480-/// this used to hardcode `SB_MI` (a 64x64 superblock) -- at `sb_size == 128`
1481-/// libaom's mask loop runs one level further and strips the top-right sample
1482-/// off blocks whose neighbour IS decoded, so a warped 128-superblock frame
1483-/// picked up wrong warp parameters (frame 6 of the 128 inter gate). Delegates
1484-/// to the single sb-aware port in [`crate::mvstack::has_top_right`]; `bs` is
1485-/// the block's own side in 4x4 (`mi`) units (square inter leaves only here).
1486-pub(super) fn has_top_right(
1487- mi_row: usize,
1488- mi_col: usize,
1489- bs: usize,
1490- fctx: &crate::decode::FrameCtx,
1491-) -> bool {
1492- crate::mvstack::has_top_right(mi_row, mi_col, bs, bs, fctx)
1493-}
1494-
14951392 /// `av1_findSamples` (`mvref_common.c`), full port: the up to
14961393 /// `LEAST_SQUARES_SAMPLES_MAX` (8) above/left/top-left/top-right neighbour
14971394 /// samples (`record_samples`) that share this block's own single reference
@@ -1523,16 +1420,8 @@ pub(crate) fn find_samples(
15231420 // motion_mode alphabet over the 2-symbol obmc one.
15241421 // lane-alloc: the `format!` (and the map lookup's `String` clone) ran on
15251422 // every warp block; the flag itself is a process constant.
1526- let proj_dbg = crate::envflags::env_flag!("EC_PROJ_MI")
1527- && crate::envflags::var("EC_PROJ_MI").is_ok_and(|v| v == format!("{mi_row},{mi_col}"));
15281423 let single_ref_match = |info: &MiInfo| {
15291424 let m = info.ref_frame == ref_frame && info.ref_frame1 == NO_REF1;
1530- if proj_dbg {
1531- eprintln!(
1532- "EC_PROJ cand ref={} ref1={:?} size={} size_h={} is_inter={} want={ref_frame} match={m}",
1533- info.ref_frame, info.ref_frame1, info.size, info.size_h, info.is_inter
1534- );
1535- }
15361425 m
15371426 };
15381427 let mut do_tl = true;
@@ -1754,46 +1643,6 @@ pub(super) fn neighbour_filter(
17541643 ))
17551644 }
17561645
1757-/// lane-obmcrec r1 MEASUREMENT rung (`EC_OBMCREC=1`): every OBMC neighbour whose
1758-/// recorded switchable-filter symbols are the `[3, 3]` "never recorded" sentinel
1759-/// -- names the neighbour's own position/shape/reference so the decode path that
1760-/// failed to record its filter can be identified. Read-only, off by default.
1761-#[allow(clippy::too_many_arguments)]
1762-fn obmcrec_probe(
1763- dir: &str,
1764- mi_row: usize,
1765- mi_col: usize,
1766- write_w: usize,
1767- write_h: usize,
1768- off4: usize,
1769- span4: usize,
1770- nb: &MiInfo,
1771- syms: [u8; 2],
1772- cell: Option<MiInfo>,
1773- fixed: bool,
1774-) {
1775- if (syms[0] <= 2 && syms[1] <= 2) || !crate::envflags::env_flag!("EC_OBMCREC") {
1776- return;
1777- }
1778- eprintln!(
1779- "OBMCREC {dir} cur_mi=({mi_row},{mi_col}) cur_wh=({write_w}x{write_h}) off4={off4} \
1780-span4={span4} syms={syms:?} fixed={fixed} nb_size=({}x{}) nb_ref={} nb_ref1={:?} nb_mv=({},{}) \
1781-nb_newmv={} cell_size={:?} cell_inter={:?} cell_ref={:?} sb_row_off={} sb_col_off={}",
1782- nb.size * 4,
1783- nb.size_h * 4,
1784- nb.ref_frame,
1785- nb.ref_frame1,
1786- nb.mv.0,
1787- nb.mv.1,
1788- nb.is_new_mv,
1789- cell.map(|c| (c.size * 4, c.size_h * 4)),
1790- cell.map(|c| c.is_inter),
1791- cell.map(|c| c.ref_frame),
1792- mi_row % 32,
1793- mi_col % 32,
1794- );
1795-}
1796-
17971646 /// One neighbour's own re-prediction over a `w`x`h` region, MC'd fresh
17981647 /// against its own `mv`/reference/filter (libaom `av1_build_inter_predictor`
17991648 /// under `av1_setup_build_prediction_by_{above,left}_pred`).
@@ -2022,71 +1871,6 @@ fn obmc_blend_h(
20221871 }
20231872 }
20241873
2025-/// libaom's own `BLOCK_SIZE` enum index for a `w4`x`h4` (mi-unit) block --
2026-/// only for the `EC_OBMC` trace rung below, so it reads byte-identical to
2027-/// the instrumented aomdec's `backup_mbmi.bsize`.
2028-fn ec_obmc_bsize(w4: usize, h4: usize) -> i32 {
2029- match (w4, h4) {
2030- (1, 1) => 0,
2031- (1, 2) => 1,
2032- (2, 1) => 2,
2033- (2, 2) => 3,
2034- (2, 4) => 4,
2035- (4, 2) => 5,
2036- (4, 4) => 6,
2037- (4, 8) => 7,
2038- (8, 4) => 8,
2039- (8, 8) => 9,
2040- (8, 16) => 10,
2041- (16, 8) => 11,
2042- (16, 16) => 12,
2043- (1, 4) => 16,
2044- (4, 1) => 17,
2045- (2, 8) => 18,
2046- (8, 2) => 19,
2047- (4, 16) => 20,
2048- (16, 4) => 21,
2049- _ => -1,
2050- }
2051-}
2052-
2053-/// The `EC_OBMC` rung: one line per blended neighbour, in the instrumented
2054-/// aomdec's own byte format (`decodeframe.c`
2055-/// `dec_build_prediction_by_{above,left}_pred`), so the two decoders' OBMC
2056-/// neighbour lists diff line for line. `filt` is libaom's packed
2057-/// `interp_filters.as_int` = `y_filter | (x_filter << 16)`.
2058-#[allow(clippy::too_many_arguments)]
2059-fn ec_obmc_trace(
2060- dir: &str,
2061- mi_row: usize,
2062- mi_col: usize,
2063- write_w: usize,
2064- write_h: usize,
2065- rel: usize,
2066- op: usize,
2067- nb: &MiInfo,
2068- h_kind: mc::InterpFilterKind,
2069- v_kind: mc::InterpFilterKind,
2070-) {
2071- if !crate::envflags::env_flag!("EC_OBMC") {
2072- return;
2073- }
2074- let sym = |k: mc::InterpFilterKind| match k {
2075- mc::InterpFilterKind::Smooth => 1u32,
2076- mc::InterpFilterKind::Sharp => 2,
2077- _ => 0,
2078- };
2079- eprintln!(
2080- "EC_OBMC {dir} mi=({mi_row},{mi_col}) wh=({write_w}x{write_h}) rel={rel} op={op} \
2081-nbmv=({},{}) nbref={} nbbsize={} filt={}",
2082- nb.mv.0,
2083- nb.mv.1,
2084- nb.ref_frame,
2085- ec_obmc_bsize(nb.size as usize, nb.size_h as usize),
2086- sym(v_kind) | (sym(h_kind) << 16),
2087- );
2088-}
2089-
20901874 /// `av1_build_obmc_inter_prediction` (libaom `reconinter.c`): re-predicts
20911875 /// the overlap strip against each bordering above/left inter neighbour's own
20921876 /// mv/ref/filter and blends it into this block's just-built single-reference
@@ -2192,23 +1976,7 @@ pub(crate) fn obmc_plan(
21921976 // `av1_setup_build_prediction_by_above_pred` reads
21931977 // `above_mbmi->interp_filters`).
21941978 let above_syms = above_filter.get(mi_col + src4).copied().unwrap_or([3; 2]);
2195- obmcrec_probe(
2196- "above",
2197- mi_row,
2198- mi_col,
2199- write_w,
2200- write_h,
2201- off4,
2202- span4,
2203- &nb,
2204- above_syms,
2205- grid.get(mi_row - 1, mi_col + src4),
2206- interp_fixed.is_some(),
2207- );
22081979 let (h_kind, v_kind) = neighbour_filter(interp_fixed, above_syms)?;
2209- ec_obmc_trace(
2210- "above", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind,
2211- );
22121980 let nb_dims = ref_dims(nb.ref_frame, refpix)?;
22131981 above.push(ObmcNb {
22141982 off4,
@@ -2225,23 +1993,7 @@ pub(crate) fn obmc_plan(
22251993 overlappable_left(grid, mi_row, mi_col, bh4, mi_rows, max_nb(bh4))
22261994 {
22271995 let left_syms = left_filter.get(mi_row + src4).copied().unwrap_or([3; 2]);
2228- obmcrec_probe(
2229- "left",
2230- mi_row,
2231- mi_col,
2232- write_w,
2233- write_h,
2234- off4,
2235- span4,
2236- &nb,
2237- left_syms,
2238- grid.get(mi_row + src4, mi_col - 1),
2239- interp_fixed.is_some(),
2240- );
22411996 let (h_kind, v_kind) = neighbour_filter(interp_fixed, left_syms)?;
2242- ec_obmc_trace(
2243- "left", mi_row, mi_col, write_w, write_h, off4, span4, &nb, h_kind, v_kind,
2244- );
22451997 let nb_dims = ref_dims(nb.ref_frame, refpix)?;
22461998 left.push(ObmcNb {
22471999 off4,
@@ -2358,41 +2110,6 @@ pub(crate) fn obmc_run(
23582110 // block, reused by every neighbour of the above and left passes.
23592111 let (mut tmp_y, mut tmp_u, mut tmp_v) = (Vec::new(), Vec::new(), Vec::new());
23602112
2361- // lane-t900 r13 rung: EC_MCB="<plane>:<px>:<py>[:<frame>]" (chroma plane
2362- // 1 only; <px>:<py> are chroma-plane pixels, the oracle's own dump
2363- // window) prints this block's chroma prediction rows before and after the
2364- // OBMC blend, matching the instrumented aomdec's EC_MCB dump.
2365- let ec_mcb: Option<(usize, usize, i64)> = crate::envflags::env_flag!("EC_MCB")
2366- .then(|| crate::envflags::var("EC_MCB").ok())
2367- .flatten()
2368- .and_then(|v| {
2369- let f: Vec<&str> = v.split(':').collect();
2370- if f.len() < 3 || f[0] != "1" {
2371- return None;
2372- }
2373- let (x, y) = (f[1].parse::<usize>().ok()?, f[2].parse::<usize>().ok()?);
2374- let fr = f.get(3).and_then(|s| s.parse::<i64>().ok()).unwrap_or(-1);
2375- let idx = PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst) as i64;
2376- // lane-av1ecmcb: the window is the CHROMA plane's own write region --
2377- // the oracle's EC_MCB spans are plane pixels, and at 4:4:4 (ss 0/0)
2378- // the chroma block is full-size, so nothing halves. The old
2379- // `write_w / 2` was a 4:2:0-era assumption that quartered the window
2380- // (and the dumps below) at ss 0/0.
2381- let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx));
2382- if x >= cpx && x < cpx + cw && y >= cpy && y < cpy + ch && (fr < 0 || fr == idx) {
2383- Some((x, y, idx))
2384- } else {
2385- None
2386- }
2387- });
2388- if let Some((_, _, idx)) = ec_mcb {
2389- let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx));
2390- eprintln!("OUR_MCB pre f={idx} cpx={cpx} cpy={cpy} cw={cw} ch={ch}");
2391- for r in 0..ch {
2392- let row: Vec<u16> = (0..cw).map(|c| pred_u[r * chroma_stride + c]).collect();
2393- eprintln!("OUR_MCB prerow{r}: {row:?}");
2394- }
2395- }
23962113 for nb in &plan.above {
23972114 let Some((ny, nu, nv)) = ref_planes_deferred(nb.ref_frame, refpix) else {
23982115 return;
@@ -2500,16 +2217,6 @@ pub(crate) fn obmc_run(
25002217 &mut tmp_u,
25012218 fctx,
25022219 );
2503- if let Some((_, _, idx)) = ec_mcb {
2504- eprintln!(
2505- "OUR_MCB left f={idx} off4={} span4={} cbw={cbw} cbh={cbh} coy={coy} mv=({},{}) ref0={}",
2506- nb.off4, nb.span4, nb.mv.0, nb.mv.1, nb.ref_frame
2507- );
2508- for r in 0..cbh {
2509- let row: Vec<u16> = (0..cbw).map(|c| tmp_u[r * cbw + c]).collect();
2510- eprintln!("OUR_MCB lrow{r}: {row:?}");
2511- }
2512- }
25132220 let ch = cbh.min((write_h >> ss_y(fctx)) - coy);
25142221 obmc_blend_h(pred_u, chroma_stride, 0, coy, cbw, ch, &tmp_u);
25152222 obmc_neighbour_pred(
@@ -2528,13 +2235,6 @@ pub(crate) fn obmc_run(
25282235 );
25292236 obmc_blend_h(pred_v, chroma_stride, 0, coy, cbw, ch, &tmp_v);
25302237 }
2531- if let Some((_, _, idx)) = ec_mcb {
2532- let (cw, ch) = (write_w >> ss_x(fctx), write_h >> ss_y(fctx));
2533- for r in 0..ch {
2534- let row: Vec<u16> = (0..cw).map(|c| pred_u[r * chroma_stride + c]).collect();
2535- eprintln!("OUR_MCB post f={idx} row{r}: {row:?}");
2536- }
2537- }
25382238 }
25392239
25402240 /// `is_any_masked_compound_used` (libaom `reconinter.h`), specialised to
@@ -2667,15 +2367,6 @@ pub(super) fn read_comp_mode(
26672367 ) -> bool {
26682368 let ctx = reference_mode_ctx(above, left);
26692369 let compound = dec.symbol(&mut cdfs.comp_mode[ctx]) == 1;
2670- if crate::envflags::env_flag!("EC_TRACE_MODE") {
2671- eprintln!(
2672- "EC_RCM ctx={ctx} val={} a={:?} l={:?} rng={}",
2673- usize::from(compound),
2674- above.map(|n| (n.is_inter, n.ref0, n.ref1)),
2675- left.map(|n| (n.is_inter, n.ref0, n.ref1)),
2676- dec.debug_state().0
2677- );
2678- }
26792370 compound
26802371 }
26812372
@@ -2979,17 +2670,3 @@ thread_local! {
29792670 /// chroma plane -- the non-vacuity bar for the assertion at that site.
29802671 pub(crate) static CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
29812672 }
2982-
2983-/// [`CHROMA_RECT_BLOCK_TX_FALLBACK`]: rect chroma units handed the block-level
2984-/// type because no luma leaf covered their own MI cell.
2985-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2986-pub(crate) fn chroma_rect_block_tx_fallback() -> usize {
2987- CHROMA_RECT_BLOCK_TX_FALLBACK.with(std::cell::Cell::get)
2988-}
2989-
2990-/// [`CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI`]: of those, the ones whose chroma
2991-/// plane had more than one unit.
2992-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2993-pub(crate) fn chroma_rect_block_tx_fallback_multi() -> usize {
2994- CHROMA_RECT_BLOCK_TX_FALLBACK_MULTI.with(std::cell::Cell::get)
2995-}
crates/ec-av1/src/decode/inter_intra_arm.rsmodified+0 -108
@@ -132,25 +132,6 @@ pub(super) fn decode_inter_block_intra_arm(
132132 .filter(|_| write_w.min(write_h) == 4 && write_w.max(write_h) == 16)
133133 .map(|s| (s.horz, s.has_chroma));
134134 if write_w.min(write_h) < 8 && strip16.is_none() {
135- if crate::envflags::env_flag!("EC_INTRA16X4") {
136- let (idx, hc, prev_inter) = match strip_chroma {
137- Some(s) => (
138- if s.horz {
139- rmi - s.pair_mi.0
140- } else {
141- cmi - s.pair_mi.1
142- },
143- s.has_chroma,
144- s.prev.is_some(),
145- ),
146- None => (9, true, false),
147- };
148- eprintln!(
149- "EC_INTRA16X4 w={write_w} h={write_h} pair_parity={idx} has_chroma={hc} prev_single_inter={prev_inter} skip={skip} mi={rmi},{cmi} tx_select={} scr={}",
150- fctx.tx_select_inter.with(std::cell::Cell::get),
151- allow_screen_content_tools,
152- );
153- }
154135 return Err(unsupported(
155136 "an intra 16x4/4x16 strip inside an inter 16x16-level 1:4 partition (its 4:2:0 chroma pair is coded once for two strips; only the inter path implements that pairing)",
156137 ));
@@ -215,14 +196,7 @@ pub(super) fn decode_inter_block_intra_arm(
215196 );
216197 return Ok(None);
217198 }
218- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
219199 let mode = dec.symbol(&mut cdfs.y_mode[size_group_wh(write_w, write_h)]);
220- if crate::envflags::env_flag!("EC_IIS") {
221- eprintln!(
222- "TRACE iis px={px} py={py} side={side} w={write_w} h={write_h} sg={} mode={mode} skip={skip}",
223- size_group_wh(write_w, write_h)
224- );
225- }
226200 if mode >= 13 {
227201 return Err(unsupported(
228202 "an intra mode this decoder does not code (round 2)",
@@ -263,10 +237,8 @@ pub(super) fn decode_inter_block_intra_arm(
263237 let uv_mode = if !has_chroma {
264238 DC_PRED
265239 } else if cfl_allowed {
266- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
267240 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
268241 } else {
269- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
270242 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
271243 };
272244 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
@@ -322,24 +294,9 @@ pub(super) fn decode_inter_block_intra_arm(
322294 let n = 2 + dec.symbol(&mut cdfs.palette_y_size[bsize_ctx]);
323295 palette_y_pending = Some((n, read_palette_colors_y(dec, n, &palette_cache, fctx)));
324296 }
325- if crate::envflags::env_flag!("EC_PALSYN") {
326- eprintln!(
327- "EC_PALSYN_PRE sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} rng={}",
328- palette_y_pending.map_or(0, |(n, _)| n),
329- dec.debug_state().0
330- );
331- }
332297 let use_palette_uv = has_chroma
333298 && uv_mode == DC_PRED
334299 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
335- if crate::envflags::env_flag!("EC_PALSYN") {
336- eprintln!(
337- "EC_PALSYN sq mi={rmi},{cmi} bw={write_w} bh={write_h} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
338- use_palette_y as i32,
339- use_palette_uv as i32,
340- dec.debug_state().0
341- );
342- }
343300 if use_palette_uv {
344301 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
345302 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
@@ -532,10 +489,6 @@ pub(super) fn decode_inter_block_intra_arm(
532489 dec,
533490 cdfs,
534491 txbset_for(tx_px, reduced),
535- // lane-sb128c r5: a TX_64X64 unit codes only its
536- // top-left 32x32 of frequencies (spec 5.11.40), so
537- // the scan and `tx_side` are the CODED corner while
538- // `side` stays the transform's true 64.
539492 default_scan(tx_px.min(32)),
540493 0,
541494 neighbours.around_mi(tu_mi, tx_px)[0],
@@ -550,7 +503,6 @@ pub(super) fn decode_inter_block_intra_arm(
550503 tu_py,
551504 tx_px,
552505 tx_px.min(32),
553- base_q_idx,
554506 None,
555507 filter_intra,
556508 Some(tu_skip_ctx),
@@ -619,32 +571,18 @@ pub(super) fn decode_inter_block_intra_arm(
619571 cdfs,
620572 neighbours,
621573 at_mi,
622- (px, py),
623574 (cpx, cpy),
624575 side,
625- // lane-av1422lpf site 6 (the intra-in-inter twin of
626- // site 5 at 41572): the plane block's own per-axis
627- // shape and stride, never the enclosing square.
628- // `palette_uv_bufs` is the decoded colour-index map
629- // at `(write_w >> ss_x, write_h >> ss_y)` (44144),
630- // i.e. per-axis already, and the lossless walk
631- // windows it at this `stride` -- at 4:2:2 a
632- // 16-wide square stride over an 8-wide map put the
633- // third unit row at index 180 of 128 samples
634- // (`palette_window`, decode.rs:2946; measured on
635- // `Y_intrabc_10b.obu`).
636576 (chroma_stride, chroma_buf_h),
637577 (cc * chunk_chroma_w, cr * chunk_chroma_h),
638578 (chunk_chroma_w, chunk_chroma_h),
639579 chroma_stride,
640580 reach,
641- (y.width, y.height),
642581 mode,
643582 uv_predict_mode,
644583 angle_delta_uv,
645584 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
646585 smooth_neighbor_uv,
647- base_q_idx,
648586 &mut u_units,
649587 &mut v_units,
650588 fctx,
@@ -696,11 +634,6 @@ pub(super) fn decode_inter_block_intra_arm(
696634 cr * chunk_luma + ur * unit_luma_h,
697635 unit_luma_w,
698636 reach,
699- px,
700- py,
701- y.width,
702- y.height,
703- fctx,
704637 );
705638 let cu_grid = if skip {
706639 push_intra(
@@ -740,15 +673,8 @@ pub(super) fn decode_inter_block_intra_arm(
740673 cu_y,
741674 cu_tx,
742675 cu_tx,
743- base_q_idx,
744- // CfL is refused above 32x32
745- // (`is_cfl_allowed`), so never here.
746676 None,
747677 None,
748- // The uv plane block is larger than
749- // the unit: `get_txb_ctx`'s offset-10
750- // rows, +3 on the `txb_skip_chroma_32`
751- // table (lane-sb128b r3).
752678 Some(3),
753679 smooth_neighbor_uv,
754680 fctx,
@@ -918,7 +844,6 @@ pub(super) fn decode_inter_block_intra_arm(
918844 py,
919845 side,
920846 luma_tx,
921- base_q_idx,
922847 None,
923848 filter_intra,
924849 None,
@@ -939,26 +864,18 @@ pub(super) fn decode_inter_block_intra_arm(
939864 cdfs,
940865 neighbours,
941866 at_mi,
942- (px, py),
943867 (cpx, cpy),
944868 side,
945- // lane-av1422lpf site 6 (the whole-block twin of the mu
946- // chunk fix at 44374): the plane block's own per-axis shape
947- // and its own stride, never the enclosing square
948- // `chroma_side`. At 4:2:0 and 4:4:4 all three are the same
949- // number.
950869 (chroma_stride, chroma_buf_h),
951870 (0, 0),
952871 (chroma_stride, chroma_buf_h),
953872 chroma_stride,
954873 reach,
955- (y.width, y.height),
956874 mode,
957875 uv_predict_mode,
958876 angle_delta_uv,
959877 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
960878 smooth_neighbor_uv,
961- base_q_idx,
962879 &mut uo,
963880 &mut vo,
964881 fctx,
@@ -1008,11 +925,6 @@ pub(super) fn decode_inter_block_intra_arm(
1008925 cu_row * chroma_tx,
1009926 chroma_tx,
1010927 reach,
1011- px,
1012- py,
1013- y.width,
1014- y.height,
1015- fctx,
1016928 );
1017929 let cu_grid = read_plane(
1018930 dec,
@@ -1032,9 +944,6 @@ pub(super) fn decode_inter_block_intra_arm(
1032944 cpy + cu_row * chroma_tx,
1033945 chroma_tx,
1034946 chroma_tx,
1035- base_q_idx,
1036- // CfL is capped at 32x32 (`is_cfl_allowed`),
1037- // so a block this size never carries alpha.
1038947 None,
1039948 None,
1040949 Some(3),
@@ -1095,7 +1004,6 @@ pub(super) fn decode_inter_block_intra_arm(
10951004 cpy,
10961005 chroma_side,
10971006 chroma_tx,
1098- base_q_idx,
10991007 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11001008 None,
11011009 None,
@@ -1133,11 +1041,6 @@ pub(super) fn decode_inter_block_intra_arm(
11331041 luma_span_x,
11341042 luma_span_y,
11351043 reach,
1136- px,
1137- py,
1138- y.width,
1139- y.height,
1140- fctx,
11411044 );
11421045 // The 4:2:2 plane block is `(chroma_w, chroma_h)` --
11431046 // 32x64 -- but codes TWO stacked TX_32X32 units, so
@@ -1171,12 +1074,8 @@ pub(super) fn decode_inter_block_intra_arm(
11711074 cpy + cu_row * cu_h,
11721075 cu_w,
11731076 cu_w,
1174- base_q_idx,
11751077 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11761078 None,
1177- // The uv plane block (32x64) is larger than the unit
1178- // (32x32): `get_txb_ctx`'s offset-10 rows, +3 on the
1179- // `txb_skip_chroma_32` table (lane-sb128b r3).
11801079 Some(3),
11811080 smooth_neighbor_uv,
11821081 fctx,
@@ -1249,7 +1148,6 @@ pub(super) fn decode_inter_block_intra_arm(
12491148 cpy,
12501149 chroma_side,
12511150 chroma_tx,
1252- base_q_idx,
12531151 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12541152 None,
12551153 None,
@@ -1278,11 +1176,6 @@ pub(super) fn decode_inter_block_intra_arm(
12781176 luma_span_x,
12791177 luma_span_y,
12801178 reach,
1281- px,
1282- py,
1283- y.width,
1284- y.height,
1285- fctx,
12861179 );
12871180 // The V twin of the U arm's per-unit window above.
12881181 if let Some((_, vb)) = &palette_uv_bufs {
@@ -1309,7 +1202,6 @@ pub(super) fn decode_inter_block_intra_arm(
13091202 cpy + cu_row * cu_h,
13101203 cu_w,
13111204 cu_w,
1312- base_q_idx,
13131205 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
13141206 None,
13151207 Some(3),
crates/ec-av1/src/decode/inter_shapes.rsmodified+1 -26
@@ -81,11 +81,6 @@ pub(super) fn read_block_tx_size(
8181 //
8282 // The RECT twin [`read_block_tx_size_rect`] has published on this arm
8383 // since lane-av1lm444loss; only the square arm had the hole.
84- let pub_above: u8 = if skip && is_inter {
85- (side_mi * MI) as u8
86- } else {
87- 4
88- };
8984 // The gate's non-vacuity arm, on the DECISION, sampled BEFORE the
9085 // write: this publish CHANGES at least one of the above-band cells it
9186 // covers -- the cell did not already hold `pub_above`, so a later
@@ -104,8 +99,6 @@ pub(super) fn read_block_tx_size(
10499 // first-touch case. The count is still a decision (no reader, no
105100 // intra-only frame, no unchanged column), so the gate keeps its teeth;
106101 // only the doc's stronger reading was wrong.
107- let overwrote = !fctx.intra_only.with(std::cell::Cell::get)
108- && (0..side_mi).any(|i| n.above_txfm.get(at_mi.1 + i) != Some(&pub_above));
109102 set_txfm_ctxs(n, at_mi, 4, side_mi, side_mi, skip && is_inter);
110103 return Ok((4, Some(leaves)));
111104 }
@@ -251,6 +244,7 @@ pub(crate) fn rect_inter_residual_supported(w: usize, h: usize) -> bool {
251244 // these triples are what decides whether those refusals can fire at all. Bit
252245 // 31 is "a triple this table does not list", which is what makes the gate a
253246 // census rather than a restatement of its own table.
247+#[cfg(test)]
254248 pub(crate) const INTER_BLOCK_SHAPES: [(usize, usize, usize); 18] = [
255249 (16, 16, 16),
256250 (32, 32, 32),
@@ -383,9 +377,6 @@ pub(super) fn rect_inter_chroma_set(w: usize, h: usize) -> Result<TxbSet> {
383377 // (`av1_ss_size_lookup[BLOCK_8X32][1][0]`, common_data.c:38) and
384378 // for which no TX_4X32 exists -- that chroma is coded as a
385379 // TX_8X32-chunked merge, not a 4-px unit.
386- if crate::envflags::env_flag!("EC_AV1_TRACE_422") {
387- eprintln!("EC_422 rect_inter_chroma_set missing (w,h)=({w},{h})");
388- }
389380 return Err(unsupported(
390381 "a rectangular inter chroma transform unit whose shape has no coefficient table set here",
391382 ));
@@ -675,16 +666,6 @@ pub(super) fn read_block_tx_size_rect(
675666 let (above_px, left_px) = (n.above_txfm[at_mi.1], n.left_txfm[at_mi.0]);
676667 let ctx = txfm_partition_ctx_rect(above_px, left_px, bw.max(bh), tx_w, tx_h);
677668 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
678- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
679- let (rng, _) = dec.debug_state();
680- eprintln!(
681- "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} above={above_px} left={left_px} maxblk={} tx={tx_w}x{tx_h} rng={rng}",
682- at_mi.0,
683- at_mi.1,
684- u8::from(split),
685- bw.max(bh),
686- );
687- }
688669 if !split {
689670 txfm_partition_update_rect(n, at_mi, (tx_w, tx_h), (bw, bh));
690671 return Ok(None);
@@ -993,16 +974,10 @@ pub(super) fn read_inter_plane_rect(
993974 skip_ctx,
994975 dc_sign_ctx(around.2),
995976 default_tx_type,
996- plane_idx,
997977 )?
998978 };
999979 let grid = extend_corner(corner, cw, ch, w, h);
1000980 let (dc_delta, ac_delta) = plane_q_delta(plane_idx, fctx);
1001- if crate::envflags::env_flag!("EC_TRACE_TXTYPE") {
1002- eprintln!(
1003- "OUR_TXTYPE plane={plane_idx} x={x} y={cy} w={w} h={h} tx_type={tx_type:?} inh={inherited_luma_tx_type:?}"
1004- );
1005- }
1006981 // `reconstruct_mc_rect` reads both buffers at the square prediction
1007982 // stride, so the dense `w x h` residual is re-laid at that stride
1008983 // (`TxParams::stride`) after the inverse transform.
crates/ec-av1/src/decode/key_tile.rsmodified+7 -265
@@ -97,22 +97,6 @@ pub(crate) fn decode_key_frame_tiles_lr(
9797 .map(|(picture, _)| picture)
9898 }
9999
100-/// lane-superres r3: the real decoded margin beyond `frame_width` up to
101-/// the mi-aligned `true_width`, set by the most recent
102-/// [`decode_key_frame_tile_with_cdfs`] OR (lane-superres r10)
103-/// [`decode_inter_frame_tile_with_cdfs`] call -- both frame kinds crop
104-/// their reconstructed buffer down from the same mi-aligned extent, so
105-/// they share this one slot. See each function's own comment at its
106-/// write site. `None` when there was no margin to save.
107-/// The margin the most recent key- or inter-frame tile decode stashed
108-/// (see [`LAST_FRAME_WIDE_MARGIN`]) -- `stream.rs`'s superres path
109-/// reads this immediately after the call, before any other frame
110-/// decode can overwrite it.
111-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
112-pub(crate) fn take_last_frame_wide_margin(fctx: &crate::decode::FrameCtx) -> Option<Picture> {
113- fctx.last_frame_wide_margin.with(|m| m.borrow_mut().take())
114-}
115-
116100 /// [`decode_key_frame_tile`], threading a cross-frame CDF forward (spec
117101 /// 7.20's `load_cdfs`): `initial_cdfs` is the caller's forwarded state (from
118102 /// a prior frame's saved reference slot) when set, or the spec 8.4 defaults
@@ -252,38 +236,6 @@ thread_local! {
252236 pub(crate) static SUB8_LOSSLESS_NO_VARTX: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
253237 }
254238
255-/// [`MU_CHUNK_WALKS`], for a gate's own before/after delta.
256-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
257-pub(crate) fn mu_chunk_walks() -> usize {
258- MU_CHUNK_WALKS.with(std::cell::Cell::get)
259-}
260-
261-/// [`MU_CHUNK_WALK_UNITS`], for a gate's own before/after delta.
262-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
263-pub(crate) fn mu_chunk_walk_units() -> usize {
264- MU_CHUNK_WALK_UNITS.with(std::cell::Cell::get)
265-}
266-
267-/// [`LOSSLESS_EDGE_CLIPPED`] -- lossless blocks whose TX grid the frame-edge
268-/// clip shortened, for a gate's own before/after delta.
269-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
270-pub(crate) fn lossless_edge_clipped() -> usize {
271- LOSSLESS_EDGE_CLIPPED.with(std::cell::Cell::get)
272-}
273-
274-/// [`LOSSLESS_EDGE_CLIP_UNITS`] -- transform units the clip removed, i.e. the
275-/// ones the unclipped pre-fix walk read past the frame edge.
276-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
277-pub(crate) fn lossless_edge_clip_units() -> usize {
278- LOSSLESS_EDGE_CLIP_UNITS.with(std::cell::Cell::get)
279-}
280-/// [`SUB8_LOSSLESS_NO_VARTX`] -- sub-8 inter leaves on a lossless segment that
281-/// read no var-tx symbol, for a gate's own before/after delta.
282-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
283-pub(crate) fn sub8_lossless_no_vartx() -> usize {
284- SUB8_LOSSLESS_NO_VARTX.with(std::cell::Cell::get)
285-}
286-
287239 // Signature mirrors the spec's per-call inputs; a parameter struct would only move them.
288240 #[allow(clippy::too_many_arguments)]
289241 pub(super) fn read_sb128_root(
@@ -329,9 +281,6 @@ pub(super) fn read_sb128_root(
329281 let (has_cols128, has_rows128) = (mi_c128 + SB_MI < mi_cols, mi_r128 + SB_MI < mi_rows);
330282 let part128 = if has_cols128 && has_rows128 {
331283 let p = dec.symbol(&mut cdfs.partition_w128[ctx128]);
332- if crate::envflags::env_flag!("EC_AV1_TRACE") {
333- eprintln!("TRACE partition_w128 ctx={ctx128} value={p}");
334- }
335284 p
336285 } else {
337286 match (has_cols128, has_rows128) {
@@ -351,7 +300,6 @@ pub(super) fn read_sb128_root(
351300 }
352301 _ => {
353302 PART128_GATHERED_SYMBOLS.with(|c| c.set(c.get() - 1));
354- bump_edge_both_cut(3);
355303 PARTITION_SPLIT
356304 }
357305 }
@@ -376,8 +324,7 @@ pub(super) fn read_sb128_root(
376324 // lane-sb128c r9: the four AB shapes at the 128 root -- one
377325 // 128x64/64x128 half plus two 64x64 quadrants, decoded by both tile
378326 // paths below in libaom `decode_partition`'s own visit order.
379- p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {
380- }
327+ p if (PARTITION_HORZ_A..=PARTITION_VERT_B).contains(&p) => {}
381328 _ => {
382329 return Err(unsupported(
383330 "a 128x128 superblock partition value outside the 8-symbol alphabet",
@@ -481,7 +428,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
481428 plane: 0,
482429 };
483430 let (cw, ch) = (width >> ss_x(fctx), height >> ss_y(fctx));
484- note_frame_chroma_alloc((width, height), (cw, ch), (ss_x(fctx), ss_y(fctx)));
485431 let (ctw, cth) = (true_width >> ss_x(fctx), true_height >> ss_y(fctx));
486432 let mut u = PlaneBuf {
487433 data: std::borrow::Cow::Owned(fresh_plane(cw * ch, ctw, cth, cw, ch)),
@@ -582,13 +528,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
582528 fctx.current_q_idx.with(|c| c.set(i32::from(base_q_idx)));
583529 fctx.quant_deltas.with(|c| c.set(deltas));
584530 fctx.current_delta_lf.with(|c| c.set([0; 4]));
585- if crate::envflags::env_flag!("EC_AV1_TRACE") {
586- eprintln!(
587- "TRACE key_tile_bytes tile={tile_num} len={} first8={:02x?} base_q_idx={base_q_idx} mi_cols={mi_cols} mi_rows={mi_rows}",
588- tile_bytes.len(),
589- &tile_bytes[..tile_bytes.len().min(8)]
590- );
591- }
592531 let mut dec = SymbolDecoder::new(tile_bytes);
593532 // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets
594533 // it codes every symbol against the tables it started with.
@@ -942,28 +881,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
942881 // mirroring [`crate::tile::sb_coeff_key_frame_tile`]'s own
943882 // three-way write exactly.
944883 let part = if has_cols && has_rows {
945- if crate::envflags::env_flag!("EC_TRACE") {
946- eprintln!(
947- "EC_PART mi_row={} mi_col={} bsize=12 ctx={} tell={} rng={}",
948- sb_r * SB_MI,
949- sb_c * SB_MI,
950- ctx,
951- dec.debug_bitpos(),
952- dec.debug_state().0
953- );
954- }
955884 let p = dec.symbol(&mut cdfs.partition_w64[ctx]);
956- if crate::envflags::env_flag!("EC_TRACE") {
957- eprintln!(
958- "EC_PART_VAL mi_row={} mi_col={} bsize=12 value={}",
959- sb_r * SB_MI,
960- sb_c * SB_MI,
961- p
962- );
963- }
964- if crate::envflags::env_flag!("EC_AV1_TRACE") {
965- eprintln!("TRACE partition_w64 ctx={ctx} value={p}");
966- }
967885 p
968886 } else {
969887 // lane-hgkf r1 (class `parsed-then-discarded`, same finding as
@@ -975,16 +893,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
975893 // the first block of that row.
976894 match (has_cols, has_rows) {
977895 (true, false) => {
978- trace_edge(
979- (sb_r * SB_MI) as usize,
980- (sb_c * SB_MI) as usize,
981- 12,
982- ctx,
983- dec.debug_state().0,
984- );
985896 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], VERT_ALIKE));
986- bump_edge32(4 + b.min(1));
987- bump_edge_part(b.min(1));
988897 if b == 1 {
989898 PARTITION_SPLIT
990899 } else {
@@ -992,26 +901,14 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
992901 }
993902 }
994903 (false, true) => {
995- trace_edge(
996- (sb_r * SB_MI) as usize,
997- (sb_c * SB_MI) as usize,
998- 12,
999- ctx,
1000- dec.debug_state().0,
1001- );
1002904 let b = dec.symbol_fixed(&gather(&cdfs.partition_w64[ctx], HORZ_ALIKE));
1003- bump_edge32(4 + b.min(1));
1004- bump_edge_part(b.min(1));
1005905 if b == 1 {
1006906 PARTITION_SPLIT
1007907 } else {
1008908 PARTITION_VERT
1009909 }
1010910 }
1011- _ => {
1012- bump_edge_both_cut(2);
1013- PARTITION_SPLIT
1014- }
911+ _ => PARTITION_SPLIT,
1015912 }
1016913 };
1017914 // lane-av1unwritten r5: the partition symbol is RESOLVED (a full CDF read or
@@ -1065,33 +962,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1065962 has_half(r32 * BLOCK_MI, BLOCK_MI, mi_rows),
1066963 );
1067964 let part32 = if has_cols32 && has_rows32 {
1068- if crate::envflags::env_flag!("EC_TRACE") {
1069- eprintln!(
1070- "EC_PART mi_row={} mi_col={} bsize=9 ctx={} tell={} rng={}",
1071- r32 * BLOCK_MI,
1072- c32 * BLOCK_MI,
1073- ctx32,
1074- dec.debug_bitpos(),
1075- dec.debug_state().0
1076- );
1077- }
1078965 let p = dec.symbol(&mut cdfs.partition_w32[ctx32]);
1079- if crate::envflags::env_flag!("EC_TRACE") {
1080- eprintln!(
1081- "EC_PART_VAL mi_row={} mi_col={} bsize=9 value={}",
1082- r32 * BLOCK_MI,
1083- c32 * BLOCK_MI,
1084- p
1085- );
1086- }
1087- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1088- let (rng, _) = dec.debug_state();
1089- eprintln!(
1090- "TRACE partition_w32 mi=({},{}) ctx={ctx32} value={p} rng={rng}",
1091- r32 * BLOCK_MI,
1092- c32 * BLOCK_MI
1093- );
1094- }
1095966 p
1096967 } else {
1097968 // lane-hgkf r1: the 32-level frame-edge bit is the
@@ -1099,19 +970,10 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1099970 // superblock level above).
1100971 match (has_cols32, has_rows32) {
1101972 (true, false) => {
1102- trace_edge(
1103- (r32 * BLOCK_MI) as usize,
1104- (c32 * BLOCK_MI) as usize,
1105- 9,
1106- ctx32,
1107- dec.debug_state().0,
1108- );
1109973 let b = dec.symbol_fixed(&gather(
1110974 &cdfs.partition_w32[ctx32],
1111975 VERT_ALIKE,
1112976 ));
1113- bump_edge32(b.min(1));
1114- bump_edge_part(2 + b.min(1));
1115977 if b == 1 {
1116978 PARTITION_SPLIT
1117979 } else {
@@ -1119,29 +981,17 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
1119981 }
1120982 }
1121983 (false, true) => {
1122- trace_edge(
1123- (r32 * BLOCK_MI) as usize,
1124- (c32 * BLOCK_MI) as usize,
1125- 9,
1126- ctx32,
1127- dec.debug_state().0,
1128- );
1129984 let b = dec.symbol_fixed(&gather(
1130985 &cdfs.partition_w32[ctx32],
1131986 HORZ_ALIKE,
1132987 ));
1133- bump_edge32(b.min(1));
1134- bump_edge_part(2 + b.min(1));
1135988 if b == 1 {
1136989 PARTITION_SPLIT
1137990 } else {
1138991 PARTITION_VERT
1139992 }
1140993 }
1141- _ => {
1142- bump_edge_both_cut(1);
1143- PARTITION_SPLIT
1144- }
994+ _ => PARTITION_SPLIT,
1145995 }
1146996 };
1147997 // lane-av1unwritten r4: VERT on a 32x32 block selects
@@ -1198,16 +1048,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
11981048 let at16 = (sr, sc);
11991049 let ctx16 = neighbours.partition_ctx(at16, SUB);
12001050 if has_cols16 && has_rows16 {
1201- if crate::envflags::env_flag!("EC_TRACE") {
1202- eprintln!(
1203- "EC_PART mi_row={} mi_col={} bsize=6 ctx={} tell={} rng={}",
1204- sr * SUB_MI as usize,
1205- sc * SUB_MI as usize,
1206- ctx16,
1207- dec.debug_bitpos(),
1208- dec.debug_state().0
1209- );
1210- }
12111051 let part16 = dec.symbol(&mut cdfs.partition_w16[ctx16]);
12121052 // lane-av1unwritten r6: the partition symbol is RESOLVED and about to be
12131053 // dispatched. `partition_subsize_dims` is libaom's `get_partition_subsize`
@@ -1217,21 +1057,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
12171057 // keep decoding because the helper is exact, not a heuristic. key-frame 16x16 level.
12181058 refuse_invalid_subsize((16, 16), part16, fctx)?;
12191059
1220- if crate::envflags::env_flag!("EC_TRACE") {
1221- eprintln!(
1222- "EC_PART_VAL mi_row={} mi_col={} bsize=6 value={}",
1223- sr * SUB_MI as usize,
1224- sc * SUB_MI as usize,
1225- part16
1226- );
1227- }
1228- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1229- eprintln!(
1230- "TRACE partition_w16 mi=({},{}) ctx={ctx16} value={part16}",
1231- sr * SUB_MI as usize,
1232- sc * SUB_MI as usize
1233- );
1234- }
12351060 if part16 == PARTITION_HORZ || part16 == PARTITION_VERT
12361061 {
12371062 let (bw, bh) = if part16 == PARTITION_HORZ {
@@ -1303,8 +1128,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
13031128 // rectangle: libaom switches those squares onto `has_tr_vert_*`/
13041129 // `has_bl_vert_*` (`reconintra.c` `get_has_tr_table`), which is
13051130 // `Reach::vert_ab_partition()` (lane-part32 r5, cherry-picked here).
1306- let arm = part16 - PARTITION_HORZ_A;
1307- bump_ab16(arm);
13081131 let _vert_guard = if part16 == PARTITION_VERT_A
13091132 || part16 == PARTITION_VERT_B
13101133 {
@@ -1327,7 +1150,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
13271150 &mut y,
13281151 &mut u,
13291152 &mut v,
1330- base_q_idx,
13311153 enable_filter_intra,
13321154 allow_screen_content_tools,
13331155 allow_intrabc,
@@ -1522,15 +1344,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
15221344 {
15231345 // lane-av1unwritten r6: arm census --
15241346 // which partition values reach here.
1525- note_subsize_arm(
1526- part16,
1527- chroma_plane_block_codable(
1528- partition_subsize_dims((16, 16), part16).0,
1529- partition_subsize_dims((16, 16), part16).1,
1530- ss_x(fctx),
1531- ss_y(fctx),
1532- ),
1533- );
15341347 decode_rect4_16(
15351348 &mut dec,
15361349 &mut cdfs,
@@ -1603,16 +1416,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
16031416 }
16041417 let leaf_ctx =
16051418 neighbours.partition_ctx_mi(leaf_mi, 8);
1606- if crate::envflags::env_flag!("EC_TRACE") {
1607- eprintln!(
1608- "EC_PART mi_row={} mi_col={} bsize=3 ctx={} tell={} rng={}",
1609- leaf_mi.0,
1610- leaf_mi.1,
1611- leaf_ctx,
1612- dec.debug_bitpos(),
1613- dec.debug_state().0
1614- );
1615- }
16161419 let part8 =
16171420 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
16181421 // lane-av1unwritten r9: the
@@ -1621,17 +1424,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
16211424 // r9 made sensitive to a second
16221425 // site at an already covered level.
16231426 refuse_invalid_subsize((8, 8), part8, fctx)?;
1624- if crate::envflags::env_flag!("EC_TRACE") {
1625- eprintln!(
1626- "EC_PART_VAL mi_row={} mi_col={} bsize=3 value={}",
1627- leaf_mi.0, leaf_mi.1, part8
1628- );
1629- }
1630- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1631- eprintln!(
1632- "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8}"
1633- );
1634- }
16351427 if part8 == PARTITION_HORZ
16361428 || part8 == PARTITION_VERT
16371429 {
@@ -1665,7 +1457,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
16651457 &mut y,
16661458 &mut u,
16671459 &mut v,
1668- base_q_idx,
16691460 enable_filter_intra,
16701461 allow_screen_content_tools,
16711462 allow_intrabc,
@@ -1686,7 +1477,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
16861477 &mut y,
16871478 &mut u,
16881479 &mut v,
1689- base_q_idx,
16901480 enable_filter_intra,
16911481 allow_intrabc,
16921482 reduced_tx_set,
@@ -1706,7 +1496,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
17061496 &mut y,
17071497 &mut u,
17081498 &mut v,
1709- base_q_idx,
17101499 enable_filter_intra,
17111500 allow_intrabc,
17121501 tx_select,
@@ -1755,7 +1544,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
17551544 // quadrants get no neighbour or tx-grid
17561545 // write.
17571546 if !has_cols16 && !has_rows16 {
1758- bump_edge_both_cut(0);
17591547 } else {
17601548 // lane-golomb r1 (class
17611549 // `parsed-then-discarded`): the gathered
@@ -1765,13 +1553,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
17651553 // This path can only walk the four SPLIT
17661554 // leaves, so a 0 refuses by name instead
17671555 // of desyncing.
1768- trace_edge(
1769- sr * SUB_MI as usize,
1770- sc * SUB_MI as usize,
1771- 6,
1772- ctx16,
1773- dec.debug_state().0,
1774- );
17751556 let edge_split = if has_cols16 {
17761557 dec.symbol_fixed(&gather(
17771558 &cdfs.partition_w16[ctx16],
@@ -1786,7 +1567,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
17861567 // lane-hgkf r1: slots 2/3 of
17871568 // [`EDGE_PART_HITS`], the gate's proof the
17881569 // non-SPLIT edge arm actually decoded.
1789- bump_edge_part(if edge_split == 1 { 3 } else { 2 });
17901570 if edge_split == 0 {
17911571 // lane-av1subsizesweep: this arm is the ONE
17921572 // frame-edge partition read in the file that
@@ -1826,17 +1606,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
18261606 refuse_invalid_subsize((16, 16), edge_part, fctx)?;
18271607 // lane-av1unwritten r6: arm census -- which
18281608 // partition value reaches here.
1829- note_subsize_arm(
1830- edge_part,
1831- chroma_plane_block_codable(
1832- partition_subsize_dims((16, 16), edge_part)
1833- .0,
1834- partition_subsize_dims((16, 16), edge_part)
1835- .1,
1836- ss_x(fctx),
1837- ss_y(fctx),
1838- ),
1839- );
18401609 let (mi_row0, mi_col0) =
18411610 (sr as u32 * SUB_MI, sc as u32 * SUB_MI);
18421611 let (bw, bh) =
@@ -1893,7 +1662,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
18931662 neighbours.left_mode[sr] = right;
18941663 }
18951664 let leaf_ctx = neighbours.partition_ctx_mi(leaf_mi, 8);
1896- let pre8 = dec.debug_state().0;
18971665 let part8 =
18981666 dec.symbol(&mut cdfs.partition_w8[leaf_ctx]);
18991667 // lane-av1unwritten r9: key-frame 8x8
@@ -1907,11 +1675,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
19071675 // than live pixels, and it is guarded
19081676 // anyway.
19091677 refuse_invalid_subsize((8, 8), part8, fctx)?;
1910- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1911- eprintln!(
1912- "TRACE partition_w8 mi=({mr},{mc}) ctx={leaf_ctx} value={part8} pre_rng={pre8}"
1913- );
1914- }
19151678 let leaf_mode = if part8 == PARTITION_NONE {
19161679 decode_leaf8(
19171680 &mut dec,
@@ -1924,7 +1687,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
19241687 &mut y,
19251688 &mut u,
19261689 &mut v,
1927- base_q_idx,
19281690 enable_filter_intra,
19291691 allow_screen_content_tools,
19301692 allow_intrabc,
@@ -1945,7 +1707,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
19451707 &mut y,
19461708 &mut u,
19471709 &mut v,
1948- base_q_idx,
19491710 enable_filter_intra,
19501711 allow_intrabc,
19511712 reduced_tx_set,
@@ -1965,7 +1726,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
19651726 &mut y,
19661727 &mut u,
19671728 &mut v,
1968- base_q_idx,
19691729 enable_filter_intra,
19701730 allow_intrabc,
19711731 tx_select,
@@ -2018,9 +1778,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
20181778 reduced_tx_set,
20191779 fctx,
20201780 )?;
2021- if !has_rows32 {
2022- bump_edge32(2);
2023- }
1781+ if !has_rows32 {}
20241782 // lane-hgkf r1: at the frame edge only the first half of the strip is
20251783 // coded (libaom `decode_partition` guards the second half with the same
20261784 // test that made this partition non-square).
@@ -2064,9 +1822,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
20641822 reduced_tx_set,
20651823 fctx,
20661824 )?;
2067- if !has_cols32 {
2068- bump_edge32(3);
2069- }
1825+ if !has_cols32 {}
20701826 // lane-hgkf r1: at the frame edge only the first half of the strip is
20711827 // coded (libaom `decode_partition` guards the second half with the same
20721828 // test that made this partition non-square).
@@ -2453,9 +2209,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
24532209 reduced_tx_set,
24542210 fctx,
24552211 )?;
2456- if !has_rows {
2457- bump_edge32(6);
2458- }
2212+ if !has_rows {}
24592213 // lane-golomb r1: at the frame edge only the first half of the
24602214 // strip is coded (libaom `decode_partition` guards the second
24612215 // with the same has_rows test that made this partition non-square).
@@ -2499,9 +2253,7 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
24992253 reduced_tx_set,
25002254 fctx,
25012255 )?;
2502- if !has_cols {
2503- bump_edge32(7);
2504- }
2256+ if !has_cols {}
25052257 // lane-golomb r1: at the frame edge only the first half of the
25062258 // strip is coded (libaom `decode_partition` guards the second
25072259 // with the same has_cols test that made this partition non-square).
@@ -2675,16 +2427,6 @@ pub(crate) fn decode_key_frame_tile_with_cdfs(
26752427 }
26762428 crate::timeline::recon_done();
26772429
2678- // Decode-order frame marker for the EC_OBMC / EC_TRACE_MODE ladders.
2679- if crate::envflags::env_flag!("EC_OBMC")
2680- || crate::envflags::env_flag!("EC_TRACE_MODE")
2681- || crate::envflags::env_flag!("EC_PRED")
2682- {
2683- eprintln!(
2684- "EC_PICT idx={}",
2685- PREFILT_PICTURE_IDX.load(std::sync::atomic::Ordering::SeqCst)
2686- );
2687- }
26882430 // lane-av1fwd: the encoder's filter search re-decodes this same key
26892431 // frame tile per candidate -- capture it once (see [`FilterReplay`]),
26902432 // on the shape whose tail is the two filter calls and nothing else.
crates/ec-av1/src/decode/leaf8.rsmodified+8 -166
@@ -140,7 +140,7 @@ pub(super) fn decode_block_128rect(
140140 // lane-inter128intra r1: `get_tx_size_context` compares the bands
141141 // against `tx_size_wide/high[max_txsize_rect_lookup[bsize]]` --
142142 // TX_64X64 for every 128-axis block, hence the `min(64)`.
143- let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
143+ let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64));
144144 dec.symbol(&mut cdfs.tx_size_cat3[ctx])
145145 } else {
146146 0
@@ -223,11 +223,6 @@ pub(super) fn decode_block_128rect(
223223 tu_row * logical_tx,
224224 logical_tx,
225225 reach,
226- px,
227- py,
228- y.width,
229- y.height,
230- fctx,
231226 );
232227 if skip {
233228 push_intra(
@@ -272,7 +267,6 @@ pub(super) fn decode_block_128rect(
272267 tu_py,
273268 logical_tx,
274269 coeff_tx_side,
275- base_q_idx,
276270 None,
277271 None,
278272 Some(tu_skip_ctx),
@@ -325,11 +319,6 @@ pub(super) fn decode_block_128rect(
325319 luma_span,
326320 luma_span_h,
327321 reach,
328- px,
329- py,
330- y.width,
331- y.height,
332- fctx,
333322 );
334323 if skip {
335324 push_intra(
@@ -386,7 +375,6 @@ pub(super) fn decode_block_128rect(
386375 cu_y,
387376 chroma_tx,
388377 chroma_tx,
389- base_q_idx,
390378 None,
391379 None,
392380 Some(3),
@@ -531,7 +519,6 @@ pub(super) fn decode_leaf8(
531519 y: &mut PlaneBuf<'static>,
532520 u: &mut PlaneBuf<'static>,
533521 v: &mut PlaneBuf<'static>,
534- base_q_idx: u8,
535522 enable_filter_intra: bool,
536523 allow_screen_content_tools: bool,
537524 allow_intrabc: bool,
@@ -810,19 +797,7 @@ pub(super) fn decode_leaf8(
810797 if tu_px >= y.true_width || tu_py >= y.true_height {
811798 continue;
812799 }
813- let tu_reach = tu_reach(
814- 8,
815- 8,
816- tu_col * 4,
817- tu_row * 4,
818- 4,
819- reach,
820- px,
821- py,
822- y.width,
823- y.height,
824- fctx,
825- );
800+ let tu_reach = tu_reach(8, 8, tu_col * 4, tu_row * 4, 4, reach);
826801 push_intra(
827802 y,
828803 u,
@@ -946,19 +921,7 @@ pub(super) fn decode_leaf8(
946921 if chroma_units_ll {
947922 for cu_row in 0..cu_shape.1 / 4 {
948923 for cu_col in 0..cu_shape.0 / 4 {
949- let cu_reach = tu_reach(
950- 8,
951- 8,
952- cu_col * 4,
953- cu_row * 4,
954- 4,
955- reach,
956- px,
957- py,
958- y.width,
959- y.height,
960- fctx,
961- );
924+ let cu_reach = tu_reach(8, 8, cu_col * 4, cu_row * 4, 4, reach);
962925 push_intra(
963926 y,
964927 u,
@@ -1005,19 +968,7 @@ pub(super) fn decode_leaf8(
1005968 for (buf, plane) in [(ub, 1usize), (vb, 2usize)] {
1006969 if let Some(buf) = buf {
1007970 for cu_row in 0..2 {
1008- let cu_reach = tu_reach(
1009- 8,
1010- 8,
1011- 0,
1012- cu_row * 4,
1013- 4,
1014- reach,
1015- px,
1016- py,
1017- y.width,
1018- y.height,
1019- fctx,
1020- );
971+ let cu_reach = tu_reach(8, 8, 0, cu_row * 4, 4, reach);
1021972 set_palette_pred(
1022973 palette_window(&buf, cw, 0, cu_row * 4, 4, 4),
1023974 fctx,
@@ -1070,19 +1021,7 @@ pub(super) fn decode_leaf8(
10701021 if chroma_units_ll {
10711022 for cu_row in 0..cu_shape.1 / 4 {
10721023 for cu_col in 0..cu_shape.0 / 4 {
1073- let cu_reach = tu_reach(
1074- 8,
1075- 8,
1076- cu_col * 4,
1077- cu_row * 4,
1078- 4,
1079- reach,
1080- px,
1081- py,
1082- y.width,
1083- y.height,
1084- fctx,
1085- );
1024+ let cu_reach = tu_reach(8, 8, cu_col * 4, cu_row * 4, 4, reach);
10861025 push_intra(
10871026 y,
10881027 u,
@@ -1115,19 +1054,7 @@ pub(super) fn decode_leaf8(
11151054 .or_else(|| palette_uv_bufs.as_ref().map(|(_, vb)| vb.clone()));
11161055 if let Some(vb) = vb {
11171056 for cu_row in 0..2 {
1118- let cu_reach = tu_reach(
1119- 8,
1120- 8,
1121- 0,
1122- cu_row * 4,
1123- 4,
1124- reach,
1125- px,
1126- py,
1127- y.width,
1128- y.height,
1129- fctx,
1130- );
1057+ let cu_reach = tu_reach(8, 8, 0, cu_row * 4, 4, reach);
11311058 set_palette_pred(palette_window(&vb, cw, 0, cu_row * 4, 4, 4), fctx);
11321059 push_intra(
11331060 y,
@@ -1214,7 +1141,6 @@ pub(super) fn decode_leaf8(
12141141 py,
12151142 8,
12161143 TX8,
1217- base_q_idx,
12181144 None,
12191145 filter_intra,
12201146 None,
@@ -1301,7 +1227,6 @@ pub(super) fn decode_leaf8(
13011227 cpy,
13021228 csz,
13031229 csz,
1304- base_q_idx,
13051230 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
13061231 None,
13071232 None,
@@ -1331,7 +1256,6 @@ pub(super) fn decode_leaf8(
13311256 cpy,
13321257 csz,
13331258 csz,
1334- base_q_idx,
13351259 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
13361260 None,
13371261 None,
@@ -1357,19 +1281,7 @@ pub(super) fn decode_leaf8(
13571281 let tu_px = px + tu_col * 4;
13581282 let tu_py = py + tu_row * 4;
13591283 let tu_around = neighbours.around_mi(tu_mi, 4)[0];
1360- let tu_reach = tu_reach(
1361- 8,
1362- 8,
1363- tu_col * 4,
1364- tu_row * 4,
1365- 4,
1366- reach,
1367- px,
1368- py,
1369- y.width,
1370- y.height,
1371- fctx,
1372- );
1284+ let tu_reach = tu_reach(8, 8, tu_col * 4, tu_row * 4, 4, reach);
13731285 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
13741286 // Each 4x4 unit predicts from its own window of the block's
13751287 // 8x8 colour-index map ([`decode_block`]'s per-TU slice at
@@ -1407,21 +1319,12 @@ pub(super) fn decode_leaf8(
14071319 tu_py,
14081320 4,
14091321 4,
1410- base_q_idx,
14111322 None,
14121323 filter_intra,
14131324 Some(tu_skip_ctx),
14141325 smooth_neighbor,
14151326 fctx,
14161327 )?;
1417- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1418- eprintln!(
1419- "TRACE tu_bitpos mi=({},{}) tell={}",
1420- tu_mi.0,
1421- tu_mi.1,
1422- dec.debug_bitpos()
1423- );
1424- }
14251328 neighbours.record_mi_luma(tu_mi, 4, &tu_grid);
14261329 // The FIRST (top-left, co-located with this group's chroma)
14271330 // TU's coded tx_type is what the group's chroma inherits --
@@ -1551,7 +1454,6 @@ pub(super) fn decode_leaf8(
15511454 cdfs,
15521455 neighbours,
15531456 leaf_mi,
1554- (px, py),
15551457 (cpx, cpy),
15561458 8,
15571459 (blk_w, blk_h),
@@ -1559,13 +1461,11 @@ pub(super) fn decode_leaf8(
15591461 (blk_w, blk_h),
15601462 blk_w,
15611463 reach,
1562- (y.width, y.height),
15631464 mode,
15641465 uv_predict_mode,
15651466 angle_delta_uv,
15661467 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
15671468 smooth_neighbor_uv,
1568- base_q_idx,
15691469 &mut uo,
15701470 &mut vo,
15711471 fctx,
@@ -1600,7 +1500,6 @@ pub(super) fn decode_leaf8(
16001500 cdfs,
16011501 neighbours,
16021502 leaf_mi,
1603- (px, py),
16041503 (cpx, cpy),
16051504 8,
16061505 (8, 8),
@@ -1608,13 +1507,11 @@ pub(super) fn decode_leaf8(
16081507 (8, 8),
16091508 8,
16101509 reach,
1611- (y.width, y.height),
16121510 mode,
16131511 uv_predict_mode,
16141512 angle_delta_uv,
16151513 palette_uv_bufs.as_ref().map(|(a, b)| (&a[..], &b[..])),
16161514 smooth_neighbor_uv,
1617- base_q_idx,
16181515 &mut uo,
16191516 &mut vo,
16201517 fctx,
@@ -1651,7 +1548,6 @@ pub(super) fn decode_leaf8(
16511548 cpy,
16521549 csz,
16531550 csz,
1654- base_q_idx,
16551551 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
16561552 None,
16571553 None,
@@ -1679,7 +1575,6 @@ pub(super) fn decode_leaf8(
16791575 cpy,
16801576 csz,
16811577 csz,
1682- base_q_idx,
16831578 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
16841579 None,
16851580 None,
@@ -1872,7 +1767,6 @@ pub(super) fn leaf8_chroma422_unit(
18721767 usize::from(around.0) + usize::from(around.1),
18731768 dc_sign_ctx(around.2),
18741769 default_tx,
1875- plane_idx,
18761770 )?;
18771771 let residual = dequant_and_inverse_typed_wh(
18781772 &levels,
@@ -1949,28 +1843,10 @@ pub(super) fn read_intra_mode_sub8(
19491843 // lane-av1mono: a monochrome leaf codes no chroma mode (libaom
19501844 // `decodemv.c:933`), so fold `NumPlanes == 1` into `has_chroma`.
19511845 let has_chroma = has_chroma && !mono(fctx);
1952- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
1953- let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
1954- crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
1955- if ec_istep {
1956- eprintln!(
1957- "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=sub8 rng={}",
1958- dec.debug_state().0
1959- );
1960- }
19611846 // Same `EC_ISTEP` ladder the square/rect readers print, so a cross-decoder
19621847 // range diff lands on the ELEMENT inside a 4x4 leaf, not just the block.
19631848 macro_rules! istep {
1964- ($name:literal, $val:expr) => {
1965- if ec_istep {
1966- eprintln!(
1967- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={}",
1968- $name,
1969- $val,
1970- dec.debug_state().0
1971- );
1972- }
1973- };
1849+ ($name:literal, $val:expr) => {};
19741850 }
19751851 // lane-seg2: same `intra_segment_id` placement as the square and rect
19761852 // readers (spec 5.11.6) -- a `BLOCK_4X4` leaf codes its own `segment_id`
@@ -1982,13 +1858,6 @@ pub(super) fn read_intra_mode_sub8(
19821858 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, false, fctx);
19831859 }
19841860 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) != 0;
1985- if trace {
1986- eprintln!(
1987- "TRACE sub8 skip mi=({mi_r},{mi_c}) ctx={skip_ctx} value={} rng={}",
1988- skip as i32,
1989- dec.debug_state().0
1990- );
1991- }
19921861 istep!("skip", skip as i32);
19931862 if !seg_id_pre_skip(fctx) {
19941863 intra_segment_id(dec, cdfs, mi_r, mi_c, seg_w_mi, seg_h_mi, skip, fctx);
@@ -2000,13 +1869,6 @@ pub(super) fn read_intra_mode_sub8(
20001869 istep!("dq", 0);
20011870 if allow_intrabc {
20021871 let use_intrabc = dec.symbol(&mut cdfs.intrabc) != 0;
2003- if ec_istep {
2004- eprintln!(
2005- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=intrabc val={} rng={}",
2006- u8::from(use_intrabc),
2007- dec.debug_state().0
2008- );
2009- }
20101872 if use_intrabc {
20111873 // lane-av1txr: `read_intrabc_info` (spec 5.11.13) reads the block
20121874 // vector right after the flag and RETURNS -- no y/uv mode, angle
@@ -2022,12 +1884,6 @@ pub(super) fn read_intra_mode_sub8(
20221884 let left_ctx = INTRA_MODE_CTX[left_mode];
20231885 let mode = dec.symbol(&mut cdfs.kf_y_mode[above_ctx][left_ctx]);
20241886 istep!("mode", mode);
2025- if trace {
2026- eprintln!(
2027- "TRACE sub8 y_mode mi=({mi_r},{mi_c}) ctx=({above_ctx},{left_ctx}) value={mode} rng={}",
2028- dec.debug_state().0
2029- );
2030- }
20311887 // No `angle_delta` at all below 8x8: spec 5.11.6's `intra_angle_info_y`/
20321888 // `_uv` are gated on `MiSize >= BLOCK_8X8` (libaom `av1_use_angle_delta`,
20331889 // blockd.h), so a directional mode on a `BLOCK_4X4` leaf carries no delta
@@ -2046,18 +1902,10 @@ pub(super) fn read_intra_mode_sub8(
20461902 // divergence at the rect leaf mi (8,16) of `ll444.obu`; class
20471903 // `wrong-alphabet-same-value`, lane-av1-llsub8).
20481904 let uv_mode = if cfl_allowed_px(seg_w_mi * MI, seg_h_mi * MI, fctx) {
2049- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
20501905 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
20511906 } else {
2052- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
20531907 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
20541908 };
2055- if trace {
2056- eprintln!(
2057- "TRACE sub8 uv_mode value={uv_mode} rng={}",
2058- dec.debug_state().0
2059- );
2060- }
20611909 let alpha = if uv_mode == UV_CFL_PRED {
20621910 Some(read_cfl_alphas(dec, cdfs))
20631911 } else {
@@ -2072,12 +1920,6 @@ pub(super) fn read_intra_mode_sub8(
20721920 let mut filter_intra = None;
20731921 if mode == DC_PRED && enable_filter_intra {
20741922 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[fi_class]) != 0;
2075- if trace {
2076- eprintln!(
2077- "TRACE sub8 use_filter_intra value={}",
2078- use_filter_intra as i32
2079- );
2080- }
20811923 if use_filter_intra {
20821924 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
20831925 filter_intra = Some(fi_mode);
crates/ec-av1/src/decode/leaf_sub8.rsmodified+3 -77
@@ -35,7 +35,6 @@ pub(super) fn sub8_leaf_chroma444(
3535 u: &mut PlaneBuf<'static>,
3636 v: &mut PlaneBuf<'static>,
3737 scan4: &[u16],
38- base_q_idx: u8,
3938 smooth_neighbor_uv: bool,
4039 fctx: &crate::decode::FrameCtx,
4140 ) -> Result<(Grid, Grid, usize, usize)> {
@@ -307,7 +306,6 @@ pub(super) fn sub8_leaf_chroma444(
307306 py,
308307 4,
309308 TX4,
310- base_q_idx,
311309 None,
312310 None,
313311 None,
@@ -333,7 +331,6 @@ pub(super) fn sub8_leaf_chroma444(
333331 py,
334332 4,
335333 TX4,
336- base_q_idx,
337334 None,
338335 None,
339336 None,
@@ -419,7 +416,6 @@ pub(super) fn sub8_leaf_chroma444(
419416 upy,
420417 4,
421418 TX4,
422- base_q_idx,
423419 None,
424420 None,
425421 Some(3),
@@ -468,7 +464,6 @@ pub(super) fn sub8_leaf_chroma444(
468464 skip_ctx,
469465 dc_sign_ctx(around[plane_idx].2),
470466 default_tx,
471- plane_idx,
472467 )?;
473468 let residual = dequant_and_inverse_typed_wh(
474469 &levels,
@@ -533,7 +528,6 @@ pub(super) fn sub8_leaf_chroma444(
533528 py,
534529 4,
535530 TX4,
536- base_q_idx,
537531 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
538532 None,
539533 None,
@@ -558,7 +552,6 @@ pub(super) fn sub8_leaf_chroma444(
558552 py,
559553 4,
560554 TX4,
561- base_q_idx,
562555 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
563556 None,
564557 None,
@@ -616,7 +609,6 @@ pub(super) fn sub8_leaf_chroma444(
616609 upy,
617610 4,
618611 TX4,
619- base_q_idx,
620612 None,
621613 None,
622614 Some(3),
@@ -666,7 +658,6 @@ pub(super) fn sub8_leaf_chroma444(
666658 skip_ctx,
667659 dc_sign_ctx(around[plane_idx].2),
668660 default_tx,
669- plane_idx,
670661 )?;
671662 let residual = dequant_and_inverse_typed_wh(
672663 &levels,
@@ -795,16 +786,7 @@ pub(super) fn sub8_leaf_chroma422(
795786 u: &mut PlaneBuf<'static>,
796787 v: &mut PlaneBuf<'static>,
797788 scan4: &[u16],
798- base_q_idx: u8,
799789 smooth_neighbor_uv: bool,
800- // The owning luma leaf's own shape (`(4, 4)` for a split leaf, `(8, 4)` /
801- // `(4, 8)` for a rect pair's strip): libaom's `has_top_right` /
802- // `has_bottom_left` answer for this chroma TX_4X4 unit comes from the
803- // LEAF's own rect table row at the leaf's mi (`bsize` is the leaf, the
804- // unit covers it whole), never the standalone square-4x4 table the old
805- // `Reach::of(4, ..)` lookup used -- that said 1 where `has_tr_8x4` says 0
806- // at mi(27,44) (the oracle's own EC_PRED prints `n_tr=0` there), so the
807- // D45 unit read undecoded pixels to its upper right.
808790 leaf_shape: (usize, usize),
809791 fctx: &crate::decode::FrameCtx,
810792 ) -> Result<(Grid, Grid)> {
@@ -1128,7 +1110,6 @@ pub(super) fn sub8_leaf_chroma422(
11281110 cpy,
11291111 4,
11301112 TX4,
1131- base_q_idx,
11321113 None,
11331114 None,
11341115 None,
@@ -1154,7 +1135,6 @@ pub(super) fn sub8_leaf_chroma422(
11541135 cpy,
11551136 4,
11561137 TX4,
1157- base_q_idx,
11581138 None,
11591139 None,
11601140 None,
@@ -1182,7 +1162,6 @@ pub(super) fn sub8_leaf_chroma422(
11821162 cpy,
11831163 4,
11841164 TX4,
1185- base_q_idx,
11861165 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
11871166 None,
11881167 None,
@@ -1207,7 +1186,6 @@ pub(super) fn sub8_leaf_chroma422(
12071186 cpy,
12081187 4,
12091188 TX4,
1210- base_q_idx,
12111189 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
12121190 None,
12131191 None,
@@ -1257,13 +1235,9 @@ pub(super) fn decode_leaf_split4(
12571235 y: &mut PlaneBuf<'static>,
12581236 u: &mut PlaneBuf<'static>,
12591237 v: &mut PlaneBuf<'static>,
1260- base_q_idx: u8,
12611238 enable_filter_intra: bool,
12621239 allow_intrabc: bool,
12631240 reduced_tx_set: bool,
1264- // Returns `(below_mode, right_mode)`: the mode a neighbour BELOW this 8x8
1265- // group sees (its bottom-left 4x4, libaom reads mi(row-1, col)) and the
1266- // one a neighbour to its RIGHT sees (its top-right 4x4, mi(row, col-1))., fctx: &crate::decode::FrameCtx
12671241 fctx: &crate::decode::FrameCtx,
12681242 ) -> Result<(usize, usize)> {
12691243 let (r, c) = outer_at;
@@ -1426,7 +1400,6 @@ pub(super) fn decode_leaf_split4(
14261400 py,
14271401 4,
14281402 4,
1429- base_q_idx,
14301403 None,
14311404 None,
14321405 None,
@@ -1464,7 +1437,6 @@ pub(super) fn decode_leaf_split4(
14641437 u,
14651438 v,
14661439 scan4,
1467- base_q_idx,
14681440 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
14691441 fctx,
14701442 )?;
@@ -1484,7 +1456,6 @@ pub(super) fn decode_leaf_split4(
14841456 u,
14851457 v,
14861458 scan4,
1487- base_q_idx,
14881459 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
14891460 (4, 4),
14901461 fctx,
@@ -1555,7 +1526,6 @@ pub(super) fn decode_leaf_split4(
15551526 py,
15561527 4,
15571528 4,
1558- base_q_idx,
15591529 None,
15601530 filter_intra,
15611531 None,
@@ -1586,7 +1556,6 @@ pub(super) fn decode_leaf_split4(
15861556 u,
15871557 v,
15881558 scan4,
1589- base_q_idx,
15901559 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
15911560 fctx,
15921561 )?;
@@ -1612,7 +1581,6 @@ pub(super) fn decode_leaf_split4(
16121581 u,
16131582 v,
16141583 scan4,
1615- base_q_idx,
16161584 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
16171585 (4, 4),
16181586 fctx,
@@ -1770,7 +1738,6 @@ pub(super) fn decode_leaf_split4(
17701738 cpy,
17711739 4,
17721740 TX4,
1773- base_q_idx,
17741741 None,
17751742 None,
17761743 None,
@@ -1796,7 +1763,6 @@ pub(super) fn decode_leaf_split4(
17961763 cpy,
17971764 4,
17981765 TX4,
1799- base_q_idx,
18001766 None,
18011767 None,
18021768 None,
@@ -1826,7 +1792,6 @@ pub(super) fn decode_leaf_split4(
18261792 cpy,
18271793 4,
18281794 TX4,
1829- base_q_idx,
18301795 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
18311796 None,
18321797 None,
@@ -1851,7 +1816,6 @@ pub(super) fn decode_leaf_split4(
18511816 cpy,
18521817 4,
18531818 TX4,
1854- base_q_idx,
18551819 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
18561820 None,
18571821 None,
@@ -1960,7 +1924,6 @@ pub(super) fn decode_leaf_rect8(
19601924 y: &mut PlaneBuf<'static>,
19611925 u: &mut PlaneBuf<'static>,
19621926 v: &mut PlaneBuf<'static>,
1963- base_q_idx: u8,
19641927 enable_filter_intra: bool,
19651928 allow_intrabc: bool,
19661929 tx_select: bool,
@@ -2137,19 +2100,7 @@ pub(super) fn decode_leaf_rect8(
21372100 let tu_reach = if single {
21382101 reach
21392102 } else {
2140- tu_reach(
2141- bw,
2142- bh,
2143- tu_px - px,
2144- tu_py - py,
2145- tw,
2146- reach,
2147- px,
2148- py,
2149- y.width,
2150- y.height,
2151- fctx,
2152- )
2103+ tu_reach(bw, bh, tu_px - px, tu_py - py, tw, reach)
21532104 };
21542105 let mut yb = vec![0u16; tw * th];
21552106 mc::predict_with_filter(
@@ -2252,7 +2203,6 @@ pub(super) fn decode_leaf_rect8(
22522203 skip_ctx,
22532204 dc_sign_ctx(around.2),
22542205 TxType::DctDct,
2255- 0,
22562206 )?;
22572207 if li == 0 {
22582208 chroma_tx = tx_type;
@@ -2384,7 +2334,6 @@ pub(super) fn decode_leaf_rect8(
23842334 u,
23852335 v,
23862336 scan4,
2387- base_q_idx,
23882337 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
23892338 fctx,
23902339 )?;
@@ -2406,7 +2355,6 @@ pub(super) fn decode_leaf_rect8(
24062355 u,
24072356 v,
24082357 scan4,
2409- base_q_idx,
24102358 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
24112359 (bw, bh),
24122360 fctx,
@@ -2438,7 +2386,7 @@ pub(super) fn decode_leaf_rect8(
24382386 let depth = if tx_select && !lossless(fctx) {
24392387 // lane-av1txbands: the `TXFM_CONTEXT` band read every other rect
24402388 // reader already does.
2441- let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
2389+ let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh);
24422390 dec.symbol(&mut cdfs.tx_size_cat0[ctx])
24432391 } else {
24442392 0
@@ -2475,19 +2423,7 @@ pub(super) fn decode_leaf_rect8(
24752423 // (lane-palette2 r12): a transform unit inside a block is not
24762424 // a block at that position, so its reach comes from the
24772425 // block's own row, offset by the unit's position.
2478- let tu_reach = tu_reach(
2479- bw,
2480- bh,
2481- tu_px - px,
2482- tu_py - py,
2483- 4,
2484- reach,
2485- px,
2486- py,
2487- y.width,
2488- y.height,
2489- fctx,
2490- );
2426+ let tu_reach = tu_reach(bw, bh, tu_px - px, tu_py - py, 4, reach);
24912427 let tu_skip_ctx = neighbours.luma_skip_ctx(tu_mi, 1);
24922428 if skip {
24932429 // A skipped leaf still predicts per transform unit: the
@@ -2537,7 +2473,6 @@ pub(super) fn decode_leaf_rect8(
25372473 tu_py,
25382474 4,
25392475 TX4,
2540- base_q_idx,
25412476 None,
25422477 filter_intra,
25432478 Some(tu_skip_ctx),
@@ -2576,7 +2511,6 @@ pub(super) fn decode_leaf_rect8(
25762511 u,
25772512 v,
25782513 scan4,
2579- base_q_idx,
25802514 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
25812515 fctx,
25822516 )?;
@@ -2604,7 +2538,6 @@ pub(super) fn decode_leaf_rect8(
26042538 u,
26052539 v,
26062540 scan4,
2607- base_q_idx,
26082541 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
26092542 (bw, bh),
26102543 fctx,
@@ -2661,7 +2594,6 @@ pub(super) fn decode_leaf_rect8(
26612594 0,
26622595 dc_sign_ctx(around.2),
26632596 TxType::DctDct,
2664- 0,
26652597 )?;
26662598 if levels.iter().any(|&l| l != 0) {
26672599 if vert {
@@ -2738,7 +2670,6 @@ pub(super) fn decode_leaf_rect8(
27382670 u,
27392671 v,
27402672 scan4,
2741- base_q_idx,
27422673 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
27432674 fctx,
27442675 )?;
@@ -2769,7 +2700,6 @@ pub(super) fn decode_leaf_rect8(
27692700 u,
27702701 v,
27712702 scan4,
2772- base_q_idx,
27732703 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
27742704 (bw, bh),
27752705 fctx,
@@ -2970,7 +2900,6 @@ pub(super) fn decode_leaf_rect8(
29702900 cpy,
29712901 4,
29722902 TX4,
2973- base_q_idx,
29742903 None,
29752904 None,
29762905 None,
@@ -2996,7 +2925,6 @@ pub(super) fn decode_leaf_rect8(
29962925 cpy,
29972926 4,
29982927 TX4,
2999- base_q_idx,
30002928 None,
30012929 None,
30022930 None,
@@ -3027,7 +2955,6 @@ pub(super) fn decode_leaf_rect8(
30272955 cpy,
30282956 4,
30292957 TX4,
3030- base_q_idx,
30312958 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
30322959 None,
30332960 None,
@@ -3052,7 +2979,6 @@ pub(super) fn decode_leaf_rect8(
30522979 cpy,
30532980 4,
30542981 TX4,
3055- base_q_idx,
30562982 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
30572983 None,
30582984 None,
crates/ec-av1/src/decode/mod.rsmodified+5 -438
@@ -40,7 +40,6 @@ use ec_core::{Error, Result};
4040 // itself was lifted by lane-av112bitc before that (the combines absorb the
4141 // CONV_BUF gain drop, `INTER_POST_ROUND - delta`, see `mc::combine_compound`).
4242
43-
4443 mod frame_tile;
4544
4645 mod inter_block8;
@@ -431,38 +430,6 @@ thread_local! {
431430 static COEFF_TRACE_CUR: std::cell::Cell<usize> = const { std::cell::Cell::new(usize::MAX) };
432431 }
433432
434-/// Called by [`crate::stream::decode_stream`] before each frame's tiles with
435-/// that frame's DECODE-order index.
436-pub fn set_coeff_trace_frame(idx: usize) {
437- COEFF_TRACE_FRAME.with(|c| {
438- if c.get().is_none() {
439- let want = match crate::envflags::var("EC_TRACE_COEFF_FRAME") {
440- Ok(v) => v.parse::<usize>().unwrap_or(usize::MAX),
441- // unset: keep tracing every frame, as before this rung existed
442- Err(_) => usize::MAX - 1,
443- };
444- c.set(Some(want));
445- }
446- });
447- COEFF_TRACE_CUR.with(|c| c.set(idx));
448- if crate::envflags::env_flag!("EC_TRACE_COEFF") {
449- eprintln!("EC_COEFF_FRAME decode_idx={idx}");
450- }
451-}
452-
453-pub(crate) fn coeff_trace_on() -> bool {
454- if !crate::envflags::env_flag!("EC_TRACE_COEFF") {
455- return false;
456- }
457- match COEFF_TRACE_FRAME.with(|c| c.get()) {
458- // no `set_coeff_trace_frame` caller (direct tile-decode tests), or the
459- // env var unset: trace every frame.
460- None => true,
461- Some(w) if w >= usize::MAX - 1 => true,
462- Some(w) => COEFF_TRACE_CUR.with(|c| c.get()) == w,
463- }
464-}
465-
466433 /// Sets [`SB128`] for this thread (called once per frame from `stream.rs`).
467434 pub(crate) fn set_sb128(v: bool, fctx: &crate::decode::FrameCtx) {
468435 fctx.sb128_flag.with(|c| c.set(v));
@@ -544,20 +511,6 @@ thread_local! {
544511 static PART128_GATHERED_SYMBOLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
545512 }
546513
547-/// Current value of `PART128_GATHERED_SYMBOLS`: 128 roots that read the
548-/// half-out-of-frame gathered split_or_horz/split_or_vert symbol (spec
549-/// 5.11.4), which this decoder used to read and throw away.
550-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
551-pub(crate) fn part128_gathered_symbols() -> usize {
552- PART128_GATHERED_SYMBOLS.with(|c| c.get())
553-}
554-
555-/// Current value of [`PART128_SYMBOLS`].
556-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
557-pub(crate) fn part128_symbols() -> usize {
558- PART128_SYMBOLS.with(|c| c.get())
559-}
560-
561514 /// [`gather`] over an alphabet of any length -- the 128-level partition CDF
562515 /// has 8 symbols (no `PARTITION_HORZ_4`/`_VERT_4` at `BLOCK_128X128`, spec
563516 /// `partition_cdf_length`), so its forced-split gather sums 5 elements where
@@ -903,17 +856,6 @@ pub(crate) fn set_segmentation(
903856 prev: Option<&[u8]>,
904857 fctx: &crate::decode::FrameCtx,
905858 ) {
906- if crate::envflags::env_flag!("EC_HDR") {
907- eprintln!(
908- "EC_SEGHDR enabled={} update_map={} temporal={} preskip={} last_active={} data={:?}",
909- seg.enabled,
910- seg.update_map,
911- seg.temporal_update,
912- seg.seg_id_pre_skip,
913- seg.last_active_seg_id,
914- seg.feature_data
915- );
916- }
917859 fctx.seg.with(|s| *s.borrow_mut() = seg);
918860 fctx.seg_mi_dims.with(|c| c.set((mi_rows, mi_cols)));
919861 fctx.seg_ids
@@ -940,19 +882,6 @@ pub(crate) fn take_segment_ids(fctx: &crate::decode::FrameCtx) -> Vec<u8> {
940882 fctx.seg_ids.with(|m| m.borrow().clone())
941883 }
942884
943-/// How many distinct segment ids any decoded block has carried.
944-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
945-pub(crate) fn segment_ids_seen() -> usize {
946- SEG_IDS_SEEN.with(|c| c.get().count_ones() as usize)
947-}
948-
949-/// The lowest and highest quantizer index any decoded block was dequantized
950-/// with (`(i32::MAX, i32::MIN)` when nothing decoded).
951-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
952-pub(crate) fn block_q_span() -> (i32, i32) {
953- BLOCK_Q_SPAN.with(|c| c.get())
954-}
955-
956885 /// `seg_feature_active_idx(segment_id, feature)` for the frame currently
957886 /// being decoded, with its `FeatureData` value.
958887 fn seg_feature(segment_id: usize, feature: usize, fctx: &crate::decode::FrameCtx) -> Option<i32> {
@@ -977,9 +906,6 @@ fn block_q_idx(fctx: &crate::decode::FrameCtx) -> i32 {
977906 // lane-d792: which SEGMENT a block's quantizer came out of, beside the
978907 // `EC_DQCOEFF` grid rung -- a dequant that is too low with the levels
979908 // already proven equal is a segment-id defect, not a quantizer one.
980- if crate::envflags::env_flag!("EC_DQCOEFF") {
981- eprintln!("OUR_Q base={base} seg={seg_id} q={q}");
982- }
983909 q
984910 }
985911
@@ -1153,12 +1079,6 @@ fn read_segment_id(
11531079 let id = neg_deinterleave(coded, pred, last_active + 1).clamp(0, last_active);
11541080 // Mirrors the oracle's own `EC_SEG mi_row=.. cdf=.. pred=.. coded=.. id=..`
11551081 // (libaom `decodemv.c:read_segment_id`), for a cross-decoder segment diff.
1156- if crate::envflags::env_flag!("EC_TRACE_SEG") {
1157- eprintln!(
1158- "EC_SEG mi_row={mi_r} mi_col={mi_c} cdf={ctx} pred={pred} coded={coded} id={id} rng={}",
1159- dec.debug_state().0
1160- );
1161- }
11621082 id as u8
11631083 }
11641084
@@ -1324,15 +1244,8 @@ fn tu_reach(
13241244 row_off: usize,
13251245 tx: usize,
13261246 block: Reach,
1327- px: usize,
1328- py: usize,
1329- width: usize,
1330- height: usize,
1331- fctx: &crate::decode::FrameCtx,
13321247 ) -> Reach {
1333- let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block);
1334- let standalone = Reach::of(tx, px + col_off, py + row_off, width, height, fctx);
1335- fixed
1248+ Reach::of_tu(bw, bh, col_off, row_off, tx, tx, block)
13361249 }
13371250
13381251 /// [`tu_reach`] for a unit whose LUMA footprint is a `tx_w` x `tx_h` rect
@@ -1351,38 +1264,17 @@ fn tu_reach_rect(
13511264 tx_w: usize,
13521265 tx_h: usize,
13531266 block: Reach,
1354- px: usize,
1355- py: usize,
1356- width: usize,
1357- height: usize,
1358- fctx: &crate::decode::FrameCtx,
13591267 ) -> Reach {
1360- let fixed = Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block);
1361- if tx_w == tx_h {
1362- let standalone = Reach::of(tx_w, px + col_off, py + row_off, width, height, fctx);
1363- }
1364- fixed
1268+ Reach::of_tu(bw, bh, col_off, row_off, tx_w, tx_h, block)
13651269 }
13661270
1367-/// lane-comppin r4: decode-order picture counter for `EC_AV1_PREFILT_DUMP`,
1368-/// mirroring stream.rs's `pictures_decoded` so the two dumps index
1369-/// identically against aomdec's own `ec_frame_idx` in decodeframe.c.
1370-static PREFILT_PICTURE_IDX: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1371-
13721271 /// Records one decoded forward keyframe (see [`FWD_KF_HITS`]).
1373-pub(crate) fn note_fwd_kf() {
1374-}
1272+pub(crate) fn note_fwd_kf() {}
13751273
13761274 thread_local! {
13771275 static TXFM_SPLIT_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
13781276 }
13791277
1380-/// Current value of [`TXFM_SPLIT_READS`].
1381-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1382-pub(crate) fn txfm_split_reads() -> usize {
1383- TXFM_SPLIT_READS.with(|c| c.get())
1384-}
1385-
13861278 /// Sets the current thread's [`TX_SELECT_INTER`]/[`REDUCED_TX_SET_INTER`]/
13871279 /// [`ENABLE_FILTER_INTRA_INTER`].
13881280 pub(crate) fn set_inter_tx_mode(
@@ -1399,16 +1291,6 @@ pub(crate) fn set_inter_tx_mode(
13991291 .with(|c| c.set(enable_filter_intra));
14001292 }
14011293
1402-fn bump_ab16(arm: usize) {
1403-}
1404-
1405-/// Bumps one bucket of [`INTER_EDGE_STRIP_HITS`].
1406-pub(crate) fn bump_inter_edge_strip(idx: usize) {
1407-}
1408-
1409-fn bump_edge_both_cut(level: usize) {
1410-}
1411-
14121294 // lane-av1muchroma site 1: the total number of samples by which
14131295 // `decode_block`'s SKIP arm chroma bookkeeping grids fell SHORT of their own
14141296 // plane block, summed over every skipped block decoded. It reads the
@@ -1423,12 +1305,6 @@ thread_local! {
14231305 const { std::cell::Cell::new(0) };
14241306 }
14251307
1426-/// Current value of [`SKIP_ARM_CHROMA_SHORT_SAMPLES`].
1427-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1428-pub(crate) fn skip_arm_chroma_short_samples() -> usize {
1429- SKIP_ARM_CHROMA_SHORT_SAMPLES.with(|c| c.get())
1430-}
1431-
14321308 // Number of times `decode_block`'s SKIP arm ran at a shape where the
14331309 // per-axis and square chroma allocations DIFFER -- i.e. at 4:2:2, where
14341310 // the square is half the plane block. Zero on 4:2:0 and 4:4:4, where the
@@ -1440,12 +1316,6 @@ thread_local! {
14401316 const { std::cell::Cell::new(0) };
14411317 }
14421318
1443-/// Current value of [`SKIP_ARM_CHROMA_RECT_SHAPES`].
1444-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1445-pub(crate) fn skip_arm_chroma_rect_shapes() -> usize {
1446- SKIP_ARM_CHROMA_RECT_SHAPES.with(|c| c.get())
1447-}
1448-
14491319 // lane-av1floorshift: the two FRAME chroma plane allocators
14501320 // (`decode_key_frame_tile_with_cdfs` and `decode_inter_tile`'s `PlaneBuf` trio)
14511321 // size U and V as `(width >> ss_x) x (height >> ss_y)` with `width`/`height`
@@ -1488,147 +1358,6 @@ thread_local! {
14881358 const { std::cell::Cell::new(0) };
14891359 }
14901360
1491-/// Current value of [`FRAME_CHROMA_ALLOC_CALLS`].
1492-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1493-pub(crate) fn frame_chroma_alloc_calls() -> usize {
1494- FRAME_CHROMA_ALLOC_CALLS.with(|c| c.get())
1495-}
1496-
1497-/// Current value of [`FRAME_CHROMA_ALLOC_SHORT_SAMPLES`].
1498-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1499-pub(crate) fn frame_chroma_alloc_short_samples() -> usize {
1500- FRAME_CHROMA_ALLOC_SHORT_SAMPLES.with(|c| c.get())
1501-}
1502-
1503-/// Current value of [`FRAME_CHROMA_ALLOC_CROP_SHAPES`].
1504-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1505-pub(crate) fn frame_chroma_alloc_crop_shapes() -> usize {
1506- FRAME_CHROMA_ALLOC_CROP_SHAPES.with(|c| c.get())
1507-}
1508-
1509-/// The census both frame chroma plane allocators share. `shape` is the frame's
1510-/// own 32-aligned coded `(width, height)`, `ss` its `(ss_x, ss_y)`.
1511-///
1512-/// `round_ss` is libaom's chroma CROP (`av1_round_shift`), the extent the
1513-/// committed reference planes are stored at and the bound every chroma walk
1514-/// inside the tile is clamped against.
1515-///
1516-/// `alloc` is the allocator's OWN `(cw, ch)` -- the numbers that size the
1517-/// `PlaneBuf` -- not a recomputation of them. That is what makes the gate
1518-/// bite: the shortfall is a difference between what was allocated and what the
1519-/// tile may address, so replacing the shift with a bare `>> 1` (the 4:2:0-only
1520-/// form this lane's target class is made of) moves it on the 4:2:2 and 4:4:4
1521-/// witnesses, where the correct shift and the hardcoded one are different
1522-/// numbers. A counter that recomputed `shape >> ss` beside the allocation
1523-/// would have read the same value either way and proved nothing.
1524-fn note_frame_chroma_alloc(shape: (usize, usize), alloc: (usize, usize), ss: (usize, usize)) {
1525- let (need_w, need_h) = (round_ss(shape.0, ss.0), round_ss(shape.1, ss.1));
1526- // Decidability: the floor and the crop are the same number on this frame,
1527- // so the shortfall below is the same number the two forms would have given.
1528- if (need_w, need_h) != (shape.0 >> ss.0, shape.1 >> ss.1) {
1529- if crate::envflags::env_flag!("EC_AV1_CHROMA_ALLOC_SWEEP") {
1530- eprintln!(
1531- "CHROMA_ALLOC luma={}x{} ss={:?} floor={}x{} round_ss={}x{} alloc={}x{}",
1532- shape.0,
1533- shape.1,
1534- ss,
1535- shape.0 >> ss.0,
1536- shape.1 >> ss.1,
1537- need_w,
1538- need_h,
1539- alloc.0,
1540- alloc.1,
1541- );
1542- }
1543- }
1544- let want = need_w * need_h;
1545- let got = alloc.0 * alloc.1;
1546-}
1547-
1548-/// lane-av1ibcfork: this decoder's half of the per-unit BIT INTERVAL -- the
1549-/// exact mirror of the oracle's `EC_ECDUMP_IN` / `EC_ECDUMP_OUT` /
1550-/// `EC_ECDUMP_END` triple (`aom-oracle2/src/av1/decoder/decodetxb.c`: one
1551-/// print in `read_coeffs_txb` before and after its `aom_read_symbol`, one in
1552-/// the single caller `av1_read_coeffs_txb` after the whole unit).
1553-///
1554-/// Why three prints and not one `EC_CENSUS_UNIT`: a COUNT is not a key. The
1555-/// two sides can walk a different NUMBER of units and still be paired, because
1556-/// the interval is what a unit CONSUMED. Entry position alone drifts the moment
1557-/// one side consumes a different number of bits, and list index is invalid the
1558-/// moment one side misses a unit -- both were measured here and both
1559-/// mis-attribute. `post_bit` after the `txb_skip` read is the same
1560-/// `aom_reader_tell` the oracle prints there; `end_bit` is the end of the whole
1561-/// unit including the optional luma `tx_type`, the eob, the base/BR passes and
1562-/// the sign/Golomb loop, so a unit that reads the right symbols in the wrong
1563-/// ORDER is caught too.
1564-///
1565-/// `bit` counts the bits this decoder has pulled out of its window, so it sits
1566-/// at a CONSTANT offset from the oracle's tell (the OBU header libaom counts
1567-/// before `aom_reader_init`). The offset is measured per fixture, never
1568-/// assumed: +14 on `444_intrabc_rect4_witness.obu`.
1569-#[inline]
1570-fn unit_iv_on() -> bool {
1571- crate::envflags::env_flag!("EC_UNITIV")
1572-}
1573-
1574-/// The unit's ENTRY position. Returns it so the caller can pass the same value
1575-/// to [`unit_iv_skip`] and [`unit_iv_end`] without reading the decoder again.
1576-#[inline]
1577-#[track_caller]
1578-fn unit_iv_in(plane: usize, w: usize, h: usize, ctx: usize, dec: &SymbolDecoder) -> usize {
1579- if !unit_iv_on() {
1580- return 0;
1581- }
1582- let bit = dec.debug_bitpos();
1583- let (mi_r, mi_c) = SymbolDecoder::symr_mi();
1584- eprintln!(
1585- "EC_UNITIV_IN side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} bit={bit} at {}",
1586- std::panic::Location::caller()
1587- );
1588- bit
1589-}
1590-
1591-/// The position immediately after this unit's `txb_skip` read. `bit_in ==
1592-/// post_bit` means the read consumed ZERO bits (a CDF row already at a
1593-/// boundary), so this is also the real-read filter: the reader logs a step
1594-/// either way, and counting raw lines overstates the symbol count ~2x (measured
1595-/// on `444_intrabc_rect4_witness.obu`: 2395 lines, 512 real reads, against the
1596-/// oracle's 513 -- not the "~1069 fewer" an earlier round reported).
1597-#[inline]
1598-fn unit_iv_skip(
1599- dec: &SymbolDecoder,
1600- bit_in: usize,
1601- plane: usize,
1602- w: usize,
1603- h: usize,
1604- ctx: usize,
1605- all_zero: bool,
1606-) {
1607- if !unit_iv_on() {
1608- return;
1609- }
1610- let (mi_r, mi_c) = SymbolDecoder::symr_mi();
1611- eprintln!(
1612- "EC_UNITIV_SKIP side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} az={} bit={bit_in} post_bit={}",
1613- all_zero as i32,
1614- dec.debug_bitpos()
1615- );
1616-}
1617-
1618-/// The position after the WHOLE unit. One call per successful read, on both
1619-/// the all-zero early return and the full coefficient walk.
1620-#[inline]
1621-fn unit_iv_end(dec: &SymbolDecoder, plane: usize, w: usize, h: usize, ctx: usize) {
1622- if !unit_iv_on() {
1623- return;
1624- }
1625- let (mi_r, mi_c) = SymbolDecoder::symr_mi();
1626- eprintln!(
1627- "EC_UNITIV_END side=ours plane={plane} mi=({mi_r},{mi_c}) w={w} h={h} ctx={ctx} end_bit={}",
1628- dec.debug_bitpos()
1629- );
1630-}
1631-
16321361 /// A just-decoded palette-Y block's own predicted pixels
16331362 /// (`side*side`, row-major, `colors[map[i]]`), consumed by
16341363 /// [`PlaneBuf::reconstruct`]'s next call in place of `predict()` -- the
@@ -1675,27 +1404,12 @@ fn palette_window(
16751404 /// `EC_DEBUG_PAL=1` traces every arm and every consumption with its call site.
16761405 #[track_caller]
16771406 fn set_palette_pred(buf: Vec<u16>, fctx: &crate::decode::FrameCtx) {
1678- if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1679- let stale = fctx.palette_pred.with(|c| c.borrow().is_some());
1680- eprintln!(
1681- "PALSET len={} stale={stale} at {}",
1682- buf.len(),
1683- std::panic::Location::caller()
1684- );
1685- }
16861407 fctx.palette_pred.with(|c| *c.borrow_mut() = Some(buf));
16871408 }
16881409
16891410 #[track_caller]
16901411 fn take_palette_pred(fctx: &crate::decode::FrameCtx) -> Option<Vec<u16>> {
16911412 let got = fctx.palette_pred.with(|c| c.borrow_mut().take());
1692- if crate::envflags::env_flag!("EC_DEBUG_PAL") {
1693- eprintln!(
1694- "PALTAKE len={:?} at {}",
1695- got.as_ref().map(Vec::len),
1696- std::panic::Location::caller()
1697- );
1698- }
16991413 got
17001414 }
17011415
@@ -1760,13 +1474,6 @@ pub(crate) struct TxParams {
17601474 /// ran on a frame that is NOT `CodedLossless`.
17611475 static LOSSLESS_WHT_UNITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
17621476
1763-/// [`LOSSLESS_WHT_UNITS`] -- total over the process, read as a before/after
1764-/// delta around one decode.
1765-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1766-pub(crate) fn lossless_wht_units() -> usize {
1767- LOSSLESS_WHT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
1768-}
1769-
17701477 /// lane-whtshape: 4x4 Walsh-Hadamard units reconstructed as part of a LOSSLESS
17711478 /// transform unit that was itself NOT 4x4 -- a shape libaom cannot code.
17721479 /// `read_tx_mode` (`av1/decoder/decodeframe.c:140`) returns `ONLY_4X4` for a
@@ -1783,13 +1490,6 @@ pub(crate) fn lossless_wht_units() -> usize {
17831490 static LOSSLESS_WHT_SPLIT_UNITS: std::sync::atomic::AtomicUsize =
17841491 std::sync::atomic::AtomicUsize::new(0);
17851492
1786-/// [`LOSSLESS_WHT_SPLIT_UNITS`] -- total over the process, read as a
1787-/// before/after delta around one decode.
1788-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1789-pub(crate) fn lossless_wht_split_units() -> usize {
1790- LOSSLESS_WHT_SPLIT_UNITS.load(std::sync::atomic::Ordering::Relaxed)
1791-}
1792-
17931493 impl TxParams {
17941494 /// The one copy of the produce-the-residual code.
17951495 fn run(self, grid: &[i32]) -> Vec<i32> {
@@ -2130,14 +1830,6 @@ fn push_mc_rect(
21301830 // localized a 4:4:4 intra-BC SKIP block committing its chroma plane block
21311831 // at `(px/2, py/2)` instead of the ss origin, clobbering a neighbouring
21321832 // block's reconstruction (lanes/av1ibcfork.report.md).
2133- if crate::envflags::env_flag!("EC_MCPUSH") {
2134- eprintln!(
2135- "EC_MCPUSH plane={plane} x={x} y={cy} stride={stride} w={w} h={h} \
2136- res_len={} at {}",
2137- residual.len(),
2138- std::panic::Location::caller()
2139- );
2140- }
21411833 let Some((src, stride)) = prediction.inline(stride) else {
21421834 let Pred::Cur {
21431835 plane: sp,
@@ -2452,7 +2144,7 @@ fn exec_mc(
24522144 1 => &mut *u,
24532145 _ => &mut *v,
24542146 };
2455- target.reconstruct_mc_rect(x, oy, plane, stride, w, h, prediction, residual, fctx);
2147+ target.reconstruct_mc_rect(x, oy, stride, w, h, prediction, residual, fctx);
24562148 }
24572149
24582150 // The `tx_type` the last plane-0 [`read_plane`] actually coded, kept so
@@ -2483,11 +2175,6 @@ thread_local! {
24832175 static RECT_INTRABC_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
24842176 }
24852177
2486-/// Current value of [`RECT_INTRABC_READS`].
2487-pub(crate) fn rect_intrabc_reads() -> usize {
2488- RECT_INTRABC_READS.with(|c| c.get())
2489-}
2490-
24912178 thread_local! {
24922179 /// lane-av1-ibc128chunk: the mu-chunk walk's per-axis chroma extents, as
24932180 /// `(64 >> ss_x) << 8 | (64 >> ss_y)` on the LAST chunk -- the pair the
@@ -2497,12 +2184,6 @@ thread_local! {
24972184 const { std::cell::Cell::new(0) };
24982185 }
24992186
2500-/// Current value of [`INTRABC_128RECT_CHUNK_SHAPE`].
2501-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2502-pub fn intrabc_128rect_chunk_shape() -> usize {
2503- INTRABC_128RECT_CHUNK_SHAPE.with(|c| c.get())
2504-}
2505-
25062187 /// Records one coded block into [`INTRABC_MI_GRID`]: every block contributes
25072188 /// its size (libaom's `scan_row_mbmi` advances `processed_rows` off any
25082189 /// candidate's `bsize`, ref-match or not), an intrabc one also its DV as an
@@ -2582,8 +2263,7 @@ fn record_intrabc_mi_rect(
25822263
25832264 /// Bump [`FIMV_FRAME_HITS`] -- called once per decoded frame header whose
25842265 /// `force_integer_mv` bit is set.
2585-pub fn note_force_integer_mv_frame() {
2586-}
2266+pub fn note_force_integer_mv_frame() {}
25872267
25882268 // lane-t900 r27: OBMC blends that actually READ a recorded switchable filter
25892269 // off the neighbour band -- the positive half of the proof for "an OBMC
@@ -2595,48 +2275,6 @@ thread_local! {
25952275 static OBMC_FILTER_BAND_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
25962276 }
25972277
2598-/// Current value of [`OBMC_FILTER_BAND_READS`].
2599-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2600-pub(crate) fn obmc_filter_band_reads() -> usize {
2601- OBMC_FILTER_BAND_READS.with(|c| c.get())
2602-}
2603-
2604-/// lane-inter16ab r5: the six RECTANGULAR wedge shapes, in this order --
2605-/// the counter slots of [`RECT_WEDGE_HITS`]/[`RECT_WII_HITS`].
2606-pub(crate) const RECT_WEDGE_SHAPES: [(usize, usize); 6] =
2607- [(8, 16), (16, 8), (16, 32), (32, 16), (8, 32), (32, 8)];
2608-
2609-fn rect_wedge_slot(bw: usize, bh: usize) -> Option<usize> {
2610- RECT_WEDGE_SHAPES.iter().position(|&s| s == (bw, bh))
2611-}
2612-
2613-// lane-intra14 r1: set while an INTRA block of an INTER frame is decoded
2614-// through one of the key-frame rect readers ([`decode_block_rect4`],
2615-// [`decode_block_rect64`]). `Some((size_group, skip))` tells
2616-// [`read_intra_mode_rect`] that (a) `skip`/segment id/cdef/delta-q were
2617-// already read by [`decode_inter_block`] and (b) the luma mode comes off
2618-// `y_mode_cdf[size_group_lookup[bsize]]` (libaom `read_intra_block_mode_info`,
2619-// decodemv.c:1189), never the key frame's above/left `kf_y_mode` pair.
2620-
2621-// lane-modectx r1: how many times a `kf_y_mode`/`y_mode` neighbour read at a
2622-// TILE edge found its coarse fallback band holding a NON-DC mode -- i.e. a
2623-// mode from the previous tile, where libaom's `up_available`/`left_available`
2624-// make the neighbour DC_PRED. Measured 0 over 20 two-tile-column streams:
2625-// `above_mode` is cleared per tile in `Neighbours::start_tile` and `left_mode`
2626-// per superblock row in `start_row`, so the luma fallback cannot leak the way
2627-// lane-mtfix's `above_uv_mode` one did. The gate asserts it stays 0 -- this is
2628-// the invariant that makes the coarse fallback safe.
2629-thread_local! {
2630- static MODE_TILE_EDGE_COARSE_LEAKS: std::cell::Cell<usize> =
2631- const { std::cell::Cell::new(0) };
2632-}
2633-
2634-/// Current value of [`MODE_TILE_EDGE_COARSE_LEAKS`].
2635-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2636-pub(crate) fn mode_tile_edge_coarse_leaks() -> usize {
2637- MODE_TILE_EDGE_COARSE_LEAKS.with(|c| c.get())
2638-}
2639-
26402278 thread_local! {
26412279 static UV_LEFT_SS_Y_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
26422280 }
@@ -2652,19 +2290,6 @@ thread_local! {
26522290 static UV_OWNER_EPOCH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
26532291 }
26542292
2655-fn bump_edge_part(slot: usize) {
2656-}
2657-
2658-/// [`bump_edge32`] of `base + bit`, returning the bit -- the gathered edge
2659-/// reads are `if`-conditions, so the counter has to ride the expression.
2660-fn bump_edge32_bit(base: usize, bit: usize) -> usize {
2661- bump_edge32(base + bit.min(1));
2662- bit
2663-}
2664-
2665-fn bump_edge32(slot: usize) {
2666-}
2667-
26682293 /// One 16x4 / 4x16 inter strip's chroma situation, handed to
26692294 /// [`decode_inter_block`] out of band (the same one-shot thread-local idiom
26702295 /// `REDUCED_TX_SET_INTER` uses) rather than through twenty-three call sites
@@ -2686,11 +2311,6 @@ pub(crate) struct InterStripChroma {
26862311 prev: Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>,
26872312 }
26882313
2689-/// The single-reference MC parameters of the inter block that decoded
2690-/// last -- read by the next 1:4 strip to build its pair's chroma.
2691-fn bump_ab16_inter(arm: usize) {
2692-}
2693-
26942314 /// Everything [`decode_inter_block`] needs to fold temporal MV candidates
26952315 /// (spec 7.10.2.8), threaded down from [`decode_inter_frame_tile_with_cdfs`]:
26962316 /// the current frame's own projected field ([`crate::motion_field::setup_motion_field`]'s
@@ -2803,12 +2423,6 @@ pub(crate) fn build_motion_field(
28032423 crate::par::run_bands_mut(&bands, cols, fctx, cells, |r0, r1, mine, _| {
28042424 fill(r0, r1, mine);
28052425 });
2806- if crate::envflags::env_flag!("EC_TRACE_TPL") {
2807- eprintln!("EC_TPL_SAVED oh={order_hint}");
2808- for (r, row) in field.occupancy().iter().enumerate() {
2809- eprintln!("EC_TPL_SAVED r{r} {row}");
2810- }
2811- }
28122426 field
28132427 }
28142428
@@ -2852,32 +2466,12 @@ pub fn cdef_mixed_skip_units() -> usize {
28522466 CDEF_MIXED_SKIP_UNITS.with(|c| c.get())
28532467 }
28542468
2855-/// Current value of `CDEF_SKIPPED_UNITS`.
2856-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2857-pub(crate) fn cdef_skipped_units() -> usize {
2858- CDEF_SKIPPED_UNITS.with(|c| c.get())
2859-}
2860-
28612469 /// How many 8x8 CDEF units [`apply_cdef`] visited whose skip band no coded
28622470 /// block wrote this frame -- a writer gap, always a defect (lane-cdefstrip r1).
28632471 pub fn cdef_unwritten_skip_units() -> usize {
28642472 CDEF_UNWRITTEN_SKIP_UNITS.with(|c| c.get())
28652473 }
28662474
2867-/// Current value of `CDEF_STRADDLE_UNITS`.
2868-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2869-pub(crate) fn cdef_straddle_units() -> usize {
2870- CDEF_STRADDLE_UNITS.with(|c| c.get())
2871-}
2872-
2873-fn note_sub8_chroma_tx(first_sub: TxType, chroma_ref: TxType, coeffs: bool) {
2874-}
2875-
2876-/// Counts one [`CHROMA_EOB_CLASS1_HITS`] when `plane_idx`'s inherited
2877-/// `tx_type` put this block's `eob_pt` on the class-1 row.
2878-fn note_chroma_class1(plane_idx: usize, tx_type: TxType) {
2879-}
2880-
28812475 // Which plane the in-flight INTRA reconstruction is writing (0=Y, 1=U, 2=V).
28822476 // lane-av1cmpaudit: aomdec's `EC_PREDOUT8`/`EC_PREDND` print `plane=`, and
28832477 // without the same field on our side an `EC_PREDOUT8` vs `OUR_PRED` diff of a
@@ -2889,11 +2483,6 @@ thread_local! {
28892483 static RECON_PLANE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
28902484 }
28912485
2892-/// The plane index the `EC_PRED` rung prints as `plane=`.
2893-fn recon_plane() -> usize {
2894- RECON_PLANE.with(std::cell::Cell::get)
2895-}
2896-
28972486 /// Restores [`RECON_PLANE`] on drop, so `exec_intra` needs no cleanup path on
28982487 /// either of its two early returns.
28992488 struct PlaneGuard(usize);
@@ -2953,12 +2542,6 @@ const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
29532542 const VERT_ALIKE: [usize; 6] = [2, PARTITION_SPLIT, 4, 6, 7, 9];
29542543 const HORZ_ALIKE: [usize; 6] = [1, PARTITION_SPLIT, 4, 5, 6, 8];
29552544
2956-fn trace_edge(mi_r: usize, mi_c: usize, bsize: u32, ctx: usize, rng: u32) {
2957- if crate::envflags::env_flag!("EC_AV1_TRACE") {
2958- eprintln!("OUR_PART mi_row={mi_r} mi_col={mi_c} bsize={bsize} ctx={ctx} rng={rng}");
2959- }
2960-}
2961-
29622545 fn element_prob(cdf: &[u16], element: usize) -> u16 {
29632546 cdf[element] - if element > 0 { cdf[element - 1] } else { 0 }
29642547 }
@@ -3164,9 +2747,6 @@ fn base_ctx(
31642747 // once; `base_ctx_rect_offsets_match_the_transcribed_tables_over_the_whole_domain`
31652748 // pins the rule against the tables over their whole 5x5 domain.
31662749 if let Some((w, h)) = rect_shape {
3167- if crate::envflags::env_flag!("EC_NZOFF_DUMP") {
3168- eprintln!("NZOFF stride={stride} shape={w}x{h} row={row} col={col}");
3169- }
31702750 if w < h && row < 2 {
31712751 return ctx + 11;
31722752 }
@@ -3580,7 +3160,6 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) ->
35803160 const GROUP_START: [usize; 12] = [0, 1, 2, 3, 5, 9, 17, 33, 65, 129, 257, 513];
35813161 const OFFSET_BITS: [u32; 12] = [0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
35823162
3583- let trace = crate::envflags::env_flag!("EC_AV1_TRACE");
35843163 // libaom's `eob_flag_cdf*` tables carry a second dimension the 2D scan
35853164 // never touches: `TX_CLASS_HORIZ`/`TX_CLASS_VERT` (`V_DCT`/`H_DCT`) adapt
35863165 // a wholly separate CDF from every other tx_type (`decodetxb.c`'s
@@ -3591,22 +3170,11 @@ fn read_eob(dec: &mut SymbolDecoder, coding: &mut TxbTables, class: TxClass) ->
35913170 (TxClass::TwoD, _) | (_, None) => coding.eob_pt,
35923171 (_, Some(class1)) => class1,
35933172 };
3594- if crate::envflags::env_flag!("EC_AV1_EOBPT_CDF") {
3595- let (range, value) = dec.debug_state();
3596- eprintln!("EC_AV1_EOBPT_CDF {eob_pt:?} range={range} value={value}");
3597- }
3598- crate::msac::SymbolDecoder::set_symr_cdf("eob_pt");
35993173 let group = dec.symbol(eob_pt) + 1;
3600- if trace {
3601- eprintln!("TRACE eob_pt value={group} rng={}", dec.debug_state().0);
3602- }
36033174 let bits = OFFSET_BITS[group];
36043175 let mut offset = 0u32;
36053176 if bits > 0 {
36063177 let top = dec.symbol(&mut coding.eob_extra[group - 3]) as u32;
3607- if trace {
3608- eprintln!("TRACE eob_extra ctx={} value={top}", group - 3);
3609- }
36103178 offset = top << (bits - 1);
36113179 if bits > 1 {
36123180 offset |= dec.literal(bits - 1);
@@ -3715,4 +3283,3 @@ pub(crate) fn decode_key_frame_tile(
37153283
37163284 #[cfg(test)]
37173285 mod tests;
3718-
crates/ec-av1/src/decode/post_filter.rsmodified+10 -13
@@ -68,16 +68,16 @@ fn cdef_rows(
6868 .enumerate()
6969 .map(|(k, &(a, b))| {
7070 let start = row_of(a, p) * geom[p].stride;
71- let end = if k == last { len } else { row_of(b, p) * geom[p].stride };
71+ let end = if k == last {
72+ len
73+ } else {
74+ row_of(b, p) * geom[p].stride
75+ };
7276 (start, end)
7377 })
7478 .collect()
7579 };
76- let (yd, ud, vd) = (
77- y.data.to_mut(),
78- u.data.to_mut(),
79- v.data.to_mut(),
80- );
80+ let (yd, ud, vd) = (y.data.to_mut(), u.data.to_mut(), v.data.to_mut());
8181 let (ry, ru, rv) = (
8282 plane_ranges(0, yd.len()),
8383 plane_ranges(1, ud.len()),
@@ -97,7 +97,10 @@ fn cdef_rows(
9797 (start, end)
9898 })
9999 .collect();
100- crate::par::carve_ranges(w, &ranges).into_iter().map(Some).collect()
100+ crate::par::carve_ranges(w, &ranges)
101+ .into_iter()
102+ .map(Some)
103+ .collect()
101104 }
102105 None => (0..n).map(|_| None).collect(),
103106 };
@@ -161,9 +164,6 @@ pub(super) fn apply_cdef(
161164 wrote: Option<&mut [u8]>,
162165 ) {
163166 // lane-part32 r2 debug rung, env-gated: see `apply_deblock`'s sibling.
164- if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_CDEF") {
165- return;
166- }
167167 // `cdef.bits == 0` still means "no filtering at all" whenever the single
168168 // (index 0) strength pair is all-zero -- the fast path every existing
169169 // gate stream takes. A `bits > 0` frame can still be all-zero-strength
@@ -295,9 +295,6 @@ pub(super) fn apply_loop_restoration(
295295 fctx: &crate::decode::FrameCtx,
296296 ) {
297297 // lane-svt1 debug rung, env-gated: see `apply_cdef`/`apply_deblock`'s siblings.
298- if crate::envflags::env_flag!("EC_AV1_DEBUG_SKIP_LR") {
299- return;
300- }
301298 let mut out = scratch_empty();
302299 crate::restoration::apply_loop_restoration_plane(
303300 &y.data,
crates/ec-av1/src/decode/rect.rsmodified+6 -278
@@ -61,41 +61,15 @@ pub(super) fn read_intra_mode_rect(
6161 // `palette_uv` even on a chroma-reference strip. Fold the plane count
6262 // into the same `has_chroma` this reader already gates on.
6363 let has_chroma = has_chroma && !mono(fctx);
64- crate::msac::SymbolDecoder::set_symr_mi(mi_r as i64, mi_c as i64);
65- let ec_istep = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
66- if ec_istep {
67- // Mirrors the oracle's own `EC_IMODE mi_row=.. mi_col=.. rng=..` line
68- // (decodemv.c:818), printed at the same point: before the first
69- // mode-info symbol of the block, so a cross-decoder range ladder can
70- // be keyed on the BLOCK, not just on the symbol sequence.
71- eprintln!(
72- "EC_IMODE mi_row={mi_r} mi_col={mi_c} fn=rect bw={bw} bh={bh} efi={} cls={:?} rng={}",
73- enable_filter_intra as i32,
74- filter_intra_size_class_rect(bw, bh),
75- dec.debug_state().0
76- );
77- }
7864 macro_rules! istep {
79- ($name:literal, $val:expr) => {
80- if ec_istep {
81- let (rng, _) = dec.debug_state();
82- eprintln!(
83- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name={} val={} rng={rng}",
84- $name, $val
85- );
86- }
87- };
65+ ($name:literal, $val:expr) => {};
8866 }
8967 // lane-sbrect10 r1: libaom `is_cfl_allowed` (blockd.h) is
9068 // `block_size_wide <= 32 && block_size_high <= 32` -- enforce it HERE, at
9169 // the one point every rect caller routes through, so no call site can
9270 // offer the 14-symbol CFL alphabet on a 64-axis block (class
9371 // wrong-alphabet-same-value: same value, wrong interval, silent desync).
94- let cfl = if cfl && bw.max(bh) > 32 {
95- false
96- } else {
97- cfl
98- };
72+ let cfl = if cfl && bw.max(bh) > 32 { false } else { cfl };
9973 // lane-intra14 r1: on the INTER block path everything up to and including
10074 // `is_inter` was already read by [`decode_inter_block`], so this reader
10175 // starts at the mode syntax with the `skip` that caller read.
@@ -160,7 +134,6 @@ pub(super) fn read_intra_mode_rect(
160134 // frame's `read_intra_frame_mode_info` (decodemv.c:1065 `read_intra_mode`
161135 // off `kf_y_mode_cdf[above][left]`).
162136 let mode = if let Some((size_group, _)) = inter {
163- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
164137 dec.symbol(&mut cdfs.y_mode[size_group])
165138 } else {
166139 let above_ctx = INTRA_MODE_CTX[above_mode];
@@ -185,10 +158,8 @@ pub(super) fn read_intra_mode_rect(
185158 let uv_mode = if !has_chroma {
186159 DC_PRED
187160 } else if cfl {
188- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
189161 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
190162 } else {
191- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
192163 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
193164 };
194165 istep!("uv_mode", uv_mode as i32);
@@ -233,15 +204,6 @@ pub(super) fn read_intra_mode_rect(
233204 }
234205 }
235206 let mut filter_intra = None;
236- if crate::envflags::env_flag!("EC_AV1_TRACE") {
237- let (rng, _) = dec.debug_state();
238- eprintln!(
239- "TRACE_RECT_PREFI mode={mode} uv_mode={uv_mode} enable_filter_intra={} \
240- class={:?} rng={rng}",
241- enable_filter_intra as i32,
242- filter_intra_size_class_rect(bw, bh)
243- );
244- }
245207 // As the square path: `av1_filter_intra_allowed` excludes a palette-Y
246208 // block (reconintra.h:77), so no `use_filter_intra` symbol exists there.
247209 if mode == DC_PRED
@@ -250,9 +212,6 @@ pub(super) fn read_intra_mode_rect(
250212 && let Some(class) = filter_intra_size_class_rect(bw, bh)
251213 {
252214 let use_filter_intra = dec.symbol(&mut cdfs.filter_intra[class]) != 0;
253- if crate::envflags::env_flag!("EC_AV1_TRACE") {
254- eprintln!("TRACE_RECT_USEFI value={}", use_filter_intra as i32);
255- }
256215 istep!("use_filter_intra", use_filter_intra as i32);
257216 if use_filter_intra {
258217 let fi_mode = dec.symbol(&mut cdfs.filter_intra_mode);
@@ -334,9 +293,6 @@ pub(super) fn record_strip_palette(
334293 // the neighbour bands (`EC_PALPUB=1`) -- the rung that names which decode
335294 // path left a stale `left_palette_size` behind when
336295 // `av1_get_palette_mode_ctx` disagrees with libaom's.
337- if crate::envflags::env_flag!("EC_PALPUB") {
338- eprintln!("EC_PALPUB strip mi={r},{c} bw={bw} bh={bh} y={y_size} uv={uv_size}");
339- }
340296 // lane-kf900 r6: the palette side bands are mi-granular now, so a strip
341297 // writes its OWN span on BOTH axes -- the old `last` split-axis rule only
342298 // existed because the 16px [`SUB`] cell held one slot for all the strips
@@ -503,17 +459,12 @@ pub(super) fn decode_rect_split(
503459 at_mi: (usize, usize),
504460 bw: usize,
505461 bh: usize,
506- // The transform unit's own width and height in pixels. Square for every
507- // 2:1 strip from the first split on, but a 1:4 strip's FIRST split is
508- // still a 2:1 RECT unit (`sub_tx_size_map[TX_32X8] == TX_16X8`,
509- // `[TX_64X16] == TX_32X16`) -- see [`depth_to_tx_wh`].
510462 tx_w: usize,
511463 tx_h: usize,
512464 m: &RectStripModes,
513465 y: &mut PlaneBuf<'static>,
514466 u: &mut PlaneBuf<'static>,
515467 v: &mut PlaneBuf<'static>,
516- base_q_idx: u8,
517468 reduced_tx_set: bool,
518469 fctx: &crate::decode::FrameCtx,
519470 ) -> Result<()> {
@@ -593,14 +544,6 @@ pub(super) fn decode_rect_split(
593544 (64, 32) | (32, 64) | (64, 16) | (16, 64) | (32, 32) | (16, 16) | (8, 8)
594545 );
595546 if !m.skip {
596- if let Some(i) = match (chroma_w, chroma_h) {
597- (32, 8) => Some(0),
598- (8, 32) => Some(1),
599- (8, 4) => Some(2),
600- (4, 8) => Some(3),
601- _ => None,
602- } {
603- }
604547 if !m.skip && chroma.is_none() && !chroma_tiled {
605548 // Diagnostic for the next caller that lands here (class
606549 // refusal-names-a-correlate: the message names the tool, not the
@@ -754,9 +697,6 @@ pub(super) fn decode_rect_split(
754697 // (`av1_get_ext_tx_set_type` resolves EXT_TX_SET_DCTONLY once
755698 // the square-up size is TX_64X64), and this unit covers its
756699 // whole block, so `get_txb_ctx` gives txb_skip ctx 0 flat.
757- if crate::envflags::env_flag!("EC_RECT64TU") {
758- eprintln!("EC_RECT64TU mi={tu_mi:?} tx={tx_w}x{tx_h} mode={}", m.mode);
759- }
760700 let tu_around = neighbours.around_mi_rect(tu_mi, tx_w, tx_h)[0];
761701 let mut coding = cdfs.txb(TxbSet::Luma64, fi_tx_row(m.mode, m.filter_intra));
762702 let (corner, tu_tx_type) = read_coeffs(
@@ -834,7 +774,6 @@ pub(super) fn decode_rect_split(
834774 tu_skip_ctx,
835775 dc_sign_ctx(tu_around.2),
836776 TxType::DctDct,
837- 0,
838777 )?;
839778 let residual = dequant_and_inverse_typed_wh(
840779 &tu_grid,
@@ -890,7 +829,6 @@ pub(super) fn decode_rect_split(
890829 tu_py,
891830 tx_w,
892831 tx_w,
893- base_q_idx,
894832 None,
895833 m.filter_intra,
896834 Some(tu_skip_ctx),
@@ -1117,11 +1055,6 @@ pub(super) fn decode_rect_split(
11171055 cu_row * span_y,
11181056 span_x,
11191057 block_reach,
1120- px,
1121- py,
1122- y.width,
1123- y.height,
1124- fctx,
11251058 );
11261059 let (cu_x, cu_y) = (cpx + cu_col * 4, cpy + cu_row * 4);
11271060 if let Some((ub, vb)) = &m.palette_uv {
@@ -1149,7 +1082,6 @@ pub(super) fn decode_rect_split(
11491082 cu_y,
11501083 4,
11511084 4,
1152- base_q_idx,
11531085 m.alpha
11541086 .zip(ac)
11551087 .map(|((au, av), ac)| (if plane_idx == 1 { au } else { av }, ac)),
@@ -1308,16 +1240,10 @@ pub(super) fn decode_rect_split(
13081240 uw << ss_x(fctx),
13091241 uh << ss_y(fctx),
13101242 reach,
1311- px,
1312- py,
1313- y.width,
1314- y.height,
1315- fctx,
13161243 );
13171244 if cu_reach.above_right != reach.above_right
13181245 || cu_reach.below_left != reach.below_left
1319- {
1320- }
1246+ {}
13211247 // 32x32 does not fit read_coeffs_rect's scratch (768). The
13221248 // square reader is the path every other 32x32 chroma unit uses.
13231249 let levels = if uw == uh {
@@ -1339,7 +1265,6 @@ pub(super) fn decode_rect_split(
13391265 cu_y,
13401266 uw,
13411267 uw,
1342- base_q_idx,
13431268 cfl,
13441269 None,
13451270 bigger.then_some(3),
@@ -1360,7 +1285,6 @@ pub(super) fn decode_rect_split(
13601285 skip_ctx,
13611286 dc_sign_ctx(cu_around[plane_idx].2),
13621287 default_tx,
1363- plane_idx,
13641288 )?;
13651289 let residual = dequant_and_inverse_typed_wh(
13661290 &levels,
@@ -1450,7 +1374,6 @@ pub(super) fn decode_rect_split(
14501374 skip_ctx,
14511375 dc_sign_ctx(around[plane_idx].2),
14521376 default_tx,
1453- plane_idx,
14541377 )?;
14551378 // The same delta_q proof the unsplit rect64 path records
14561379 // (lane-rectsplit r4: lifting the split-transform refusal moved
@@ -1527,13 +1450,6 @@ pub(super) fn decode_rect_split(
15271450 0,
15281451 fctx,
15291452 );
1530- if crate::envflags::env_flag!("EC_AV1_TRACE") {
1531- let (rng, _) = dec.debug_state();
1532- eprintln!(
1533- "TRACE_RECT_SPLIT mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} \
1534- tx={tx_w}x{tx_h} rng={rng}"
1535- );
1536- }
15371453 Ok(())
15381454 }
15391455
@@ -1921,13 +1837,6 @@ pub(super) fn decode_intra_rect_in_inter(
19211837 }
19221838 neighbours.above_side[c] = bw;
19231839 neighbours.left_side[r] = bh;
1924- if crate::envflags::env_flag!("EC_INTRA16X4") {
1925- eprintln!(
1926- "EC_INTRA16X4 decoded mi={mi_r},{mi_c} px={},{} horz={horz} has_chroma={has_chroma} skip={skip} mode={mode} uv={uv:?}",
1927- mi_c * MI,
1928- mi_r * MI
1929- );
1930- }
19311840 return Ok(());
19321841 }
19331842 // lane-inter128intra r1: the 128 superblock's PARTITION_HORZ/VERT half
@@ -1965,13 +1874,6 @@ pub(super) fn decode_intra_rect_in_inter(
19651874 // palette_syntax`), so a 128-root half consumes no palette syntax and
19661875 // a screen-content frame's half is syntactically identical to the
19671876 // non-screen one this arm already decodes byte-exact.
1968- if coeff_trace_on() {
1969- // lane-t900 r16: which decode-order frame this arm fires in --
1970- // interleaved with the `EC_COEFF_FRAME` markers, this is what
1971- // proves the hit is counted out of a frame that compares exact
1972- // (class `counter-from-refused-stream`).
1973- eprintln!("EC_INTRA128 mi_row={r} mi_col={c} bw={bw} bh={bh}");
1974- }
19751877 fctx.intra_in_inter_mode.with(|c| c.set(Some((3, skip))));
19761878 let res = decode_block_128rect(
19771879 dec,
@@ -1994,11 +1896,6 @@ pub(super) fn decode_intra_rect_in_inter(
19941896 return res;
19951897 }
19961898 let Some((size_group, tx_cat)) = intra_in_inter_size_row(bw, bh) else {
1997- if crate::envflags::env_flag!("EC_OBMCREC") {
1998- eprintln!(
1999- "OBMCREC intra-in-inter shape bw={bw} bh={bh} mi=({mi_r},{mi_c}) skip={skip}"
2000- );
2001- }
20021899 // lane-obmcrec r1: the message used to name a 16x4/4x16 strip
20031900 // (class refusal-names-a-correlate). lane-t900 r20: the shapes that
20041901 // can arrive here are enumerated against the measured block-shape
@@ -2072,26 +1969,12 @@ pub(super) fn decode_intra_rect_in_inter(
20721969 };
20731970 fctx.intra_in_inter_mode.with(|c| c.set(None));
20741971 res?;
2075- let shape = match (bw, bh) {
2076- (64, 16) => 0,
2077- (16, 64) => 1,
2078- (32, 8) => 2,
2079- _ => 3,
2080- };
20811972 return Ok(());
20821973 }
2083- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
20841974 let mode = dec.symbol(&mut cdfs.y_mode[size_group]);
20851975 // lane-t900 r1: this arm read six mode symbols with no ladder rung of its
20861976 // own, so a cross-decoder bisection could only see the block's first
20871977 // coefficient. Same names/format as [`read_tx_size`]'s rung.
2088- let step_trace = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
2089- if step_trace {
2090- eprintln!(
2091- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=y_mode val={mode} grp={size_group} rng={}",
2092- dec.debug_state().0
2093- );
2094- }
20951978 if mode >= 13 {
20961979 return Err(unsupported(
20971980 "an intra mode this decoder does not code (round 2)",
@@ -2116,19 +1999,10 @@ pub(super) fn decode_intra_rect_in_inter(
21161999 let uv_mode = if !has_chroma {
21172000 DC_PRED
21182001 } else if cfl_allowed {
2119- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
21202002 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
21212003 } else {
2122- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
21232004 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
21242005 };
2125- if step_trace {
2126- eprintln!(
2127- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=uv_mode val={uv_mode} cfl={} rng={}",
2128- u8::from(cfl_allowed),
2129- dec.debug_state().0
2130- );
2131- }
21322006 let alpha = if cfl_allowed && uv_mode == UV_CFL_PRED {
21332007 Some(read_cfl_alphas(dec, cdfs))
21342008 } else {
@@ -2172,14 +2046,6 @@ pub(super) fn decode_intra_rect_in_inter(
21722046 let use_palette_uv = has_chroma
21732047 && uv_mode == DC_PRED
21742048 && dec.symbol(&mut cdfs.palette_uv_mode[usize::from(use_palette_y)]) != 0;
2175- if crate::envflags::env_flag!("EC_PALSYN") {
2176- eprintln!(
2177- "EC_PALSYN rect mi={mi_r},{mi_c} bw={bw} bh={bh} mode={mode} uv={uv_mode} ctx={palette_ctx} y={} uv={} rng={}",
2178- use_palette_y as i32,
2179- use_palette_uv as i32,
2180- dec.debug_state().0
2181- );
2182- }
21832049 if use_palette_uv {
21842050 let n = 2 + dec.symbol(&mut cdfs.palette_uv_size[bsize_ctx]);
21852051 let (u_colors, v_colors) = read_palette_colors_uv(dec, n, &palette_uv_cache, fctx);
@@ -2254,18 +2120,12 @@ pub(super) fn decode_intra_rect_in_inter(
22542120 // segment regardless of frame type; class sweep of the sub8 leaf's fix).
22552121 let depth = if fctx.tx_select_inter.with(std::cell::Cell::get) && !lossless(fctx) {
22562122 // The frame's own `TXFM_CONTEXT` bands -- [`tx_size_context_txfm_rect`].
2257- let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64), fctx);
2123+ let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw.min(64), bh.min(64));
22582124 let d = match tx_cat {
22592125 1 => dec.symbol(&mut cdfs.tx_size_cat1[ctx]),
22602126 2 => dec.symbol(&mut cdfs.tx_size_cat2[ctx]),
22612127 _ => dec.symbol(&mut cdfs.tx_size_cat3[ctx]),
22622128 };
2263- if step_trace {
2264- eprintln!(
2265- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat={tx_cat} rng={}",
2266- dec.debug_state().0
2267- );
2268- }
22692129 d
22702130 } else {
22712131 0
@@ -2273,9 +2133,6 @@ pub(super) fn decode_intra_rect_in_inter(
22732133 // lane-intrasplit r3: print EVERY intra strip with its depth, not only the
22742134 // split ones -- a `depth=0`-only stream is a witness gap in the SOURCE, and
22752135 // the two are indistinguishable when the diagnostic fires on splits alone.
2276- if crate::envflags::env_flag!("EC_SPLITSTRIP") {
2277- eprintln!("EC_SPLITSTRIP mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} depth={depth}");
2278- }
22792136 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
22802137 // lane-inter16ab r8: libaom runs `set_txfm_ctxs(tx_size, n4_w, n4_h,
22812138 // skip && is_inter, xd)` (decodeframe.c `decode_block`) for EVERY block
@@ -2320,7 +2177,6 @@ pub(super) fn decode_intra_rect_in_inter(
23202177 y,
23212178 u,
23222179 v,
2323- base_q_idx,
23242180 fctx.reduced_tx_set_inter.with(std::cell::Cell::get),
23252181 fctx,
23262182 )?;
@@ -2352,11 +2208,6 @@ pub(super) fn decode_intra_rect_in_inter(
23522208 palette_uv.as_ref().map_or(0, |p| p.size),
23532209 palette_uv.as_ref().map_or([0u16; 8], |p| p.u_colors),
23542210 );
2355- let class = match bw.max(bh) {
2356- 64 => 0,
2357- 32 => 1,
2358- _ => 2,
2359- };
23602211 Ok(())
23612212 }
23622213
@@ -2397,8 +2248,6 @@ pub(super) fn decode_intrabc_rect(
23972248 base_q_idx: u8,
23982249 fctx: &crate::decode::FrameCtx,
23992250 ) -> Result<()> {
2400- // [horz, vert]: see `INTRABC_RECT_CODED_HITS` / `INTRABC_RECT_SKIPPED_HITS`.
2401- let idx = usize::from(bh > bw);
24022251 if skip {
24032252 } else {
24042253 }
@@ -2449,12 +2298,6 @@ pub(super) fn decode_intrabc_rect(
24492298 fctx,
24502299 )?;
24512300 // lane-ibc444c: per-block geometry, for the chroma-tail attribution.
2452- if crate::envflags::env_flag!("EC_IBCBLOCK") {
2453- eprintln!(
2454- "EC_IBCBLOCK mi=({mi_r},{mi_c}) bw={bw} bh={bh} cpx={cpx} cpy={cpy} \
2455- cw={cw} ch={ch} cside={cside} skip={skip}"
2456- );
2457- }
24582301 // The whole-block prediction: `predict_inter_block` runs once, before any
24592302 // coefficient is read. The source is this frame's own reconstruction,
24602303 // which is already written.
@@ -2958,12 +2801,6 @@ pub(super) fn decode_intrabc_128rect(
29582801 base_q_idx: u8,
29592802 fctx: &crate::decode::FrameCtx,
29602803 ) -> Result<()> {
2961- if crate::envflags::env_flag!("EC_AV1_TRACE") {
2962- let (rng, _) = dec.debug_state();
2963- eprintln!(
2964- "EC_IBC128 mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} skip={skip} dv=({dv_row},{dv_col}) rng={rng}"
2965- );
2966- }
29672804 let (px, py) = (mi_c * MI, mi_r * MI);
29682805 // lane-av1-ibc128chunk: the block's chroma PLANE BLOCK is per-axis
29692806 // `(bw >> ss_x) x (bh >> ss_y)` -- 4:2:0 halves both (this fn's
@@ -3283,38 +3120,6 @@ pub(super) fn decode_intrabc_128rect(
32833120 } else {
32843121 neighbours.around_mi_rect(unit_mi, unit_luma_w, unit_luma_h)
32853122 };
3286- if crate::envflags::env_flag!("EC_ECDUMP") {
3287- // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
3288- #[allow(clippy::needless_range_loop)]
3289- for p in 1..3 {
3290- let ab: Vec<String> = (0..unit_luma_w / MI)
3291- .map(|k| {
3292- format!(
3293- "{:?}/{}",
3294- neighbours.above[unit_mi.1 + k][p].dc,
3295- neighbours.above[unit_mi.1 + k][p].level
3296- )
3297- })
3298- .collect();
3299- let lf: Vec<String> = (0..unit_luma_h / MI)
3300- .map(|k| {
3301- format!(
3302- "{:?}/{}",
3303- neighbours.left[unit_mi.0 + k][p].dc,
3304- neighbours.left[unit_mi.0 + k][p].level
3305- )
3306- })
3307- .collect();
3308- eprintln!(
3309- "EC_IBC128_BANDS mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={p} ctx=({},{},{}) above=[{}] left=[{}]",
3310- cu_around[p].0,
3311- cu_around[p].1,
3312- cu_around[p].2,
3313- ab.join(","),
3314- lf.join(",")
3315- );
3316- }
3317- }
33183123 let (cu_x, cu_y) = (
33193124 cpx + cc * chunk_chroma_w + uc * cu_tx,
33203125 cpy + cr * chunk_chroma_h + ur * cu_tx,
@@ -3364,13 +3169,6 @@ pub(super) fn decode_intrabc_128rect(
33643169 plane_idx,
33653170 &cu_grid,
33663171 );
3367- if crate::envflags::env_flag!("EC_ECDUMP") {
3368- let st = crate::decode::neighbour_state(&cu_grid);
3369- eprintln!(
3370- "EC_IBC128_STAMP mi=({mi_r},{mi_c}) unit=({cr},{cc}) plane={plane_idx} state=({:?},{})",
3371- st.dc, st.level
3372- );
3373- }
33743172 // lane-av1-ibcrect: per-unit chroma context -- the
33753173 // end-of-block record's composed-grid re-stamp
33763174 // must not stand (replayed below).
@@ -3690,14 +3488,8 @@ pub(super) fn decode_block_rect(
36903488 // 1920x792 128-superblock stream,
36913489 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
36923490 // `tx_size_cat2` row 1 where libaom reads row 2.
3693- let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
3491+ let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh);
36943492 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
3695- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
3696- eprintln!(
3697- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
3698- dec.debug_state().0
3699- );
3700- }
37013493 d
37023494 } else {
37033495 0
@@ -3717,13 +3509,6 @@ pub(super) fn decode_block_rect(
37173509 // unit's reconstruction inside this same strip (spec 5.11.36) --
37183510 // [`decode_rect_split`], the unit named by [`depth_to_tx_wh`].
37193511 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
3720- if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
3721- eprintln!(
3722- "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
3723- depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
3724- angle_y={angle_delta_y}"
3725- );
3726- }
37273512 let modes = RectStripModes {
37283513 skip,
37293514 mode,
@@ -3757,7 +3542,6 @@ pub(super) fn decode_block_rect(
37573542 y,
37583543 u,
37593544 v,
3760- base_q_idx,
37613545 reduced_tx_set,
37623546 fctx,
37633547 )?;
@@ -3782,14 +3566,6 @@ pub(super) fn decode_block_rect(
37823566 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
37833567 let (chroma_w, chroma_h) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
37843568 let reach = Reach::of_rect(bw, bh, px, py, y.width, y.height, fctx);
3785- if crate::envflags::env_flag!("EC_AV1_TRACE") {
3786- let (rng, _) = dec.debug_state();
3787- eprintln!(
3788- "TRACE_RECT_IMODE mi_row={mi_r} mi_col={mi_c} mode={mode} uv_mode={uv_mode} \
3789- skip={} tx={depth} rng={rng}",
3790- skip as i32
3791- );
3792- }
37933569 // As [`decode_block`]'s own [`PALETTE_PRED`] wiring: a palette-Y/UV
37943570 // block's prediction is the reconstructed colour-index map, set fresh
37953571 // right before each `reconstruct_rect` call below (lane-palette2 r4).
@@ -3987,12 +3763,7 @@ pub(super) fn decode_block_rect(
39873763 0,
39883764 dc_sign_ctx(around[0].2),
39893765 TxType::DctDct,
3990- 0,
39913766 )?;
3992- if crate::envflags::env_flag!("EC_AV1_TRACE") {
3993- let (rng, _) = dec.debug_state();
3994- eprintln!("TRACE_RECT_COEFF plane=0 mi_row={mi_r} mi_col={mi_c} rng={rng}");
3995- }
39963767 let luma_residual = dequant_and_inverse_typed_wh(
39973768 &luma_levels,
39983769 bw,
@@ -4039,12 +3810,7 @@ pub(super) fn decode_block_rect(
40393810 dc_sign_ctx(around[1].2),
40403811 u_default_tx,
40413812 fctx,
4042- 1,
40433813 )?;
4044- if crate::envflags::env_flag!("EC_AV1_TRACE") {
4045- let (rng, _) = dec.debug_state();
4046- eprintln!("TRACE_RECT_COEFF plane=1 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4047- }
40483814 let u_residual = dequant_and_inverse_typed_wh(
40493815 &u_levels,
40503816 chroma_w,
@@ -4090,12 +3856,7 @@ pub(super) fn decode_block_rect(
40903856 dc_sign_ctx(around[2].2),
40913857 v_default_tx,
40923858 fctx,
4093- 2,
40943859 )?;
4095- if crate::envflags::env_flag!("EC_AV1_TRACE") {
4096- let (rng, _) = dec.debug_state();
4097- eprintln!("TRACE_RECT_COEFF plane=2 mi_row={mi_r} mi_col={mi_c} rng={rng}");
4098- }
40993860 let v_residual = dequant_and_inverse_typed_wh(
41003861 &v_levels,
41013862 chroma_w,
@@ -4153,9 +3914,6 @@ pub(super) fn decode_block_rect(
41533914 0,
41543915 fctx,
41553916 );
4156- if crate::envflags::env_flag!("EC_AV1_TRACE") {
4157- eprintln!("TRACE_RECT32_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh}");
4158- }
41593917 Ok(())
41603918 }
41613919
@@ -4200,12 +3958,6 @@ pub(super) fn decode_leaf_rect(
42003958 fctx: &crate::decode::FrameCtx,
42013959 ) -> Result<usize> {
42023960 let _ = base_q_idx;
4203- if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4204- eprintln!(
4205- "decode_leaf_rect: leaf_mi={leaf_mi:?} bw={bw} bh={bh} outer_at={outer_at:?} rng={}",
4206- dec.debug_state().0
4207- );
4208- }
42093961 let (r, c) = outer_at;
42103962 let mut above_mode = neighbours.above_mode[c];
42113963 let mut left_mode = neighbours.left_mode[r];
@@ -4306,9 +4058,6 @@ pub(super) fn decode_leaf_rect(
43064058 let (pal_uv_size, pal_uv_colors) = palette_uv
43074059 .as_ref()
43084060 .map_or((0, [0u16; 8]), |p| (p.size, p.u_colors));
4309- if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4310- eprintln!(" skip={skip} mode={mode} angle_delta_y={angle_delta_y} uv_mode={uv_mode}");
4311- }
43124061 let uv_predict_mode = if uv_mode == UV_CFL_PRED {
43134062 DC_PRED
43144063 } else {
@@ -4328,7 +4077,7 @@ pub(super) fn decode_leaf_rect(
43284077 // The mixed frame's 16x8 leaf at mi(10,0) forked exactly here: ours
43294078 // read `tx_size_cat1` (rng 55700->49918) where the oracle's next
43304079 // read was the leaf's own txb_skip.
4331- let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh, fctx);
4080+ let ctx = tx_size_context_txfm_rect(neighbours, leaf_mi, bw, bh);
43324081 // lane-rectsplitx r1: `bsize_to_tx_size_cat` (libaom `blockd.h`,
43334082 // `bsize_to_tx_size_depth_table`) is 2 for BLOCK_16X8/BLOCK_8X16, so
43344083 // the category is 1 -- NOT the 2 the 32x16 strips read. Same symbol
@@ -4346,14 +4095,6 @@ pub(super) fn decode_leaf_rect(
43464095 // symbol in the tile is read from the wrong place (class
43474096 // `wrong-alphabet-same-value`, here same alphabet / wrong row).
43484097 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
4349- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
4350- eprintln!(
4351- "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
4352- leaf_mi.0,
4353- leaf_mi.1,
4354- dec.debug_state().0
4355- );
4356- }
43574098 d
43584099 } else {
43594100 0
@@ -4398,7 +4139,6 @@ pub(super) fn decode_leaf_rect(
43984139 y,
43994140 u,
44004141 v,
4401- base_q_idx,
44024142 reduced_tx_set,
44034143 fctx,
44044144 )?;
@@ -4561,17 +4301,7 @@ pub(super) fn decode_leaf_rect(
45614301 0,
45624302 dc_sign_ctx(around[0].2),
45634303 TxType::DctDct,
4564- 0,
45654304 )?;
4566- if crate::envflags::env_flag!("EC_AV1_RECTX_TRACE") {
4567- let nz: Vec<(usize, i32)> = l_levels
4568- .iter()
4569- .copied()
4570- .enumerate()
4571- .filter(|(_, v)| *v != 0)
4572- .collect();
4573- eprintln!(" luma_tx_type={luma_tx_type:?} nz_levels={nz:?}");
4574- }
45754305 luma_levels = l_levels;
45764306 let luma_residual = dequant_and_inverse_typed_wh(
45774307 &luma_levels,
@@ -4619,7 +4349,6 @@ pub(super) fn decode_leaf_rect(
46194349 dc_sign_ctx(around[1].2),
46204350 u_default_tx,
46214351 fctx,
4622- 1,
46234352 )?;
46244353 u_levels = u_l;
46254354 let u_residual = dequant_and_inverse_typed_wh(
@@ -4667,7 +4396,6 @@ pub(super) fn decode_leaf_rect(
46674396 dc_sign_ctx(around[2].2),
46684397 v_default_tx,
46694398 fctx,
4670- 2,
46714399 )?;
46724400 v_levels = v_l;
46734401 let v_residual = dequant_and_inverse_typed_wh(
crates/ec-av1/src/decode/rect4.rsmodified+10 -175
@@ -161,14 +161,8 @@ pub(super) fn decode_block_rect4(
161161 // 1920x792 128-superblock stream,
162162 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
163163 // `tx_size_cat2` row 1 where libaom reads row 2.
164- let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
164+ let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh);
165165 let d = dec.symbol(&mut cdfs.tx_size_cat2[ctx]);
166- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
167- eprintln!(
168- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=2 rng={}",
169- dec.debug_state().0
170- );
171- }
172166 d
173167 } else {
174168 0
@@ -210,7 +204,6 @@ pub(super) fn decode_block_rect4(
210204 y,
211205 u,
212206 v,
213- base_q_idx,
214207 false,
215208 fctx,
216209 )?;
@@ -333,7 +326,6 @@ pub(super) fn decode_block_rect4(
333326 0,
334327 dc_sign_ctx(around[0].2),
335328 TxType::DctDct,
336- 0,
337329 )?;
338330 let luma_residual = dequant_and_inverse_typed_wh(
339331 &luma_levels,
@@ -375,20 +367,7 @@ pub(super) fn decode_block_rect4(
375367 for plane in [1usize, 2] {
376368 for unit_row in 0..4usize {
377369 let unit_mi = (mi_r + unit_row * 2, mi_c);
378- let unit_reach = tu_reach_rect(
379- bw,
380- bh,
381- 0,
382- unit_row * 8,
383- 8,
384- 8,
385- reach,
386- px,
387- py,
388- y.width,
389- y.height,
390- fctx,
391- );
370+ let unit_reach = tu_reach_rect(bw, bh, 0, unit_row * 8, 8, 8, reach);
392371 if let Some((ub, vb)) = &palette_uv_bufs {
393372 let pbuf = if plane == 1 { ub } else { vb };
394373 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
@@ -496,7 +475,6 @@ pub(super) fn decode_block_rect4(
496475 0,
497476 dc_sign_ctx(around[0].2),
498477 TxType::DctDct,
499- 0,
500478 )?;
501479 let mut planes = Vec::with_capacity(2);
502480 // Index loop mirrors the spec's per-position form over several offsets; an iterator would obscure it.
@@ -525,7 +503,6 @@ pub(super) fn decode_block_rect4(
525503 dc_sign_ctx(chroma_around[plane].2),
526504 default_tx,
527505 fctx,
528- plane,
529506 )?;
530507 planes.push((levels, tx_type));
531508 }
@@ -662,20 +639,7 @@ pub(super) fn decode_block_rect4(
662639 // libaom's `set_entropy_context` leaves.
663640 for plane in [1usize, 2] {
664641 for unit_row in 0..4usize {
665- let unit_reach = tu_reach_rect(
666- bw,
667- bh,
668- 0,
669- unit_row * 8,
670- 8,
671- 8,
672- reach,
673- px,
674- py,
675- y.width,
676- y.height,
677- fctx,
678- );
642+ let unit_reach = tu_reach_rect(bw, bh, 0, unit_row * 8, 8, 8, reach);
679643 if let Some((ub, vb)) = &palette_uv_bufs {
680644 let pbuf = if plane == 1 { ub } else { vb };
681645 set_palette_pred(palette_window(pbuf, chroma_w, 0, unit_row * 8, 4, 8), fctx);
@@ -933,9 +897,6 @@ pub(super) fn decode_intrabc_owned_rect(
933897 // 73501 V (f1) and 9216 U + 8192 V (f2) are wrong -- chroma-only, which is
934898 // what makes this a chroma-sizing defect and not a block-geometry one.
935899 // Re-measured by this lane; see lanes/av1chromarect.report.md.
936- if crate::envflags::env_flag!("EC_HALVSWEEP") {
937- eprintln!("EC_HALV ibc_owned mi=({mi_r},{mi_c}) bw={bw} bh={bh} skip={skip}");
938- }
939900 let (cw, ch) = (bw >> ss_x(fctx), bh >> ss_y(fctx));
940901 let (cpx, cpy) = (px >> ss_x(fctx), py >> ss_y(fctx));
941902 let side = bw.max(bh);
@@ -1737,15 +1698,6 @@ pub(super) fn decode_rect4_16_intrabc(
17371698 bh,
17381699 );
17391700 let split = dec.symbol(&mut cdfs.txfm_partition[ctx]) == 1;
1740- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
1741- let (rng, _) = dec.debug_state();
1742- eprintln!(
1743- "EC_ISTEP mi_row={} mi_col={} name=txfm_split_rect val={} ctx={ctx} rng={rng}",
1744- lmi.0,
1745- lmi.1,
1746- u8::from(split)
1747- );
1748- }
17491701 if !split {
17501702 None
17511703 } else {
@@ -2303,16 +2255,8 @@ pub(super) fn decode_rect4_16_strip(
23032255 let depth = if tx_select && !lossless(fctx) {
23042256 // lane-av1txbands: every frame reads the real `TXFM_CONTEXT` bands
23052257 // (`get_tx_size_context`, libaom `pred_common.h:342`).
2306- let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
2258+ let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh);
23072259 let d = dec.symbol(&mut cdfs.tx_size_cat1[ctx]);
2308- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
2309- eprintln!(
2310- "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=1 rng={}",
2311- lmi.0,
2312- lmi.1,
2313- dec.debug_state().0
2314- );
2315- }
23162260 d
23172261 } else {
23182262 0
@@ -2387,7 +2331,6 @@ pub(super) fn decode_rect4_16_strip(
23872331 tu_skip_ctx,
23882332 dc_sign_ctx(tu_around.2),
23892333 TxType::DctDct,
2390- 0,
23912334 )?;
23922335 let residual = dequant_and_inverse_typed_wh(
23932336 &tu_grid,
@@ -2440,7 +2383,6 @@ pub(super) fn decode_rect4_16_strip(
24402383 tu_py,
24412384 tx_w,
24422385 tx_w,
2443- base_q_idx,
24442386 None,
24452387 filter_intra,
24462388 Some(tu_skip_ctx),
@@ -2496,7 +2438,6 @@ pub(super) fn decode_rect4_16_strip(
24962438 0,
24972439 dc_sign_ctx(around.2),
24982440 TxType::DctDct,
2499- 0,
25002441 )?;
25012442 let residual = dequant_and_inverse_typed_wh(
25022443 &levels,
@@ -2632,8 +2573,7 @@ pub(super) fn decode_rect4_16_strip(
26322573 ss_y(fctx),
26332574 false,
26342575 )
2635- {
2636- }
2576+ {}
26372577 // lane-av1-rect14: a lossless frame forces TX_4X4 on every plane
26382578 // (`av1_get_tx_size`, blockd.h:1381). The pair's chroma block is
26392579 // 8x4 (HORZ_4) or 4x8 (VERT_4) -- two TX_4X4s, plane-major
@@ -2676,11 +2616,6 @@ pub(super) fn decode_rect4_16_strip(
26762616 4 << ss_x(fctx),
26772617 4 << ss_y(fctx),
26782618 pair_reach,
2679- ppx,
2680- ppy,
2681- y.width,
2682- y.height,
2683- fctx,
26842619 );
26852620 if let Some((ub, vb)) = &palette_uv_bufs {
26862621 let buf = if plane == 1 { ub } else { vb };
@@ -2771,11 +2706,6 @@ pub(super) fn decode_rect4_16_strip(
27712706 4 << ss_x(fctx),
27722707 4 << ss_y(fctx),
27732708 pair_reach,
2774- ppx,
2775- ppy,
2776- y.width,
2777- y.height,
2778- fctx,
27792709 );
27802710 if let Some((ub, vb)) = &palette_uv_bufs {
27812711 let buf = if plane == 1 { ub } else { vb };
@@ -2799,7 +2729,6 @@ pub(super) fn decode_rect4_16_strip(
27992729 cpy + oy,
28002730 4,
28012731 4,
2802- base_q_idx,
28032732 None,
28042733 None,
28052734 offset,
@@ -2839,20 +2768,7 @@ pub(super) fn decode_rect4_16_strip(
28392768 // `set_entropy_context` zeroed the block's own cells,
28402769 // so the pair-wide zero stamp below stays correct.
28412770 for unit_row in 0..2usize {
2842- let unit_reach = tu_reach_rect(
2843- pw,
2844- ph,
2845- 0,
2846- unit_row * 8,
2847- 8,
2848- 8,
2849- pair_reach,
2850- ppx,
2851- ppy,
2852- y.width,
2853- y.height,
2854- fctx,
2855- );
2771+ let unit_reach = tu_reach_rect(pw, ph, 0, unit_row * 8, 8, 8, pair_reach);
28562772 if let Some((ub, vb)) = &palette_uv_bufs {
28572773 let pbuf = if plane == 1 { ub } else { vb };
28582774 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
@@ -2928,20 +2844,7 @@ pub(super) fn decode_rect4_16_strip(
29282844 for plane in [1usize, 2] {
29292845 for unit_row in 0..2usize {
29302846 let unit_mi = (pair_mi.0 + unit_row * 2, pair_mi.1);
2931- let unit_reach = tu_reach_rect(
2932- pw,
2933- ph,
2934- 0,
2935- unit_row * 8,
2936- 8,
2937- 8,
2938- pair_reach,
2939- ppx,
2940- ppy,
2941- y.width,
2942- y.height,
2943- fctx,
2944- );
2847+ let unit_reach = tu_reach_rect(pw, ph, 0, unit_row * 8, 8, 8, pair_reach);
29452848 if let Some((ub, vb)) = &palette_uv_bufs {
29462849 let pbuf = if plane == 1 { ub } else { vb };
29472850 set_palette_pred(palette_window(pbuf, cw, 0, unit_row * 8, 4, 8), fctx);
@@ -3014,9 +2917,7 @@ pub(super) fn decode_rect4_16_strip(
30142917 // row is unreachable there. It is also the witness arm:
30152918 // a restored `/2 chroma height` lands on (8,4) and the
30162919 // counter reads 0.
3017- (8, 8) => {
3018- (TxbSet::Chroma8, default_scan(8))
3019- }
2920+ (8, 8) => (TxbSet::Chroma8, default_scan(8)),
30202921 // lane-av1-422o: with the `chroma422_pair16` arm above,
30212922 // the (2,16) own-strip shape and the 4:4:4 shapes are the
30222923 // only residents; anything else is a named-lane gap.
@@ -3039,7 +2940,6 @@ pub(super) fn decode_rect4_16_strip(
30392940 dc_sign_ctx(around[plane].2),
30402941 default_tx,
30412942 fctx,
3042- plane,
30432943 )?;
30442944 planes.push((levels, tx_type));
30452945 }
@@ -3280,7 +3180,7 @@ pub(super) fn decode_block_rect64(
32803180 // 1920x792 128-superblock stream,
32813181 // decode-order frame 1: the 32x8 HORZ_4 strip at mi(48,176) read
32823182 // `tx_size_cat2` row 1 where libaom reads row 2.
3283- let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh, fctx);
3183+ let ctx = tx_size_context_txfm_rect(neighbours, (mi_r, mi_c), bw, bh);
32843184 // lane-rectsplit r1: `bsize_to_tx_size_cat` (libaom `decodemv.c`)
32853185 // counts `sub_tx_size_map` steps from the block's own max rect
32863186 // transform down to TX_4X4, minus one -- BLOCK_64X32's chain
@@ -3289,12 +3189,6 @@ pub(super) fn decode_block_rect64(
32893189 // block uses), not the 2 a 32x16 strip uses. Reading the cat-2 CDF
32903190 // here was a wrong-table read of a real symbol.
32913191 let d = dec.symbol(&mut cdfs.tx_size_cat3[ctx]);
3292- if crate::envflags::env_flag!("EC_TRACE_MODE_STEP") {
3293- eprintln!(
3294- "EC_ISTEP mi_row={mi_r} mi_col={mi_c} name=tx_depth val={d} ctx={ctx} cat=3 rng={}",
3295- dec.debug_state().0
3296- );
3297- }
32983192 d
32993193 } else {
33003194 0
@@ -3315,15 +3209,7 @@ pub(super) fn decode_block_rect64(
33153209 // 1:4 strip is the 2:1 rect TX_32X16 at depth 1 (lane-rectchroma r1
33163210 // measured the old square formula mis-tiling exactly that strip).
33173211 let (tx_w, tx_h) = depth_to_tx_wh(bw, bh, depth, fctx);
3318- if bw.max(bh) / bw.min(bh) == 4 {
3319- }
3320- if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
3321- eprintln!(
3322- "DUMP64SPLIT mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} \
3323- depth={depth} tx={tx_w}x{tx_h} mode={mode} uv={uv_predict_mode} skip={skip} \
3324- angle_y={angle_delta_y}"
3325- );
3326- }
3212+ if bw.max(bh) / bw.min(bh) == 4 {}
33273213 let modes = RectStripModes {
33283214 skip,
33293215 mode,
@@ -3357,7 +3243,6 @@ pub(super) fn decode_block_rect64(
33573243 y,
33583244 u,
33593245 v,
3360- base_q_idx,
33613246 reduced_tx_set,
33623247 fctx,
33633248 )?;
@@ -3491,12 +3376,6 @@ pub(super) fn decode_block_rect64(
34913376 // 32x16/16x32 under a 64x16/16x64 1:4 strip (lane-tx64x16).
34923377 let (luma_cw, luma_ch) = (bw.min(32), bh.min(32));
34933378 let scan32 = default_scan(TX32);
3494- if coeff_trace_on() {
3495- let (rng, _) = dec.debug_state();
3496- eprintln!(
3497- "EC_COEFF plane=0 row={mi_r} col={mi_c} tx_size={luma_cw}x{luma_ch} rng={rng}"
3498- );
3499- }
35003379 let (luma_corner, luma_tx_type) = if (luma_cw, luma_ch) == (32, 32) {
35013380 let mut luma_coding = cdfs.txb(TxbSet::Luma64, mode);
35023381 read_coeffs(
@@ -3533,26 +3412,13 @@ pub(super) fn decode_block_rect64(
35333412 0,
35343413 dc_sign_ctx(around[0].2),
35353414 TxType::DctDct,
3536- 0,
35373415 )?
35383416 };
3539- if coeff_trace_on() {
3540- let (rng, _) = dec.debug_state();
3541- eprintln!("EC_COEFF_VAL plane=0 row={mi_r} col={mi_c} rng={rng}");
3542- }
35433417 let mut luma_levels = vec![0i32; bw * bh];
35443418 for row in 0..luma_ch {
35453419 luma_levels[row * bw..][..luma_cw]
35463420 .copy_from_slice(&luma_corner[row * luma_cw..][..luma_cw]);
35473421 }
3548- {
3549- let cur = block_q_idx(fctx);
3550- if crate::envflags::env_flag!("EC_AV1_TRACE") {
3551- eprintln!(
3552- "TRACE rect64_dequant plane=0 base_q_idx={base_q_idx} current_q_idx={cur}"
3553- );
3554- }
3555- }
35563422 let luma_residual = dequant_and_inverse_typed_wh(
35573423 &luma_levels,
35583424 bw,
@@ -3582,22 +3448,6 @@ pub(super) fn decode_block_rect64(
35823448 smooth_neighbor,
35833449 fctx,
35843450 );
3585- if crate::envflags::env_flag!("EC_SBPART_DUMP64") {
3586- let leftcol: Vec<u16> = if px > 0 {
3587- (py..py + bh)
3588- .map(|row| y.data[row * y.width + px - 1])
3589- .collect()
3590- } else {
3591- vec![]
3592- };
3593- eprintln!(
3594- "DUMP64 mi_r={mi_r} mi_c={mi_c} px={px} py={py} bw={bw} bh={bh} mode={mode} \
3595- skip={skip} eob_nonzero={} row0={:?} leftcol={:?}",
3596- luma_corner.iter().any(|&v| v != 0),
3597- &y.data[py * y.width + px..][..bw],
3598- leftcol,
3599- );
3600- }
36013451 // CHROMA. At 4:2:0 the plane block is already one adjusted UV
36023452 // transform (<=32 on each axis). At 4:4:4 a 64-axis strip's chroma
36033453 // is larger than that, so it is tiled into 32-capped units.
@@ -3624,15 +3474,6 @@ pub(super) fn decode_block_rect64(
36243474 // arm nothing had reached) from `nh >= 2` (the arm the corpus census
36253475 // already covered), and can see WHY a candidate block did not fire.
36263476 // Diagnostic only; no decode behaviour depends on it.
3627- if crate::envflags::env_flag!("EC_PALWALK") {
3628- eprintln!(
3629- "EC_PALWALK mi={r},{c} px={px} py={py} bw={bw} bh={bh} cw={chroma_w} \
3630- ch={chroma_h} uw={uw} uh={uh} nw={nw} nh={nh} ast={allow_screen_content_tools} \
3631- puv={} py_pal={}",
3632- palette_uv.is_some() as i32,
3633- palette_y.is_some() as i32
3634- );
3635- }
36363477 let mut u_levels = vec![0i32; chroma_w * chroma_h];
36373478 let mut v_levels = vec![0i32; chroma_w * chroma_h];
36383479 // The tiled units below stamp their own coefficient context
@@ -3703,7 +3544,6 @@ pub(super) fn decode_block_rect64(
37033544 cpy + cu_row * uh,
37043545 uw,
37053546 uw,
3706- base_q_idx,
37073547 cfl,
37083548 None,
37093549 bigger.then_some(3),
@@ -3725,7 +3565,6 @@ pub(super) fn decode_block_rect64(
37253565 dc_sign_ctx(cu_around[plane_idx].2),
37263566 TxType::DctDct,
37273567 fctx,
3728- plane_idx,
37293568 )?;
37303569 let residual = dequant_and_inverse_typed_wh(
37313570 &levels,
@@ -3844,9 +3683,5 @@ pub(super) fn decode_block_rect64(
38443683 // 3840x1608 10-bit stream's first silent wall, decode-order frame 33 at
38453684 // mi(16,480)). Same write as [`set_txfm_ctxs`], rect-aware.
38463685 txfm_partition_update_rect(neighbours, (mi_r, mi_c), (tx_w, tx_h), (bw, bh));
3847- if crate::envflags::env_flag!("EC_AV1_TRACE") {
3848- let (rng, _) = dec.debug_state();
3849- eprintln!("TRACE_RECT64_END mi_row={mi_r} mi_col={mi_c} bw={bw} bh={bh} rng={rng}");
3850- }
38513686 Ok(())
38523687 }
crates/ec-av1/src/decode/replay.rsmodified+1 -7
@@ -508,11 +508,6 @@ pub(super) fn cdef_band(
508508 let y_dir = if y_pri_strength != 0 { dir } else { 0 };
509509 let t = cdef_adjust_strength(y_pri_strength, var);
510510 // lane-cdef r1 rung: one line per filtered 8x8 luma CDEF unit.
511- if crate::envflags::env_flag!("EC_AV1_CDEF_DBG") {
512- eprintln!(
513- "EC_CDEF mi_r={mi_r} mi_c={mi_c} x={ox} y={oy} sidx={sidx} dir={dir} var={var} t={t} pri={y_pri_strength} sec={y_sec_strength} damp={damping}"
514- );
515- }
516511 let enable_primary = t != 0;
517512 let enable_secondary = y_sec_strength != 0;
518513 if (ox + 8 > frame_w || oy + 8 > frame_h)
@@ -520,8 +515,7 @@ pub(super) fn cdef_band(
520515 || enable_secondary
521516 || cdef.uv_pri_strength[sidx] != 0
522517 || cdef.uv_sec_strength[sidx] != 0)
523- {
524- }
518+ {}
525519 if enable_primary || enable_secondary {
526520 cdef_filter_block(
527521 &win_y,
crates/ec-av1/src/decode/sub8_inter.rsmodified+85 -187
@@ -71,7 +71,6 @@ pub(super) fn decode_inter_sub8_split4(
7171 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 4] =
7272 [None; 4];
7373 let mut first_tx_type = TxType::DctDct;
74- let mut sub0_tx_type = TxType::DctDct;
7574 // This loop iteration's own sub-block luma `tx_type` (libaom `mbmi->tx_type`
7675 // after its `read_tx_type`): the per-piece 4:4:4 chroma units inherit it
7776 // (`av1_get_tx_type`, blockd.h -- inter chroma never codes its own symbol).
@@ -110,11 +109,6 @@ pub(super) fn decode_inter_sub8_split4(
110109 let skip_ctx =
111110 usize::from(neighbours.above_skip[cmi]) + usize::from(neighbours.left_skip[rmi]);
112111 let skip = dec.symbol(&mut cdfs.skip[skip_ctx]) == 1;
113- let ec_skip_post = if std::env::var_os("EC_DBG_SUB8").is_some() {
114- Some(dec.debug_state().0)
115- } else {
116- None
117- };
118112 inter_segment_id(dec, cdfs, rmi, cmi, 1, 1, skip, false, fctx);
119113 maybe_read_cdef_idx(dec, rmi, cmi, (2, 2), skip, fctx);
120114 maybe_read_delta_q(dec, cdfs, rmi, cmi, false, skip, fctx);
@@ -127,21 +121,7 @@ pub(super) fn decode_inter_sub8_split4(
127121 neighbours.left_inter[rmi],
128122 );
129123 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
130- if std::env::var_os("EC_DBG_SUB8").is_some() {
131- eprintln!(
132- "EC_DBG piece mi=({rmi},{cmi}) skip={skip} skipctx={skip_ctx} skip_post={:?} is_inter={is_inter} iictx={ii_ctx} post={}",
133- ec_skip_post,
134- dec.debug_state().0
135- );
136- }
137124 if !is_inter {
138- if crate::envflags::env_flag!("EC_SUB8INTRA") {
139- eprintln!(
140- "EC_SUB8INTRA shape=4x4 sub={i} has_chroma={} skip={skip} mi={rmi},{cmi} tx_select={}",
141- i == 3,
142- fctx.tx_select_inter.with(std::cell::Cell::get),
143- );
144- }
145125 // lane-sub8intra: the `BLOCK_4X4` twin of the HORZ/VERT arm --
146126 // same [`decode_intra_sub8_leaf`], no tx-depth symbol, chroma on
147127 // the chroma-reference sub-blocks (`is_chroma_reference`: the
@@ -161,7 +141,6 @@ pub(super) fn decode_inter_sub8_split4(
161141 y,
162142 u,
163143 v,
164- base_q_idx,
165144 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
166145 fctx.tx_select_inter.with(std::cell::Cell::get),
167146 reduced_tx_set,
@@ -175,12 +154,6 @@ pub(super) fn decode_inter_sub8_split4(
175154 // Same print point as the oracle's `EC_MODE` (entry of
176155 // `read_inter_block_mode_info`, i.e. after skip / is_inter), so the
177156 // two range ladders line up element for element.
178- if crate::envflags::env_flag!("EC_TRACE_MODE") {
179- eprintln!(
180- "EC_MODE mi_row={rmi} mi_col={cmi} rng={}",
181- dec.debug_state().0
182- );
183- }
184157 let ref_frame = read_single_ref(
185158 dec,
186159 cdfs,
@@ -230,7 +203,6 @@ pub(super) fn decode_inter_sub8_split4(
230203 tpl,
231204 );
232205 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
233- let mut is_globalmv = false;
234206 let (mv, is_new_mv) = if !not_new {
235207 let mut idx = 0usize;
236208 while idx < 2 && stack.entries.len() > idx + 1 {
@@ -254,7 +226,6 @@ pub(super) fn decode_inter_sub8_split4(
254226 )
255227 } else {
256228 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
257- is_globalmv = !not_zero;
258229 let mv = if !not_zero {
259230 gm_table[(ref_frame - LAST_FRAME) as usize]
260231 } else {
@@ -276,17 +247,8 @@ pub(super) fn decode_inter_sub8_split4(
276247 };
277248 // Same print point as the oracle's `EC_MODE_MV` (right after
278249 // `assign_mv`), the second rung of the sub-8x8 range ladder.
279- if crate::envflags::env_flag!("EC_TRACE_MODE") {
280- eprintln!(
281- "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}",
282- mv.0,
283- mv.1,
284- dec.debug_state().0
285- );
286- }
287250 // No `interintra` and no `motion_mode`/`obmc` symbol below 8x8 (see
288251 // this function's own doc); `read_mb_interp_filter` still runs.
289- let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
290252 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
291253 || neighbours.above_ref1[cmi] == Some(ref_frame)
292254 {
@@ -301,18 +263,6 @@ pub(super) fn decode_inter_sub8_split4(
301263 } else {
302264 [3, 3]
303265 };
304- if crate::envflags::env_flag!("EC_AV1_IFDBG") {
305- eprintln!(
306- "IFDBG4 mi=({rmi},{cmi}) ref={ref_frame} above_ref={} above_ref1={:?} \
307- above_filt={:?} left_ref={} left_ref1={:?} left_filt={:?}",
308- neighbours.above_ref[cmi],
309- neighbours.above_ref1[cmi],
310- neighbours.above_filter[cmi],
311- neighbours.left_ref[rmi],
312- neighbours.left_ref1[rmi],
313- neighbours.left_filter[rmi],
314- );
315- }
316266 // lane-t900 r9: this reader's sub-blocks have a 4-px side, and libaom
317267 // `is_nontrans_global_motion` returns 0 for
318268 // `AOMMIN(mi_size_wide, mi_size_high) < 2` BEFORE testing any model --
@@ -328,16 +278,6 @@ pub(super) fn decode_inter_sub8_split4(
328278 left_filter_ctx,
329279 false,
330280 );
331- if crate::envflags::env_flag!("EC_TRACE_MODE") {
332- eprintln!(
333- "EC_MODE_VAL4 mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \
334- ref0={ref_frame} mv0=({},{}) stack={} rng={}",
335- mv.0,
336- mv.1,
337- stack.entries.len(),
338- dec.debug_state().0
339- );
340- }
341281 grid.set(
342282 rmi,
343283 cmi,
@@ -387,7 +327,11 @@ pub(super) fn decode_inter_sub8_split4(
387327 let pred_y: Vec<u16>;
388328 let sy = if pred_deferred(refpix) {
389329 push_pred(build);
390- Pred::Cur { plane: 0, stride: B4, off: 0 }
330+ Pred::Cur {
331+ plane: 0,
332+ stride: B4,
333+ off: 0,
334+ }
391335 } else {
392336 let mut built: [Vec<u16>; 3] = Default::default();
393337 build(y, u, v, refpix, fctx, &mut built);
@@ -429,9 +373,6 @@ pub(super) fn decode_inter_sub8_split4(
429373 fctx,
430374 )?;
431375 piece_tx_type = tx_type;
432- if i == 0 {
433- sub0_tx_type = tx_type;
434- }
435376 if i == 3 {
436377 // `av1_get_tx_type`'s chroma tail scales `blk_row`/`blk_col`
437378 // back by the subsampling, but it indexes `xd->tx_type_map`,
@@ -497,7 +438,18 @@ pub(super) fn decode_inter_sub8_split4(
497438 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
498439 let (su, sv) = if pred_deferred(refpix) {
499440 push_pred(build_c);
500- (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 })
441+ (
442+ Pred::Cur {
443+ plane: 1,
444+ stride: B4,
445+ off: 0,
446+ },
447+ Pred::Cur {
448+ plane: 2,
449+ stride: B4,
450+ off: 0,
451+ },
452+ )
501453 } else {
502454 let mut built: [Vec<u16>; 3] = Default::default();
503455 build_c(y, u, v, refpix, fctx, &mut built);
@@ -681,7 +633,18 @@ pub(super) fn decode_inter_sub8_split4(
681633 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
682634 let (su, sv) = if pred_deferred(refpix) {
683635 push_pred(build_c);
684- (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 })
636+ (
637+ Pred::Cur {
638+ plane: 1,
639+ stride: B4,
640+ off: 0,
641+ },
642+ Pred::Cur {
643+ plane: 2,
644+ stride: B4,
645+ off: 0,
646+ },
647+ )
685648 } else {
686649 let mut built: [Vec<u16>; 3] = Default::default();
687650 build_c(y, u, v, refpix, fctx, &mut built);
@@ -899,7 +862,18 @@ pub(super) fn decode_inter_sub8_split4(
899862 let (pred_u, pred_v): (Vec<u16>, Vec<u16>);
900863 let (su, sv) = if pred_deferred(refpix) {
901864 push_pred(build);
902- (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 })
865+ (
866+ Pred::Cur {
867+ plane: 1,
868+ stride: B4,
869+ off: 0,
870+ },
871+ Pred::Cur {
872+ plane: 2,
873+ stride: B4,
874+ off: 0,
875+ },
876+ )
903877 } else {
904878 let mut built: [Vec<u16>; 3] = Default::default();
905879 build(y, u, v, refpix, fctx, &mut built);
@@ -977,8 +951,6 @@ pub(super) fn decode_inter_sub8_split4(
977951 fctx,
978952 )?
979953 .0;
980- let coded = ug.iter().chain(vg.iter()).any(|&c| c != 0);
981- note_sub8_chroma_tx(sub0_tx_type, first_tx_type, coded);
982954 (ug, vg)
983955 };
984956 let round_up_even = |n: usize| n.div_ceil(2) * 2;
@@ -1031,7 +1003,6 @@ pub(super) fn decode_intra_sub8_leaf(
10311003 grid: &mut MiGrid,
10321004 group_mi: (usize, usize),
10331005 lmi: (usize, usize),
1034- // `(bw, bh)`: 8x4 / 4x8 under HORZ/VERT, 4x4 under SPLIT.
10351006 (bw, bh): (usize, usize),
10361007 has_chroma: bool,
10371008 skip: bool,
@@ -1039,7 +1010,6 @@ pub(super) fn decode_intra_sub8_leaf(
10391010 y: &mut PlaneBuf<'static>,
10401011 u: &mut PlaneBuf<'static>,
10411012 v: &mut PlaneBuf<'static>,
1042- base_q_idx: u8,
10431013 enable_filter_intra: bool,
10441014 tx_select: bool,
10451015 reduced_tx_set: bool,
@@ -1055,19 +1025,9 @@ pub(super) fn decode_intra_sub8_leaf(
10551025 let (above_mode, left_mode) = neighbours.modes_above_left(r, c);
10561026 let leaf_above = neighbours.mode_above_mi(lmi.0, lmi.1).unwrap_or(above_mode);
10571027 let leaf_left = neighbours.mode_left_mi(lmi.0, lmi.1).unwrap_or(left_mode);
1058- let step = crate::envflags::env_flag!("EC_TRACE_MODE_STEP");
10591028 // `size_group_lookup[BLOCK_8X4] == size_group_lookup[BLOCK_4X8] == 0`
10601029 // (libaom common_data.h:61).
1061- crate::msac::SymbolDecoder::set_symr_cdf("y_mode");
10621030 let mode = dec.symbol(&mut cdfs.y_mode[0]);
1063- if step {
1064- eprintln!(
1065- "EC_ISTEP mi_row={} mi_col={} name=mode val={mode} rng={}",
1066- lmi.0,
1067- lmi.1,
1068- dec.debug_state().0
1069- );
1070- }
10711031 // No angle delta below 8x8 (`av1_use_angle_delta`), for luma or chroma.
10721032 let angle_delta_y = 0;
10731033 let (uv_mode, alpha) = if has_chroma {
@@ -1081,20 +1041,10 @@ pub(super) fn decode_intra_sub8_leaf(
10811041 // always 4x4-or-smaller, so the predicate stays true and this read
10821042 // is unchanged.
10831043 let uv_mode = if cfl_allowed_px(bw, bh, fctx) {
1084- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
10851044 dec.symbol(&mut cdfs.uv_mode_cfl[mode])
10861045 } else {
1087- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
10881046 dec.symbol(&mut cdfs.uv_mode_no_cfl[mode])
10891047 };
1090- if step {
1091- eprintln!(
1092- "EC_ISTEP mi_row={} mi_col={} name=uv_mode val={uv_mode} rng={}",
1093- lmi.0,
1094- lmi.1,
1095- dec.debug_state().0
1096- );
1097- }
10981048 let alpha = if uv_mode == UV_CFL_PRED {
10991049 Some(read_cfl_alphas(dec, cdfs))
11001050 } else {
@@ -1113,24 +1063,8 @@ pub(super) fn decode_intra_sub8_leaf(
11131063 .expect("BLOCK_4X8/BLOCK_8X4 are inside av1_filter_intra_allowed_bsize")
11141064 };
11151065 let use_fi = dec.symbol(&mut cdfs.filter_intra[fi_class]);
1116- if step {
1117- eprintln!(
1118- "EC_ISTEP mi_row={} mi_col={} name=use_filter_intra val={use_fi} rng={}",
1119- lmi.0,
1120- lmi.1,
1121- dec.debug_state().0
1122- );
1123- }
11241066 if use_fi != 0 {
11251067 let fi = dec.symbol(&mut cdfs.filter_intra_mode);
1126- if step {
1127- eprintln!(
1128- "EC_ISTEP mi_row={} mi_col={} name=filter_intra_mode val={fi} rng={}",
1129- lmi.0,
1130- lmi.1,
1131- dec.debug_state().0
1132- );
1133- }
11341068 filter_intra = Some(fi);
11351069 }
11361070 }
@@ -1146,16 +1080,8 @@ pub(super) fn decode_intra_sub8_leaf(
11461080 // no depth symbol either (sweep of the class fixed at the key-frame pair
11471081 // path).
11481082 let depth = if tx_select && bw != bh && !lossless(fctx) {
1149- let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh, fctx);
1083+ let ctx = tx_size_context_txfm_rect(neighbours, lmi, bw, bh);
11501084 let d = dec.symbol(&mut cdfs.tx_size_cat0[ctx]);
1151- if step {
1152- eprintln!(
1153- "EC_ISTEP mi_row={} mi_col={} name=tx_depth val={d} ctx={ctx} cat=0 rng={}",
1154- lmi.0,
1155- lmi.1,
1156- dec.debug_state().0
1157- );
1158- }
11591085 d
11601086 } else {
11611087 0
@@ -1180,19 +1106,7 @@ pub(super) fn decode_intra_sub8_leaf(
11801106 (lmi.0, lmi.1 + tu)
11811107 };
11821108 let (tu_px, tu_py) = (tu_mi.1 * MI, tu_mi.0 * MI);
1183- let tu_reach = tu_reach(
1184- bw,
1185- bh,
1186- tu_px - px,
1187- tu_py - py,
1188- 4,
1189- reach,
1190- px,
1191- py,
1192- y.width,
1193- y.height,
1194- fctx,
1195- );
1109+ let tu_reach = tu_reach(bw, bh, tu_px - px, tu_py - py, 4, reach);
11961110 if skip {
11971111 let zeros = vec![0i32; 16];
11981112 push_intra(
@@ -1239,7 +1153,6 @@ pub(super) fn decode_intra_sub8_leaf(
12391153 tu_py,
12401154 4,
12411155 TX4,
1242- base_q_idx,
12431156 None,
12441157 filter_intra,
12451158 Some(tu_skip_ctx),
@@ -1295,7 +1208,6 @@ pub(super) fn decode_intra_sub8_leaf(
12951208 py,
12961209 4,
12971210 TX4,
1298- base_q_idx,
12991211 None,
13001212 filter_intra,
13011213 None,
@@ -1345,7 +1257,6 @@ pub(super) fn decode_intra_sub8_leaf(
13451257 0,
13461258 dc_sign_ctx(around.2),
13471259 TxType::DctDct,
1348- 0,
13491260 )?;
13501261 let residual = dequant_and_inverse_typed_wh(
13511262 &levels,
@@ -1485,7 +1396,6 @@ pub(super) fn decode_intra_sub8_leaf(
14851396 u,
14861397 v,
14871398 scan4,
1488- base_q_idx,
14891399 neighbours.smooth_uv_neighbour(lmi.0, lmi.1, r, c, fctx),
14901400 (bw, bh),
14911401 fctx,
@@ -1655,8 +1565,7 @@ pub(super) fn decode_intra_sub8_leaf(
16551565 // At 4:4:4 a TX_4X4 chroma unit IS one mi cell.
16561566 let tu_mi = (lmi.0 + oy / MI, lmi.1 + ox / MI);
16571567 let tu_around = neighbours.around_mi(tu_mi, MI);
1658- let tu_r =
1659- tu_reach(bw, bh, ox, oy, 4, reach_c, px, py, y.width, y.height, fctx);
1568+ let tu_r = tu_reach(bw, bh, ox, oy, 4, reach_c);
16601569 // The plane block (8x4/4x8) is bigger than the TX_4X4
16611570 // transform, so `get_txb_ctx`'s chroma ctx_offset is 10,
16621571 // not 7 -- our chroma tables carry the offset-10 rows at
@@ -1680,7 +1589,6 @@ pub(super) fn decode_intra_sub8_leaf(
16801589 py + oy,
16811590 4,
16821591 TX4,
1683- base_q_idx,
16841592 None,
16851593 None,
16861594 Some(3),
@@ -1736,7 +1644,6 @@ pub(super) fn decode_intra_sub8_leaf(
17361644 skip_ctx,
17371645 dc_sign_ctx(around.2),
17381646 uv_tx,
1739- plane,
17401647 )?;
17411648 let residual = dequant_and_inverse_typed_wh(
17421649 &levels,
@@ -1796,7 +1703,6 @@ pub(super) fn decode_intra_sub8_leaf(
17961703 unit_y,
17971704 4,
17981705 TX4,
1799- base_q_idx,
18001706 alpha.zip(ac).map(|((au, _), ac)| (au, ac)),
18011707 None,
18021708 None,
@@ -1821,7 +1727,6 @@ pub(super) fn decode_intra_sub8_leaf(
18211727 unit_y,
18221728 4,
18231729 TX4,
1824- base_q_idx,
18251730 alpha.zip(ac).map(|((_, av), ac)| (av, ac)),
18261731 None,
18271732 None,
@@ -1946,7 +1851,6 @@ pub(super) fn decode_inter_sub8_rect2(
19461851 let mut piece: [Option<(i8, (i32, i32), mc::InterpFilterKind, mc::InterpFilterKind)>; 2] =
19471852 [None; 2];
19481853 let mut first_tx_type = TxType::DctDct;
1949- let mut sub0_tx_type = TxType::DctDct;
19501854 // lane-av1-444: `is_chroma_reference` is unconditional at subsampling 0/0
19511855 // (av1_common_int.h:1459), so every 8x4/4x8 piece is its own chroma
19521856 // reference and codes its own 8x4/4x8 U/V units right after its luma --
@@ -2027,15 +1931,6 @@ pub(super) fn decode_inter_sub8_rect2(
20271931 );
20281932 let is_inter = dec.symbol(&mut cdfs.intra_inter[ii_ctx]) == 1;
20291933 if !is_inter {
2030- if crate::envflags::env_flag!("EC_SUB8INTRA") {
2031- eprintln!(
2032- "EC_SUB8INTRA shape={}x{} sub={i} has_chroma={} skip={skip} mi={rmi},{cmi} tx_select={}",
2033- bw,
2034- bh,
2035- piece_is_chroma_ref(i),
2036- fctx.tx_select_inter.with(std::cell::Cell::get),
2037- );
2038- }
20391934 // lane-sub8x4 r2: refusal and bypass lifted -- see the split arm's
20401935 // note above for the gate that proves this leaf.
20411936 // Its chroma rule is `is_sub8x8_inter`'s: when the
@@ -2056,7 +1951,6 @@ pub(super) fn decode_inter_sub8_rect2(
20561951 y,
20571952 u,
20581953 v,
2059- base_q_idx,
20601954 fctx.enable_filter_intra_inter.with(std::cell::Cell::get),
20611955 fctx.tx_select_inter.with(std::cell::Cell::get),
20621956 reduced_tx_set,
@@ -2067,12 +1961,6 @@ pub(super) fn decode_inter_sub8_rect2(
20671961 }
20681962 continue;
20691963 }
2070- if crate::envflags::env_flag!("EC_TRACE_MODE") {
2071- eprintln!(
2072- "EC_MODE mi_row={rmi} mi_col={cmi} rng={}",
2073- dec.debug_state().0
2074- );
2075- }
20761964 let ref_frame = read_single_ref(
20771965 dec,
20781966 cdfs,
@@ -2119,7 +2007,6 @@ pub(super) fn decode_inter_sub8_rect2(
21192007 tpl,
21202008 );
21212009 let not_new = dec.symbol(&mut cdfs.new_mv[stack.new_mv_ctx]) == 1;
2122- let mut is_globalmv = false;
21232010 let (mv, is_new_mv) = if !not_new {
21242011 let mut idx = 0usize;
21252012 while idx < 2 && stack.entries.len() > idx + 1 {
@@ -2143,7 +2030,6 @@ pub(super) fn decode_inter_sub8_rect2(
21432030 )
21442031 } else {
21452032 let not_zero = dec.symbol(&mut cdfs.zero_mv[stack.zero_mv_ctx]) == 1;
2146- is_globalmv = !not_zero;
21472033 let mv = if !not_zero {
21482034 gm_table[(ref_frame - LAST_FRAME) as usize]
21492035 } else {
@@ -2163,15 +2049,6 @@ pub(super) fn decode_inter_sub8_rect2(
21632049 };
21642050 (mv, false)
21652051 };
2166- if crate::envflags::env_flag!("EC_TRACE_MODE") {
2167- eprintln!(
2168- "EC_MODE_MV mi_row={rmi} mi_col={cmi} mv0=({},{}) rng={}",
2169- mv.0,
2170- mv.1,
2171- dec.debug_state().0
2172- );
2173- }
2174- let gm_ref = &global_motion[(ref_frame - LAST_FRAME) as usize];
21752052 let above_filter_ctx = if neighbours.above_ref[cmi] == ref_frame
21762053 || neighbours.above_ref1[cmi] == Some(ref_frame)
21772054 {
@@ -2249,17 +2126,6 @@ pub(super) fn decode_inter_sub8_rect2(
22492126 leaves.push((0, 0, bw, bh));
22502127 set_txfm_ctxs(neighbours, lmi, bw.max(bh), w_mi, h_mi, skip);
22512128 }
2252- if crate::envflags::env_flag!("EC_TRACE_MODE") {
2253- eprintln!(
2254- "EC_MODE_VALR mi_row={rmi} mi_col={cmi} newmv={is_new_mv} globalmv={is_globalmv} \
2255- ref0={ref_frame} mv0=({},{}) stack={} leaves={} rng={}",
2256- mv.0,
2257- mv.1,
2258- stack.entries.len(),
2259- leaves.len(),
2260- dec.debug_state().0
2261- );
2262- }
22632129 grid_stamp_rect(grid, rmi, cmi, w_mi, h_mi, ref_frame, mv, is_new_mv);
22642130 piece[i] = Some((ref_frame, mv, h_filter, v_filter));
22652131 // Prediction over the leaf's true footprint, laid out at the group's
@@ -2301,7 +2167,11 @@ pub(super) fn decode_inter_sub8_rect2(
23012167 let pred_y: Vec<u16>;
23022168 let sy = if pred_deferred(refpix) {
23032169 push_pred(build);
2304- Pred::Cur { plane: 0, stride: SIDE, off: 0 }
2170+ Pred::Cur {
2171+ plane: 0,
2172+ stride: SIDE,
2173+ off: 0,
2174+ }
23052175 } else {
23062176 let mut built: [Vec<u16>; 3] = Default::default();
23072177 build(y, u, v, refpix, fctx, &mut built);
@@ -2404,9 +2274,6 @@ pub(super) fn decode_inter_sub8_rect2(
24042274 if idx == 0 {
24052275 piece_tx_type = tu_tx_type;
24062276 }
2407- if idx == 0 && i == 0 {
2408- sub0_tx_type = tu_tx_type;
2409- }
24102277 if idx == 0 && i == 1 {
24112278 // `av1_get_tx_type` indexes `xd->tx_type_map`, which
24122279 // `set_mi_offsets` (av1_common_int.h:1679) re-points to the
@@ -2475,7 +2342,18 @@ pub(super) fn decode_inter_sub8_rect2(
24752342 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
24762343 let (su, sv) = if pred_deferred(refpix) {
24772344 push_pred(build_c);
2478- (Pred::Cur { plane: 1, stride: SIDE, off: 0 }, Pred::Cur { plane: 2, stride: SIDE, off: 0 })
2345+ (
2346+ Pred::Cur {
2347+ plane: 1,
2348+ stride: SIDE,
2349+ off: 0,
2350+ },
2351+ Pred::Cur {
2352+ plane: 2,
2353+ stride: SIDE,
2354+ off: 0,
2355+ },
2356+ )
24792357 } else {
24802358 let mut built: [Vec<u16>; 3] = Default::default();
24812359 build_c(y, u, v, refpix, fctx, &mut built);
@@ -2725,7 +2603,18 @@ pub(super) fn decode_inter_sub8_rect2(
27252603 let (pred_cu, pred_cv): (Vec<u16>, Vec<u16>);
27262604 let (su, sv) = if pred_deferred(refpix) {
27272605 push_pred(build_c);
2728- (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 })
2606+ (
2607+ Pred::Cur {
2608+ plane: 1,
2609+ stride: B4,
2610+ off: 0,
2611+ },
2612+ Pred::Cur {
2613+ plane: 2,
2614+ stride: B4,
2615+ off: 0,
2616+ },
2617+ )
27292618 } else {
27302619 let mut built: [Vec<u16>; 3] = Default::default();
27312620 build_c(y, u, v, refpix, fctx, &mut built);
@@ -2940,7 +2829,18 @@ pub(super) fn decode_inter_sub8_rect2(
29402829 let (pred_u, pred_v): (Vec<u16>, Vec<u16>);
29412830 let (su, sv) = if pred_deferred(refpix) {
29422831 push_pred(build);
2943- (Pred::Cur { plane: 1, stride: B4, off: 0 }, Pred::Cur { plane: 2, stride: B4, off: 0 })
2832+ (
2833+ Pred::Cur {
2834+ plane: 1,
2835+ stride: B4,
2836+ off: 0,
2837+ },
2838+ Pred::Cur {
2839+ plane: 2,
2840+ stride: B4,
2841+ off: 0,
2842+ },
2843+ )
29442844 } else {
29452845 let mut built: [Vec<u16>; 3] = Default::default();
29462846 build(y, u, v, refpix, fctx, &mut built);
@@ -3018,8 +2918,6 @@ pub(super) fn decode_inter_sub8_rect2(
30182918 fctx,
30192919 )?
30202920 .0;
3021- let coded = ug.iter().chain(vg.iter()).any(|&c| c != 0);
3022- note_sub8_chroma_tx(sub0_tx_type, first_tx_type, coded);
30232921 (ug, vg)
30242922 };
30252923 let round_up_even = |n: usize| n.div_ceil(2) * 2;
crates/ec-av1/src/decode/tests.rsmodified+36 -8
@@ -543,13 +543,42 @@ fn cdef_filter_block_under_test(
543543 ) {
544544 if let Some(t) = archmage::X64V3Token::summon() {
545545 return super::cdef_simd::filter_block_avx2(
546- t, src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir,
547- pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax,
546+ t,
547+ src,
548+ dst,
549+ stride,
550+ ox,
551+ oy,
552+ bw,
553+ bh,
554+ pri_strength,
555+ sec_strength,
556+ dir,
557+ pri_damping,
558+ sec_damping,
559+ enable_primary,
560+ enable_secondary,
561+ coeff_shift,
562+ smax,
548563 );
549564 }
550565 super::cdef_filter_block_scalar(
551- src, dst, stride, ox, oy, bw, bh, pri_strength, sec_strength, dir,
552- pri_damping, sec_damping, enable_primary, enable_secondary, coeff_shift, smax,
566+ src,
567+ dst,
568+ stride,
569+ ox,
570+ oy,
571+ bw,
572+ bh,
573+ pri_strength,
574+ sec_strength,
575+ dir,
576+ pri_damping,
577+ sec_damping,
578+ enable_primary,
579+ enable_secondary,
580+ coeff_shift,
581+ smax,
553582 )
554583 }
555584
@@ -890,8 +919,8 @@ fn filter_intra_classes_carry_their_own_libaom_default_row() {
890919 );
891920 }
892921 }
893-use archmage::SimdToken;
894922 use super::*;
923+use archmage::SimdToken;
895924
896925 /// lane-tx64x16 r3: the two new 4:1 chroma scans are a TRANSPOSED PAIR --
897926 /// `SCAN_4X16[i]` must name the transpose of the position
@@ -1513,7 +1542,6 @@ fn a_skipped_block_decodes_to_pure_prediction() {
15131542 DC_PRED,
15141543 &mut cdfs.kf_y_mode[INTRA_MODE_CTX[DC_PRED]][INTRA_MODE_CTX[DC_PRED]],
15151544 );
1516- crate::msac::SymbolDecoder::set_symr_cdf("uv_mode");
15171545 enc.symbol(DC_PRED, &mut cdfs.uv_mode_no_cfl[DC_PRED]);
15181546 let data = enc.finish();
15191547 let decoded = decode_key_frame_tile(
@@ -1718,7 +1746,6 @@ fn a_non_split_inter_sb_partition_refuses_by_name_instead_of_desyncing() {
17181746 // helpers are `#[cfg(test)]`-private to it).
17191747 use crate::probe::run_with_stdin;
17201748
1721-
17221749 /// Decodes one AV1 OBU stream with ffmpeg and hands back its one 4:2:0
17231750 /// frame's planes, at ffmpeg's own (coded, block-padded) size.
17241751 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
@@ -1830,7 +1857,8 @@ fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
18301857 "-of",
18311858 "csv=p=0",
18321859 ])
1833- .arg(&path).output()
1860+ .arg(&path)
1861+ .output()
18341862 .expect("ffprobe failed to run");
18351863 let _ = std::fs::remove_file(&path);
18361864 assert!(
crates/ec-av1/src/encode/coef.rsmodified+40 -31
@@ -962,7 +962,13 @@ impl Plane<'_> {
962962 }
963963
964964 /// Puts a snapshot back.
965- pub(super) fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
965+ pub(super) fn restore(
966+ &mut self,
967+ x: usize,
968+ y: usize,
969+ side: usize,
970+ saved: &(Vec<u8>, Vec<CoefCtx>),
971+ ) {
966972 for row in 0..side {
967973 self.reconstruction[(y + row) * self.width + x..][..side]
968974 .copy_from_slice(&saved.0[row * side..][..side]);
@@ -1080,19 +1086,20 @@ impl Plane<'_> {
10801086 })
10811087 .collect();
10821088 if let Some(k) = search.top_k
1083- && k < scored.len() {
1084- let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
1085- let dc_entry = dc_pos.map(|i| scored.remove(i));
1086- scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1087- scored.truncate(if dc_entry.is_some() {
1088- k.saturating_sub(1)
1089- } else {
1090- k
1091- });
1092- if let Some(dc_entry) = dc_entry {
1093- scored.push(dc_entry);
1094- }
1089+ && k < scored.len()
1090+ {
1091+ let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
1092+ let dc_entry = dc_pos.map(|i| scored.remove(i));
1093+ scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1094+ scored.truncate(if dc_entry.is_some() {
1095+ k.saturating_sub(1)
1096+ } else {
1097+ k
1098+ });
1099+ if let Some(dc_entry) = dc_entry {
1100+ scored.push(dc_entry);
10951101 }
1102+ }
10961103 let ranking: Vec<(f64, u8)> = if census_on() {
10971104 scored
10981105 .iter()
@@ -1179,8 +1186,6 @@ impl Plane<'_> {
11791186 trial = candidate;
11801187 }
11811188 }
1182- ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
1183- .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
11841189 }
11851190 // lane-txset: the block's own transform type, searched on the mode
11861191 // and angle the trials above settled -- the same ordering the angle
@@ -1405,7 +1410,8 @@ pub(super) const HAS_TR_8X16: [u8; 16] = [
14051410 /// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
14061411 pub(super) const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
14071412 /// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1408-pub(super) const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
1413+pub(super) const HAS_TR_16X8: [u8; 16] =
1414+ [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
14091415 /// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
14101416 pub(super) const HAS_BL_16X8: [u8; 16] = [
14111417 254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0,
@@ -1785,18 +1791,6 @@ impl Reach {
17851791 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
17861792 }
17871793
1788- /// Marks every [`Reach::of`] made until the returned guard drops as being
1789- /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
1790- /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
1791- /// unaffected: libaom's own comment says vertical rectangles keep their
1792- /// non-vert table, which is what [`Reach::of_rect`] already reads.
1793- /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
1794- /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
1795- /// can count the sub-block work that partition creates (lane-ab16).
1796- pub(crate) fn in_vert_ab() -> bool {
1797- VERT_AB_PARTITION.with(std::cell::Cell::get)
1798- }
1799-
18001794 pub(crate) fn vert_ab_partition() -> VertAbGuard {
18011795 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
18021796 }
@@ -1814,7 +1808,12 @@ impl Reach {
18141808 /// row of a superblock reads into the superblock above, which is decoded;
18151809 /// the rightmost column would read into the superblock to the right, which
18161810 /// is not; and everything between is the table's to answer.
1817- pub(super) fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1811+ pub(super) fn top_right(
1812+ side: usize,
1813+ x: usize,
1814+ y: usize,
1815+ fctx: &crate::decode::FrameCtx,
1816+ ) -> bool {
18181817 let (row, col, per_side) = Self::position(side, x, y, fctx);
18191818 if row == 0 {
18201819 return true;
@@ -1851,7 +1850,12 @@ impl Reach {
18511850 /// reads into the superblock to its left, which is decoded only as far
18521851 /// down as its own bottom; the bottom row would read into the superblock
18531852 /// below, which is not decoded at all; and the table answers the rest.
1854- pub(super) fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
1853+ pub(super) fn bottom_left(
1854+ side: usize,
1855+ x: usize,
1856+ y: usize,
1857+ fctx: &crate::decode::FrameCtx,
1858+ ) -> bool {
18551859 let (row, col, per_side) = Self::position(side, x, y, fctx);
18561860 if col == 0 {
18571861 return row * side + side < reach_sb_px(fctx);
@@ -2032,7 +2036,12 @@ pub(super) fn obmc_min_side() -> usize {
20322036 /// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
20332037 /// search pay it, so the alphabet cancels out of a comparison and only its
20342038 /// per-value spread decides.
2035-pub(super) fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
2039+pub(super) fn motion_mode_bits(
2040+ write_w: usize,
2041+ write_h: usize,
2042+ motion: u8,
2043+ warp_alphabet: bool,
2044+) -> f64 {
20362045 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
20372046 return 0.0;
20382047 };
crates/ec-av1/src/encode/frame.rsmodified+50 -37
@@ -52,7 +52,8 @@ pub(super) fn deltaq_res_log2() -> Option<u8> {
5252 /// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
5353 /// speed presets take, because the streams every other test pins move under
5454 /// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
55-pub(super) static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
55+pub(super) static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 =
56+ std::sync::atomic::AtomicU8::new(u8::MAX);
5657
5758 /// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
5859 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -270,13 +271,8 @@ pub(super) fn dq_summary(offsets: &[i32]) -> String {
270271 /// grid that is one flat value, i.e. on no delta_q at all). Process-global
271272 /// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
272273 /// keeps the LARGEST count seen since the last read.
273-pub(super) static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
274-
275-/// [`DELTAQ_LEVELS`], reset to 0.
276-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
277-pub(crate) fn take_deltaq_levels() -> usize {
278- DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
279-}
274+pub(super) static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize =
275+ std::sync::atomic::AtomicUsize::new(0);
280276
281277 /// This superblock's search state: the quantizer it is coded at, and the
282278 /// lambda that quantizer implies. RD lambda goes as the square of the step,
@@ -404,7 +400,12 @@ pub(super) static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::A
404400 /// the left/above winners, first-best tie-break. Built once on the frame's
405401 /// own thread and read-only afterwards, so it cannot make a tile's bytes
406402 /// depend on the thread count.
407-pub(super) fn tpl_coarse_pass(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<((i32, i32), u32)> {
403+pub(super) fn tpl_coarse_pass(
404+ cur: &[u8],
405+ next: &[u8],
406+ width: usize,
407+ height: usize,
408+) -> Vec<((i32, i32), u32)> {
408409 let (cells_x, cells_y) = (width / 16, height / 16);
409410 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
410411 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
@@ -823,10 +824,11 @@ pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f
823824 ] {
824825 let mv = (from.0 + dy * step, from.1 + dx * step);
825826 if let Some(s) = sad(r, bx, by, mv)
826- && s.0 < best.0 {
827- best = s;
828- centre = mv;
829- }
827+ && s.0 < best.0
828+ {
829+ best = s;
830+ centre = mv;
831+ }
830832 }
831833 step /= 2;
832834 }
@@ -1288,28 +1290,29 @@ pub(crate) fn encode_inter_frame(
12881290 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
12891291 // off, and the census then prices the default `res = 4` grid).
12901292 if dq_census()
1291- && let Some(f) = &tpl_factors {
1292- let res = deltaq_res.unwrap_or(4);
1293- let off = |libaom: Option<f64>| -> Vec<i32> {
1294- (0..sb_cols * _sb_rows)
1295- .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
1296- .collect()
1297- };
1298- let strength = dq_tpl_strength(dq_level);
1299- let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
1300- let coded = match (deltaq_res.is_some(), strength) {
1301- (false, _) => "none".to_string(),
1302- (true, None) => "ours".to_string(),
1303- (true, Some(k)) => format!("libaom k={k}"),
1304- };
1305- eprintln!(
1306- "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
1307- sb_cols * _sb_rows,
1308- r_frame.unwrap_or(f64::NAN),
1309- dq_summary(&ours),
1310- dq_summary(&aom),
1311- );
1312- }
1293+ && let Some(f) = &tpl_factors
1294+ {
1295+ let res = deltaq_res.unwrap_or(4);
1296+ let off = |libaom: Option<f64>| -> Vec<i32> {
1297+ (0..sb_cols * _sb_rows)
1298+ .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
1299+ .collect()
1300+ };
1301+ let strength = dq_tpl_strength(dq_level);
1302+ let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
1303+ let coded = match (deltaq_res.is_some(), strength) {
1304+ (false, _) => "none".to_string(),
1305+ (true, None) => "ours".to_string(),
1306+ (true, Some(k)) => format!("libaom k={k}"),
1307+ };
1308+ eprintln!(
1309+ "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
1310+ sb_cols * _sb_rows,
1311+ r_frame.unwrap_or(f64::NAN),
1312+ dq_summary(&ours),
1313+ dq_summary(&aom),
1314+ );
1315+ }
13131316 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
13141317 header.delta.q_present = true;
13151318 header.delta.q_res = res.trailing_zeros() as u8;
@@ -2332,9 +2335,19 @@ pub(crate) fn encode_inter_frame(
23322335 // rectangles partition the frame, so the order does not change the bytes).
23332336 let mut searched_blocks = Vec::new();
23342337 for (tile_blocks, pixels) in search_tiles(layout.count(), fctx, search_tile)? {
2335- put_rect(&mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma);
2338+ put_rect(
2339+ &mut luma.reconstruction,
2340+ frame_width,
2341+ pixels.luma_rect,
2342+ &pixels.luma,
2343+ );
23362344 for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) {
2337- put_rect(&mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes);
2345+ put_rect(
2346+ &mut plane.reconstruction,
2347+ frame_width / 2,
2348+ pixels.chroma_rect,
2349+ bytes,
2350+ );
23382351 }
23392352 searched_blocks.push(tile_blocks);
23402353 }
crates/ec-av1/src/encode/inter_search.rsmodified+44 -39
@@ -212,7 +212,8 @@ pub(super) fn arfmode() -> u8 {
212212 }
213213
214214 /// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
215-pub(super) static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
215+pub(super) static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 =
216+ std::sync::atomic::AtomicU8::new(u8::MAX);
216217
217218 /// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
218219 /// process constant ([`crate::envflags`]), so an in-process witness needs
@@ -279,11 +280,6 @@ thread_local! {
279280 const { std::cell::Cell::new(None) };
280281 }
281282
282-#[cfg(test)]
283-pub(super) fn set_test_top_k_override(value: Option<usize>) {
284- TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
285-}
286-
287283 /// The default: unpruned, thirteen full trials per block, same as before this
288284 /// lever. Set from the sweep in the lane report if the quality gate clears it.
289285 pub(crate) const PRUNE_TOP_K: Option<usize> = None;
@@ -317,11 +313,6 @@ thread_local! {
317313 const { std::cell::Cell::new(None) };
318314 }
319315
320-#[cfg(test)]
321-pub(super) fn set_test_top_k_override_inter(value: Option<usize>) {
322- TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
323-}
324-
325316 /// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
326317 /// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
327318 /// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
@@ -374,21 +365,6 @@ pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
374365 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
375366 }
376367
377-#[cfg(test)]
378-pub(super) fn stage_reset() {
379- crate::par::set_stage_times(true);
380- STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
381-}
382-
383-#[cfg(test)]
384-pub(super) fn stage_read() -> [std::time::Duration; 4] {
385- crate::par::set_stage_times(false);
386- STAGE_NS.with(|c| {
387- c.each_ref()
388- .map(|cell| std::time::Duration::from_nanos(cell.get()))
389- })
390-}
391-
392368 /// One mode's coding of one block, before it is committed.
393369 #[derive(Clone)]
394370 pub(super) struct Trial {
@@ -526,7 +502,11 @@ where
526502 /// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
527503 /// by design) and moved into the worker, exactly as the decoder's filter bands
528504 /// do it through [`crate::par::scope`].
529-pub(super) fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
505+pub(super) fn search_tiles<T, F>(
506+ tiles: usize,
507+ fctx: &crate::decode::FrameCtx,
508+ job: F,
509+) -> Result<Vec<T>>
530510 where
531511 T: Send,
532512 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
@@ -600,7 +580,11 @@ pub(super) struct TilePixels {
600580
601581 /// The rectangle `[x0, x1) x [y0, y1)` of a plane with `stride`, copied out as
602582 /// its rows back to back.
603-pub(super) fn take_rect(plane: &[u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize)) -> Vec<u8> {
583+pub(super) fn take_rect(
584+ plane: &[u8],
585+ stride: usize,
586+ (x0, y0, x1, y1): (usize, usize, usize, usize),
587+) -> Vec<u8> {
604588 let mut out = Vec::with_capacity((x1 - x0) * (y1 - y0));
605589 for y in y0..y1 {
606590 out.extend_from_slice(&plane[y * stride + x0..y * stride + x1]);
@@ -610,7 +594,12 @@ pub(super) fn take_rect(plane: &[u8], stride: usize, (x0, y0, x1, y1): (usize, u
610594
611595 /// The inverse of [`take_rect`]: writes `rows` (as `take_rect` produced them)
612596 /// back into the rectangle of `plane`.
613-pub(super) fn put_rect(plane: &mut [u8], stride: usize, (x0, y0, x1, y1): (usize, usize, usize, usize), rows: &[u8]) {
597+pub(super) fn put_rect(
598+ plane: &mut [u8],
599+ stride: usize,
600+ (x0, y0, x1, y1): (usize, usize, usize, usize),
601+ rows: &[u8],
602+) {
614603 let w = x1 - x0;
615604 for (row, y) in (y0..y1).enumerate() {
616605 plane[y * stride + x0..y * stride + x1].copy_from_slice(&rows[row * w..(row + 1) * w]);
@@ -622,7 +611,10 @@ pub(super) fn put_rect(plane: &mut [u8], stride: usize, (x0, y0, x1, y1): (usize
622611 /// tables the frame stores (spec 7.20), which is what
623612 /// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
624613 /// below publish.
625-pub(super) fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
614+pub(super) fn tile_info_of(
615+ layout: &crate::tile::TileLayout,
616+ tile_size_bytes: u32,
617+) -> ec_av1_syntax::TileInfo {
626618 ec_av1_syntax::TileInfo {
627619 uniform_spacing: true,
628620 cols: layout.cols(),
@@ -1380,9 +1372,19 @@ pub(crate) fn encode_key_frame_inner(
13801372 let searched = search_tiles(layout.count(), fctx, search_tile)?;
13811373 let mut searched_coded = Vec::with_capacity(searched.len());
13821374 for (coded, pixels) in searched {
1383- put_rect(&mut luma.reconstruction, frame_width, pixels.luma_rect, &pixels.luma);
1375+ put_rect(
1376+ &mut luma.reconstruction,
1377+ frame_width,
1378+ pixels.luma_rect,
1379+ &pixels.luma,
1380+ );
13841381 for (plane, bytes) in chroma.iter_mut().zip(&pixels.chroma) {
1385- put_rect(&mut plane.reconstruction, frame_width / 2, pixels.chroma_rect, bytes);
1382+ put_rect(
1383+ &mut plane.reconstruction,
1384+ frame_width / 2,
1385+ pixels.chroma_rect,
1386+ bytes,
1387+ );
13861388 }
13871389 searched_coded.push(coded);
13881390 }
@@ -2104,7 +2106,8 @@ pub(super) fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64>
21042106 /// always), the shape [`set_frame_interp`] has: the witness that has to see
21052107 /// `mv_hp` symbols coded turns it on through this while holding
21062108 /// [`crate::speed::knob_write`].
2107-pub(super) static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
2109+pub(super) static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 =
2110+ std::sync::atomic::AtomicU8::new(u8::MAX);
21082111
21092112 /// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
21102113 #[allow(dead_code)] // set only from the `#[cfg(test)]` gates
@@ -4448,9 +4451,10 @@ pub(super) fn search_inter_block(
44484451 planes,
44494452 (reference.width, reference.height),
44504453 fctx,
4451- ) {
4452- candidates.push((1, pred));
4453- }
4454+ )
4455+ {
4456+ candidates.push((1, pred));
4457+ }
44544458 if warp_alphabet
44554459 && let Some(pred) = warp_prediction(
44564460 grid,
@@ -4462,9 +4466,10 @@ pub(super) fn search_inter_block(
44624466 info.ref_frame,
44634467 planes,
44644468 fctx,
4465- ) {
4466- candidates.push((2, pred));
4467- }
4469+ )
4470+ {
4471+ candidates.push((2, pred));
4472+ }
44684473 for (motion, pred) in candidates {
44694474 let luma_trial = luma.code_from_prediction(
44704475 x,
crates/ec-av1/src/encode/mod.rsmodified+0 -50
@@ -821,12 +821,6 @@ fn rectres() -> bool {
821821 static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
822822 std::sync::atomic::AtomicBool::new(false);
823823
824-/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
825-#[cfg(test)]
826-pub(crate) fn force_b128_rectres(on: bool) {
827- FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
828-}
829-
830824 /// How many rect/AB pieces the search left WITH a residual rather than
831825 /// skipped, since the last [`take_b128_rectres_hits`] (class
832826 /// `gate-blind-to-feature`).
@@ -981,12 +975,6 @@ pub fn take_b128_vert_hits() -> usize {
981975 /// RD there prefers one whole block; the gate census is the unforced count.
982976 static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
983977
984-/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
985-#[cfg(test)]
986-pub(crate) fn force_b128_rect(which: u8) {
987- FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
988-}
989-
990978 /// lane-ab128: whether the 128 superblock root offers its four AB shapes --
991979 /// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
992980 /// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
@@ -1029,12 +1017,6 @@ pub fn take_b128_ab_hits() -> [usize; 4] {
10291017 /// prefers one whole block).
10301018 static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
10311019
1032-/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
1033-#[cfg(test)]
1034-pub(crate) fn force_b128_ab(which: u8) {
1035- FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
1036-}
1037-
10381020 /// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
10391021 /// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
10401022 /// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
@@ -1073,20 +1055,6 @@ static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
10731055 /// for content on which the root also wins its own comparison.
10741056 static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
10751057
1076-/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
1077-/// forced residual block only reaches the writer if its root is taken.
1078-#[cfg(test)]
1079-pub(crate) fn force_b128_residual(on: bool) {
1080- FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
1081- force_b128_root(on);
1082-}
1083-
1084-/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
1085-#[cfg(test)]
1086-pub(crate) fn force_b128_root(on: bool) {
1087- FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
1088-}
1089-
10901058 /// How many 128 roots came out cheaper WITH a residual than skipped, since
10911059 /// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
10921060 static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -1475,12 +1443,6 @@ fn partition_hit(which: usize) {
14751443 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14761444 }
14771445
1478-/// Takes (and clears) the counts.
1479-#[cfg(test)]
1480-pub(crate) fn take_partition_hits() -> [usize; 4] {
1481- [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1482-}
1483-
14841446 /// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
14851447 /// rate-distortion trials the block search actually runs, by kind, and where
14861448 /// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
@@ -2002,12 +1964,6 @@ thread_local! {
20021964 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
20031965 }
20041966
2005-/// [`IBC_SHARE`] for the last key frame encoded on this thread.
2006-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2007-pub(crate) fn intrabc_source_share() -> f64 {
2008- IBC_SHARE.with(std::cell::Cell::get)
2009-}
2010-
20111967 thread_local! {
20121968 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
20131969 /// header offers the per-frame `allow_screen_content_tools` bit at all.
@@ -2043,12 +1999,6 @@ thread_local! {
20431999 const { std::cell::Cell::new(None) };
20442000 }
20452001
2046-/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2047-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2048-pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2049- LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2050-}
2051-
20522002 #[cfg(test)]
20532003 pub(crate) fn force_screen(value: Option<bool>) {
20542004 SCREEN_FORCE.with(|c| c.set(value));
crates/ec-av1/src/encode/more_tests.rsmodified+664 -1228
@@ -1,1260 +1,696 @@
1-use super::*;
21 use super::tests::*;
2+use super::*;
33
4-
5-
6- /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
7- /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
8- /// Five passes over the same `testsrc2` clip
9- /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
10- /// uses: each shape forced at every root ([`force_b128_ab`]), so every
11- /// context and every visit order the shape reads is exercised rather than
12- /// the handful the RD would pick, and then an UNFORCED pass whose
13- /// per-shape count is REPORTED (it is the number the gate rows are read
14- /// against).
15- ///
16- /// Each pass is sample-exact against the encoder's own reconstruction
17- /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
18- /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
19- /// before this lane by construction: `write_sb128_root` could only name
20- /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
21- ///
22- /// Runs only inside `superblock_size_global_suite`.
23- pub(super) fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
24- let _knobs = crate::speed::knob_write();
25- force_sb128(true);
26- let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
27- std::fs::create_dir_all(&dir).unwrap();
28- let clip = dir.join("testsrc2-1280x768.y4m");
29- let ok = ec_testkit::ffmpeg()
30- .args(["-v", "error", "-y", "-f", "lavfi"])
31- .args(["-i", "testsrc2=size=1280x768:rate=24"])
32- .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
33- .arg(&clip)
34- .status()
35- .expect("ffmpeg failed to run")
36- .success();
37- assert!(ok, "ffmpeg could not write the synthetic clip");
38- let (width, height) = (1280usize, 768usize);
39- let pictures = crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
40- let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
41- let mut unforced = [0usize; 4];
42- for force in [4u8, 5, 6, 7, 0] {
43- force_b128_ab(force);
44- let label = if force == 0 {
45- "unforced"
46- } else {
47- names[usize::from(force) - 4]
48- };
49- let _ = take_b128_ab_hits();
50- let _ = crate::tile::take_sb128_ab_hits();
51- let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
52- let won = take_b128_ab_hits();
53- let coded = crate::tile::take_sb128_ab_hits();
54- eprintln!(
55- "{label}: search won {won:?} AB roots, writer coded {coded:?} \
56- (HORZ_A/HORZ_B/VERT_A/VERT_B)"
57- );
58- if force == 0 {
59- // The unforced counts are REPORTED, not asserted: a zero here
60- // would be an RD result, not a defect (the four forced passes
61- // already prove the writer and the reader agree on the shape).
62- unforced = won;
63- } else {
64- let i = usize::from(force) - 4;
65- assert!(
66- coded[i] > 0,
67- "no {label} root was coded with {label} forced"
68- );
69- }
70- let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
71- assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
72- for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
73- for (plane, got, want) in [
74- ("luma", &dec.y, &frame.reconstruction.y),
75- ("U", &dec.u, &frame.reconstruction.u),
76- ("V", &dec.v, &frame.reconstruction.v),
77- ] {
78- let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
79- assert_eq!(
80- differ, 0,
81- "{label} frame {i}: {plane} -- {differ} samples differ"
82- );
83- assert_eq!(
84- got.len(),
85- want.len(),
86- "{label} frame {i}: {plane} is {} samples, the reconstruction's is {}",
87- got.len(),
88- want.len()
89- );
90- }
91- }
92- let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
93- assert_eq!(
94- encoded.frames.len(),
95- ff.len(),
96- "{label}: frame count: ours vs ffmpeg"
97- );
98- for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
99- assert_eq!(
100- dec.y, frame.reconstruction.y,
101- "{label} frame {i}: ffmpeg luma"
102- );
103- assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
104- assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
105- }
106- }
107- force_b128_ab(0);
108- eprintln!(
109- "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
110- unforced[0], unforced[1], unforced[2], unforced[3],
111- );
4+#[test]
5+fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
6+ let _knobs = crate::speed::knob_read();
7+ let fctx = &crate::decode::FrameCtx::for_encoder();
8+ // 256x128, not the 128x64 this started at: once a leaf could search
9+ // its second reference (lane-av1comp4) the small card's every
10+ // eligible block went to a compound winner, which commits its flat
11+ // transform, and the split below stopped firing on content that
12+ // still splits at every larger size ([[gate-blind-to-feature]] --
13+ // the guard is right, the fixture had shrunk under it).
14+ let (width, height) = (256usize, 128usize);
15+ let pictures: Vec<Picture> = (0..5)
16+ .map(|i| panned_test_card(width, height, i * 3))
17+ .collect();
18+ let _ = take_inter_tx_split_hits();
19+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
20+ let raw = take_inter_tx_split_hits();
21+ // Summed over the four block classes the census keys on (leaf/32x32 x
22+ // single/compound): this assert is about the split firing at all.
23+ let split = [
24+ raw.iter().step_by(2).sum::<usize>(),
25+ raw.iter().skip(1).step_by(2).sum::<usize>(),
26+ ];
27+ eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
28+ // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
29+ // content splits -- a green round trip in which the split never fires
30+ // would prove only the flat path.
31+ if tx_select() && tx_select_inter() {
32+ assert!(split[1] > 0, "the inter var-tx split never fired");
11233 }
113-
114- #[test]
115- fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
116- let _knobs = crate::speed::knob_read();
117- let fctx = &crate::decode::FrameCtx::for_encoder();
118- // 256x128, not the 128x64 this started at: once a leaf could search
119- // its second reference (lane-av1comp4) the small card's every
120- // eligible block went to a compound winner, which commits its flat
121- // transform, and the split below stopped firing on content that
122- // still splits at every larger size ([[gate-blind-to-feature]] --
123- // the guard is right, the fixture had shrunk under it).
124- let (width, height) = (256usize, 128usize);
125- let pictures: Vec<Picture> = (0..5)
126- .map(|i| panned_test_card(width, height, i * 3))
127- .collect();
128- let _ = take_inter_tx_split_hits();
129- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
130- let raw = take_inter_tx_split_hits();
131- // Summed over the four block classes the census keys on (leaf/32x32 x
132- // single/compound): this assert is about the split firing at all.
133- let split = [
134- raw.iter().step_by(2).sum::<usize>(),
135- raw.iter().skip(1).step_by(2).sum::<usize>(),
136- ];
137- eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
138- // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
139- // content splits -- a green round trip in which the split never fires
140- // would prove only the flat path.
141- if tx_select() && tx_select_inter() {
142- assert!(split[1] > 0, "the inter var-tx split never fired");
143- }
144- let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
145- assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
146- for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
147- let recon = &frame.reconstruction;
148- for (plane, got, want, stride) in [
149- ("luma", &dec.y, &recon.y, width),
150- ("U", &dec.u, &recon.u, width / 2),
151- ("V", &dec.v, &recon.v, width / 2),
152- ] {
153- assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
154- if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
155- panic!(
156- "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
34+ let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
35+ assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
36+ for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
37+ let recon = &frame.reconstruction;
38+ for (plane, got, want, stride) in [
39+ ("luma", &dec.y, &recon.y, width),
40+ ("U", &dec.u, &recon.u, width / 2),
41+ ("V", &dec.v, &recon.v, width / 2),
42+ ] {
43+ assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
44+ if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
45+ panic!(
46+ "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
15747 reconstruction {} ({} of {} samples differ)",
158- at % stride,
159- at / stride,
160- got[at],
161- want[at],
162- got.iter().zip(want).filter(|(a, b)| a != b).count(),
163- got.len(),
164- );
165- }
48+ at % stride,
49+ at / stride,
50+ got[at],
51+ want[at],
52+ got.iter().zip(want).filter(|(a, b)| a != b).count(),
53+ got.len(),
54+ );
16655 }
16756 }
16857 }
169-
170- /// The rate term the mode search ranks every decision by has to be the
171- /// rate the writer then spends. The search prices a block's coefficients
172- /// through `tile::coeff_bits` -- the writer's own symbol chain, but
173- /// against the default CDFs a tile starts from and the contexts of a
174- /// block whose neighbours coded nothing -- while the tile writer codes
175- /// them against a state that has been adapting all frame (the
176- /// price-the-narrowing class). This measures that drift: the sum of what
177- /// the search paid for the coefficients it kept, against the bytes the
178- /// writer actually emitted for the whole tile (which also carries the
179- /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
180- /// expected to be the larger of the two).
181- #[test]
182- fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
183- let _knobs = crate::speed::knob_read();
184- let fctx = &crate::decode::FrameCtx::for_encoder();
185- let (width, height) = (256usize, 128usize);
186- let pictures: Vec<Picture> = (0..5)
187- .map(|i| panned_test_card(width, height, i * 2))
188- .collect();
189- let _ = take_predicted_bits();
190- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
191- let predicted = take_predicted_bits();
192- assert_eq!(predicted.len(), encoded.frames.len());
193-
194- eprintln!("frame predicted bits written bits drift");
195- // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
196- // defect this gate exists to catch), a positive one is the written
197- // side carrying syntax the coefficient sum leaves out -- and since
198- // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
199- // on that side, so the two directions no longer share a bound.
200- let mut worst_over: f64 = 0.0;
201- let mut worst_under: f64 = 0.0;
202- // The census is per CODED frame, so it is zipped in coding order --
203- // which is not display order under a pyramid.
204- let coded: Vec<&Encoded> = encoded
205- .coding_order
206- .iter()
207- .map(|&i| &encoded.frames[i])
208- .collect();
209- for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
210- let written = frame.tile.len() as f64 * 8.0;
211- let drift = (written - bits) / written;
212- worst_over = worst_over.max(-drift);
213- // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
214- // all (150-250 bits of tile, nearly all of it partition/mode/mv
215- // syntax the coefficient sum never counts), so its ratio measures
216- // that floor rather than any drift. Frames under 512 written bits
217- // are left out of the under-price bound for that reason; the
218- // over-price bound -- the defect direction, where the search pays
219- // MORE than the writer -- still covers every frame.
220- if written >= 512.0 {
221- worst_under = worst_under.max(drift);
222- }
223- eprintln!(
224- "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
225- drift * 100.0
226- );
58+}
59+
60+/// The rate term the mode search ranks every decision by has to be the
61+/// rate the writer then spends. The search prices a block's coefficients
62+/// through `tile::coeff_bits` -- the writer's own symbol chain, but
63+/// against the default CDFs a tile starts from and the contexts of a
64+/// block whose neighbours coded nothing -- while the tile writer codes
65+/// them against a state that has been adapting all frame (the
66+/// price-the-narrowing class). This measures that drift: the sum of what
67+/// the search paid for the coefficients it kept, against the bytes the
68+/// writer actually emitted for the whole tile (which also carries the
69+/// partition/mode/skip/mv syntax the sum leaves out, so the writer is
70+/// expected to be the larger of the two).
71+#[test]
72+fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
73+ let _knobs = crate::speed::knob_read();
74+ let fctx = &crate::decode::FrameCtx::for_encoder();
75+ let (width, height) = (256usize, 128usize);
76+ let pictures: Vec<Picture> = (0..5)
77+ .map(|i| panned_test_card(width, height, i * 2))
78+ .collect();
79+ let _ = take_predicted_bits();
80+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
81+ let predicted = take_predicted_bits();
82+ assert_eq!(predicted.len(), encoded.frames.len());
83+
84+ eprintln!("frame predicted bits written bits drift");
85+ // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
86+ // defect this gate exists to catch), a positive one is the written
87+ // side carrying syntax the coefficient sum leaves out -- and since
88+ // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
89+ // on that side, so the two directions no longer share a bound.
90+ let mut worst_over: f64 = 0.0;
91+ let mut worst_under: f64 = 0.0;
92+ // The census is per CODED frame, so it is zipped in coding order --
93+ // which is not display order under a pyramid.
94+ let coded: Vec<&Encoded> = encoded
95+ .coding_order
96+ .iter()
97+ .map(|&i| &encoded.frames[i])
98+ .collect();
99+ for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
100+ let written = frame.tile.len() as f64 * 8.0;
101+ let drift = (written - bits) / written;
102+ worst_over = worst_over.max(-drift);
103+ // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
104+ // all (150-250 bits of tile, nearly all of it partition/mode/mv
105+ // syntax the coefficient sum never counts), so its ratio measures
106+ // that floor rather than any drift. Frames under 512 written bits
107+ // are left out of the under-price bound for that reason; the
108+ // over-price bound -- the defect direction, where the search pays
109+ // MORE than the writer -- still covers every frame.
110+ if written >= 512.0 {
111+ worst_under = worst_under.max(drift);
227112 }
228- // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
229- // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
230- // over-prices every frame but the last (its sum EXCLUDES the
231- // partition/mode/skip/mv syntax the written side carries, so the true
232- // coefficient over-price is larger still): the writer's CDFs adapt to
233- // the content while the search's stay at the defaults. The bound is
234- // set just above the worst measured point -- a widening drift is the
235- // thing this gate exists to catch.
236- assert!(
237- worst_over <= 0.16,
238- "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
239- worst_over * 100.0
240- );
241- // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
242- // the worst inter frame, where nearly every block now codes an MV
243- // residual and a reference the coefficient sum never counts. Re-measured
244- // at +29.6% once the encoder's grid published compound blocks properly
245- // (compound share 8.8% -> 11.5%): a compound block carries a second
246- // reference tree, a compound mode symbol and -- for the half-new modes
247- // -- an MV residual, none of which the coefficient sum counts.
248- // lane-av1txbits: pricing against the tables the frame's writer really
249- // starts from collapses the over-price above to nothing, so the whole
250- // remaining gap is the syntax the coefficient sum leaves out. That is
251- // the default on a non-screen frame since lane-av1price2 (this
252- // fixture is one), and it reads +32.6% here.
253- // lane-av1obmc: every eligible single-reference inter block now also
254- // carries a `motion_mode` symbol the coefficient sum never counts,
255- // and an OBMC block carries the more expensive of the two values --
256- // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
257- // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
258- // decisions, so this bound and the byte pins above FAIL BY DESIGN
259- // under it; the default path (no motion_mode syntax at all) is the
260- // one they are measured on.
261- // lane-av1pyrdef: `encode_sequence` codes this fixture under the
262- // coding pyramid now, so the five frames are a key frame, a hidden
263- // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
264- // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
265- // near-empty leaves below it. Both bounds stand where they were.
266- // lane-av1rejudge: local warp is ON by default now, so every eligible
267- // single-reference block carries that same `motion_mode` symbol (a
268- // 3-value alphabet where a warp sample exists) on the DEFAULT path --
269- // +34.9% here, one point past the OBMC reading above. The bound moves
270- // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
271- // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
272- // symbol and one or two magnitude symbols, none of which the
273- // coefficient sum counts either -- +36.9% here against the same
274- // fixture's +34.9% with `EC_AV1_CFL=0`.
275- // ... and a directional block whose `angle_delta_y` is no longer
276- // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
277- assert!(
278- worst_under <= 0.40,
279- "the writer spent {:.2}% more than the search priced -- more than \
280- the mode/mv syntax outside the coefficient sum explains",
281- worst_under * 100.0
113+ eprintln!(
114+ "{i:5} {bits:14.0} {written:12.0} {:+6.2}%",
115+ drift * 100.0
282116 );
283117 }
284-
285- /// The census behind step (1) of the pricer lane: for every transform
286- /// block the writer really codes, what the search priced those levels at
287- /// against what the writer spent on them, split by table set and non-zero
288- /// count. One average hides the interesting part -- the classes the
289- /// estimate is systematically wrong about (all-zero blocks, the
290- /// one-coefficient blocks the inter search lives on) -- so the split is
291- /// printed and only the total is asserted on.
292- #[test]
293- fn pricer_error_census_by_block_class() {
294- let _knobs = crate::speed::knob_read();
295- let fctx = &crate::decode::FrameCtx::for_encoder();
296- let (width, height) = (256usize, 128usize);
297- let pictures: Vec<Picture> = (0..5)
298- .map(|i| panned_test_card(width, height, i * 2))
299- .collect();
300- crate::tile::pricer_census_on();
301- let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
302- let rows = crate::tile::take_pricer_census();
303- assert!(!rows.is_empty(), "the census saw no transform block");
304-
305- println!("| set | nz | blocks | priced bits | written bits | error |");
306- println!("|---|---|---|---|---|---|");
307- let (mut priced_all, mut written_all) = (0.0, 0.0);
308- for ((set, bucket), (blocks, priced, written)) in &rows {
309- priced_all += priced;
310- written_all += written;
311- println!(
312- "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
313- crate::tile::census_bucket_label(*bucket),
314- if *written > 0.0 {
315- (priced - written) / written * 100.0
316- } else {
317- 0.0
318- }
319- );
320- }
118+ // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
119+ // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
120+ // over-prices every frame but the last (its sum EXCLUDES the
121+ // partition/mode/skip/mv syntax the written side carries, so the true
122+ // coefficient over-price is larger still): the writer's CDFs adapt to
123+ // the content while the search's stay at the defaults. The bound is
124+ // set just above the worst measured point -- a widening drift is the
125+ // thing this gate exists to catch.
126+ assert!(
127+ worst_over <= 0.16,
128+ "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
129+ worst_over * 100.0
130+ );
131+ // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
132+ // the worst inter frame, where nearly every block now codes an MV
133+ // residual and a reference the coefficient sum never counts. Re-measured
134+ // at +29.6% once the encoder's grid published compound blocks properly
135+ // (compound share 8.8% -> 11.5%): a compound block carries a second
136+ // reference tree, a compound mode symbol and -- for the half-new modes
137+ // -- an MV residual, none of which the coefficient sum counts.
138+ // lane-av1txbits: pricing against the tables the frame's writer really
139+ // starts from collapses the over-price above to nothing, so the whole
140+ // remaining gap is the syntax the coefficient sum leaves out. That is
141+ // the default on a non-screen frame since lane-av1price2 (this
142+ // fixture is one), and it reads +32.6% here.
143+ // lane-av1obmc: every eligible single-reference inter block now also
144+ // carries a `motion_mode` symbol the coefficient sum never counts,
145+ // and an OBMC block carries the more expensive of the two values --
146+ // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
147+ // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
148+ // decisions, so this bound and the byte pins above FAIL BY DESIGN
149+ // under it; the default path (no motion_mode syntax at all) is the
150+ // one they are measured on.
151+ // lane-av1pyrdef: `encode_sequence` codes this fixture under the
152+ // coding pyramid now, so the five frames are a key frame, a hidden
153+ // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
154+ // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
155+ // near-empty leaves below it. Both bounds stand where they were.
156+ // lane-av1rejudge: local warp is ON by default now, so every eligible
157+ // single-reference block carries that same `motion_mode` symbol (a
158+ // 3-value alphabet where a warp sample exists) on the DEFAULT path --
159+ // +34.9% here, one point past the OBMC reading above. The bound moves
160+ // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
161+ // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
162+ // symbol and one or two magnitude symbols, none of which the
163+ // coefficient sum counts either -- +36.9% here against the same
164+ // fixture's +34.9% with `EC_AV1_CFL=0`.
165+ // ... and a directional block whose `angle_delta_y` is no longer
166+ // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
167+ assert!(
168+ worst_under <= 0.40,
169+ "the writer spent {:.2}% more than the search priced -- more than \
170+ the mode/mv syntax outside the coefficient sum explains",
171+ worst_under * 100.0
172+ );
173+}
174+
175+/// The census behind step (1) of the pricer lane: for every transform
176+/// block the writer really codes, what the search priced those levels at
177+/// against what the writer spent on them, split by table set and non-zero
178+/// count. One average hides the interesting part -- the classes the
179+/// estimate is systematically wrong about (all-zero blocks, the
180+/// one-coefficient blocks the inter search lives on) -- so the split is
181+/// printed and only the total is asserted on.
182+#[test]
183+fn pricer_error_census_by_block_class() {
184+ let _knobs = crate::speed::knob_read();
185+ let fctx = &crate::decode::FrameCtx::for_encoder();
186+ let (width, height) = (256usize, 128usize);
187+ let pictures: Vec<Picture> = (0..5)
188+ .map(|i| panned_test_card(width, height, i * 2))
189+ .collect();
190+ crate::tile::pricer_census_on();
191+ let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
192+ let rows = crate::tile::take_pricer_census();
193+ assert!(!rows.is_empty(), "the census saw no transform block");
194+
195+ println!("| set | nz | blocks | priced bits | written bits | error |");
196+ println!("|---|---|---|---|---|---|");
197+ let (mut priced_all, mut written_all) = (0.0, 0.0);
198+ for ((set, bucket), (blocks, priced, written)) in &rows {
199+ priced_all += priced;
200+ written_all += written;
321201 println!(
322- "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
323- rows.values().map(|r| r.0).sum::<u64>(),
324- (priced_all - written_all) / written_all * 100.0
325- );
326- assert!(written_all > 0.0);
327- }
328-
329- /// Low motion has to actually buy something: at least one inter frame of
330- /// a panning sequence has to cost fewer bytes than the key frame that
331- /// starts it, and the inter-block share it prints has to be non-zero --
332- /// a search that never picks an inter mode would still pass a rate gate
333- /// on a picture with no motion in it (the class this repo calls
334- /// gate-blind-to-feature), so the share is printed even though it is not
335- /// asserted on beyond being reachable at all.
336- #[test]
337- fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
338- let _knobs = crate::speed::knob_read();
339- let fctx = &crate::decode::FrameCtx::for_encoder();
340- let (width, height) = (256usize, 128usize);
341- let pictures: Vec<Picture> = (0..5)
342- .map(|i| panned_test_card(width, height, i * 2))
343- .collect();
344- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
345-
346- let key_bytes = encoded.frames[0].stream.len();
347- eprintln!("frame bytes inter share");
348- for (i, frame) in encoded.frames.iter().enumerate() {
349- eprintln!(
350- "{i:5} {:5} {:11.2}",
351- frame.stream.len(),
352- frame.inter_block_share
353- );
354- }
355- assert!(
356- encoded.frames[1..]
357- .iter()
358- .any(|f| f.stream.len() < key_bytes),
359- "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
360- );
361- assert!(
362- encoded.frames[1..]
363- .iter()
364- .any(|f| f.inter_block_share > 0.0),
365- "no inter frame coded a single inter block -- the search never fired"
366- );
367- }
368-
369- /// `frames` consecutive pictures out of a real clip, scaled to a whole
370- /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
371- /// to an arbitrary count for the fixture regression gate below.
372- pub(super) fn clip_frames(
373- clip: &str,
374- skip: &str,
375- width: usize,
376- height: usize,
377- frames: usize,
378- ) -> Vec<Picture> {
379- clip_frames_vf(
380- clip,
381- skip,
382- &format!("scale={width}:{height}"),
383- width,
384- height,
385- frames,
386- )
387- }
388-
389- /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
390- /// for a native-resolution CROP instead of a downscale (the downscale is
391- /// what destroys a screen capture's exact repeats -- class
392- /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
393- pub(super) fn clip_frames_vf(
394- clip: &str,
395- skip: &str,
396- vf: &str,
397- width: usize,
398- height: usize,
399- frames: usize,
400- ) -> Vec<Picture> {
401- // ONE definition of the gate's loader recipe, shared with
402- // `examples/enc_probe` so the instrument cannot arm a different source
403- // than the gate it reports on (class `instrument disagrees with the
404- // gate`; lane-probe).
405- crate::probe::source(clip, skip, vf, width, height, frames)
406- }
407-
408- // -----------------------------------------------------------------------
409- // The encoder's standing BD-rate baseline against libaom and rav1e.
410- // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
411- // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
412- // agreeing with our encoder proves nothing about the bitstream.
413- // -----------------------------------------------------------------------
414-
415- /// All-plane PSNR of a decoded picture against its source, on the same
416- /// 8-bit scale [`psnr`] uses.
417- pub(super) fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
418- let cat = |p: &Picture| {
419- let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
420- v.extend_from_slice(&p.y);
421- v.extend_from_slice(&p.u);
422- v.extend_from_slice(&p.v);
423- v
424- };
425- psnr(&cat(decoded), &cat(source))
426- }
427-
428- /// The pictures back as the planar 8-bit bytes an encoder reads.
429- pub(super) fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
430- let mut raw = Vec::new();
431- for p in source {
432- for plane in [&p.y, &p.u, &p.v] {
433- raw.extend(plane.iter().map(|&s| s as u8));
434- }
435- }
436- raw
437- }
438-
439- /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
440- /// through ffmpeg: one point per entry of `points`, each a quality flag
441- /// set. Returns the ladder ordered by fidelity and the total encode wall
442- /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
443- /// so both curves are measured by the same decoder.
444- pub(super) fn external_ladder(
445- source: &[Picture],
446- width: usize,
447- height: usize,
448- encoder: &str,
449- points: &[Vec<String>],
450- ) -> (Vec<(f64, f64)>, f64) {
451- // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
452- let dir = std::env::temp_dir();
453- let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
454- std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
455- let mut ladder = Vec::new();
456- let mut wall = 0.0;
457- for (i, params) in points.iter().enumerate() {
458- let obu = dir.join(format!(
459- "ec-av1-bd-{}-{encoder}-{i}.obu",
460- std::process::id()
461- ));
462- let start = std::time::Instant::now();
463- let out = ec_testkit::ffmpeg()
464- .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
465- .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
466- .arg(&raw_path)
467- .args(["-an", "-threads", "1"])
468- .args(["-g", &source.len().to_string(), "-c:v", encoder])
469- .args(params)
470- .args(["-f", "obu"])
471- .arg(&obu).output()
472- .expect("ffmpeg failed to run");
473- wall += start.elapsed().as_secs_f64();
474- assert!(
475- out.status.success(),
476- "{encoder} {params:?}: {}",
477- String::from_utf8_lossy(&out.stderr)
478- );
479- let stream = std::fs::read(&obu).expect("reference stream");
480- let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
481- // lane-dkey: every reference point must also decode through OUR
482- // decoder, sample-exact against ffmpeg's decode of the same bytes.
483- // A BD table computed off streams we cannot read is a table about
484- // an encoder we cannot check; this is the assertion that would
485- // have caught the `force_integer_mv` defect (its stream decoded to
486- // 25 dB garbage while this gate stayed green) and the crf-5 key
487- // frame desync. A failure names the encoder, the point's flags and
488- // the first differing frame/plane/sample.
489- // lane-dpm1: a failing reference point is COLLECTED, not panicked
490- // on, so one run still prints the whole BD table and names every
491- // bad point instead of stopping at the first. The collection is
492- // asserted empty by [`assert_ladder_decodes`] at the end of each
493- // gate.
494- match crate::stream::decode_stream(&stream) {
495- Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
496- "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
497- ours.len(),
498- decoded.len(),
499- )),
500- Ok(ours) => {
501- for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
502- if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
503- note_ladder_failure(format!(
504- "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
505- decoder decoded {got}, ffmpeg {want}"
506- ));
507- break;
508- }
509- }
510- }
511- Err(e) => note_ladder_failure(format!(
512- "{encoder} {params:?}: our decoder refused the stream ({e})"
513- )),
202+ "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
203+ crate::tile::census_bucket_label(*bucket),
204+ if *written > 0.0 {
205+ (priced - written) / written * 100.0
206+ } else {
207+ 0.0
514208 }
515- let mean: f64 = decoded
516- .iter()
517- .zip(source)
518- .map(|(d, s)| psnr_all(d, s))
519- .sum::<f64>()
520- / source.len() as f64;
521- ladder.push((mean, (stream.len() as f64).log10()));
522- let _ = std::fs::remove_file(&obu);
523- }
524- let _ = std::fs::remove_file(&raw_path);
525- ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
526- (ladder, wall)
527- }
528-
529- /// Every reference ladder point that did not decode sample-exactly
530- /// through our own decoder, collected across a whole gate run so the BD
531- /// table still prints and EVERY bad point is named
532- /// (`encoder params frame plane sample`) instead of only the first.
533- static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
534-
535- pub(super) fn note_ladder_failure(msg: String) {
536- eprintln!("LADDER DECODE FAILURE: {msg}");
537- LADDER_FAILURES.lock().expect("ladder failures").push(msg);
538- }
539-
540- /// Fail the gate at its END on everything [`external_ladder`] collected.
541- pub(super) fn assert_ladder_decodes() {
542- let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
543- assert!(
544- failures.is_empty(),
545- "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
546- failures.len(),
547- failures.join("\n"),
548209 );
549210 }
550-
551- /// First differing sample between two pictures, as
552- /// `(plane, index, left, right)` -- so a gate failure names the plane and
553- /// the sample instead of just "differs". A length difference counts as a
554- /// mismatch of that plane at the first index past the shorter one.
555- pub(super) fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
556- for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
557- if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
558- return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
559- }
560- if l.len() != r.len() {
561- return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
562- }
563- }
564- None
565- }
566-
567- /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
568- /// comes from ffmpeg's decode of our own stream, and at EVERY point the
569- /// stream is decoded twice -- by ffmpeg and by our own
570- /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
571- /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
572- /// in Y, U and V over every shown frame in display order. That is itself
573- /// a gate: it proves the bitstream says what the encoder thinks, in the
574- /// only two decoders that read it.
575- pub(super) fn our_ladder(
576- name: &str,
577- source: &[Picture],
578- width: usize,
579- height: usize,
580- fctx: &crate::decode::FrameCtx,
581- ) -> (Vec<(f64, f64)>, f64) {
582- let mut ladder = Vec::new();
583- let mut wall = 0.0;
584- for &q in &[150u8, 120, 90, 60] {
585- let start = std::time::Instant::now();
586- // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
587- // the gate has to be able to re-sweep it. 0.5 is the shipped one
588- // (`crate::encoder::DEADZONE`).
589- let deadzone = std::env::var("EC_AV1_DEADZONE")
590- .ok()
591- .and_then(|v| v.parse().ok())
592- .unwrap_or(0.5);
593- let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
594- wall += start.elapsed().as_secs_f64();
595- let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
596- let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
597- assert_eq!(
598- ours.len(),
599- source.len(),
600- "{name} q={q}: our decoder's display-order frame count"
601- );
602- for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
603- if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
604- panic!(
605- "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
606- {got}, the encoder reconstructed {want}"
607- );
608- }
609- }
610- for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
611- if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
612- panic!(
613- "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
614- {got}, the encoder reconstructed {want}"
615- );
616- }
617- }
618- let per_frame: Vec<f64> = decoded
619- .iter()
620- .zip(source)
621- .map(|(d, s)| psnr_all(d, s))
622- .collect();
623- // lane-txrd: does a tool's loss start at the FIRST inter frame
624- // (a local mispricing) or grow down the GOP (propagation into
625- // the reference chain)? One line per q point answers it.
626- if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
627- let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
628- eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
629- // lane-txrd: per PLANE, because an all-plane mean hides a
630- // collapse in one of them (class `metric blind to a plane`).
631- let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
632- let v: Vec<String> = decoded
633- .iter()
634- .zip(source)
635- .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
636- .collect();
637- v.join(" ")
638- };
639- eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
640- eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
641- eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
642- }
643- let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
644- ladder.push((mean, (encoded.stream.len() as f64).log10()));
645- }
646- // What this clip asked for and what the content gate left it coding
647- // under: a screen clip requests a pyramid and codes flat, and that
648- // difference is what keeps its row identical to the flat baseline
649- // (class `gate-blind-to-feature`).
211+ println!(
212+ "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
213+ rows.values().map(|r| r.0).sum::<u64>(),
214+ (priced_all - written_all) / written_all * 100.0
215+ );
216+ assert!(written_all > 0.0);
217+}
218+
219+/// Low motion has to actually buy something: at least one inter frame of
220+/// a panning sequence has to cost fewer bytes than the key frame that
221+/// starts it, and the inter-block share it prints has to be non-zero --
222+/// a search that never picks an inter mode would still pass a rate gate
223+/// on a picture with no motion in it (the class this repo calls
224+/// gate-blind-to-feature), so the share is printed even though it is not
225+/// asserted on beyond being reachable at all.
226+#[test]
227+fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
228+ let _knobs = crate::speed::knob_read();
229+ let fctx = &crate::decode::FrameCtx::for_encoder();
230+ let (width, height) = (256usize, 128usize);
231+ let pictures: Vec<Picture> = (0..5)
232+ .map(|i| panned_test_card(width, height, i * 2))
233+ .collect();
234+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
235+
236+ let key_bytes = encoded.frames[0].stream.len();
237+ eprintln!("frame bytes inter share");
238+ for (i, frame) in encoded.frames.iter().enumerate() {
650239 eprintln!(
651- "{name}: sequence, pyramid requested {:?} effective {:?}",
652- crate::encoder::Pyramid::from_env(),
653- last_sequence_pyramid(),
240+ "{i:5} {:5} {:11.2}",
241+ frame.stream.len(),
242+ frame.inter_block_share
654243 );
655- ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
656- (ladder, wall)
657- }
658-
659- /// [`our_ladder`] through the streaming facade — the surface the editor's
660- /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
661- /// each stream is also reordered (hidden `ALTREF` first,
662- /// `show_existing_frame` last per group) and each level is coded at its
663- /// own quantizer offset; without one it is the flat ladder, which
664- /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
665- /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
666- /// same BD numbers. Returns the ladder, the wall, per pyramid level over
667- /// the whole ladder how many frames and how many bytes it spent, and the
668- /// pyramid the streams were EFFECTIVELY coded under — the content gate in
669- /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
670- /// flat path, so a requested pyramid can come back `None` here.
671- pub(super) fn our_ladder_facade(
672- name: &str,
673- source: &[Picture],
674- width: usize,
675- height: usize,
676- pyramid: Option<crate::encoder::Pyramid>,
677- ) -> (
678- Vec<(f64, f64)>,
679- f64,
680- [usize; 4],
681- [usize; 4],
682- Option<crate::encoder::Pyramid>,
683- ) {
684- use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
685- let slot = |l: Level| match l {
686- Level::Key => 0,
687- Level::Arf => 1,
688- Level::Leaf => 2,
689- Level::ShowExisting => 3,
690- };
691- let mut ladder = Vec::new();
692- let mut wall = 0.0;
693- let mut effective = None;
694- let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
695- for &q in &[150u8, 120, 90, 60] {
696- let config = EncoderConfig {
697- width,
698- height,
699- base_q_idx: q,
700- gop: source.len(),
701- colour: Colour::Unspecified,
702- tile_cols_log2: 0,
703- tile_rows_log2: 0,
704- };
705- let start = std::time::Instant::now();
706- let mut enc = match pyramid {
707- None => Av1Encoder::new(config).unwrap(),
708- Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
709- };
710- let mut packets = Vec::new();
711- for picture in source {
712- packets.extend(enc.encode_frames(picture).unwrap());
713- }
714- packets.extend(enc.flush().unwrap());
715- wall += start.elapsed().as_secs_f64();
716- effective = enc.pyramid();
717- let mut stream = Vec::new();
718- for p in &packets {
719- counts[slot(p.level)] += 1;
720- bytes[slot(p.level)] += p.data.len();
721- stream.extend_from_slice(&p.data);
722- }
723- // [[gate-blind-to-hidden-frames]]: a reordered stream is only
724- // correct if the DISPLAY-order output still has one frame per
725- // source picture, in the right order -- checked against our own
726- // decoder as well as ffmpeg's, both below.
727- let ours = crate::stream::decode_stream(&stream).expect("our decoder");
728- assert_eq!(
729- ours.len(),
730- source.len(),
731- "{name} q={q}: our display-order count"
732- );
733- let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
734- for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
735- if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
736- panic!(
737- "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
738- decoded {got}, our decoder decoded {want}"
739- );
740- }
741- }
742- let mean: f64 = decoded
743- .iter()
744- .zip(source)
745- .map(|(d, s)| psnr_all(d, s))
746- .sum::<f64>()
747- / source.len() as f64;
748- ladder.push((mean, (stream.len() as f64).log10()));
749- }
750- ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
751- (ladder, wall, counts, bytes, effective)
752244 }
753-
754- /// Byte-exactness gate for encoder work that is meant to change only
755- /// how long the encoder takes.
756- ///
757- /// The BD gate above measures quality, which a speed lane can move by a
758- /// hair without failing anything; this pins the streams themselves.
759- /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
760- /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
761- /// in the tile) and again on lane-av1mv's merge of it: an extra
762- /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
763- /// above, not by this pin. Re-pinned on lane-av1price2: the search now
764- /// prices coefficients against the tables the frame's writer really
765- /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
766- /// decision change the BD gate judges. Re-pinned again on
767- /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
768- /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
769- /// is the same kind of decision change. Re-pinned on lane-av1lambda:
770- /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
771- /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
772- /// by default ([`warp_on`], a sequence/frame header bit and a new
773- /// motion_mode symbol on eligible blocks) and
774- /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
775- /// every inter frame's superblocks now code at their own lambda
776- /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
777- /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
778- /// and the two var-tx depth searches ([`tx32_depth_search`],
779- /// [`compound_var_tx`]) are on by default, all three re-judged on the
780- /// native gate's real film rows.
781- /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
782- /// every block whose chroma takes it codes a different mode symbol, two
783- /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
784- /// restores the previous streams. Re-pinned again in the same lane once
785- /// directional luma winners searched their `angle_delta_y`
786- /// (`EC_AV1_ANGLE=0` restores that half).
787- #[test]
788- fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
789- // These are DEFAULT-PRESET pins: a speed preset switches search levers
790- // off, so it legitimately moves every byte. Encode at speed 0 whatever
791- // `EC_AV1_SPEED` says (write guard: the preset is process-global).
792- let _knobs = crate::speed::knob_write();
793- let was = crate::speed::speed();
794- crate::speed::set_speed(0);
795- // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
796- // so a tree with no root `fixtures/` reported this gate green having
797- // compared nothing at all.
798- let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4");
799- let source = clip_frames(clip.to_str().unwrap(), "20", 640, 384, 4);
800- // FNV-1a over the stream: a witness that every coded bit is where it
801- // was, which a byte count alone is not.
802- let fnv = |b: &[u8]| {
803- b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
804- (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
805- })
806- };
807- // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
808- // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
809- // of 4, its leaves at q+8 and a `show_existing_frame` header per
810- // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
811- // four frames; four pictures is one short mini-GOP, which is the
812- // shape that pays least (the ARF's own quality has no later group to
813- // carry it), so this is not the BD gate's number.
814- // Re-taken again on lane-av1cfl: the chroma search offers
815- // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
816- // so every block taking either codes different syntax and different
817- // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
818- // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
819- // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
820- // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
821- // so these four pictures code as one truncated group -- a hidden
822- // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
823- // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
824- // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
825- // Re-taken on lane-fintra: the sequence header sets
826- // `enable_filter_intra`, so every DC_PRED intra block of at most
827- // 32x32 without a luma palette carries a `use_filter_intra` flag and
828- // the blocks that take one code a filter-intra mode, a different
829- // prediction and different coefficients -- 7321 -> 7373 at q=150 and
830- // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
831- // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
832- // (default pyramid `8:-32:16`, one truncated group of 8 with its
833- // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
834- // root can code a REAL residual now (one TX_64X64 luma transform and
835- // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
836- // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
837- // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
838- // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
839- // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
840- // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
841- // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
842- // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
843- // -> 9835 at q=150 and 35450 -> 35798 at q=60.
844- // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
845- // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
846- // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
847- // these four pictures -- offers every superblock a 64x64 intra root
848- // now. `EC_AV1_I64=0` restores 8557 / 33345.
849- // Re-taken on lane-pricer: the inter RD search prices a single
850- // reference through the tree and the neighbour contexts the writer
851- // really codes it with, so every inter picture's reference decisions
852- // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
853- // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
854- // for `skip`/`is_inter` and for the whole compound reference tree, so
855- // every inter block's cost -- and with it the skip and reference
856- // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
857- // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
858- // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
859- // single and compound are priced against the same syntax -- 8311 ->
860- // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
861- // Re-taken on lane-newmv: the motion search charges its own rate term
862- // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
863- // and each subpel stage re-runs from its own winner
864- // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
865- // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
866- // and 33014 -> 33090 at q=60.
867- // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
868- // from libaom's objective tpl mapping, so every inter picture's
869- // quantizer grid -- and every decision priced against it -- moved
870- // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
871- // at the merge of both lanes.
872- // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
873- // per-superblock `delta_qindex` at 1.5x the preset's strength
874- // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
875- // grids -- and every decision priced against them -- moved:
876- // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
877- // Re-taken on lane-arfpred: the top ARF is coded from a temporally
878- // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
879- // pixels -- and the leaves that predict from them -- moved:
880- // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
881- // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
882- // the shipped stream did not move.
883- // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
884- // picture is coded in 128x128 superblocks now, the inter ones
885- // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
886- // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
887- // Re-taken at the merge of lane-b128m onto main (128 superblocks on
888- // by default, on top of the ARF temporal filter).
889- // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
890- // candidates the 64 root already did ([`b128_compound`]), so every
891- // inter frame that carries `reference_select` codes different blocks
892- // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
893- // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
894- // Re-taken on lane-arftf: that filter's strength swept on the deciding
895- // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
896- // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
897- // 33017 at q=60 (the same LENGTH, different bytes).
898- // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
899- // lane-rlclamp onto the 128 compound default.
900- // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
901- // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
902- // so every inter frame whose RD takes one codes a different partition
903- // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
904- // quantizer the rect cut never wins its own comparison on this clip.
905- // `EC_AV1_B128HV=0` restores 8290 exactly.
906- let pins: [(u8, usize, u64); 2] = [
907- (150, 23666, 11535713837929557386),
908- (60, 102035, 3886390906684528357),
909- ];
910- let coded: Vec<(u8, usize, u64)> = pins
245+ assert!(
246+ encoded.frames[1..]
911247 .iter()
912- .map(|&(q, _, _)| {
913- let e = encode_sequence(&source, q, 0.5).unwrap();
914- (q, e.stream.len(), fnv(&e.stream))
915- })
916- .collect();
917- crate::speed::set_speed(was);
918- for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
919- assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
248+ .any(|f| f.stream.len() < key_bytes),
249+ "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
250+ );
251+ assert!(
252+ encoded.frames[1..]
253+ .iter()
254+ .any(|f| f.inter_block_share > 0.0),
255+ "no inter frame coded a single inter block -- the search never fired"
256+ );
257+}
258+
259+/// `frames` consecutive pictures out of a real clip, scaled to a whole
260+/// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
261+/// to an arbitrary count for the fixture regression gate below.
262+pub(super) fn clip_frames(
263+ clip: &str,
264+ skip: &str,
265+ width: usize,
266+ height: usize,
267+ frames: usize,
268+) -> Vec<Picture> {
269+ clip_frames_vf(
270+ clip,
271+ skip,
272+ &format!("scale={width}:{height}"),
273+ width,
274+ height,
275+ frames,
276+ )
277+}
278+
279+/// [`clip_frames`] with the filter chain spelled out, so a caller can ask
280+/// for a native-resolution CROP instead of a downscale (the downscale is
281+/// what destroys a screen capture's exact repeats -- class
282+/// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
283+pub(super) fn clip_frames_vf(
284+ clip: &str,
285+ skip: &str,
286+ vf: &str,
287+ width: usize,
288+ height: usize,
289+ frames: usize,
290+) -> Vec<Picture> {
291+ // ONE definition of the gate's loader recipe, shared with
292+ // `examples/enc_probe` so the instrument cannot arm a different source
293+ // than the gate it reports on (class `instrument disagrees with the
294+ // gate`; lane-probe).
295+ crate::probe::source(clip, skip, vf, width, height, frames)
296+}
297+
298+// -----------------------------------------------------------------------
299+// The encoder's standing BD-rate baseline against libaom and rav1e.
300+// Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
301+// encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
302+// agreeing with our encoder proves nothing about the bitstream.
303+// -----------------------------------------------------------------------
304+
305+/// First differing sample between two pictures, as
306+/// `(plane, index, left, right)` -- so a gate failure names the plane and
307+/// the sample instead of just "differs". A length difference counts as a
308+/// mismatch of that plane at the first index past the shorter one.
309+pub(super) fn first_plane_mismatch(
310+ a: &Picture,
311+ b: &Picture,
312+) -> Option<(&'static str, usize, i64, i64)> {
313+ for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
314+ if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
315+ return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
920316 }
921- }
922-
923- /// A ladder is only a ladder if both axes rise together.
924- pub(super) fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
925- assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
926- for w in ladder.windows(2) {
927- assert!(
928- w[1].0 > w[0].0 && w[1].1 > w[0].1,
929- "{name}: not monotone, {ladder:?}"
930- );
317+ if l.len() != r.len() {
318+ return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
931319 }
932320 }
933-
934- /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
935- /// split by block class in lane-av1txdepth): depth 0 is one transform over
936- /// the whole block, 1 its four halves; the classes are the 16x16/8x8
937- /// leaves and the 32x32 root, each single-reference or compound. A class
938- /// with no counts at all never reached `commit_inter_luma` -- which is
939- /// what its knob being off looks like (class `gate-blind-to-feature`).
940- pub(super) fn print_inter_tx_census(name: &str) {
941- let splits = take_inter_tx_split_hits();
942- let total: usize = splits.iter().sum();
943- let row = |label: &str, base: usize| {
944- let (n0, n1) = (splits[base], splits[base + 1]);
945- format!(
946- "{label} 0={n0} 1={n1} ({:.1}% split)",
947- 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
948- )
949- };
950- eprintln!(
951- "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
952- row("leaf single", 0),
953- row("leaf compound", 2),
954- row("32x32 single", 4),
955- row("32x32 compound", 6),
956- );
957- // lane-txrd: which types the two searches actually COMMITTED over
958- // this row's four encodes -- the gate could not say whether a type
959- // search fired at all (class `gate-blind-to-feature`).
960- const NAMES: [&str; 16] = [
961- "IDTX",
962- "DCT_DCT",
963- "ADST_ADST",
964- "ADST_DCT",
965- "DCT_ADST",
966- "V_DCT",
967- "H_DCT",
968- "FLIPADST_DCT",
969- "DCT_FLIPADST",
970- "FLIPADST_FLIPADST",
971- "ADST_FLIPADST",
972- "FLIPADST_ADST",
973- "V_ADST",
974- "H_ADST",
975- "V_FLIPADST",
976- "H_FLIPADST",
977- ];
978- let name_of = |t: usize| NAMES[t];
979- for (label, hits) in [
980- ("inter", take_inter_tx_type_hits()),
981- ("intra", take_tx_type_hits()),
982- ] {
983- let total: usize = hits.iter().sum();
984- let live: Vec<String> = hits
985- .iter()
986- .enumerate()
987- .filter(|&(_, &n)| n > 0)
988- .map(|(t, &n)| {
989- format!(
990- "{}={n} ({:.1}%)",
991- name_of(t),
992- 100.0 * n as f64 / total.max(1) as f64
993- )
994- })
995- .collect();
996- eprintln!(
997- "{name}: {label} tx_type of {total} units -- {}",
998- live.join(" ")
999- );
1000- }
1001- let t = take_txrd_stats();
1002- if t[0] > 0 {
1003- eprintln!(
1004- "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
1005- bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
1006- t[0],
1007- t[1],
1008- t[3] as f64 / 64.0,
1009- t[2],
1010- t[4] as f64 / 64.0,
1011- 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
1012- 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
1013- );
1014- eprintln!(
1015- "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
1016- flat: dsse {:+.2}%, dbits {:+.2}%)",
1017- t[5],
1018- t[6] as f64 / 64.0,
1019- 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
1020- 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
321+ None
322+}
323+
324+/// Byte-exactness gate for encoder work that is meant to change only
325+/// how long the encoder takes.
326+///
327+/// The BD gate above measures quality, which a speed lane can move by a
328+/// hair without failing anything; this pins the streams themselves.
329+/// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
330+/// `cdef_idx` literals and per-unit loop restoration syntax are new bits
331+/// in the tile) and again on lane-av1mv's merge of it: an extra
332+/// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
333+/// above, not by this pin. Re-pinned on lane-av1price2: the search now
334+/// prices coefficients against the tables the frame's writer really
335+/// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
336+/// decision change the BD gate judges. Re-pinned again on
337+/// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
338+/// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
339+/// is the same kind of decision change. Re-pinned on lane-av1lambda:
340+/// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
341+/// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
342+/// by default ([`warp_on`], a sequence/frame header bit and a new
343+/// motion_mode symbol on eligible blocks) and
344+/// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
345+/// every inter frame's superblocks now code at their own lambda
346+/// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
347+/// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
348+/// and the two var-tx depth searches ([`tx32_depth_search`],
349+/// [`compound_var_tx`]) are on by default, all three re-judged on the
350+/// native gate's real film rows.
351+/// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
352+/// every block whose chroma takes it codes a different mode symbol, two
353+/// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
354+/// restores the previous streams. Re-pinned again in the same lane once
355+/// directional luma winners searched their `angle_delta_y`
356+/// (`EC_AV1_ANGLE=0` restores that half).
357+#[test]
358+fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
359+ // These are DEFAULT-PRESET pins: a speed preset switches search levers
360+ // off, so it legitimately moves every byte. Encode at speed 0 whatever
361+ // `EC_AV1_SPEED` says (write guard: the preset is process-global).
362+ let _knobs = crate::speed::knob_write();
363+ let was = crate::speed::speed();
364+ crate::speed::set_speed(0);
365+ // lane-av1clipprobe: the bare `clip.exists()` -> SKIP had no env escape,
366+ // so a tree with no root `fixtures/` reported this gate green having
367+ // compared nothing at all.
368+ let clip = ec_testkit::fixture("open/sintel_trailer-1080p.mp4");
369+ let source = clip_frames(clip.to_str().unwrap(), "20", 640, 384, 4);
370+ // FNV-1a over the stream: a witness that every coded bit is where it
371+ // was, which a byte count alone is not.
372+ let fnv = |b: &[u8]| {
373+ b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
374+ (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
375+ })
376+ };
377+ // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
378+ // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
379+ // of 4, its leaves at q+8 and a `show_existing_frame` header per
380+ // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
381+ // four frames; four pictures is one short mini-GOP, which is the
382+ // shape that pays least (the ARF's own quality has no later group to
383+ // carry it), so this is not the BD gate's number.
384+ // Re-taken again on lane-av1cfl: the chroma search offers
385+ // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
386+ // so every block taking either codes different syntax and different
387+ // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
388+ // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
389+ // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
390+ // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
391+ // so these four pictures code as one truncated group -- a hidden
392+ // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
393+ // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
394+ // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
395+ // Re-taken on lane-fintra: the sequence header sets
396+ // `enable_filter_intra`, so every DC_PRED intra block of at most
397+ // 32x32 without a luma palette carries a `use_filter_intra` flag and
398+ // the blocks that take one code a filter-intra mode, a different
399+ // prediction and different coefficients -- 7321 -> 7373 at q=150 and
400+ // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
401+ // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
402+ // (default pyramid `8:-32:16`, one truncated group of 8 with its
403+ // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
404+ // root can code a REAL residual now (one TX_64X64 luma transform and
405+ // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
406+ // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
407+ // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
408+ // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
409+ // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
410+ // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
411+ // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
412+ // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
413+ // -> 9835 at q=150 and 35450 -> 35798 at q=60.
414+ // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
415+ // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
416+ // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
417+ // these four pictures -- offers every superblock a 64x64 intra root
418+ // now. `EC_AV1_I64=0` restores 8557 / 33345.
419+ // Re-taken on lane-pricer: the inter RD search prices a single
420+ // reference through the tree and the neighbour contexts the writer
421+ // really codes it with, so every inter picture's reference decisions
422+ // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
423+ // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
424+ // for `skip`/`is_inter` and for the whole compound reference tree, so
425+ // every inter block's cost -- and with it the skip and reference
426+ // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
427+ // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
428+ // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
429+ // single and compound are priced against the same syntax -- 8311 ->
430+ // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
431+ // Re-taken on lane-newmv: the motion search charges its own rate term
432+ // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
433+ // and each subpel stage re-runs from its own winner
434+ // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
435+ // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
436+ // and 33014 -> 33090 at q=60.
437+ // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
438+ // from libaom's objective tpl mapping, so every inter picture's
439+ // quantizer grid -- and every decision priced against it -- moved
440+ // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
441+ // at the merge of both lanes.
442+ // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
443+ // per-superblock `delta_qindex` at 1.5x the preset's strength
444+ // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
445+ // grids -- and every decision priced against them -- moved:
446+ // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
447+ // Re-taken on lane-arfpred: the top ARF is coded from a temporally
448+ // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
449+ // pixels -- and the leaves that predict from them -- moved:
450+ // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
451+ // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
452+ // the shipped stream did not move.
453+ // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
454+ // picture is coded in 128x128 superblocks now, the inter ones
455+ // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
456+ // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
457+ // Re-taken at the merge of lane-b128m onto main (128 superblocks on
458+ // by default, on top of the ARF temporal filter).
459+ // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
460+ // candidates the 64 root already did ([`b128_compound`]), so every
461+ // inter frame that carries `reference_select` codes different blocks
462+ // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
463+ // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
464+ // Re-taken on lane-arftf: that filter's strength swept on the deciding
465+ // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
466+ // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
467+ // 33017 at q=60 (the same LENGTH, different bytes).
468+ // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
469+ // lane-rlclamp onto the 128 compound default.
470+ // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
471+ // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
472+ // so every inter frame whose RD takes one codes a different partition
473+ // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
474+ // quantizer the rect cut never wins its own comparison on this clip.
475+ // `EC_AV1_B128HV=0` restores 8290 exactly.
476+ let pins: [(u8, usize, u64); 2] = [
477+ (150, 23666, 11535713837929557386),
478+ (60, 102035, 3886390906684528357),
479+ ];
480+ let coded: Vec<(u8, usize, u64)> = pins
481+ .iter()
482+ .map(|&(q, _, _)| {
483+ let e = encode_sequence(&source, q, 0.5).unwrap();
484+ (q, e.stream.len(), fnv(&e.stream))
485+ })
486+ .collect();
487+ crate::speed::set_speed(was);
488+ for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
489+ assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
490+ }
491+}
492+
493+/// The probe arms the gate's source (lane-probe, class `instrument
494+/// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
495+/// command line and had no `-ss`, so it read film B from frame 0 -- a
496+/// black leader -- and coded 59 kB where the gate's own ladder point
497+/// coded 89 kB of the same title; every census taken through it was
498+/// probe-relative. Both now call [`crate::probe::source`]; this pins that
499+/// the shared loader honours the seek (arming the probe's way and the
500+/// gate's way gives byte-identical streams, and dropping the seek does
501+/// not), on a synthetic clip whose content moves over time.
502+#[test]
503+fn the_probe_arms_the_gates_source() {
504+ let _knobs = crate::speed::knob_write();
505+ let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
506+ std::fs::create_dir_all(&dir).unwrap();
507+ let clip = dir.join("testsrc2.y4m");
508+ // 384x202: neither side is a multiple of 128, so the gate's centre
509+ // window is a real derivation and not the frame itself -- exactly the
510+ // shape film B has (3840x1608, never 3840x2160).
511+ let ok = ec_testkit::ffmpeg()
512+ .args([
513+ "-v",
514+ "error",
515+ "-y",
516+ "-f",
517+ "lavfi",
518+ "-i",
519+ "testsrc2=size=384x202:rate=10",
520+ ])
521+ .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
522+ .arg(&clip)
523+ .status()
524+ .expect("ffmpeg failed to run")
525+ .success();
526+ assert!(ok, "ffmpeg could not write the synthetic clip");
527+ let path = clip.to_str().unwrap();
528+
529+ // The window: superblock-aligned, centred, even offsets.
530+ let (vf, w, h) = crate::probe::gate_crop(path);
531+ assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
532+
533+ let (seek, q) = ("00:00:01", 150u8);
534+ let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
535+ let probe = crate::probe::source(path, seek, &vf, w, h, 6);
536+ assert!(
537+ gate.iter()
538+ .zip(&probe)
539+ .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
540+ "the probe's source differs from the gate's at the same window"
541+ );
542+ let bytes = |src: &[Picture]| {
543+ encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
544+ .unwrap()
545+ .stream
546+ };
547+ assert_eq!(
548+ bytes(&gate),
549+ bytes(&probe),
550+ "probe and gate code different bytes"
551+ );
552+ // The two witnesses that both halves of the arming reach ffmpeg: the
553+ // seek, and the crop's own offset (the film-B defect in miniature --
554+ // the probe was reading `crop=..:568` of a 1608-high frame).
555+ let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
556+ assert_ne!(
557+ bytes(&gate),
558+ bytes(&unseeked),
559+ "seeked and unseeked arming coded the same bytes -- the seek is inert"
560+ );
561+ let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
562+ assert_ne!(
563+ bytes(&gate),
564+ bytes(&offset),
565+ "centred and top-aligned windows coded the same bytes -- the crop is inert"
566+ );
567+ std::fs::remove_dir_all(&dir).ok();
568+}
569+
570+/// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
571+/// hardwire the REGULAR kernel, so the encoder could not have coded a
572+/// SMOOTH or SHARP frame even if the header had said so -- the search,
573+/// the trials, the recon and the frame header now all read
574+/// `FrameCtx::interp_filter`. Each of the three kernels codes its own
575+/// distinct stream (a filter that never reached the prediction would code
576+/// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
577+/// reconstructs every frame of each of them exactly, which is what proves
578+/// the header and the prediction agree.
579+#[test]
580+fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
581+ let _knobs = crate::speed::knob_write();
582+ let (width, height) = (256usize, 128usize);
583+ // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
584+ // all three kernels would code the same bytes and the test would pass
585+ // on a wiring that does nothing (class `fixture proves the symbol, not
586+ // the signal`). `panned_test_card` shifts by whole pixels, so the
587+ // search finds the sub-pel positions off the reconstruction instead:
588+ // three frames of a slow diagonal pan.
589+ let pictures: Vec<Picture> = (0..3)
590+ .map(|i| panned_test_card(width, height, i * 3))
591+ .collect();
592+ let mut streams = Vec::new();
593+ for filter in [
594+ ec_av1_syntax::InterpolationFilter::Eighttap,
595+ ec_av1_syntax::InterpolationFilter::EighttapSmooth,
596+ ec_av1_syntax::InterpolationFilter::EighttapSharp,
597+ ] {
598+ set_frame_interp(Some(filter));
599+ let fctx = &crate::decode::FrameCtx::for_encoder();
600+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
601+ .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
602+ let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
603+ assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
604+ for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
605+ assert_eq!(
606+ decoded.y, frame.reconstruction.y,
607+ "{filter:?} frame {i}: luma"
1021608 );
609+ assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
610+ assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
1022611 }
612+ streams.push((filter, encoded.stream));
1023613 }
1024-
1025- /// The video stream's coded size, from ffprobe.
1026- pub(super) fn probe_dims(clip: &str) -> Option<(usize, usize)> {
1027- crate::probe::dims(clip)
1028- }
1029-
1030- /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
1031- /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
1032- /// superblock-aligned one, still centred and still even for 4:2:0.
1033- ///
1034- /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
1035- /// superblocks by design, so no default gate row has a block the frame
1036- /// edge cuts through -- while every arbitrary export size does (3840x1608
1037- /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
1038- /// 1920x1080` is the straddling arm the edge-clipped distortion score is
1039- /// read on.
1040- pub(super) fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
1041- let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
1042- let (w, h) = spec
1043- .split_once('x')
1044- .expect("EC_AV1_NATIVE_CROP is <width>x<height>");
1045- let (cw, ch): (usize, usize) = (
1046- w.parse().expect("crop width"),
1047- h.parse().expect("crop height"),
1048- );
1049- let (nw, nh) = crate::probe::dims(clip)?;
1050- assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
1051- let (x, y) = (((nw - cw) / 2) & !1, ((nh - ch) / 2) & !1);
1052- Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
614+ set_frame_interp(None);
615+ for (i, (fa, a)) in streams.iter().enumerate() {
616+ for (fb, b) in &streams[i + 1..] {
617+ assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
618+ }
1053619 }
1054-
1055- /// The probe arms the gate's source (lane-probe, class `instrument
1056- /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
1057- /// command line and had no `-ss`, so it read film B from frame 0 -- a
1058- /// black leader -- and coded 59 kB where the gate's own ladder point
1059- /// coded 89 kB of the same title; every census taken through it was
1060- /// probe-relative. Both now call [`crate::probe::source`]; this pins that
1061- /// the shared loader honours the seek (arming the probe's way and the
1062- /// gate's way gives byte-identical streams, and dropping the seek does
1063- /// not), on a synthetic clip whose content moves over time.
1064- #[test]
1065- fn the_probe_arms_the_gates_source() {
1066- let _knobs = crate::speed::knob_write();
1067- let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
1068- std::fs::create_dir_all(&dir).unwrap();
1069- let clip = dir.join("testsrc2.y4m");
1070- // 384x202: neither side is a multiple of 128, so the gate's centre
1071- // window is a real derivation and not the frame itself -- exactly the
1072- // shape film B has (3840x1608, never 3840x2160).
1073- let ok = ec_testkit::ffmpeg()
1074- .args([
1075- "-v",
1076- "error",
1077- "-y",
1078- "-f",
1079- "lavfi",
1080- "-i",
1081- "testsrc2=size=384x202:rate=10",
1082- ])
1083- .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
1084- .arg(&clip)
1085- .status()
1086- .expect("ffmpeg failed to run")
1087- .success();
1088- assert!(ok, "ffmpeg could not write the synthetic clip");
1089- let path = clip.to_str().unwrap();
1090-
1091- // The window: superblock-aligned, centred, even offsets.
1092- let (vf, w, h) = crate::probe::gate_crop(path);
1093- assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
1094-
1095- let (seek, q) = ("00:00:01", 150u8);
1096- let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
1097- let probe = crate::probe::source(path, seek, &vf, w, h, 6);
1098- assert!(
1099- gate.iter()
1100- .zip(&probe)
1101- .all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
1102- "the probe's source differs from the gate's at the same window"
1103- );
1104- let bytes = |src: &[Picture]| {
1105- encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
1106- .unwrap()
1107- .stream
1108- };
620+}
621+
622+/// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
623+/// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
624+/// residual outright (`round_to_valid_mv` rounds it away first), so the
625+/// finest vector the encoder could commit to was a quarter pel. With the
626+/// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
627+/// non-zero component and the search's fourth stage refines to the
628+/// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
629+/// on arm, and -- the part that makes it a signal rather than a symbol
630+/// count (class `fixture proves the symbol, not the signal`) -- that some
631+/// of them come out ZERO, i.e. name a vector the off arm cannot code at
632+/// all. Both streams are decoded by ffmpeg AND by this crate's own
633+/// decoder and asserted sample-exact against the encoder's own
634+/// reconstruction, which is what proves the header bit and the symbols
635+/// agree.
636+#[test]
637+fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
638+ let _knobs = crate::speed::knob_write();
639+ let (width, height) = (256usize, 128usize);
640+ let pictures: Vec<Picture> = (0..3)
641+ .map(|i| panned_test_card(width, height, i * 3))
642+ .collect();
643+ let mut arms = Vec::new();
644+ for hp in [false, true] {
645+ set_high_precision_mv(Some(hp));
646+ let _ = crate::tile::take_hp_symbols();
647+ let fctx = &crate::decode::FrameCtx::for_encoder();
648+ let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
649+ .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
650+ let (symbols, eighth) = crate::tile::take_hp_symbols();
651+ let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
652+ let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
653+ assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
1109654 assert_eq!(
1110- bytes(&gate),
1111- bytes(&probe),
1112- "probe and gate code different bytes"
655+ ours.len(),
656+ pictures.len(),
657+ "hp={hp}: our decoder frame count"
1113658 );
1114- // The two witnesses that both halves of the arming reach ffmpeg: the
1115- // seek, and the crop's own offset (the film-B defect in miniature --
1116- // the probe was reading `crop=..:568` of a 1608-high frame).
1117- let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
1118- assert_ne!(
1119- bytes(&gate),
1120- bytes(&unseeked),
1121- "seeked and unseeked arming coded the same bytes -- the seek is inert"
1122- );
1123- let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
1124- assert_ne!(
1125- bytes(&gate),
1126- bytes(&offset),
1127- "centred and top-aligned windows coded the same bytes -- the crop is inert"
1128- );
1129- std::fs::remove_dir_all(&dir).ok();
1130- }
1131-
1132- /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
1133- /// hardwire the REGULAR kernel, so the encoder could not have coded a
1134- /// SMOOTH or SHARP frame even if the header had said so -- the search,
1135- /// the trials, the recon and the frame header now all read
1136- /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
1137- /// distinct stream (a filter that never reached the prediction would code
1138- /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
1139- /// reconstructs every frame of each of them exactly, which is what proves
1140- /// the header and the prediction agree.
1141- #[test]
1142- fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
1143- let _knobs = crate::speed::knob_write();
1144- let (width, height) = (256usize, 128usize);
1145- // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
1146- // all three kernels would code the same bytes and the test would pass
1147- // on a wiring that does nothing (class `fixture proves the symbol, not
1148- // the signal`). `panned_test_card` shifts by whole pixels, so the
1149- // search finds the sub-pel positions off the reconstruction instead:
1150- // three frames of a slow diagonal pan.
1151- let pictures: Vec<Picture> = (0..3)
1152- .map(|i| panned_test_card(width, height, i * 3))
1153- .collect();
1154- let mut streams = Vec::new();
1155- for filter in [
1156- ec_av1_syntax::InterpolationFilter::Eighttap,
1157- ec_av1_syntax::InterpolationFilter::EighttapSmooth,
1158- ec_av1_syntax::InterpolationFilter::EighttapSharp,
1159- ] {
1160- set_frame_interp(Some(filter));
1161- let fctx = &crate::decode::FrameCtx::for_encoder();
1162- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
1163- .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
1164- let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
1165- assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
1166- for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
1167- assert_eq!(
1168- decoded.y, frame.reconstruction.y,
1169- "{filter:?} frame {i}: luma"
1170- );
1171- assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
1172- assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
1173- }
1174- streams.push((filter, encoded.stream));
1175- }
1176- set_frame_interp(None);
1177- for (i, (fa, a)) in streams.iter().enumerate() {
1178- for (fb, b) in &streams[i + 1..] {
1179- assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
1180- }
1181- }
1182- }
1183-
1184- /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
1185- /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
1186- /// residual outright (`round_to_valid_mv` rounds it away first), so the
1187- /// finest vector the encoder could commit to was a quarter pel. With the
1188- /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
1189- /// non-zero component and the search's fourth stage refines to the
1190- /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
1191- /// on arm, and -- the part that makes it a signal rather than a symbol
1192- /// count (class `fixture proves the symbol, not the signal`) -- that some
1193- /// of them come out ZERO, i.e. name a vector the off arm cannot code at
1194- /// all. Both streams are decoded by ffmpeg AND by this crate's own
1195- /// decoder and asserted sample-exact against the encoder's own
1196- /// reconstruction, which is what proves the header bit and the symbols
1197- /// agree.
1198- #[test]
1199- fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
1200- let _knobs = crate::speed::knob_write();
1201- let (width, height) = (256usize, 128usize);
1202- let pictures: Vec<Picture> = (0..3)
1203- .map(|i| panned_test_card(width, height, i * 3))
1204- .collect();
1205- let mut arms = Vec::new();
1206- for hp in [false, true] {
1207- set_high_precision_mv(Some(hp));
1208- let _ = crate::tile::take_hp_symbols();
1209- let fctx = &crate::decode::FrameCtx::for_encoder();
1210- let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
1211- .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
1212- let (symbols, eighth) = crate::tile::take_hp_symbols();
1213- let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
1214- let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
1215- assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
1216- assert_eq!(
1217- ours.len(),
1218- pictures.len(),
1219- "hp={hp}: our decoder frame count"
1220- );
1221- for (i, e) in encoded.frames.iter().enumerate() {
1222- for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
1223- if let Some((plane, s, got, want)) =
1224- first_plane_mismatch(got, &e.reconstruction)
1225- {
1226- panic!(
1227- "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
659+ for (i, e) in encoded.frames.iter().enumerate() {
660+ for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
661+ if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction) {
662+ panic!(
663+ "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
1228664 the encoder reconstructed {want}"
1229- );
1230- }
665+ );
1231666 }
1232667 }
1233- arms.push((symbols, eighth, encoded.stream));
1234668 }
1235- set_high_precision_mv(None);
1236- let (off, on) = (&arms[0], &arms[1]);
1237- assert_eq!(
1238- off.0, 0,
1239- "a frame without the header bit codes no hp symbol"
1240- );
1241- assert!(
1242- on.0 > 0,
1243- "a high-precision frame codes hp symbols (got {})",
1244- on.0
1245- );
1246- assert!(
1247- on.1 > 0,
1248- "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
1249- on.0
1250- );
1251- assert_ne!(off.2, on.2, "the two arms coded the same bytes");
1252- println!(
1253- "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
1254- off.0,
1255- off.2.len(),
1256- on.0,
1257- on.1,
1258- on.2.len()
1259- );
669+ arms.push((symbols, eighth, encoded.stream));
1260670 }
671+ set_high_precision_mv(None);
672+ let (off, on) = (&arms[0], &arms[1]);
673+ assert_eq!(
674+ off.0, 0,
675+ "a frame without the header bit codes no hp symbol"
676+ );
677+ assert!(
678+ on.0 > 0,
679+ "a high-precision frame codes hp symbols (got {})",
680+ on.0
681+ );
682+ assert!(
683+ on.1 > 0,
684+ "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
685+ on.0
686+ );
687+ assert_ne!(off.2, on.2, "the two arms coded the same bytes");
688+ println!(
689+ "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
690+ off.0,
691+ off.2.len(),
692+ on.0,
693+ on.1,
694+ on.2.len()
695+ );
696+}
crates/ec-av1/src/encode/split.rsmodified+206 -267
@@ -312,13 +312,6 @@ pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
312312 std::sync::atomic::AtomicU64::new(0),
313313 ];
314314
315-/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
316-/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
317-#[cfg(test)]
318-pub(crate) fn take_txrd_stats() -> [u64; 7] {
319- std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
320-}
321-
322315 /// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
323316 #[cfg(test)]
324317 pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
@@ -969,7 +962,15 @@ thread_local! {
969962 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
970963 }
971964
972-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
965+/// Whether the luma search refines a directional winner's `angle_delta_y`
966+/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
967+pub(super) fn angle_delta_on() -> bool {
968+ static ENV: std::sync::LazyLock<Option<bool>> =
969+ std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0"));
970+ ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
971+}
972+
973+#[cfg(test)]
973974 pub(crate) fn force_intrabc(value: Option<bool>) {
974975 INTRABC_FORCE.with(|c| c.set(value));
975976 }
@@ -1059,7 +1060,12 @@ pub(super) fn ibc_index(
10591060 /// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
10601061 /// content appears at some other position, against [`intrabc_pct`]. Returns
10611062 /// the share as well, for the gate's own print.
1062-pub(super) fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
1063+pub(super) fn intrabc_worth_it(
1064+ y: &[u8],
1065+ width: usize,
1066+ true_width: usize,
1067+ true_height: usize,
1068+) -> (bool, f64) {
10631069 if true_width < 4 * 64 || true_height < 2 * 64 {
10641070 return (false, 0.0);
10651071 }
@@ -1075,9 +1081,9 @@ pub(super) fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_h
10751081 && hits
10761082 .iter()
10771083 .any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by))
1078- {
1079- matched += 1;
1080- }
1084+ {
1085+ matched += 1;
1086+ }
10811087 bx += IBC_HASH;
10821088 }
10831089 by += IBC_HASH;
@@ -1207,13 +1213,6 @@ impl Drop for Ibc {
12071213 }
12081214 }
12091215
1210-/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
1211-/// its own encode.
1212-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1213-pub(crate) fn take_intrabc_search() -> [usize; 3] {
1214- std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1215-}
1216-
12171216 /// [`crate::tile::write_dv_component`]'s static price -- the same shape as
12181217 /// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
12191218 /// infers rather than codes.
@@ -1667,19 +1666,20 @@ pub(super) fn code_square(
16671666 if let Some(ibc) = ibc
16681667 && let Some((dv, cost_ibc, src)) =
16691668 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
1670- && cost_ibc < cost {
1671- ibc_commit(luma, chroma, (x, y), src, side);
1672- ibc.last_dv = Some(dv);
1673- ibc.hits += 1;
1674- return (
1675- BlockCoeffs {
1676- skip: true,
1677- dv: Some(dv),
1678- ..BlockCoeffs::default()
1679- },
1680- cost_ibc,
1681- );
1682- }
1669+ && cost_ibc < cost
1670+ {
1671+ ibc_commit(luma, chroma, (x, y), src, side);
1672+ ibc.last_dv = Some(dv);
1673+ ibc.hits += 1;
1674+ return (
1675+ BlockCoeffs {
1676+ skip: true,
1677+ dv: Some(dv),
1678+ ..BlockCoeffs::default()
1679+ },
1680+ cost_ibc,
1681+ );
1682+ }
16831683 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
16841684 // (its levels came from `code_from_prediction`), so the searched types
16851685 // belong to a block this one no longer is.
@@ -1722,53 +1722,6 @@ pub(super) const CHROMA_MODES: [u8; 7] = [
17221722 PAETH_PRED,
17231723 ];
17241724
1725-/// The thirteen intra mode names, for the chroma fire count's print.
1726-#[cfg(test)]
1727-pub(super) const UV_MODE_NAMES: [&str; 14] = [
1728- "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V", "SMOOTH_H",
1729- "PAETH", "CFL",
1730-];
1731-
1732-/// How many blocks each chroma mode has won, indexed by the mode itself --
1733-/// the fire count that says whether the search below reaches its candidates
1734-/// at all (the `gate-blind-to-feature` class), printed once per gate run.
1735-pub(super) static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
1736- [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
1737-
1738-/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
1739-/// won, summed over both chroma planes -- the alpha histogram the gate prints
1740-/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
1741-/// magnitude only is a search that never left its first candidate).
1742-pub(super) static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
1743- [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
1744-
1745-/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
1746-/// zero on a CfL block", `1..=16` the magnitudes.
1747-#[cfg(test)]
1748-pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
1749- std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
1750-}
1751-
1752-/// How many directional luma blocks won at each `angle_delta_y`, indexed
1753-/// `delta + 3` -- the histogram that says whether the refinement below ever
1754-/// leaves zero (`gate-blind-to-feature`).
1755-pub(super) static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
1756- [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1757-
1758-/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
1759-#[cfg(test)]
1760-pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
1761- std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
1762-}
1763-
1764-/// Whether the luma search refines a directional winner's `angle_delta_y`
1765-/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
1766-pub(super) fn angle_delta_on() -> bool {
1767- static ENV: std::sync::LazyLock<Option<bool>> =
1768- std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0"));
1769- ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
1770-}
1771-
17721725 /// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
17731726 /// switches it off, which is how the lane measured its own on/off pair).
17741727 pub(super) fn cfl_on() -> bool {
@@ -1834,14 +1787,6 @@ pub(crate) fn sb128_on() -> bool {
18341787 }
18351788 }
18361789
1837-/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
1838-/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
1839-/// exactly like the speed-preset gates.
1840-#[cfg(test)]
1841-pub(crate) fn force_sb128(on: bool) {
1842- ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
1843-}
1844-
18451790 /// The luma loop-restoration unit size this sequence codes: a 128 superblock
18461791 /// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
18471792 /// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
@@ -1863,13 +1808,6 @@ pub(crate) fn filter_intra_on() -> bool {
18631808 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
18641809 }
18651810
1866-/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
1867-/// to its own encode.
1868-#[cfg(test)]
1869-pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
1870- std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
1871-}
1872-
18731811 /// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
18741812 /// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
18751813 /// Returns each plane's levels, the mode, and what the pair cost (squared
@@ -2051,7 +1989,9 @@ pub(super) fn search_chroma(
20511989 }
20521990 let mut v_colors = [0u16; 8];
20531991 for k in 0..n {
2054- v_colors[k] = (sums[k] + counts[k] / 2).checked_div(counts[k]).unwrap_or(0) as u16;
1992+ v_colors[k] = (sums[k] + counts[k] / 2)
1993+ .checked_div(counts[k])
1994+ .unwrap_or(0) as u16;
20551995 }
20561996 let candidate = crate::tile::PaletteUv {
20571997 size: pal.size,
@@ -2229,17 +2169,10 @@ pub(super) fn search_chroma(
22292169 }
22302170 }
22312171 }
2232- if let Some((alpha_u, alpha_v)) = cfl_alphas {
2233- for alpha in [alpha_u, alpha_v] {
2234- CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
2235- .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2236- }
2237- }
22382172 if census_on() {
22392173 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
22402174 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
22412175 }
2242- UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
22432176 chroma[0].commit(at.x, at.y, at.side, &u);
22442177 chroma[1].commit(at.x, at.y, at.side, &v);
22452178 (
@@ -2871,53 +2804,55 @@ pub(super) fn code_square_inter(
28712804 }
28722805 }
28732806 if let Some(new_mv) = searched_new
2874- && let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
2875- ccands.push((
2876- (new_mv, cstack.nearest_mv.1),
2877- mode_bits_of(3) + b0,
2878- InterInfo {
2879- ref_frame: crate::mvstack::LAST_FRAME,
2880- mode: InterMode::NewNearestMv,
2881- mv: new_mv,
2882- mv1: cstack.nearest_mv.1,
2883- ref1: Some(ref1),
2884- ref_mv_idx: 0,
2885- },
2886- ));
2887- }
2807+ && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
2808+ {
2809+ ccands.push((
2810+ (new_mv, cstack.nearest_mv.1),
2811+ mode_bits_of(3) + b0,
2812+ InterInfo {
2813+ ref_frame: crate::mvstack::LAST_FRAME,
2814+ mode: InterMode::NewNearestMv,
2815+ mv: new_mv,
2816+ mv1: cstack.nearest_mv.1,
2817+ ref1: Some(ref1),
2818+ ref_mv_idx: 0,
2819+ },
2820+ ));
2821+ }
28882822 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
28892823 // searches this leaf ran, each residual priced against `cbase`.
28902824 if let Some(mv1) = second_new
2891- && let Some(b1) = mv_residual_bits(mv1, cbase.1) {
2825+ && let Some(b1) = mv_residual_bits(mv1, cbase.1)
2826+ {
2827+ ccands.push((
2828+ (cstack.nearest_mv.0, mv1),
2829+ mode_bits_of(2) + b1,
2830+ InterInfo {
2831+ ref_frame: crate::mvstack::LAST_FRAME,
2832+ mode: InterMode::NearestNewMv,
2833+ mv: cstack.nearest_mv.0,
2834+ mv1,
2835+ ref1: Some(ref1),
2836+ ref_mv_idx: 0,
2837+ },
2838+ ));
2839+ if let Some((new_mv, b0)) =
2840+ searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
2841+ {
28922842 ccands.push((
2893- (cstack.nearest_mv.0, mv1),
2894- mode_bits_of(2) + b1,
2843+ (new_mv, mv1),
2844+ mode_bits_of(7) + b0 + b1,
28952845 InterInfo {
28962846 ref_frame: crate::mvstack::LAST_FRAME,
2897- mode: InterMode::NearestNewMv,
2898- mv: cstack.nearest_mv.0,
2847+ mode: InterMode::NewNewMv,
2848+ mv: new_mv,
28992849 mv1,
29002850 ref1: Some(ref1),
29012851 ref_mv_idx: 0,
29022852 },
29032853 ));
2904- if let Some((new_mv, b0)) =
2905- searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
2906- {
2907- ccands.push((
2908- (new_mv, mv1),
2909- mode_bits_of(7) + b0 + b1,
2910- InterInfo {
2911- ref_frame: crate::mvstack::LAST_FRAME,
2912- mode: InterMode::NewNewMv,
2913- mv: new_mv,
2914- mv1,
2915- ref1: Some(ref1),
2916- ref_mv_idx: 0,
2917- },
2918- ));
2919- }
29202854 }
2855+ }
29212856 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
29222857 ccands.dedup_by_key(|c| c.0);
29232858 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
@@ -3040,7 +2975,8 @@ pub(super) fn code_square_inter(
30402975 ) >= 1;
30412976 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
30422977 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
3043- if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side()
2978+ if crate::envflags::env_flag!("EC_AV1_OBMC")
2979+ && side >= obmc_min_side()
30442980 && let Some(pred) = obmc_prediction(
30452981 grid,
30462982 (mi_row, mi_col),
@@ -3052,9 +2988,10 @@ pub(super) fn code_square_inter(
30522988 planes,
30532989 (reference.width, reference.height),
30542990 fctx,
3055- ) {
3056- candidates.push((1, pred));
3057- }
2991+ )
2992+ {
2993+ candidates.push((1, pred));
2994+ }
30582995 if warp_alphabet
30592996 && let Some(pred) = warp_prediction(
30602997 grid,
@@ -3066,9 +3003,10 @@ pub(super) fn code_square_inter(
30663003 info.ref_frame,
30673004 planes,
30683005 fctx,
3069- ) {
3070- candidates.push((2, pred));
3071- }
3006+ )
3007+ {
3008+ candidates.push((2, pred));
3009+ }
30723010 for (motion, pred) in candidates {
30733011 let luma_o = luma.code_from_prediction(
30743012 x,
@@ -3125,136 +3063,137 @@ pub(super) fn code_square_inter(
31253063 }
31263064
31273065 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best
3128- && cost < intra_cost {
3129- // A compound winner commits the flat trial it was priced from:
3130- // `commit_inter_luma`'s var-tx trial set is single-reference
3131- // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3132- // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
3133- // predicting each half-side trial from BOTH references, verified
3134- // byte-identical to this when its split is disabled) and MEASURED
3135- // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
3136- // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
3137- // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
3138- // compound block's residual is small enough that the four extra
3139- // per-unit txb_skip/eob symbols cost more ladder bytes than this
3140- // encoder's static-CDF estimate prices them at, so the local RD
3141- // win does not convert. lane-av1txbits REBUILT it on top of a
3142- // search that prices against the tables the frame is really
3143- // written with (`tile::arm_pricing_cdfs`, the estimate error on
3144- // these very blocks measured down from +31% to +3%) and measured
3145- // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
3146- // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
3147- // same build without it. The static-CDF estimate was NOT what
3148- // held the compound var-tx trial back. The flat trial stays.
3149- // An OBMC winner commits the flat trial too: `commit_inter_luma`
3150- // re-predicts each var-tx unit by plain translation, which is not
3151- // the prediction this candidate was priced from.
3152- // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
3153- // 0.05 (both rejections above were measured at 0.1, the weight
3154- // the lambda lane showed was 2x too heavy): a compound winner is
3155- // offered the same var-tx split, its units predicted from BOTH
3156- // references (`mc_trial_compound`). RE-MEASURED native: film
3157- // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
3158- // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
3159- // one row 0.2 down, two flat, short of the two-down-one-flat keep
3160- // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
3161- // rather than change the default on a single 0.2 row. It fires:
3162- // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
3163- // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
3164- // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
3165- // 1.3/1.2 down there, which is where the upgrade path is if this
3166- // is picked up again.
3167- let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3168- refs[r as usize].map(|g| {
3169- (
3170- info.mv1,
3171- (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
3172- )
3173- })
3174- });
3175- let (levels, tx_depth, dcost, luma_tx_types) =
3176- if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
3177- luma.commit(x, y, side, &luma_new);
3178- (luma_new.levels.clone(), 0, 0.0, Vec::new())
3179- } else {
3180- commit_inter_luma(
3181- luma,
3182- (x, y),
3183- side,
3184- info.mv,
3185- (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3186- search,
3187- &luma_new,
3188- skip_new,
3189- second,
3190- fctx,
3191- )
3192- };
3193- // lane-txrd: chroma follows the luma type the search just chose.
3194- let [u_new, v_new] = match luma_tx_types.first().copied() {
3195- Some(t) => recode_inter_chroma(
3196- chroma,
3066+ && cost < intra_cost
3067+ {
3068+ // A compound winner commits the flat trial it was priced from:
3069+ // `commit_inter_luma`'s var-tx trial set is single-reference
3070+ // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3071+ // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
3072+ // predicting each half-side trial from BOTH references, verified
3073+ // byte-identical to this when its split is disabled) and MEASURED
3074+ // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
3075+ // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
3076+ // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
3077+ // compound block's residual is small enough that the four extra
3078+ // per-unit txb_skip/eob symbols cost more ladder bytes than this
3079+ // encoder's static-CDF estimate prices them at, so the local RD
3080+ // win does not convert. lane-av1txbits REBUILT it on top of a
3081+ // search that prices against the tables the frame is really
3082+ // written with (`tile::arm_pricing_cdfs`, the estimate error on
3083+ // these very blocks measured down from +31% to +3%) and measured
3084+ // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
3085+ // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
3086+ // same build without it. The static-CDF estimate was NOT what
3087+ // held the compound var-tx trial back. The flat trial stays.
3088+ // An OBMC winner commits the flat trial too: `commit_inter_luma`
3089+ // re-predicts each var-tx unit by plain translation, which is not
3090+ // the prediction this candidate was priced from.
3091+ // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
3092+ // 0.05 (both rejections above were measured at 0.1, the weight
3093+ // the lambda lane showed was 2x too heavy): a compound winner is
3094+ // offered the same var-tx split, its units predicted from BOTH
3095+ // references (`mc_trial_compound`). RE-MEASURED native: film
3096+ // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
3097+ // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
3098+ // one row 0.2 down, two flat, short of the two-down-one-flat keep
3099+ // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
3100+ // rather than change the default on a single 0.2 row. It fires:
3101+ // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
3102+ // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
3103+ // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
3104+ // 1.3/1.2 down there, which is where the upgrade path is if this
3105+ // is picked up again.
3106+ let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3107+ refs[r as usize].map(|g| {
3108+ (
3109+ info.mv1,
3110+ (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
3111+ )
3112+ })
3113+ });
3114+ let (levels, tx_depth, dcost, luma_tx_types) =
3115+ if motion_won != 0 || (info.ref1.is_some() && second.is_none()) {
3116+ luma.commit(x, y, side, &luma_new);
3117+ (luma_new.levels.clone(), 0, 0.0, Vec::new())
3118+ } else {
3119+ commit_inter_luma(
3120+ luma,
31973121 (x, y),
31983122 side,
31993123 info.mv,
3200- [
3201- (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
3202- (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
3203- ],
3204- info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3205- refs[r as usize].map(|g| {
3206- (
3207- info.mv1,
3208- [
3209- (
3210- g.u.as_slice(),
3211- g.width / 2,
3212- chroma[0].true_width,
3213- chroma[0].true_height,
3214- ),
3215- (
3216- g.v.as_slice(),
3217- g.width / 2,
3218- chroma[1].true_width,
3219- chroma[1].true_height,
3220- ),
3221- ],
3222- )
3223- })
3224- }),
3124+ (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
32253125 search,
3226- chroma_set,
3227- t,
3126+ &luma_new,
3127+ skip_new,
3128+ second,
32283129 fctx,
32293130 )
3230- .unwrap_or([u_new, v_new]),
3231- None => [u_new, v_new],
32323131 };
3233- chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
3234- chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
3235- return (
3236- BlockCoeffs {
3237- angle_delta_y: 0,
3238- cfl_alphas: None,
3239- filter_intra: None,
3240- luma: coeffs(&levels, side),
3241- u: coeffs(&u_new.levels, side / 2),
3242- v: coeffs(&v_new.levels, side / 2),
3243- mode: DC_PRED,
3244- uv_mode: DC_PRED,
3245- skip: skip_new,
3246- eight: None,
3247- dv: None,
3248- palette: None,
3249- palette_uv: None,
3250- tx_depth,
3251- luma_tx_types,
3252- inter: Some(info),
3253- motion_mode: motion_won,
3254- },
3255- cost + dcost,
3256- );
3257- }
3132+ // lane-txrd: chroma follows the luma type the search just chose.
3133+ let [u_new, v_new] = match luma_tx_types.first().copied() {
3134+ Some(t) => recode_inter_chroma(
3135+ chroma,
3136+ (x, y),
3137+ side,
3138+ info.mv,
3139+ [
3140+ (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
3141+ (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
3142+ ],
3143+ info.ref1.filter(|_| motion_won == 0).and_then(|r| {
3144+ refs[r as usize].map(|g| {
3145+ (
3146+ info.mv1,
3147+ [
3148+ (
3149+ g.u.as_slice(),
3150+ g.width / 2,
3151+ chroma[0].true_width,
3152+ chroma[0].true_height,
3153+ ),
3154+ (
3155+ g.v.as_slice(),
3156+ g.width / 2,
3157+ chroma[1].true_width,
3158+ chroma[1].true_height,
3159+ ),
3160+ ],
3161+ )
3162+ })
3163+ }),
3164+ search,
3165+ chroma_set,
3166+ t,
3167+ fctx,
3168+ )
3169+ .unwrap_or([u_new, v_new]),
3170+ None => [u_new, v_new],
3171+ };
3172+ chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
3173+ chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
3174+ return (
3175+ BlockCoeffs {
3176+ angle_delta_y: 0,
3177+ cfl_alphas: None,
3178+ filter_intra: None,
3179+ luma: coeffs(&levels, side),
3180+ u: coeffs(&u_new.levels, side / 2),
3181+ v: coeffs(&v_new.levels, side / 2),
3182+ mode: DC_PRED,
3183+ uv_mode: DC_PRED,
3184+ skip: skip_new,
3185+ eight: None,
3186+ dv: None,
3187+ palette: None,
3188+ palette_uv: None,
3189+ tx_depth,
3190+ luma_tx_types,
3191+ inter: Some(info),
3192+ motion_mode: motion_won,
3193+ },
3194+ cost + dcost,
3195+ );
3196+ }
32583197
32593198 census_add(8, 1);
32603199 if skip {
crates/ec-av1/src/encode/tests.rsmodified+2382 -3366

Diff too large; view file

@@ -1,3548 +1,2564 @@
11
2- /// Every (site, frame type, block side) the census can be called with
3- /// lands in its own ten-counter bucket, inside the array (class
4- /// `enumerate-table-domain`: an off-by-one here would silently add two
5- /// sites' trials together).
6- #[test]
7- fn the_split_census_buckets_are_distinct_and_in_bounds() {
8- let mut seen = std::collections::BTreeSet::new();
9- for site in 0..2 {
10- for key in [true, false] {
11- for side in [8usize, 16, 32, 64] {
12- let base = super::split_census_base(site, key, side);
13- assert!(
14- base + 10 <= super::SPLIT_CENSUS.len(),
15- "{site} {key} {side}"
16- );
17- assert!(seen.insert(base), "{site} {key} {side} collides");
18- }
2+/// Every (site, frame type, block side) the census can be called with
3+/// lands in its own ten-counter bucket, inside the array (class
4+/// `enumerate-table-domain`: an off-by-one here would silently add two
5+/// sites' trials together).
6+#[test]
7+fn the_split_census_buckets_are_distinct_and_in_bounds() {
8+ let mut seen = std::collections::BTreeSet::new();
9+ for site in 0..2 {
10+ for key in [true, false] {
11+ for side in [8usize, 16, 32, 64] {
12+ let base = super::split_census_base(site, key, side);
13+ assert!(
14+ base + 10 <= super::SPLIT_CENSUS.len(),
15+ "{site} {key} {side}"
16+ );
17+ assert!(seen.insert(base), "{site} {key} {side} collides");
1918 }
2019 }
21- assert_eq!(seen.len(), 16);
2220 }
21+ assert_eq!(seen.len(), 16);
22+}
2323
24- /// An [`crate::mvstack::MvStack`] with every context at zero and no
25- /// neighbours, for the pricer tests below to fill the one band each of
26- /// them is about.
27- /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
28- /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
29- /// against the same stack -- an offer the writer clamps prices the
30- /// residual against a predictor the decoder never derives, which is the
31- /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
32- /// side, so the stream stays legal; here the pricer's own offer set is
33- /// enumerated, class `enumerate-table-domain`).
34- ///
35- /// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt
36- /// r2, 2026-09-29). It replaces the clip gate
37- /// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`,
38- /// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a
39- /// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable
40- /// while the invariant above holds, so no recipe could ever satisfy it.
41- /// Deletion loses no coverage on either half:
42- /// * the clamp half -- this test IS the coverage, and it is strictly
43- /// stronger than any clip gate: it enumerates the pricer's whole offer
44- /// set against the writer's rule for every stack size 0..=4, and larger
45- /// stacks add entries the pricers never offer (`best_new_mv_syntax`
46- /// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are
47- /// unreachable at ANY stack size), which is why 0..=4 bounds the
48- /// domain rather than sampling it;
49- /// * the pixel half -- the deleted gate's own decode-vs-encoder-
50- /// reconstruction compare on a 1280x768 sb128 sequence is already made
51- /// four times over, by `a_128_superblock_clip_whose_root_search_codes_
52- /// 128x128_blocks_decodes_exact`,
53- /// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`,
54- /// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`
55- /// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
56- /// (same geometry, same `force_sb128(true)`, same own-reconstruction AND
57- /// ffmpeg compare).
58- ///
59- /// MEASURED before deleting (153 clip x size x frame-count x q combinations,
60- /// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF
61- /// the clip was never the variable: widening `best_new_mv_syntax`'s offer
62- /// set to `0..5` fires the counter immediately (9/2/2/1 on
63- /// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,
64- /// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp`
65- /// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix
66- /// (`deferred(unblock: the DRL owner widens the pricer past the writer's
67- /// `start + 2` ceiling, or retires the counter)`) -- this test will go red
68- /// the moment either happens, which is the signal to re-open the cell.
69- ///
70- /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
71- #[test]
72- fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
73- for n in 0..=4usize {
74- let mut stack = bare_stack();
75- for i in 0..n {
76- stack.entries.push(crate::mvstack::StackEntry {
77- mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
78- weight: 1,
79- });
80- stack.drl_ctx.push(0);
81- }
82- stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
83- stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
84- stack.pred_mv = stack.nearest_mv;
85- // Aim the vector at each entry in turn, so every index the offer
86- // set holds is the one that wins at least once.
87- for target in 0..n.max(1) {
88- let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
89- let (_, idx) =
90- best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");
91- let idx = usize::from(idx);
24+/// An [`crate::mvstack::MvStack`] with every context at zero and no
25+/// neighbours, for the pricer tests below to fill the one band each of
26+/// them is about.
27+/// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
28+/// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
29+/// against the same stack -- an offer the writer clamps prices the
30+/// residual against a predictor the decoder never derives, which is the
31+/// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
32+/// side, so the stream stays legal; here the pricer's own offer set is
33+/// enumerated, class `enumerate-table-domain`).
34+///
35+/// **This is the coverage claim for the drl-clamp cell** (lane-av1recipehunt
36+/// r2, 2026-09-29). It replaces the clip gate
37+/// `a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact`,
38+/// deleted in `3e8c65e6`+r2: that gate asserted `drl_clamp_hits() > 0` on a
39+/// real 1280x768 sb128 clip, but `DRL_CLAMP_HITS` is provably unreachable
40+/// while the invariant above holds, so no recipe could ever satisfy it.
41+/// Deletion loses no coverage on either half:
42+/// * the clamp half -- this test IS the coverage, and it is strictly
43+/// stronger than any clip gate: it enumerates the pricer's whole offer
44+/// set against the writer's rule for every stack size 0..=4, and larger
45+/// stacks add entries the pricers never offer (`best_new_mv_syntax`
46+/// breaks at `entries.len() <= idx` for `idx > 0`, so indices 3/4 are
47+/// unreachable at ANY stack size), which is why 0..=4 bounds the
48+/// domain rather than sampling it;
49+/// * the pixel half -- the deleted gate's own decode-vs-encoder-
50+/// reconstruction compare on a 1280x768 sb128 sequence is already made
51+/// four times over, by `a_128_superblock_clip_whose_root_search_codes_
52+/// 128x128_blocks_decodes_exact`,
53+/// `a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders`,
54+/// `a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact`
55+/// and `a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders`
56+/// (same geometry, same `force_sb128(true)`, same own-reconstruction AND
57+/// ffmpeg compare).
58+///
59+/// MEASURED before deleting (153 clip x size x frame-count x q combinations,
60+/// `enc_probe`): `tile::drl_clamp_hits()` = 0 on every one. MUTATION PROOF
61+/// the clip was never the variable: widening `best_new_mv_syntax`'s offer
62+/// set to `0..5` fires the counter immediately (9/2/2/1 on
63+/// mandelbrot 640x384x8, mandelbrot 320x192x8, mosaic 320x192x8,
64+/// testsrc2 640x384x8) and the same clips read 0 on revert. `note_drl_clamp`
65+/// and `DRL_CLAMP_HITS` are KEPT as the tripwire for the owning fix
66+/// (`deferred(unblock: the DRL owner widens the pricer past the writer's
67+/// `start + 2` ceiling, or retires the counter)`) -- this test will go red
68+/// the moment either happens, which is the signal to re-open the cell.
69+///
70+/// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
71+#[test]
72+fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
73+ for n in 0..=4usize {
74+ let mut stack = bare_stack();
75+ for i in 0..n {
76+ stack.entries.push(crate::mvstack::StackEntry {
77+ mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
78+ weight: 1,
79+ });
80+ stack.drl_ctx.push(0);
81+ }
82+ stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
83+ stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
84+ stack.pred_mv = stack.nearest_mv;
85+ // Aim the vector at each entry in turn, so every index the offer
86+ // set holds is the one that wins at least once.
87+ for target in 0..n.max(1) {
88+ let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
89+ let (_, idx) =
90+ best_new_mv_syntax(&stack, mv).expect("a zero residual is always codable");
91+ let idx = usize::from(idx);
92+ assert_eq!(
93+ crate::tile::signalled_drl_idx(n, 0, idx),
94+ idx,
95+ "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
96+ );
97+ }
98+ // The NEARMV arm's own offer set (`search_inter_block`,
99+ // `search_skip_64`): indices 1 and 2, offered only when the stack
100+ // really holds that entry.
101+ for idx in 1..=2usize {
102+ if stack.entries.get(idx).is_some() {
92103 assert_eq!(
93- crate::tile::signalled_drl_idx(n, 0, idx),
104+ crate::tile::signalled_drl_idx(n, 1, idx),
94105 idx,
95- "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
106+ "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
96107 );
97108 }
98- // The NEARMV arm's own offer set (`search_inter_block`,
99- // `search_skip_64`): indices 1 and 2, offered only when the stack
100- // really holds that entry.
101- for idx in 1..=2usize {
102- if stack.entries.get(idx).is_some() {
103- assert_eq!(
104- crate::tile::signalled_drl_idx(n, 1, idx),
105- idx,
106- "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
107- );
108- }
109- }
110109 }
111110 }
111+}
112112
113- pub(super) fn bare_stack() -> crate::mvstack::MvStack {
114- crate::mvstack::MvStack {
115- entries: Default::default(),
116- nearest_mv: (0, 0),
117- near_mv: (0, 0),
118- pred_mv: (0, 0),
119- new_mv_ctx: 0,
120- ref_mv_ctx: 0,
121- zero_mv_ctx: 0,
122- drl_ctx: Default::default(),
123- above_refs: (None, None),
124- left_refs: (None, None),
125- above_nbr: None,
126- left_nbr: None,
127- above_skip: false,
128- left_skip: false,
129- }
113+pub(super) fn bare_stack() -> crate::mvstack::MvStack {
114+ crate::mvstack::MvStack {
115+ entries: Default::default(),
116+ nearest_mv: (0, 0),
117+ near_mv: (0, 0),
118+ pred_mv: (0, 0),
119+ new_mv_ctx: 0,
120+ ref_mv_ctx: 0,
121+ zero_mv_ctx: 0,
122+ drl_ctx: Default::default(),
123+ above_refs: (None, None),
124+ left_refs: (None, None),
125+ above_nbr: None,
126+ left_nbr: None,
127+ above_skip: false,
128+ left_skip: false,
130129 }
130+}
131131
132- /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
133- /// `write_compound_ref_frames` codes for a pair, each at that symbol's
134- /// own neighbour-derived context. Red before lane-ctx, where the pricer
135- /// spent four constants at CDF row 0 that assumed the pair was
136- /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
137- /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
138- #[test]
139- fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
140- use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
141- use crate::encode::symbol_bits as b;
142- use crate::mvstack::{
143- ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
144- LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
145- single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
146- single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
132+/// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
133+/// `write_compound_ref_frames` codes for a pair, each at that symbol's
134+/// own neighbour-derived context. Red before lane-ctx, where the pricer
135+/// spent four constants at CDF row 0 that assumed the pair was
136+/// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
137+/// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
138+#[test]
139+fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
140+ use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
141+ use crate::encode::symbol_bits as b;
142+ use crate::mvstack::{
143+ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
144+ LAST3_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx, single_ref_p1_ctx,
145+ single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx,
146+ single_ref_p6_ctx, uni_comp_ref_p1_ctx,
147+ };
148+ // (pair, unidirectional?, the tree's symbols as (table, p index,
149+ // context selector, value)) -- transcribed from the writer.
150+ // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
151+ type Sym = (char, usize, usize, usize);
152+ let cases: [((i8, i8), bool, &[Sym]); 7] = [
153+ (
154+ (LAST_FRAME, LAST2_FRAME),
155+ true,
156+ &[('u', 0, 1, 0), ('u', 1, 7, 0)],
157+ ),
158+ (
159+ (LAST_FRAME, LAST3_FRAME),
160+ true,
161+ &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
162+ ),
163+ (
164+ (LAST_FRAME, GOLDEN_FRAME),
165+ true,
166+ &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
167+ ),
168+ ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
169+ (
170+ (LAST_FRAME, ALTREF_FRAME),
171+ false,
172+ &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
173+ ),
174+ (
175+ (LAST_FRAME, BWDREF_FRAME),
176+ false,
177+ &[
178+ ('c', 0, 3, 0),
179+ ('c', 1, 4, 0),
180+ ('b', 0, 2, 0),
181+ ('b', 1, 6, 0),
182+ ],
183+ ),
184+ (
185+ (LAST_FRAME, ALTREF2_FRAME),
186+ false,
187+ &[
188+ ('c', 0, 3, 0),
189+ ('c', 1, 4, 0),
190+ ('b', 0, 2, 0),
191+ ('b', 1, 6, 1),
192+ ],
193+ ),
194+ ];
195+ let nbr = |ref0, ref1: Option<i8>| {
196+ Some(NeighbourRef {
197+ is_inter: true,
198+ ref0,
199+ ref1,
200+ uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
201+ })
202+ };
203+ // No neighbours (every context zero), then a mixed pair that puts the
204+ // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
205+ for (above_nbr, left_nbr, above_refs, left_refs) in [
206+ (None, None, (None, None), (None, None)),
207+ (
208+ nbr(LAST_FRAME, None),
209+ nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
210+ (Some(LAST_FRAME), None),
211+ (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
212+ ),
213+ ] {
214+ let stack = crate::mvstack::MvStack {
215+ above_nbr,
216+ left_nbr,
217+ above_refs,
218+ left_refs,
219+ ..bare_stack()
147220 };
148- // (pair, unidirectional?, the tree's symbols as (table, p index,
149- // context selector, value)) -- transcribed from the writer.
150- // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
151- type Sym = (char, usize, usize, usize);
152- let cases: [((i8, i8), bool, &[Sym]); 7] = [
153- (
154- (LAST_FRAME, LAST2_FRAME),
155- true,
156- &[('u', 0, 1, 0), ('u', 1, 7, 0)],
157- ),
158- (
159- (LAST_FRAME, LAST3_FRAME),
160- true,
161- &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
162- ),
163- (
164- (LAST_FRAME, GOLDEN_FRAME),
165- true,
166- &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
167- ),
168- ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
169- (
170- (LAST_FRAME, ALTREF_FRAME),
171- false,
172- &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
173- ),
174- (
175- (LAST_FRAME, BWDREF_FRAME),
176- false,
177- &[
178- ('c', 0, 3, 0),
179- ('c', 1, 4, 0),
180- ('b', 0, 2, 0),
181- ('b', 1, 6, 0),
182- ],
183- ),
184- (
185- (LAST_FRAME, ALTREF2_FRAME),
186- false,
187- &[
188- ('c', 0, 3, 0),
189- ('c', 1, 4, 0),
190- ('b', 0, 2, 0),
191- ('b', 1, 6, 1),
192- ],
193- ),
194- ];
195- let nbr = |ref0, ref1: Option<i8>| {
196- Some(NeighbourRef {
197- is_inter: true,
198- ref0,
199- ref1,
200- uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
201- })
221+ let (a, a1) = above_refs;
222+ let (l, l1) = left_refs;
223+ let ctx_of = |sel: usize| match sel {
224+ 1 => single_ref_p1_ctx(a, a1, l, l1),
225+ 2 => single_ref_p2_ctx(a, a1, l, l1),
226+ 3 => single_ref_p3_ctx(a, a1, l, l1),
227+ 4 => single_ref_p4_ctx(a, a1, l, l1),
228+ 5 => single_ref_p5_ctx(a, a1, l, l1),
229+ 6 => single_ref_p6_ctx(a, a1, l, l1),
230+ _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
202231 };
203- // No neighbours (every context zero), then a mixed pair that puts the
204- // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
205- for (above_nbr, left_nbr, above_refs, left_refs) in [
206- (None, None, (None, None), (None, None)),
207- (
208- nbr(LAST_FRAME, None),
209- nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
210- (Some(LAST_FRAME), None),
211- (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
212- ),
213- ] {
214- let stack = crate::mvstack::MvStack {
215- above_nbr,
216- left_nbr,
217- above_refs,
218- left_refs,
219- ..bare_stack()
220- };
221- let (a, a1) = above_refs;
222- let (l, l1) = left_refs;
223- let ctx_of = |sel: usize| match sel {
224- 1 => single_ref_p1_ctx(a, a1, l, l1),
225- 2 => single_ref_p2_ctx(a, a1, l, l1),
226- 3 => single_ref_p3_ctx(a, a1, l, l1),
227- 4 => single_ref_p4_ctx(a, a1, l, l1),
228- 5 => single_ref_p5_ctx(a, a1, l, l1),
229- 6 => single_ref_p6_ctx(a, a1, l, l1),
230- _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
231- };
232- for (pair, unidir, symbols) in cases {
233- let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
234- + b(
235- &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
236- usize::from(!unidir),
237- );
238- for &(table, p, sel, v) in symbols {
239- let row = ctx_of(sel);
240- want += match table {
241- 'u' => b(&UNI_COMP_REF[row][p], v),
242- 'c' => b(&COMP_REF[row][p], v),
243- _ => b(&COMP_BWDREF[row][p], v),
244- };
245- }
246- let got = super::compound_ref_bits(pair, &stack);
247- assert!(
248- (got - want).abs() < 1e-9,
249- "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
250- priced {got} bits, writer codes {want}"
232+ for (pair, unidir, symbols) in cases {
233+ let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
234+ + b(
235+ &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
236+ usize::from(!unidir),
251237 );
238+ for &(table, p, sel, v) in symbols {
239+ let row = ctx_of(sel);
240+ want += match table {
241+ 'u' => b(&UNI_COMP_REF[row][p], v),
242+ 'c' => b(&COMP_REF[row][p], v),
243+ _ => b(&COMP_BWDREF[row][p], v),
244+ };
252245 }
246+ let got = super::compound_ref_bits(pair, &stack);
247+ assert!(
248+ (got - want).abs() < 1e-9,
249+ "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
250+ priced {got} bits, writer codes {want}"
251+ );
253252 }
254253 }
254+}
255255
256- /// The `skip` and `is_inter` symbols are priced at the SAME context
257- /// tile.rs codes them with -- `above_skip + left_skip` for the first and
258- /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
259- /// on every neighbour configuration whose context is not zero (class
260- /// pricer-context-zero).
261- #[test]
262- fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
263- use crate::cdf::{INTRA_INTER, SKIP};
264- use crate::encode::symbol_bits as b;
265- use crate::mvstack::NeighbourRef;
266- let nbr = |is_inter| NeighbourRef {
267- is_inter,
268- ref0: if is_inter {
269- crate::mvstack::LAST_FRAME
270- } else {
271- 0
272- },
273- ref1: None,
274- uni: false,
256+/// The `skip` and `is_inter` symbols are priced at the SAME context
257+/// tile.rs codes them with -- `above_skip + left_skip` for the first and
258+/// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
259+/// on every neighbour configuration whose context is not zero (class
260+/// pricer-context-zero).
261+#[test]
262+fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
263+ use crate::cdf::{INTRA_INTER, SKIP};
264+ use crate::encode::symbol_bits as b;
265+ use crate::mvstack::NeighbourRef;
266+ let nbr = |is_inter| NeighbourRef {
267+ is_inter,
268+ ref0: if is_inter {
269+ crate::mvstack::LAST_FRAME
270+ } else {
271+ 0
272+ },
273+ ref1: None,
274+ uni: false,
275+ };
276+ for (above, left, above_skip, left_skip) in [
277+ (None, None, false, false),
278+ (Some(nbr(true)), Some(nbr(true)), true, false),
279+ (Some(nbr(false)), Some(nbr(false)), true, true),
280+ (Some(nbr(false)), None, false, true),
281+ (None, Some(nbr(true)), true, true),
282+ ] {
283+ let stack = crate::mvstack::MvStack {
284+ above_nbr: above,
285+ left_nbr: left,
286+ above_skip,
287+ left_skip,
288+ ..bare_stack()
275289 };
276- for (above, left, above_skip, left_skip) in [
277- (None, None, false, false),
278- (Some(nbr(true)), Some(nbr(true)), true, false),
279- (Some(nbr(false)), Some(nbr(false)), true, true),
280- (Some(nbr(false)), None, false, true),
281- (None, Some(nbr(true)), true, true),
282- ] {
283- let stack = crate::mvstack::MvStack {
284- above_nbr: above,
285- left_nbr: left,
286- above_skip,
287- left_skip,
288- ..bare_stack()
289- };
290- let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
291- let ii_ctx = crate::tile::intra_inter_ctx(
292- above.is_some(),
293- left.is_some(),
294- above.is_some_and(|n| n.is_inter),
295- left.is_some_and(|n| n.is_inter),
290+ let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
291+ let ii_ctx = crate::tile::intra_inter_ctx(
292+ above.is_some(),
293+ left.is_some(),
294+ above.is_some_and(|n| n.is_inter),
295+ left.is_some_and(|n| n.is_inter),
296+ );
297+ for v in [false, true] {
298+ let (got, want) = (
299+ super::skip_bits_at(&stack, v),
300+ b(&SKIP[skip_ctx], usize::from(v)),
301+ );
302+ assert!(
303+ (got - want).abs() < 1e-9,
304+ "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
305+ );
306+ let (got, want) = (
307+ super::intra_inter_bits_at(&stack, v),
308+ b(&INTRA_INTER[ii_ctx], usize::from(v)),
309+ );
310+ assert!(
311+ (got - want).abs() < 1e-9,
312+ "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
296313 );
297- for v in [false, true] {
298- let (got, want) = (
299- super::skip_bits_at(&stack, v),
300- b(&SKIP[skip_ctx], usize::from(v)),
301- );
302- assert!(
303- (got - want).abs() < 1e-9,
304- "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
305- );
306- let (got, want) = (
307- super::intra_inter_bits_at(&stack, v),
308- b(&INTRA_INTER[ii_ctx], usize::from(v)),
309- );
310- assert!(
311- (got - want).abs() < 1e-9,
312- "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
313- );
314- }
315314 }
316315 }
316+}
317317
318- /// [`super::single_ref_bits`] pays exactly what tile.rs'
319- /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
320- /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
321- /// the context that symbol's own `single_ref_p*_ctx` derives from the
322- /// block's above/left neighbours. Red before lane-pricer, where every
323- /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
324- #[test]
325- fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
326- use crate::cdf::SINGLE_REF as SR;
327- use crate::encode::symbol_bits as b;
328- use crate::mvstack::{
329- ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
330- LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
331- single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
332- };
333- let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
334- above_refs,
335- left_refs,
336- above_nbr,
337- left_nbr,
338- ..bare_stack()
339- };
340- let nbr = |ref0, ref1| {
341- Some(crate::mvstack::NeighbourRef {
342- is_inter: true,
343- ref0,
344- ref1,
345- uni: false,
346- })
318+/// [`super::single_ref_bits`] pays exactly what tile.rs'
319+/// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
320+/// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
321+/// the context that symbol's own `single_ref_p*_ctx` derives from the
322+/// block's above/left neighbours. Red before lane-pricer, where every
323+/// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
324+#[test]
325+fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
326+ use crate::cdf::SINGLE_REF as SR;
327+ use crate::encode::symbol_bits as b;
328+ use crate::mvstack::{
329+ ALTREF_FRAME, ALTREF2_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST_FRAME, LAST2_FRAME,
330+ LAST3_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
331+ single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
332+ };
333+ let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
334+ above_refs,
335+ left_refs,
336+ above_nbr,
337+ left_nbr,
338+ ..bare_stack()
339+ };
340+ let nbr = |ref0, ref1| {
341+ Some(crate::mvstack::NeighbourRef {
342+ is_inter: true,
343+ ref0,
344+ ref1,
345+ uni: false,
346+ })
347+ };
348+ // (reference, the symbols `write_single_ref` emits as (p index, value))
349+ let cases: [(i8, &[(usize, usize)]); 7] = [
350+ (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
351+ (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
352+ (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
353+ (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
354+ (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
355+ (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
356+ (ALTREF_FRAME, &[(0, 1), (1, 1)]),
357+ ];
358+ // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
359+ // that puts every p* context on a different row -- the second with a
360+ // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
361+ // off row 0.
362+ for (above_refs, left_refs, above_nbr, left_nbr) in [
363+ ((None, None), (None, None), None, None),
364+ (
365+ (Some(LAST_FRAME), None),
366+ (Some(ALTREF_FRAME), Some(LAST_FRAME)),
367+ nbr(LAST_FRAME, None),
368+ nbr(ALTREF_FRAME, Some(LAST_FRAME)),
369+ ),
370+ ] {
371+ let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
372+ let (a, a1) = above_refs;
373+ let (l, l1) = left_refs;
374+ let ctx_of = |p: usize| match p {
375+ 0 => single_ref_p1_ctx(a, a1, l, l1),
376+ 1 => single_ref_p2_ctx(a, a1, l, l1),
377+ 2 => single_ref_p3_ctx(a, a1, l, l1),
378+ 3 => single_ref_p4_ctx(a, a1, l, l1),
379+ 4 => single_ref_p5_ctx(a, a1, l, l1),
380+ _ => single_ref_p6_ctx(a, a1, l, l1),
347381 };
348- // (reference, the symbols `write_single_ref` emits as (p index, value))
349- let cases: [(i8, &[(usize, usize)]); 7] = [
350- (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
351- (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
352- (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
353- (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
354- (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
355- (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
356- (ALTREF_FRAME, &[(0, 1), (1, 1)]),
357- ];
358- // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
359- // that puts every p* context on a different row -- the second with a
360- // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
361- // off row 0.
362- for (above_refs, left_refs, above_nbr, left_nbr) in [
363- ((None, None), (None, None), None, None),
364- (
365- (Some(LAST_FRAME), None),
366- (Some(ALTREF_FRAME), Some(LAST_FRAME)),
367- nbr(LAST_FRAME, None),
368- nbr(ALTREF_FRAME, Some(LAST_FRAME)),
369- ),
370- ] {
371- let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
372- let (a, a1) = above_refs;
373- let (l, l1) = left_refs;
374- let ctx_of = |p: usize| match p {
375- 0 => single_ref_p1_ctx(a, a1, l, l1),
376- 1 => single_ref_p2_ctx(a, a1, l, l1),
377- 2 => single_ref_p3_ctx(a, a1, l, l1),
378- 3 => single_ref_p4_ctx(a, a1, l, l1),
379- 4 => single_ref_p5_ctx(a, a1, l, l1),
380- _ => single_ref_p6_ctx(a, a1, l, l1),
381- };
382- for (ref_frame, symbols) in cases {
383- // Plus the `comp_mode = 0` symbol the writer codes ahead of
384- // the reference syntax on a `reference_select` frame.
385- let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
386- if super::reference_select() {
387- want += b(
388- &crate::cdf::COMP_MODE
389- [crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)],
390- 0,
391- );
392- }
393- let got = super::single_ref_bits(ref_frame, &stack);
394- assert!(
395- (got - want).abs() < 1e-9,
396- "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
397- priced {got} bits, writer codes {want}"
382+ for (ref_frame, symbols) in cases {
383+ // Plus the `comp_mode = 0` symbol the writer codes ahead of
384+ // the reference syntax on a `reference_select` frame.
385+ let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
386+ if super::reference_select() {
387+ want += b(
388+ &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(above_nbr, left_nbr)],
389+ 0,
398390 );
399391 }
392+ let got = super::single_ref_bits(ref_frame, &stack);
393+ assert!(
394+ (got - want).abs() < 1e-9,
395+ "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
396+ priced {got} bits, writer codes {want}"
397+ );
400398 }
401399 }
400+}
402401
403- /// lane-av1tpl2's propagated map, on the two properties every decision
404- /// under it rests on: a frame the whole lookahead window repeats exactly
405- /// (uniform texture) leans on every cell alike, so every factor is 1 and
406- /// the weighting is a no-op; and where the window really does save bits
407- /// by predicting -- the textured half of a frame whose other half is
408- /// flat -- the factor FALLS below 1, i.e. that half is coded more
409- /// distortion-averse than the half nothing gains from.
410- /// The distortion metric itself (lane-sse): a block the true frame edge
411- /// cuts through is scored over its INSIDE part only, so a difference that
412- /// lives entirely in the padding costs nothing and a block wholly past
413- /// the edge scores zero. Before this, the search ranked modes,
414- /// transforms and partition trees on samples the display crop throws
415- /// away -- which lane-b64b had fixed for the 64x64 root alone.
416- #[test]
417- fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
418- // A 40x40 true frame on a 64x64 padded coding surface.
419- let source = vec![10u8; 64 * 64];
420- let plane = fresh_plane(&source, 64, 64, 40, 40);
421- let mut reconstruction = vec![10u8; 64 * 64];
422- // Off by 190 at (50, 50) -- past the true edge in both axes.
423- reconstruction[50 * 64 + 50] = 200;
424- assert_eq!(
425- plane.block_sse(0, 0, 64, &reconstruction),
426- 0.0,
427- "padding was scored"
428- );
429- // Off by 10 at (39, 39) -- the last sample the decoder shows.
430- reconstruction[39 * 64 + 39] = 20;
431- assert_eq!(
432- plane.block_sse(0, 0, 64, &reconstruction),
433- 100.0,
434- "inside was not scored"
435- );
436- // A 16x16 block whose every sample is padding.
437- let block = vec![200u8; 16 * 16];
438- assert_eq!(
439- plane.block_sse(48, 0, 16, &block),
440- 0.0,
441- "a block past the edge scored"
442- );
443- // A 16x16 block the edge cuts: 8 of its columns are inside.
444- assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
445- }
402+/// lane-av1tpl2's propagated map, on the two properties every decision
403+/// under it rests on: a frame the whole lookahead window repeats exactly
404+/// (uniform texture) leans on every cell alike, so every factor is 1 and
405+/// the weighting is a no-op; and where the window really does save bits
406+/// by predicting -- the textured half of a frame whose other half is
407+/// flat -- the factor FALLS below 1, i.e. that half is coded more
408+/// distortion-averse than the half nothing gains from.
409+/// The distortion metric itself (lane-sse): a block the true frame edge
410+/// cuts through is scored over its INSIDE part only, so a difference that
411+/// lives entirely in the padding costs nothing and a block wholly past
412+/// the edge scores zero. Before this, the search ranked modes,
413+/// transforms and partition trees on samples the display crop throws
414+/// away -- which lane-b64b had fixed for the 64x64 root alone.
415+#[test]
416+fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
417+ // A 40x40 true frame on a 64x64 padded coding surface.
418+ let source = vec![10u8; 64 * 64];
419+ let plane = fresh_plane(&source, 64, 64, 40, 40);
420+ let mut reconstruction = vec![10u8; 64 * 64];
421+ // Off by 190 at (50, 50) -- past the true edge in both axes.
422+ reconstruction[50 * 64 + 50] = 200;
423+ assert_eq!(
424+ plane.block_sse(0, 0, 64, &reconstruction),
425+ 0.0,
426+ "padding was scored"
427+ );
428+ // Off by 10 at (39, 39) -- the last sample the decoder shows.
429+ reconstruction[39 * 64 + 39] = 20;
430+ assert_eq!(
431+ plane.block_sse(0, 0, 64, &reconstruction),
432+ 100.0,
433+ "inside was not scored"
434+ );
435+ // A 16x16 block whose every sample is padding.
436+ let block = vec![200u8; 16 * 16];
437+ assert_eq!(
438+ plane.block_sse(48, 0, 16, &block),
439+ 0.0,
440+ "a block past the edge scored"
441+ );
442+ // A 16x16 block the edge cuts: 8 of its columns are inside.
443+ assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
444+}
446445
447- /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
448- /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
449- /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
450- #[test]
451- fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
452- let (base, res) = (162u8, 4i32);
453- let rf = 2.0;
454- // A superblock the window leans on more than the frame average is
455- // coded FINER (lower qindex); a slack one coarser; the average one
456- // exactly at the base.
457- assert!(
458- super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,
459- "leaned-on SB must go finer"
460- );
461- assert!(
462- super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,
463- "idle SB must go coarser"
464- );
465- assert_eq!(
466- super::deltaq_libaom(base, rf, rf, 1.0, res),
467- base,
468- "the average SB moves 0"
469- );
470- // Every offset is a whole number of steps and inside +-(res * 9 - 1).
471- let max = ((res * 9 - 1) / res) * res;
472- for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
473- for k in [0.5f64, 1.0, 1.5] {
474- let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
475- let d = q - i32::from(base);
476- assert_eq!(
477- d % res,
478- 0,
479- "r={r} k={k}: offset {d} is not a whole {res}-step"
480- );
481- assert!(
482- d.abs() <= max,
483- "r={r} k={k}: offset {d} past libaom's +-{max}"
484- );
485- }
446+/// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
447+/// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
448+/// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
449+#[test]
450+fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
451+ let (base, res) = (162u8, 4i32);
452+ let rf = 2.0;
453+ // A superblock the window leans on more than the frame average is
454+ // coded FINER (lower qindex); a slack one coarser; the average one
455+ // exactly at the base.
456+ assert!(
457+ super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base,
458+ "leaned-on SB must go finer"
459+ );
460+ assert!(
461+ super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base,
462+ "idle SB must go coarser"
463+ );
464+ assert_eq!(
465+ super::deltaq_libaom(base, rf, rf, 1.0, res),
466+ base,
467+ "the average SB moves 0"
468+ );
469+ // Every offset is a whole number of steps and inside +-(res * 9 - 1).
470+ let max = ((res * 9 - 1) / res) * res;
471+ for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
472+ for k in [0.5f64, 1.0, 1.5] {
473+ let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
474+ let d = q - i32::from(base);
475+ assert_eq!(
476+ d % res,
477+ 0,
478+ "r={r} k={k}: offset {d} is not a whole {res}-step"
479+ );
480+ assert!(
481+ d.abs() <= max,
482+ "r={r} k={k}: offset {d} past libaom's +-{max}"
483+ );
486484 }
487- // The clamp is REACHED from both ends, so the bound is a real bound
488- // and not a formula that never gets there.
489- assert_eq!(
490- i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base),
491- -max
492- );
493- assert_eq!(
494- i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base),
495- max
496- );
497- // A stronger `k` never moves less than a weaker one.
498- let d = |k: f64| {
499- (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs()
500- };
501- assert!(
502- d(0.5) <= d(1.0) && d(1.0) <= d(1.5),
503- "strength must be monotone: {} {} {}",
504- d(0.5),
505- d(1.0),
506- d(1.5)
507- );
508- // The frame reference is libaom's log-mean: flat in, the same value out.
509- assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
510485 }
486+ // The clamp is REACHED from both ends, so the bound is a real bound
487+ // and not a formula that never gets there.
488+ assert_eq!(
489+ i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base),
490+ -max
491+ );
492+ assert_eq!(
493+ i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base),
494+ max
495+ );
496+ // A stronger `k` never moves less than a weaker one.
497+ let d =
498+ |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs();
499+ assert!(
500+ d(0.5) <= d(1.0) && d(1.0) <= d(1.5),
501+ "strength must be monotone: {} {} {}",
502+ d(0.5),
503+ d(1.0),
504+ d(1.5)
505+ );
506+ // The frame reference is libaom's log-mean: flat in, the same value out.
507+ assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
508+}
509+
510+/// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
511+/// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
512+/// shipped default, and the multiplier reaches the strength.
513+#[test]
514+fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
515+ let d = crate::speed::DQ_LEVEL_K;
516+ assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
517+ assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
518+ // Short and broken fields fall back per SLOT, not per spec.
519+ assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
520+ assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
521+ assert_eq!(super::DqLevel::TopArf as usize, 0);
522+ assert_eq!(super::DqLevel::MidArf as usize, 1);
523+ assert_eq!(super::DqLevel::Leaf as usize, 2);
524+}
511525
512- /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
513- /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
514- /// shipped default, and the multiplier reaches the strength.
515- #[test]
516- fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
517- let d = crate::speed::DQ_LEVEL_K;
518- assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
519- assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
520- // Short and broken fields fall back per SLOT, not per spec.
521- assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
522- assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
523- assert_eq!(super::DqLevel::TopArf as usize, 0);
524- assert_eq!(super::DqLevel::MidArf as usize, 1);
525- assert_eq!(super::DqLevel::Leaf as usize, 2);
526+#[test]
527+fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
528+ // Four 64x64 superblocks across: the shipped map forms its ratio per
529+ // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
530+ // only ever produce one ratio -- and one ratio, mean-normalised, is
531+ // the flat map, whatever the content underneath it.
532+ let (w, h) = (256usize, 64usize);
533+ let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
534+ let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
535+ let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
536+ assert_eq!(f.len(), 64, "16x4 cells of 16x16");
537+ for (i, &v) in f.iter().enumerate() {
538+ assert!(
539+ (v - 1.0).abs() < 1e-6,
540+ "cell {i} factor {v}, a flat map must move no lambda"
541+ );
526542 }
527543
528- #[test]
529- fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
530- // Four 64x64 superblocks across: the shipped map forms its ratio per
531- // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
532- // only ever produce one ratio -- and one ratio, mean-normalised, is
533- // the flat map, whatever the content underneath it.
534- let (w, h) = (256usize, 64usize);
535- let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
536- let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
537- let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
538- assert_eq!(f.len(), 64, "16x4 cells of 16x16");
539- for (i, &v) in f.iter().enumerate() {
544+ // Left half textured, right half constant: the window saves bits
545+ // predicting the left half and nothing at all on the right.
546+ let split: Vec<u8> = (0..w * h)
547+ .map(|i| {
548+ if i % w < w / 2 {
549+ ((i * 37) % 251) as u8
550+ } else {
551+ 128
552+ }
553+ })
554+ .collect();
555+ let frames: Vec<&[u8]> = vec![&split, &split, &split];
556+ let cells_x = w / 16;
557+ for k in [0.25f64, 0.5, 1.0, 2.0] {
558+ let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
559+ for r in 0..h / 16 {
560+ let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
540561 assert!(
541- (v - 1.0).abs() < 1e-6,
542- "cell {i} factor {v}, a flat map must move no lambda"
562+ lean < 1.0,
563+ "k={k} row {r}: leaned-on cell factor {lean} must be < 1"
564+ );
565+ assert!(
566+ idle > 1.0,
567+ "k={k} row {r}: idle cell factor {idle} must be > 1"
543568 );
544- }
545-
546- // Left half textured, right half constant: the window saves bits
547- // predicting the left half and nothing at all on the right.
548- let split: Vec<u8> = (0..w * h)
549- .map(|i| {
550- if i % w < w / 2 {
551- ((i * 37) % 251) as u8
552- } else {
553- 128
554- }
555- })
556- .collect();
557- let frames: Vec<&[u8]> = vec![&split, &split, &split];
558- let cells_x = w / 16;
559- for k in [0.25f64, 0.5, 1.0, 2.0] {
560- let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
561- for r in 0..h / 16 {
562- let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
563- assert!(
564- lean < 1.0,
565- "k={k} row {r}: leaned-on cell factor {lean} must be < 1"
566- );
567- assert!(
568- idle > 1.0,
569- "k={k} row {r}: idle cell factor {idle} must be > 1"
570- );
571- }
572569 }
573570 }
571+}
574572
575- /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
576- /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
577- /// row holds `32 >> bw_in_mi_log2` bits and the table holds
578- /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
579- /// superblock must therefore hit every bit of the table EXACTLY ONCE.
580- /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
581- /// only a quarter of the 16x8 table and read the wrong byte for every
582- /// block row but the first (silently wrong above-right/below-left
583- /// availability -- wrong pixels, no error).
584- #[test]
585- fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
586- for (bw, bh) in [
587- (16usize, 8usize),
588- (8, 16),
589- (32, 16),
590- (16, 32),
591- (64, 32),
592- (32, 64),
573+/// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
574+/// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
575+/// row holds `32 >> bw_in_mi_log2` bits and the table holds
576+/// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
577+/// superblock must therefore hit every bit of the table EXACTLY ONCE.
578+/// r4's `4 - bw_log2` index halved the row stride: the walk then covered
579+/// only a quarter of the 16x8 table and read the wrong byte for every
580+/// block row but the first (silently wrong above-right/below-left
581+/// availability -- wrong pixels, no error).
582+#[test]
583+fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
584+ for (bw, bh) in [
585+ (16usize, 8usize),
586+ (8, 16),
587+ (32, 16),
588+ (16, 32),
589+ (64, 32),
590+ (32, 64),
591+ ] {
592+ let (bw_log2, bh_log2) = (
593+ (bw / 4).trailing_zeros() as usize,
594+ (bh / 4).trailing_zeros() as usize,
595+ );
596+ let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
597+ for (name, table) in [
598+ ("has_tr", rect_reach_tables(bw, bh).0),
599+ ("has_bl", rect_reach_tables(bw, bh).1),
593600 ] {
594- let (bw_log2, bh_log2) = (
595- (bw / 4).trailing_zeros() as usize,
596- (bh / 4).trailing_zeros() as usize,
601+ assert_eq!(
602+ table.len() * 8,
603+ rows * cols,
604+ "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
597605 );
598- let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
599- for (name, table) in [
600- ("has_tr", rect_reach_tables(bw, bh).0),
601- ("has_bl", rect_reach_tables(bw, bh).1),
602- ] {
603- assert_eq!(
604- table.len() * 8,
605- rows * cols,
606- "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
607- );
608- let mut seen = vec![0u32; table.len() * 8];
609- for blk_row in 0..rows {
610- for blk_col in 0..cols {
611- let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
612- assert!(
613- idx < seen.len(),
614- "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
615- );
616- seen[idx] += 1;
617- }
606+ let mut seen = vec![0u32; table.len() * 8];
607+ for blk_row in 0..rows {
608+ for blk_col in 0..cols {
609+ let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
610+ assert!(
611+ idx < seen.len(),
612+ "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
613+ );
614+ seen[idx] += 1;
618615 }
619- assert!(
620- seen.iter().all(|&n| n == 1),
621- "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
622- (row stride is not {cols})"
623- );
624616 }
617+ assert!(
618+ seen.iter().all(|&n| n == 1),
619+ "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
620+ (row stride is not {cols})"
621+ );
625622 }
626623 }
627- use super::*;
628- use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
629- use crate::probe::run_with_stdin;
630-
631- /// Every rectangular shape this decoder codes, at every position a block
632- /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
633- /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
634- /// (`reconintra.c`) answer, whose bodies are ported below.
635- ///
636- /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
637- /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
638- /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
639- /// and 7 (below-left) of the 21 reachable positions with no gate seeing
640- /// it. The per-shape `(len, byte sum)` fingerprints below come from the
641- /// oracle's own arrays, so a re-routed or truncated table fails here even
642- /// where the two rows happen to agree.
643- ///
644- /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
645- /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
646- /// callers handle by predicting each transform unit as its own block.
647- /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
648- /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
649- /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
650- /// (the horizontal shapes, which those partitions never produce).
651- #[test]
652- fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
653- // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
654- // it pins the 64 reach explicitly instead of following the process's
655- // own superblock knob (`for_encoder`), which made it red under
656- // `EC_AV1_SB128=1` for no defect of the code under test.
657- let fctx = &crate::decode::FrameCtx::new();
658- // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
659- const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
660- (4, 8, 64, 9280, 64, 550),
661- (8, 4, 64, 3712, 64, 9630),
662- (8, 16, 16, 2352, 16, 134),
663- (16, 8, 16, 960, 16, 2400),
664- (16, 32, 4, 620, 4, 32),
665- (32, 16, 4, 32, 4, 184),
666- (32, 64, 1, 127, 1, 0),
667- (64, 32, 1, 19, 1, 34),
668- (4, 16, 32, 5472, 32, 14),
669- (16, 4, 32, 960, 32, 6464),
670- (8, 32, 8, 1400, 8, 2),
671- (32, 8, 8, 32, 8, 1136),
672- (16, 64, 2, 382, 2, 0),
673- (64, 16, 2, 4, 2, 84),
674- ];
675- /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
676- /// a block whose transform covers it whole (`row_off == col_off == 0`,
677- /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
678- /// superblock (`sb_mi_size == 16`).
679- fn libaom_reach(
680- bw: usize,
681- bh: usize,
682- x: usize,
683- y: usize,
684- width: usize,
685- height: usize,
686- _fctx: &crate::decode::FrameCtx,
687- ) -> (bool, bool) {
688- let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
689- let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
690- let sb_mi_size = 16usize;
691- let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
692- let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
693- let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
694- let (tr_table, bl_table) = rect_reach_tables(bw, bh);
695- let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
696- // has_top_right: top_available && right_available, then row_off == 0.
697- let top_right = if y == 0 || x + bw >= width {
698- false
699- } else if blk_row_in_sb == 0 {
700- // (`col_off + tx_wide_unit < plane_bw_unit` above this is
701- // `bw_unit < bw_unit`, false for a whole-block transform.)
702- true
703- } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
704- false
705- } else {
706- bit(tr_table)
707- };
708- // has_bottom_left: bottom_available && left_available, col_off == 0.
709- let bottom_left = if x == 0 || y + bh >= height {
710- false
711- } else if blk_col_in_sb == 0 {
712- // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
713- (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
714- } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
715- false
716- } else {
717- bit(bl_table)
718- };
719- (top_right, bottom_left)
720- }
721- for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
722- let (tr, bl) = rect_reach_tables(bw, bh);
723- let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
724- assert_eq!(
725- (tr.len(), sum(tr), bl.len(), sum(bl)),
726- (tr_len, tr_sum, bl_len, bl_sum),
727- "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
728- );
729- // Two superblocks across and down, so the superblock-relative
730- // position (and not the frame position) is what decides.
731- for sb_y in [0usize, 64] {
732- for sb_x in [0usize, 64] {
733- for y in (sb_y..sb_y + 64).step_by(bh) {
734- for x in (sb_x..sb_x + 64).step_by(bw) {
735- let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
736- let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
737- assert_eq!(
738- (got.above_right, got.below_left),
739- want,
740- "{bw}x{bh} at ({x}, {y})"
741- );
742- }
624+}
625+use super::*;
626+use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
627+use crate::probe::run_with_stdin;
628+
629+/// Every rectangular shape this decoder codes, at every position a block
630+/// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
631+/// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
632+/// (`reconintra.c`) answer, whose bodies are ported below.
633+///
634+/// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
635+/// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
636+/// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
637+/// and 7 (below-left) of the 21 reachable positions with no gate seeing
638+/// it. The per-shape `(len, byte sum)` fingerprints below come from the
639+/// oracle's own arrays, so a re-routed or truncated table fails here even
640+/// where the two rows happen to agree.
641+///
642+/// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
643+/// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
644+/// callers handle by predicting each transform unit as its own block.
645+/// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
646+/// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
647+/// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
648+/// (the horizontal shapes, which those partitions never produce).
649+#[test]
650+fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
651+ // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
652+ // it pins the 64 reach explicitly instead of following the process's
653+ // own superblock knob (`for_encoder`), which made it red under
654+ // `EC_AV1_SB128=1` for no defect of the code under test.
655+ let fctx = &crate::decode::FrameCtx::new();
656+ // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
657+ const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
658+ (4, 8, 64, 9280, 64, 550),
659+ (8, 4, 64, 3712, 64, 9630),
660+ (8, 16, 16, 2352, 16, 134),
661+ (16, 8, 16, 960, 16, 2400),
662+ (16, 32, 4, 620, 4, 32),
663+ (32, 16, 4, 32, 4, 184),
664+ (32, 64, 1, 127, 1, 0),
665+ (64, 32, 1, 19, 1, 34),
666+ (4, 16, 32, 5472, 32, 14),
667+ (16, 4, 32, 960, 32, 6464),
668+ (8, 32, 8, 1400, 8, 2),
669+ (32, 8, 8, 32, 8, 1136),
670+ (16, 64, 2, 382, 2, 0),
671+ (64, 16, 2, 4, 2, 84),
672+ ];
673+ /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
674+ /// a block whose transform covers it whole (`row_off == col_off == 0`,
675+ /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
676+ /// superblock (`sb_mi_size == 16`).
677+ fn libaom_reach(
678+ bw: usize,
679+ bh: usize,
680+ x: usize,
681+ y: usize,
682+ width: usize,
683+ height: usize,
684+ _fctx: &crate::decode::FrameCtx,
685+ ) -> (bool, bool) {
686+ let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
687+ let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
688+ let sb_mi_size = 16usize;
689+ let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
690+ let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
691+ let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
692+ let (tr_table, bl_table) = rect_reach_tables(bw, bh);
693+ let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
694+ // has_top_right: top_available && right_available, then row_off == 0.
695+ let top_right = if y == 0 || x + bw >= width {
696+ false
697+ } else if blk_row_in_sb == 0 {
698+ // (`col_off + tx_wide_unit < plane_bw_unit` above this is
699+ // `bw_unit < bw_unit`, false for a whole-block transform.)
700+ true
701+ } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
702+ false
703+ } else {
704+ bit(tr_table)
705+ };
706+ // has_bottom_left: bottom_available && left_available, col_off == 0.
707+ let bottom_left = if x == 0 || y + bh >= height {
708+ false
709+ } else if blk_col_in_sb == 0 {
710+ // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
711+ (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
712+ } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
713+ false
714+ } else {
715+ bit(bl_table)
716+ };
717+ (top_right, bottom_left)
718+ }
719+ for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
720+ let (tr, bl) = rect_reach_tables(bw, bh);
721+ let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
722+ assert_eq!(
723+ (tr.len(), sum(tr), bl.len(), sum(bl)),
724+ (tr_len, tr_sum, bl_len, bl_sum),
725+ "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
726+ );
727+ // Two superblocks across and down, so the superblock-relative
728+ // position (and not the frame position) is what decides.
729+ for sb_y in [0usize, 64] {
730+ for sb_x in [0usize, 64] {
731+ for y in (sb_y..sb_y + 64).step_by(bh) {
732+ for x in (sb_x..sb_x + 64).step_by(bw) {
733+ let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
734+ let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
735+ assert_eq!(
736+ (got.above_right, got.below_left),
737+ want,
738+ "{bw}x{bh} at ({x}, {y})"
739+ );
743740 }
744741 }
745742 }
746743 }
747744 }
745+}
748746
749- /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
750- pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
751- let out = run_with_stdin(
752- ec_testkit::ffmpeg().args([
753- "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
754- ]),
755- stream,
756- );
757- assert!(
758- out.status.success(),
759- "ffmpeg refused the stream: {}",
760- String::from_utf8_lossy(&out.stderr)
761- );
762- let (luma, chroma) = (width * height, width * height / 4);
763- assert_eq!(
764- out.stdout.len(),
765- luma + 2 * chroma,
766- "expected one 4:2:0 frame"
767- );
768- Picture {
769- width,
770- height,
771- y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
772- u: out.stdout[luma..luma + chroma]
773- .iter()
774- .map(|&v| u16::from(v))
775- .collect(),
776- v: out.stdout[luma + chroma..]
777- .iter()
778- .map(|&v| u16::from(v))
779- .collect(),
780- }
747+/// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
748+pub(super) fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
749+ let out = run_with_stdin(
750+ ec_testkit::ffmpeg().args([
751+ "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
752+ ]),
753+ stream,
754+ );
755+ assert!(
756+ out.status.success(),
757+ "ffmpeg refused the stream: {}",
758+ String::from_utf8_lossy(&out.stderr)
759+ );
760+ let (luma, chroma) = (width * height, width * height / 4);
761+ assert_eq!(
762+ out.stdout.len(),
763+ luma + 2 * chroma,
764+ "expected one 4:2:0 frame"
765+ );
766+ Picture {
767+ width,
768+ height,
769+ y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
770+ u: out.stdout[luma..luma + chroma]
771+ .iter()
772+ .map(|&v| u16::from(v))
773+ .collect(),
774+ v: out.stdout[luma + chroma..]
775+ .iter()
776+ .map(|&v| u16::from(v))
777+ .collect(),
781778 }
779+}
782780
783- /// A picture with something of everything in it: a gradient, an edge, a
784- /// ripple and a block of flat colour, none of them aligned to the block
785- /// grid.
786- /// The in-loop filters actually FIRE and the stream still decodes to
787- /// exactly what the encoder kept as its reconstruction
788- /// (gate-blind-to-feature: a filter search that always answered "off"
789- /// would leave every other test just as green, and the BD gate that
790- /// would notice is `#[ignore]`d).
791- ///
792- /// Run:
793- /// cargo test -p ec-av1 --release --lib -- \
794- /// encode::tests::the_filter_search_picks_real_filters
795- #[test]
796- fn the_filter_search_picks_real_filters() {
797- let _knobs = crate::speed::knob_read();
798- let fctx = &crate::decode::FrameCtx::for_encoder();
799- let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
800- let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
801- let fired = encoded
781+/// A picture with something of everything in it: a gradient, an edge, a
782+/// ripple and a block of flat colour, none of them aligned to the block
783+/// grid.
784+/// The in-loop filters actually FIRE and the stream still decodes to
785+/// exactly what the encoder kept as its reconstruction
786+/// (gate-blind-to-feature: a filter search that always answered "off"
787+/// would leave every other test just as green, and the BD gate that
788+/// would notice is `#[ignore]`d).
789+///
790+/// Run:
791+/// cargo test -p ec-av1 --release --lib -- \
792+/// encode::tests::the_filter_search_picks_real_filters
793+#[test]
794+fn the_filter_search_picks_real_filters() {
795+ let _knobs = crate::speed::knob_read();
796+ let fctx = &crate::decode::FrameCtx::for_encoder();
797+ let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
798+ let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
799+ let fired = encoded
800+ .frames
801+ .iter()
802+ .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
803+ .count();
804+ assert!(
805+ fired > 0,
806+ "no frame of this sequence chose any in-loop filtering: {:?}",
807+ encoded
802808 .frames
803809 .iter()
804- .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
805- .count();
806- assert!(
807- fired > 0,
808- "no frame of this sequence chose any in-loop filtering: {:?}",
809- encoded
810- .frames
811- .iter()
812- .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
813- .collect::<Vec<_>>()
814- );
815- // The reconstruction the encoder predicts from is the FILTERED one,
816- // and it is what a decoder of the stream produces -- byte for byte,
817- // frame for frame.
818- let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
819- assert_eq!(decoded.len(), encoded.frames.len());
820- for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
821- assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
822- assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
823- assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
824- }
810+ .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
811+ .collect::<Vec<_>>()
812+ );
813+ // The reconstruction the encoder predicts from is the FILTERED one,
814+ // and it is what a decoder of the stream produces -- byte for byte,
815+ // frame for frame.
816+ let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
817+ assert_eq!(decoded.len(), encoded.frames.len());
818+ for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
819+ assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
820+ assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
821+ assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
825822 }
823+}
826824
827- pub(super) fn test_card(width: usize, height: usize) -> Picture {
828- let mut picture = Picture::grey(width, height);
829- for y in 0..height {
830- for x in 0..width {
831- let gradient = x as f64 * 200.0 / width as f64;
832- let ripple = 30.0
833- * (x as f64 * std::f64::consts::PI / 23.0).sin()
834- * (y as f64 * std::f64::consts::PI / 37.0).cos();
835- let edge = if x > width * 3 / 7 && y > height / 3 {
836- 40.0
837- } else {
838- 0.0
839- };
840- picture.y[y * width + x] =
841- (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
842- }
843- }
844- for y in 0..height / 2 {
845- for x in 0..width / 2 {
846- let i = y * width / 2 + x;
847- picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
848- picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
849- }
825+pub(super) fn test_card(width: usize, height: usize) -> Picture {
826+ let mut picture = Picture::grey(width, height);
827+ for y in 0..height {
828+ for x in 0..width {
829+ let gradient = x as f64 * 200.0 / width as f64;
830+ let ripple = 30.0
831+ * (x as f64 * std::f64::consts::PI / 23.0).sin()
832+ * (y as f64 * std::f64::consts::PI / 37.0).cos();
833+ let edge = if x > width * 3 / 7 && y > height / 3 {
834+ 40.0
835+ } else {
836+ 0.0
837+ };
838+ picture.y[y * width + x] = (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
850839 }
851- picture
852840 }
853-
854- pub(super) fn psnr(a: &[u16], b: &[u16]) -> f64 {
855- let squared: f64 = a
856- .iter()
857- .zip(b)
858- .map(|(&x, &y)| {
859- let d = f64::from(x) - f64::from(y);
860- d * d
861- })
862- .sum();
863- if squared == 0.0 {
864- return f64::INFINITY;
841+ for y in 0..height / 2 {
842+ for x in 0..width / 2 {
843+ let i = y * width / 2 + x;
844+ picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
845+ picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
865846 }
866- 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
867847 }
848+ picture
849+}
850+
851+pub(super) fn psnr(a: &[u16], b: &[u16]) -> f64 {
852+ let squared: f64 = a
853+ .iter()
854+ .zip(b)
855+ .map(|(&x, &y)| {
856+ let d = f64::from(x) - f64::from(y);
857+ d * d
858+ })
859+ .sum();
860+ if squared == 0.0 {
861+ return f64::INFINITY;
862+ }
863+ 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
864+}
865+
866+/// lane-i64's witness: a smooth gradient is exactly the picture a whole
867+/// 64x64 intra block predicts as well as four 32x32 ones, so the key
868+/// frame's new root fires on most superblocks -- and what BOTH decoders
869+/// produce is the encoder's own reconstruction, sample for sample.
870+///
871+/// The fire count is the `gate-blind-to-feature` guard: without it every
872+/// assert below passes on a stream that codes no whole superblock at all.
873+#[test]
874+fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
875+ let _knobs = crate::speed::knob_read();
876+ let fctx = &crate::decode::FrameCtx::for_encoder();
877+ // 4 x 3 superblocks, all of them wholly inside the frame.
878+ let (width, height) = (256usize, 192usize);
879+ let mut picture = Picture::grey(width, height);
880+ for y in 0..height {
881+ for x in 0..width {
882+ picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
883+ }
884+ }
885+ for y in 0..height / 2 {
886+ for x in 0..width / 2 {
887+ picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
888+ picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
889+ }
890+ }
891+ let _ = take_i64_root_hits();
892+ let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
893+ let [roots, _offered, _edge] = take_i64_root_hits();
894+ // The counters are process-global, so another test encoding in
895+ // parallel can only ADD to them -- the per-FRAME fact is the mode
896+ // list, which carries one entry per coded block and so exactly 12
897+ // when every superblock was coded as one 64x64 intra block.
898+ assert_eq!(
899+ encoded.modes.len(),
900+ 12,
901+ "not every superblock was coded as one 64x64 intra block"
902+ );
903+ assert!(
904+ roots >= 8,
905+ "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
906+ );
907+ eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
908+
909+ let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
910+ assert_eq!(ours.len(), 1, "our decoder's frames");
911+ assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
912+ assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
913+ assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
914+
915+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
916+ assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
917+ assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
918+ assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
919+}
920+
921+/// The claim the whole encoder rests on: what a decoder produces is what
922+/// the encoder said it would, sample for sample, on every plane.
923+///
924+/// Prediction reads the reconstruction, so a single sample of drift
925+/// anywhere would spread into every block below and to the right of it —
926+/// which is why this is an equality and not a tolerance.
927+#[test]
928+fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
929+ let _knobs = crate::speed::knob_read();
930+ let fctx = &crate::decode::FrameCtx::for_encoder();
931+ for &(width, height) in &[
932+ (64usize, 64usize),
933+ (96, 64),
934+ (160, 96),
935+ (32, 48),
936+ (248, 152),
937+ ] {
938+ let picture = test_card(width, height);
939+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
940+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
941+ assert_eq!(
942+ decoded.y, encoded.reconstruction.y,
943+ "{width}x{height}: luma"
944+ );
945+ assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
946+ assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
947+ }
948+ // One q index from each of the four coefficient-CDF contexts
949+ // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
950+ let (width, height) = (64usize, 64usize);
951+ let picture = test_card(width, height);
952+ let _ = take_tx_depth_hits();
953+ for &q in &[15u8, 45, 100, 200] {
954+ let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
955+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
956+ assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
957+ assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
958+ assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
959+ }
960+ // lane-av1tx: the exactness above is only a claim about SPLIT
961+ // transforms if some block actually split one (`gate-blind-to-feature`
962+ // -- with `tx_depth` stuck at 0 every assert here passes on the
963+ // pre-lane stream). The test card's edges split at these four
964+ // quantizers; the counter is per-process (another test encoding in
965+ // parallel can only ADD to it, so this can be masked, never falsely
966+ // failed), so it is read once for the whole q ladder.
967+ let depths = take_tx_depth_hits();
968+ assert!(
969+ depths[1] + depths[2] > 0,
970+ "no block split its transform: depths {depths:?}"
971+ );
972+}
973+
974+/// A synthetic screen-content picture -- a few flat colours in a grid of
975+/// boxes with hard edges and text-like bars, the shape a desktop capture
976+/// has -- so the palette path is exercised on content it is for.
977+#[cfg(test)]
978+pub(super) fn screen_card(width: usize, height: usize) -> Picture {
979+ const INK: [u16; 4] = [16, 90, 180, 235];
980+ let mut picture = Picture::grey(width, height);
981+ for y in 0..height {
982+ for x in 0..width {
983+ let cell = (x / 24 + y / 24) % 2;
984+ let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
985+ picture.y[y * width + x] = INK[cell * 2 + bar];
986+ }
987+ }
988+ // Four chroma colours, not two: a two-colour chroma block only ever
989+ // codes a `PaletteSizeUV` of 2, which leaves
990+ // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
991+ // deltas and the neighbour cache flags, exercised only when
992+ // neighbouring blocks share colours) unproven by the ffmpeg oracle.
993+ const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
994+ const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
995+ for y in 0..height / 2 {
996+ for x in 0..width / 2 {
997+ let cell = (x / 12 + 2 * (y / 12)) % 4;
998+ picture.u[y * (width / 2) + x] = CHROMA_U[cell];
999+ picture.v[y * (width / 2) + x] = CHROMA_V[cell];
1000+ }
1001+ }
1002+ picture
1003+}
8681004
869- /// lane-i64's witness: a smooth gradient is exactly the picture a whole
870- /// 64x64 intra block predicts as well as four 32x32 ones, so the key
871- /// frame's new root fires on most superblocks -- and what BOTH decoders
872- /// produce is the encoder's own reconstruction, sample for sample.
873- ///
874- /// The fire count is the `gate-blind-to-feature` guard: without it every
875- /// assert below passes on a stream that codes no whole superblock at all.
876- #[test]
877- fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
878- let _knobs = crate::speed::knob_read();
879- let fctx = &crate::decode::FrameCtx::for_encoder();
880- // 4 x 3 superblocks, all of them wholly inside the frame.
881- let (width, height) = (256usize, 192usize);
882- let mut picture = Picture::grey(width, height);
883- for y in 0..height {
884- for x in 0..width {
885- picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
1005+/// The lane's own end-to-end check: on screen content the detector fires,
1006+/// blocks really take a palette (fire count, class
1007+/// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
1008+/// symbol this lane writes -- reconstructs exactly what the encoder did.
1009+/// The film-shaped `test_card` must NOT trip the detector, which is what
1010+/// keeps every non-screen stream byte-identical.
1011+#[test]
1012+fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
1013+ let _knobs = crate::speed::knob_read();
1014+ let fctx = &crate::decode::FrameCtx::for_encoder();
1015+ let (width, height) = (192usize, 96usize);
1016+ let _ = crate::tile::take_palette_hits();
1017+ let picture = screen_card(width, height);
1018+ let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
1019+ assert!(
1020+ encoded.screen,
1021+ "the detector did not fire on screen content -- no palette syntax was coded at all"
1022+ );
1023+ let hits = crate::tile::take_palette_hits();
1024+ assert!(hits[0] > 0, "no block took a palette: {hits:?}");
1025+ eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
1026+ // The chroma half is a claim about the plane-1 syntax only if some
1027+ // block really took a chroma palette (`gate-blind-to-feature`): every
1028+ // exactness assert below passes on a stream that codes
1029+ // `palette_uv_mode == 0` everywhere.
1030+ let uv_hits = crate::tile::take_palette_uv_hits();
1031+ assert!(
1032+ uv_hits[0] > 0,
1033+ "no block took a chroma palette: {uv_hits:?}"
1034+ );
1035+ let uv_cached = crate::tile::take_palette_uv_cache_hits();
1036+ eprintln!(
1037+ "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
1038+ uv_hits[0],
1039+ &uv_hits[2..]
1040+ );
1041+ assert!(
1042+ uv_cached > 0,
1043+ "no chroma base colour came out of the neighbour cache -- \
1044+ `write_palette_colors_uv`'s cache half is unproven by the oracle below"
1045+ );
1046+ let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
1047+ assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
1048+ assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
1049+ assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
1050+ let decoded = ffmpeg_decode(&encoded.stream, width, height);
1051+ assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
1052+ assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
1053+ assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
1054+ // A whole GOP: the inter frames' own intra blocks carry the palette
1055+ // syntax too (the three intra arms of the inter writers), which only
1056+ // ffmpeg reading the frames back can prove.
1057+ let moved: Vec<Picture> = (0..4)
1058+ .map(|f| {
1059+ let base = screen_card(width, height);
1060+ let mut out = Picture::grey(width, height);
1061+ for y in 0..height {
1062+ for x in 0..width {
1063+ let sx = (x + f * 7) % width;
1064+ out.y[y * width + x] = base.y[y * width + sx];
1065+ }
8861066 }
887- }
888- for y in 0..height / 2 {
889- for x in 0..width / 2 {
890- picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
891- picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
1067+ for y in 0..height / 2 {
1068+ for x in 0..width / 2 {
1069+ let sx = (x + f * 3) % (width / 2);
1070+ out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
1071+ out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
1072+ }
8921073 }
893- }
894- let _ = take_i64_root_hits();
895- let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
896- let [roots, _offered, _edge] = take_i64_root_hits();
897- // The counters are process-global, so another test encoding in
898- // parallel can only ADD to them -- the per-FRAME fact is the mode
899- // list, which carries one entry per coded block and so exactly 12
900- // when every superblock was coded as one 64x64 intra block.
1074+ out
1075+ })
1076+ .collect();
1077+ let _ = crate::tile::take_palette_hits();
1078+ let _ = crate::tile::take_palette_uv_hits();
1079+ let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
1080+ let gop_hits = crate::tile::take_palette_hits();
1081+ let gop_uv_hits = crate::tile::take_palette_uv_hits();
1082+ let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
1083+ eprintln!(
1084+ "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
1085+ {} chroma palette blocks",
1086+ inter_screen, gop_hits[0], gop_uv_hits[0]
1087+ );
1088+ assert!(
1089+ gop_uv_hits[0] > 0,
1090+ "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
1091+ );
1092+ assert!(
1093+ inter_screen > 0,
1094+ "no inter frame set allow_screen_content_tools"
1095+ );
1096+ let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
1097+ assert_eq!(
1098+ gop_decoded.len(),
1099+ gop.frames.len(),
1100+ "our decoder: GOP frame count"
1101+ );
1102+ for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
9011103 assert_eq!(
902- encoded.modes.len(),
903- 12,
904- "not every superblock was coded as one 64x64 intra block"
905- );
906- assert!(
907- roots >= 8,
908- "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
1104+ ours.y, frame.reconstruction.y,
1105+ "our decoder: GOP frame {i} luma"
9091106 );
910- eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
911-
912- let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
913- assert_eq!(ours.len(), 1, "our decoder's frames");
914- assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
915- assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
916- assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
917-
918- let decoded = ffmpeg_decode(&encoded.stream, width, height);
919- assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
920- assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
921- assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
9221107 }
923-
924- /// The claim the whole encoder rests on: what a decoder produces is what
925- /// the encoder said it would, sample for sample, on every plane.
926- ///
927- /// Prediction reads the reconstruction, so a single sample of drift
928- /// anywhere would spread into every block below and to the right of it —
929- /// which is why this is an equality and not a tolerance.
930- #[test]
931- fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
932- let _knobs = crate::speed::knob_read();
933- let fctx = &crate::decode::FrameCtx::for_encoder();
934- for &(width, height) in &[
935- (64usize, 64usize),
936- (96, 64),
937- (160, 96),
938- (32, 48),
939- (248, 152),
940- ] {
941- let picture = test_card(width, height);
942- let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
943- let decoded = ffmpeg_decode(&encoded.stream, width, height);
1108+ {
1109+ let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
1110+ assert_eq!(ff.len(), gop.frames.len(), "ffmpeg: GOP frame count");
1111+ for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
9441112 assert_eq!(
945- decoded.y, encoded.reconstruction.y,
946- "{width}x{height}: luma"
1113+ theirs.y, frame.reconstruction.y,
1114+ "ffmpeg: GOP frame {i} luma"
9471115 );
948- assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
949- assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
950- }
951- // One q index from each of the four coefficient-CDF contexts
952- // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
953- let (width, height) = (64usize, 64usize);
954- let picture = test_card(width, height);
955- let _ = take_tx_depth_hits();
956- for &q in &[15u8, 45, 100, 200] {
957- let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
958- let decoded = ffmpeg_decode(&encoded.stream, width, height);
crates/ec-av1/src/encoder/tests.rsmodified+2881 -3398

Diff too large; view file

@@ -1,1437 +1,2379 @@
1- use super::*;
21
3- fn test_card(width: usize, height: usize, shift: usize) -> Picture {
4- let mut picture = Picture::grey(width, height);
5- for y in 0..height {
6- for x in 0..width {
7- let sx = (x + shift) % width;
8- picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
9- }
10- }
11- for y in 0..height / 2 {
12- for x in 0..width / 2 {
13- let i = y * (width / 2) + x;
14- picture.u[i] = ((100 + shift * 4) % 256) as u16;
15- picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
16- }
17- }
18- picture
19- }
2+use super::*;
203
21- /// Drives a whole stream through the facade the way a caller must since
22- /// it holds one picture of lookahead: every picture through
23- /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].
24- fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {
25- let mut packets = Vec::with_capacity(pictures.len());
26- for (i, picture) in pictures.iter().enumerate() {
27- packets.extend(
28- enc.encode_frames(picture)
29- .unwrap_or_else(|e| panic!("picture {i}: {e}")),
30- );
4+fn test_card(width: usize, height: usize, shift: usize) -> Picture {
5+ let mut picture = Picture::grey(width, height);
6+ for y in 0..height {
7+ for x in 0..width {
8+ let sx = (x + shift) % width;
9+ picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
3110 }
32- packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));
33- packets
34- }
35-
36- /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden
37- /// counts and leaf count match the packets a real run emits, at three
38- /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends
39- /// the run's budget exactly (`gop` frame targets, no more and no less).
40- ///
41- /// Both halves matter: a shape that misses a level (the old model priced
42- /// ONE hidden frame per group when the mid level had made it two) splits
43- /// the budget by weights that do not add up to the run.
44- #[test]
45- fn the_rate_loop_prices_the_frames_the_pyramid_codes() {
46- let _knobs = crate::speed::knob_read();
47- let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect();
48- let quarters = Pyramid {
49- quarter_q_offset: Some(-20),
50- ..Pyramid::default()
51- };
52- let two_level = Pyramid {
53- mid_q_offset: None,
54- ..Pyramid::default()
55- };
56- for (gop, pyramid) in [
57- (48, Pyramid::default()),
58- (12, Pyramid::default()),
59- (48, quarters),
60- (48, two_level),
61- ] {
62- let config = EncoderConfig {
63- width: 64,
64- height: 64,
65- base_q_idx: 100,
66- gop,
67- colour: Colour::Bt709Limited,
68- tile_cols_log2: 0,
69- tile_rows_log2: 0,
70- };
71- let rate = RateTarget::BytesPerFrame(2_000);
72- let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
73- let packets = encode_all(&mut enc, &pictures[..gop]);
74- let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
75- let (hidden, leaves) = gop_shape(pyramid, gop);
76- let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
77- assert_eq!(
78- (hidden_frames, leaves, 1),
79- (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
80- "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
81- );
82- assert_eq!(
83- hidden_frames + leaves + 1,
84- gop,
85- "gop {gop}: every picture is coded exactly once"
86- );
87- // The plan adds up: one leaf's target times the run's whole
88- // weight is the run's whole budget.
89- let target_bytes = 2_000.0;
90- let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
91- let planned = loop_.target[0]
92- + loop_.target[2]
93- * (leaves as f64
94- + hidden
95- .iter()
96- .map(|&(o, n)| n as f64 * loop_.weight(o))
97- .sum::<f64>());
98- assert!(
99- (planned - target_bytes * gop as f64).abs() < 1.0,
100- "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
101- target_bytes * gop as f64
102- );
11+ }
12+ for y in 0..height / 2 {
13+ for x in 0..width / 2 {
14+ let i = y * (width / 2) + x;
15+ picture.u[i] = ((100 + shift * 4) % 256) as u16;
16+ picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
10317 }
10418 }
19+ picture
20+}
10521
106- /// A level at its quantizer BOUND hands its unspent bytes to the levels
107- /// that can still move ([[vorbis-rate-loop-windup]]'s class in the
108- /// small), and it does so AT ONCE, not once the bound level's frames are
109- /// all coded: the loop is driven by a synthetic per-level model where the
110- /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255
111- /// clamp) and spends half its plan, and the leaves' target must jump to
112- /// the run's remainder with EVERY remaining hidden frame priced at that
113- /// measured rate. The old division -- whole remainder over whole
114- /// remaining weight -- handed most of the shortfall straight back to the
115- /// hidden slot (which carries most of the pyramid's weight and cannot
116- /// spend it), so the leaves only saw the surplus at the end of the run,
117- /// when there was nothing left to code with it.
118- #[test]
119- fn a_bound_level_hands_its_unspent_bytes_to_the_others() {
120- let pyramid = Pyramid::default();
121- let (gop, target_bytes) = (48usize, 2_000.0);
22+/// Drives a whole stream through the facade the way a caller must since
23+/// it holds one picture of lookahead: every picture through
24+/// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].
25+fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {
26+ let mut packets = Vec::with_capacity(pictures.len());
27+ for (i, picture) in pictures.iter().enumerate() {
28+ packets.extend(
29+ enc.encode_frames(picture)
30+ .unwrap_or_else(|e| panic!("picture {i}: {e}")),
31+ );
32+ }
33+ packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));
34+ packets
35+}
36+
37+/// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden
38+/// counts and leaf count match the packets a real run emits, at three
39+/// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends
40+/// the run's budget exactly (`gop` frame targets, no more and no less).
41+///
42+/// Both halves matter: a shape that misses a level (the old model priced
43+/// ONE hidden frame per group when the mid level had made it two) splits
44+/// the budget by weights that do not add up to the run.
45+#[test]
46+fn the_rate_loop_prices_the_frames_the_pyramid_codes() {
47+ let _knobs = crate::speed::knob_read();
48+ let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect();
49+ let quarters = Pyramid {
50+ quarter_q_offset: Some(-20),
51+ ..Pyramid::default()
52+ };
53+ let two_level = Pyramid {
54+ mid_q_offset: None,
55+ ..Pyramid::default()
56+ };
57+ for (gop, pyramid) in [
58+ (48, Pyramid::default()),
59+ (12, Pyramid::default()),
60+ (48, quarters),
61+ (48, two_level),
62+ ] {
63+ let config = EncoderConfig {
64+ width: 64,
65+ height: 64,
66+ base_q_idx: 100,
67+ gop,
68+ colour: Colour::Bt709Limited,
69+ tile_cols_log2: 0,
70+ tile_rows_log2: 0,
71+ };
72+ let rate = RateTarget::BytesPerFrame(2_000);
73+ let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
74+ let packets = encode_all(&mut enc, &pictures[..gop]);
75+ let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
12276 let (hidden, leaves) = gop_shape(pyramid, gop);
123- let run_bytes = target_bytes * gop as f64;
124- let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
125- let scale0 = rl.target[2];
126- let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum();
127- // The key codes exactly its plan; the first hidden frame is at the
128- // floor and spends half of its.
129- let key_bytes = rl.target[0].round();
130- rl.update(Level::Key, 0, 100, key_bytes as usize);
131- let (offset, n0) = hidden[0];
132- let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round();
133- rl.update(Level::Arf, offset, 0, arf_bytes as usize);
134- // Every frame of THAT LEVEL still to come is priced at what the bound
135- // one measured -- and only that level: its slot-mates (the mid ARF)
136- // sit at their own offset and are still free to follow the plan.
137- // Everything else shares the rest.
138- let want = (run_bytes - key_bytes - arf_bytes * n0 as f64)
139- / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset));
140- assert!(
141- want < scale0 * RateLoop::REPLAN_CLAMP,
142- "this arm must not reach the windup bound: {want:.1} vs {:.1}",
143- scale0 * RateLoop::REPLAN_CLAMP
77+ let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
78+ assert_eq!(
79+ (hidden_frames, leaves, 1),
80+ (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
81+ "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
14482 );
145- assert!(
146- (rl.target[2] - want).abs() < 1e-6,
147- "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \
148- give {:.3})",
149- rl.target[2],
150- (run_bytes - key_bytes - arf_bytes)
151- / (leaves as f64 + hidden_weight - rl.weight(offset))
83+ assert_eq!(
84+ hidden_frames + leaves + 1,
85+ gop,
86+ "gop {gop}: every picture is coded exactly once"
15287 );
153- // And the re-plan stays BOUNDED: hidden levels that spend nothing at
154- // all cannot run the leaves' target away.
155- let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
156- rl.update(Level::Key, 0, 100, key_bytes as usize);
157- for &(offset, n) in &hidden {
158- for _ in 0..n {
159- rl.update(Level::Arf, offset, 0, 1);
160- }
161- }
88+ // The plan adds up: one leaf's target times the run's whole
89+ // weight is the run's whole budget.
90+ let target_bytes = 2_000.0;
91+ let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
92+ let planned = loop_.target[0]
93+ + loop_.target[2]
94+ * (leaves as f64
95+ + hidden
96+ .iter()
97+ .map(|&(o, n)| n as f64 * loop_.weight(o))
98+ .sum::<f64>());
16299 assert!(
163- rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9,
164- "the re-plan is unbounded: leaf target {:.1} past {:.1}",
165- rl.target[2],
166- scale0 * RateLoop::REPLAN_CLAMP
100+ (planned - target_bytes * gop as f64).abs() < 1.0,
101+ "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
102+ target_bytes * gop as f64
167103 );
168- // ... and BOTH ways: a re-plan that reached zero would stop the loop
169- // dead (`update` returns on a non-positive target).
170- let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
171- rl.update(Level::Key, 0, 100, key_bytes as usize);
172- for &(offset, n) in &hidden {
173- for _ in 0..n {
174- rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize);
104+ }
105+}
106+
107+/// A level at its quantizer BOUND hands its unspent bytes to the levels
108+/// that can still move ([[vorbis-rate-loop-windup]]'s class in the
109+/// small), and it does so AT ONCE, not once the bound level's frames are
110+/// all coded: the loop is driven by a synthetic per-level model where the
111+/// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255
112+/// clamp) and spends half its plan, and the leaves' target must jump to
113+/// the run's remainder with EVERY remaining hidden frame priced at that
114+/// measured rate. The old division -- whole remainder over whole
115+/// remaining weight -- handed most of the shortfall straight back to the
116+/// hidden slot (which carries most of the pyramid's weight and cannot
117+/// spend it), so the leaves only saw the surplus at the end of the run,
118+/// when there was nothing left to code with it.
119+#[test]
120+fn a_bound_level_hands_its_unspent_bytes_to_the_others() {
121+ let pyramid = Pyramid::default();
122+ let (gop, target_bytes) = (48usize, 2_000.0);
123+ let (hidden, leaves) = gop_shape(pyramid, gop);
124+ let run_bytes = target_bytes * gop as f64;
125+ let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
126+ let scale0 = rl.target[2];
127+ let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum();
128+ // The key codes exactly its plan; the first hidden frame is at the
129+ // floor and spends half of its.
130+ let key_bytes = rl.target[0].round();
131+ rl.update(Level::Key, 0, 100, key_bytes as usize);
132+ let (offset, n0) = hidden[0];
133+ let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round();
134+ rl.update(Level::Arf, offset, 0, arf_bytes as usize);
135+ // Every frame of THAT LEVEL still to come is priced at what the bound
136+ // one measured -- and only that level: its slot-mates (the mid ARF)
137+ // sit at their own offset and are still free to follow the plan.
138+ // Everything else shares the rest.
139+ let want = (run_bytes - key_bytes - arf_bytes * n0 as f64)
140+ / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset));
141+ assert!(
142+ want < scale0 * RateLoop::REPLAN_CLAMP,
143+ "this arm must not reach the windup bound: {want:.1} vs {:.1}",
144+ scale0 * RateLoop::REPLAN_CLAMP
145+ );
146+ assert!(
147+ (rl.target[2] - want).abs() < 1e-6,
148+ "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \
149+ give {:.3})",
150+ rl.target[2],
151+ (run_bytes - key_bytes - arf_bytes) / (leaves as f64 + hidden_weight - rl.weight(offset))
152+ );
153+ // And the re-plan stays BOUNDED: hidden levels that spend nothing at
154+ // all cannot run the leaves' target away.
155+ let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
156+ rl.update(Level::Key, 0, 100, key_bytes as usize);
157+ for &(offset, n) in &hidden {
158+ for _ in 0..n {
159+ rl.update(Level::Arf, offset, 0, 1);
160+ }
161+ }
162+ assert!(
163+ rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9,
164+ "the re-plan is unbounded: leaf target {:.1} past {:.1}",
165+ rl.target[2],
166+ scale0 * RateLoop::REPLAN_CLAMP
167+ );
168+ // ... and BOTH ways: a re-plan that reached zero would stop the loop
169+ // dead (`update` returns on a non-positive target).
170+ let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
171+ rl.update(Level::Key, 0, 100, key_bytes as usize);
172+ for &(offset, n) in &hidden {
173+ for _ in 0..n {
174+ rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize);
175+ }
176+ }
177+ assert!(
178+ rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9,
179+ "the re-plan froze the loop: leaf target {:.1} under {:.1}",
180+ rl.target[2],
181+ scale0 * RateLoop::REPLAN_FLOOR
182+ );
183+}
184+
185+/// The mini-GOP layout leaves no short tail group, and leaves the long
186+/// GOP the fixed rule already coded alone: 47 inter pictures are
187+/// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),
188+/// while a 12-picture GOP stops being 8 + 3 (lane-gopad).
189+#[test]
190+fn the_mini_gop_layout_leaves_no_short_tail() {
191+ let groups = |remaining: usize, mini_gop: usize, absorb: bool| {
192+ let (mut left, mut out) = (remaining, Vec::new());
193+ while left > 0 {
194+ let g = group_target(left, mini_gop, absorb).min(left);
195+ assert!(g > 0);
196+ out.push(g);
197+ left -= g;
198+ }
199+ out
200+ };
201+ // gop 48: what mini_gop 8 already coded, under either rule.
202+ assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]);
203+ assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]);
204+ // gop 12: 8 + 3 becomes one group of 11.
205+ assert_eq!(groups(11, 8, false), vec![8, 3]);
206+ assert_eq!(groups(11, 8, true), vec![11]);
207+ // A run shorter than a group is one group, as before (the 4-picture
208+ // pin clip).
209+ assert_eq!(groups(3, 8, true), vec![3]);
210+ // No group is ever below half the shape, and none is over 1.5x it.
211+ for mini_gop in 2..=16 {
212+ for remaining in 1..=64 {
213+ for g in groups(remaining, mini_gop, true) {
214+ assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}");
215+ assert!(
216+ g * 2 >= mini_gop || remaining < mini_gop,
217+ "{remaining}/{mini_gop}: short tail {g}"
218+ );
175219 }
176220 }
177- assert!(
178- rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9,
179- "the re-plan froze the loop: leaf target {:.1} under {:.1}",
180- rl.target[2],
181- scale0 * RateLoop::REPLAN_FLOOR
182- );
183221 }
184-
185- /// The mini-GOP layout leaves no short tail group, and leaves the long
186- /// GOP the fixed rule already coded alone: 47 inter pictures are
187- /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),
188- /// while a 12-picture GOP stops being 8 + 3 (lane-gopad).
189- #[test]
190- fn the_mini_gop_layout_leaves_no_short_tail() {
191- let groups = |remaining: usize, mini_gop: usize, absorb: bool| {
192- let (mut left, mut out) = (remaining, Vec::new());
193- while left > 0 {
194- let g = group_target(left, mini_gop, absorb).min(left);
195- assert!(g > 0);
196- out.push(g);
197- left -= g;
222+}
223+
224+/// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
225+/// in order.
226+fn concat(packets: &[Packet]) -> Vec<u8> {
227+ packets.iter().flat_map(|p| p.data.clone()).collect()
228+}
229+
230+/// The facade's latency contract (lane-av1facade, deepened on
231+/// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
232+/// their picture back and return an empty packet, every later call
233+/// returns the packet of the picture that many frames earlier, and
234+/// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
235+/// exactly one non-empty packet per picture, `depth - 1` calls later.
236+#[test]
237+fn one_in_one_out_delayed_by_the_lookahead_depth() {
238+ let _knobs = crate::speed::knob_read();
239+ let config = EncoderConfig {
240+ width: 64,
241+ height: 64,
242+ base_q_idx: 100,
243+ gop: 2,
244+ colour: Colour::Bt709Limited,
245+ tile_cols_log2: 0,
246+ tile_rows_log2: 0,
247+ };
248+ let delay = crate::encode::tpl_depth() as u64 - 1;
249+ let pictures = delay + 5;
250+ let mut enc = Av1Encoder::new(config).unwrap();
251+ for t in 0..pictures {
252+ let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
253+ if t < delay {
254+ assert!(packet.data.is_empty(), "call {t} holds its picture back");
255+ continue;
256+ }
257+ assert!(!packet.data.is_empty(), "picture {t}: empty packet");
258+ assert_eq!(packet.order, t - delay, "picture {t}: order");
259+ }
260+ let tail = enc.flush().unwrap();
261+ assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
262+ for (i, p) in tail.iter().enumerate() {
263+ assert_eq!(
264+ p.order,
265+ pictures - delay + i as u64,
266+ "flushed packet {i}: order"
267+ );
268+ assert!(!p.data.is_empty(), "flushed packet {i}: empty");
269+ }
270+ assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
271+}
272+
273+/// A screen-like card: hard-edged 4-pixel bands of two flat luma values
274+/// with a moving block over the lower half — few colours per 16x16 block
275+/// at high variance, which is exactly what
276+/// [`crate::encode::picture_is_screen`] separates. Used unforced, so the
277+/// gate below runs the real detector rather than an override.
278+fn screen_card(width: usize, height: usize, shift: usize) -> Picture {
279+ let mut picture = Picture::grey(width, height);
280+ for y in 0..height {
281+ for x in 0..width {
282+ let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 };
283+ let over = y >= height / 2 && (x + shift) % width < width / 3;
284+ picture.y[y * width + x] = if over { 128 } else { band };
285+ }
286+ }
287+ picture
288+}
289+
290+/// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on
291+/// lane-av1pyrdef): the streaming facade — what the editor's export
292+/// drives — codes byte for byte what [`crate::encode::encode_sequence`]
293+/// codes, which is the path the BD gate measures. Both now drive ONE
294+/// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the
295+/// identity is by construction; this pins it anyway, over both content
296+/// classes the content gate splits:
297+///
298+/// * film-like (the gate's own clip when the fixture is there, a
299+/// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the
300+/// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two
301+/// paths' whole streams are identical;
302+/// * screen-like: the content gate drops BOTH paths back to flat, one
303+/// packet per picture, identical frame by frame as well as whole.
304+///
305+/// Never skipped, since a skipped identity gate is the defect it is meant
306+/// to catch.
307+#[test]
308+fn the_facade_codes_the_same_bytes_as_encode_sequence() {
309+ let _knobs = crate::speed::knob_read();
310+ let frames = 12usize;
311+ let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| {
312+ // The probe inside already printed the ONE line naming the
313+ // resolved path and the escape hatch, so this is a note about
314+ // what runs instead — not a second SKIP.
315+ eprintln!(" ...so the film arm runs on a synthetic card, not real film");
316+ (0..frames).map(|t| test_card(64, 64, t)).collect()
317+ });
318+ let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();
319+ let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");
320+ for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] {
321+ let (width, height) = (pictures[0].width, pictures[0].height);
322+ for q in [150u8, 60] {
323+ let config = EncoderConfig {
324+ width,
325+ height,
326+ base_q_idx: q,
327+ // One key frame then all inter, which is
328+ // `encode_sequence`'s only shape, and the gate's recipe.
329+ gop: frames,
330+ // `encode_sequence` writes an unspecified colour config.
331+ colour: Colour::Unspecified,
332+ tile_cols_log2: 0,
333+ tile_rows_log2: 0,
334+ };
335+ let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
336+ let mut packets = Vec::new();
337+ for picture in pictures {
338+ packets.extend(enc.encode_frames(picture).unwrap());
198339 }
199- out
200- };
201- // gop 48: what mini_gop 8 already coded, under either rule.
202- assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]);
203- assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]);
204- // gop 12: 8 + 3 becomes one group of 11.
205- assert_eq!(groups(11, 8, false), vec![8, 3]);
206- assert_eq!(groups(11, 8, true), vec![11]);
207- // A run shorter than a group is one group, as before (the 4-picture
208- // pin clip).
209- assert_eq!(groups(3, 8, true), vec![3]);
210- // No group is ever below half the shape, and none is over 1.5x it.
211- for mini_gop in 2..=16 {
212- for remaining in 1..=64 {
213- for g in groups(remaining, mini_gop, true) {
214- assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}");
215- assert!(
216- g * 2 >= mini_gop || remaining < mini_gop,
217- "{remaining}/{mini_gop}: short tail {g}"
340+ packets.extend(enc.flush().unwrap());
341+ assert_eq!(
342+ enc.pyramid().is_none(),
343+ is_screen,
344+ "{content} q={q}: the content gate read this clip the other way round"
345+ );
346+ let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
347+ assert_eq!(
348+ (
349+ packets.iter().map(|p| p.data.len()).sum::<usize>(),
350+ concat(&packets)
351+ ),
352+ (sequence.stream.len(), sequence.stream.clone()),
353+ "{content} q={q}: the facade's stream is not the sequence path's"
354+ );
355+ assert_eq!(
356+ sequence.frames.len(),
357+ frames,
358+ "{content} q={q}: one entry per picture, in display order"
359+ );
360+ if is_screen {
361+ assert_eq!(
362+ packets.len(),
363+ frames,
364+ "{content} q={q}: one packet per picture"
365+ );
366+ for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() {
367+ let cropped = crate::encode::crop_encoded(coded, width, height);
368+ assert_eq!(
369+ (packet.data.len(), packet.data.clone()),
370+ (cropped.stream.len(), cropped.stream.clone()),
371+ "{content} q={q} frame {i}: the facade's bytes are not the \
372+ sequence path's"
218373 );
219374 }
375+ } else {
376+ assert!(
377+ packets.iter().any(|p| p.level == Level::Arf),
378+ "{content} q={q}: a non-screen stream coded no hidden frame"
379+ );
220380 }
221381 }
222382 }
223-
224- /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
225- /// in order.
226- fn concat(packets: &[Packet]) -> Vec<u8> {
227- packets.iter().flat_map(|p| p.data.clone()).collect()
383+}
384+
385+/// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by
386+/// the caller but applied only to camera material. Over screen content
387+/// the encoder must drop back to the flat path and code byte for byte
388+/// what a flat encoder codes — that is what keeps the BD gate's screen
389+/// row identical to the flat baseline — and over non-screen content the
390+/// same request must still reorder (class `gate-blind-to-feature`: a gate
391+/// that only checked the screen half would pass with the pyramid deleted).
392+#[test]
393+fn the_content_gate_keeps_screen_streams_flat() {
394+ let _knobs = crate::speed::knob_read();
395+ let frames = 8usize;
396+ let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect();
397+ let config = EncoderConfig {
398+ width: 64,
399+ height: 64,
400+ base_q_idx: 120,
401+ gop: frames,
402+ colour: Colour::Unspecified,
403+ tile_cols_log2: 0,
404+ tile_rows_log2: 0,
405+ };
406+ crate::encode::force_screen(Some(true));
407+ let mut flat = Av1Encoder::new(config).unwrap();
408+ let flat_packets = encode_all(&mut flat, &pictures);
409+ let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
410+ let gated_packets = encode_all(&mut gated, &pictures);
411+ assert_eq!(
412+ gated.pyramid(),
413+ None,
414+ "the gate left a screen stream on the pyramid"
415+ );
416+ assert_eq!(
417+ concat(&gated_packets),
418+ concat(&flat_packets),
419+ "a screen stream's bytes are not the flat path's"
420+ );
421+ crate::encode::force_screen(Some(false));
422+ let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
423+ let kept_packets = encode_all(&mut kept, &pictures);
424+ assert_eq!(
425+ kept.pyramid(),
426+ Some(Pyramid::default()),
427+ "the gate ate a film stream"
428+ );
429+ assert!(
430+ kept_packets.iter().any(|p| p.level == Level::Arf),
431+ "a non-screen stream coded no hidden frame"
432+ );
433+ crate::encode::force_screen(None);
434+}
435+
436+/// A key frame every `gop` pictures, inter otherwise — checked against
437+/// what the facade itself reports, and (below) against what `ffprobe`
438+/// reads back out of the coded bytes.
439+#[test]
440+fn gop_cadence_is_honored() {
441+ let _knobs = crate::speed::knob_read();
442+ let config = EncoderConfig {
443+ width: 64,
444+ height: 64,
445+ base_q_idx: 100,
446+ gop: 3,
447+ colour: Colour::Unspecified,
448+ tile_cols_log2: 0,
449+ tile_rows_log2: 0,
450+ };
451+ let mut enc = Av1Encoder::new(config).unwrap();
452+ let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect();
453+ let keys: Vec<bool> = encode_all(&mut enc, &pictures)
454+ .iter()
455+ .map(|p| p.key)
456+ .collect();
457+ assert_eq!(keys, vec![true, false, false, true, false, false, true]);
458+}
459+
460+fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
461+ let path = std::env::temp_dir().join(format!(
462+ "ec-av1-facade-probe-{}-{}.obu",
463+ std::process::id(),
464+ std::ptr::addr_of!(stream) as usize
465+ ));
466+ std::fs::write(&path, stream).expect("writing the probe stream");
467+ let out = ec_testkit::ffprobe()
468+ .args([
469+ "-v",
470+ "error",
471+ "-f",
472+ "obu",
473+ "-select_streams",
474+ "v:0",
475+ "-show_entries",
476+ "frame=key_frame,width,height",
477+ "-of",
478+ "csv=p=0",
479+ ])
480+ .arg(&path)
481+ .output()
482+ .expect("ffprobe failed to run");
483+ let _ = std::fs::remove_file(&path);
484+ assert!(
485+ out.status.success(),
486+ "ffprobe refused the stream: {}",
487+ String::from_utf8_lossy(&out.stderr)
488+ );
489+ String::from_utf8_lossy(&out.stdout)
490+ .lines()
491+ .map(|line| {
492+ let mut f = line.trim().split(',');
493+ let key: u32 = f.next().unwrap().parse().unwrap();
494+ let width: u32 = f.next().unwrap().parse().unwrap();
495+ let height: u32 = f.next().unwrap().parse().unwrap();
496+ (key == 1, width, height)
497+ })
498+ .collect()
499+}
500+
501+fn ffprobe_colour(stream: &[u8]) -> String {
502+ let path = std::env::temp_dir().join(format!(
503+ "ec-av1-facade-colour-probe-{}-{}.obu",
504+ std::process::id(),
505+ std::ptr::addr_of!(stream) as usize
506+ ));
507+ std::fs::write(&path, stream).expect("writing the probe stream");
508+ let out = ec_testkit::ffprobe()
509+ .args([
510+ "-v",
511+ "error",
512+ "-f",
513+ "obu",
514+ "-select_streams",
515+ "v:0",
516+ "-show_entries",
517+ "stream=color_primaries,color_transfer,color_space,color_range",
518+ "-of",
519+ "csv=p=0",
520+ ])
521+ .arg(&path)
522+ .output()
523+ .expect("ffprobe failed to run");
524+ let _ = std::fs::remove_file(&path);
525+ assert!(
526+ out.status.success(),
527+ "ffprobe refused the stream: {}",
528+ String::from_utf8_lossy(&out.stderr)
529+ );
530+ String::from_utf8_lossy(&out.stdout).trim().to_string()
531+}
532+
533+/// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
534+/// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
535+/// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
536+/// coded size confirm what the facade already reported.
537+#[test]
538+fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
539+ let _knobs = crate::speed::knob_read();
540+ let (width, height) = (96usize, 96usize);
541+ let config = EncoderConfig {
542+ width,
543+ height,
544+ base_q_idx: 120,
545+ gop: 15,
546+ colour: Colour::Bt709Limited,
547+ tile_cols_log2: 0,
548+ tile_rows_log2: 0,
549+ };
550+ let mut enc = Av1Encoder::new(config).unwrap();
551+ assert_eq!(enc.display_size(), (width, height));
552+ let (coded_w, coded_h) = enc.coded_size();
553+ assert_eq!(
554+ (coded_w, coded_h),
555+ (
556+ width.next_multiple_of(SUPERBLOCK),
557+ height.next_multiple_of(SUPERBLOCK)
558+ )
559+ );
560+
561+ let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect();
562+ let packets: Vec<Packet> = encode_all(&mut enc, &pictures);
563+ let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
564+ assert_eq!(
565+ packets.iter().map(|p| p.key).collect::<Vec<_>>(),
566+ expect_key,
567+ "facade's own key/inter flags"
568+ );
569+
570+ let stream = concat(&packets);
571+ let frames = ffprobe_frames(&stream);
572+ assert_eq!(frames.len(), 30, "ffprobe frame count");
573+ for (t, (key, w, h)) in frames.iter().enumerate() {
574+ assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
575+ assert_eq!(
576+ (*w, *h),
577+ (width as u32, height as u32),
578+ "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
579+ );
228580 }
229-
230- /// The facade's latency contract (lane-av1facade, deepened on
231- /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
232- /// their picture back and return an empty packet, every later call
233- /// returns the packet of the picture that many frames earlier, and
234- /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
235- /// exactly one non-empty packet per picture, `depth - 1` calls later.
236- #[test]
237- fn one_in_one_out_delayed_by_the_lookahead_depth() {
238- let _knobs = crate::speed::knob_read();
581+}
582+
583+/// The configured colour properties are what `ffprobe` reports back,
584+/// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
585+/// is the default a player assumes and the one this test would silently
586+/// pass without wiring for (`ffprobe` reports "unknown" for the
587+/// hardcoded "unspecified" this crate wrote before the facade existed,
588+/// which is a visibly different string).
589+#[test]
590+fn bt709_limited_colour_is_reported_by_ffprobe() {
591+ let _knobs = crate::speed::knob_read();
592+ let config = EncoderConfig {
593+ width: 64,
594+ height: 64,
595+ base_q_idx: 100,
596+ gop: 4,
597+ colour: Colour::Bt709Limited,
598+ tile_cols_log2: 0,
599+ tile_rows_log2: 0,
600+ };
601+ let mut enc = Av1Encoder::new(config).unwrap();
602+ let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
603+ let colour = ffprobe_colour(&packets[0].data);
604+ assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
605+}
606+
607+/// The same, for BT.601: a different set of CICP integers must produce a
608+/// different string, or the wiring could be a no-op that happens to read
609+/// as BT.709 for every input.
610+#[test]
611+fn bt601_limited_colour_is_reported_by_ffprobe() {
612+ let _knobs = crate::speed::knob_read();
613+ let config = EncoderConfig {
614+ width: 64,
615+ height: 64,
616+ base_q_idx: 100,
617+ gop: 4,
618+ colour: Colour::Bt601Limited,
619+ tile_cols_log2: 0,
620+ tile_rows_log2: 0,
621+ };
622+ let mut enc = Av1Encoder::new(config).unwrap();
623+ let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
624+ let colour = ffprobe_colour(&packets[0].data);
625+ assert_eq!(
626+ colour, "tv,smpte170m,smpte170m,smpte170m",
627+ "ffprobe colour fields"
628+ );
629+}
630+
631+/// A frame whose size does not match the encoder's configured geometry
632+/// is refused by name.
633+#[test]
634+fn geometry_mismatch_is_refused() {
635+ let _knobs = crate::speed::knob_read();
636+ let config = EncoderConfig {
637+ width: 64,
638+ height: 64,
639+ base_q_idx: 100,
640+ gop: 4,
641+ colour: Colour::Bt709Limited,
642+ tile_cols_log2: 0,
643+ tile_rows_log2: 0,
644+ };
645+ let mut enc = Av1Encoder::new(config).unwrap();
646+ let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
647+ assert!(err.to_string().contains("64x64"), "{err}");
648+}
649+
650+/// `gop == 0` is refused at construction, not the first `encode()` call.
651+#[test]
652+fn zero_gop_is_refused() {
653+ let _knobs = crate::speed::knob_read();
654+ let config = EncoderConfig {
655+ width: 64,
656+ height: 64,
657+ base_q_idx: 100,
658+ gop: 0,
659+ colour: Colour::Bt709Limited,
660+ tile_cols_log2: 0,
661+ tile_rows_log2: 0,
662+ };
663+ let err = Av1Encoder::new(config).unwrap_err();
664+ assert!(err.to_string().contains("gop"), "{err}");
665+}
666+
667+/// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
668+/// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
669+/// to this facade's own input size, and re-coded through the facade so the
670+/// rate-target surface is exercised at the entry point a caller actually
671+/// drives.
672+fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
673+ h264_clip_frames_at(20, width, height, frames)
674+}
675+
676+fn h264_clip_frames_at(
677+ start: u32,
678+ width: usize,
679+ height: usize,
680+ frames: usize,
681+) -> Option<Vec<Picture>> {
682+ // lane-av1speed3: the wall tables below are read on REAL film as
683+ // well as on the colour-bar fixture (`bars` vs `film` in the BD
684+ // gate's own vocabulary), and the film crop lives outside the repo --
685+ // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other
686+ // caller still gets the fixture.
687+ //
688+ // lane-av1clipprobe: the default path resolves through `EC_FIXTURES`
689+ // first, which is the root `scripts/verify-fixture-library.sh`
690+ // validates -- so the preflight's verdict and these bytes are the same
691+ // tree, and GREEN-with-an-absent-root is no longer reachable by
692+ // pointing EC_FIXTURES somewhere the gates do not read.
693+ let clip = match std::env::var("EC_AV1_WALL_CLIP") {
694+ Ok(p) => std::path::PathBuf::from(p),
695+ Err(_) => ec_testkit::fixture("open/sintel_trailer-1080p.mp4"),
696+ };
697+ // `what` is the CALLING GATE's name, carried in so that both exits from
698+ // this function print exactly one line naming it: the ffmpeg line
699+ // above, and the probe's line naming the resolved path. Callers
700+ // therefore `return` on `None` WITHOUT printing a second one -- the
701+ // second "no fixture" line per gate was the noise that hid this defect.
702+ let out = ec_testkit::ffmpeg()
703+ .args([
704+ "-v",
705+ "error",
706+ "-ss",
707+ &start.to_string(),
708+ "-i",
709+ clip.to_str().unwrap(),
710+ ])
711+ .args(["-frames:v", &frames.to_string()])
712+ .args(["-vf", &format!("scale={width}:{height}")])
713+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
714+ .output()
715+ .expect("ffmpeg failed to run");
716+ assert!(
717+ out.status.success(),
718+ "{}",
719+ String::from_utf8_lossy(&out.stderr)
720+ );
721+ let (luma, chroma) = (width * height, width * height / 4);
722+ let frame_len = luma + 2 * chroma;
723+ assert_eq!(
724+ out.stdout.len(),
725+ frame_len * frames,
726+ "expected {frames} 4:2:0 frames"
727+ );
728+ Some(
729+ (0..frames)
730+ .map(|i| {
731+ let bytes = &out.stdout[i * frame_len..][..frame_len];
732+ Picture {
733+ width,
734+ height,
735+ y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
736+ u: bytes[luma..luma + chroma]
737+ .iter()
738+ .map(|&v| u16::from(v))
739+ .collect(),
740+ v: bytes[luma + chroma..]
741+ .iter()
742+ .map(|&v| u16::from(v))
743+ .collect(),
744+ }
745+ })
746+ .collect(),
747+ )
748+}
749+
750+/// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
751+/// coded size within ±20% of `frames * target` once the first few
752+/// frames' settling has been discarded (the key frame's own reference
753+/// state and the controller's first couple of steps).
754+#[test]
755+fn bytes_per_frame_target_settles_within_20_percent() {
756+ let _knobs = crate::speed::knob_read();
757+ let Some(pictures) = h264_clip_frames(640, 384, 24) else {
758+ return;
759+ };
760+ let target_bytes = 4_000u32;
761+ let config = EncoderConfig {
762+ width: 640,
763+ height: 384,
764+ base_q_idx: 100,
765+ gop: 24,
766+ colour: Colour::Bt709Limited,
767+ tile_cols_log2: 0,
768+ tile_rows_log2: 0,
769+ };
770+ let mut enc =
771+ Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
772+ let sizes: Vec<usize> = encode_all(&mut enc, &pictures)
773+ .iter()
774+ .map(|p| p.data.len())
775+ .collect();
776+ // Discard the key frame (always far larger than an inter target) and
777+ // the next 4 inter frames the loop needs to step toward it.
778+ let settled = &sizes[5..];
779+ let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
780+ let low = f64::from(target_bytes) * 0.8;
781+ let high = f64::from(target_bytes) * 1.2;
782+ assert!(
783+ mean >= low && mean <= high,
784+ "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
785+ );
786+}
787+
788+/// One (bitrate, pyramid) arm's tally, built on the worker thread and
789+/// handed back through the progress channel
790+/// (`bitrate_target_lands_within_5_percent_over_48_frames`). Per LEVEL,
791+/// so a miss reads as WHICH level's model is off rather than as one
792+/// aggregate percentage.
793+struct ArmResult {
794+ /// [`RateLoop::target`] as the arm's own encoder computed it.
795+ targets: [f64; 3],
796+ coded: usize,
797+ bytes: [usize; 4],
798+ count: [usize; 4],
799+}
800+
801+impl ArmResult {
802+ fn take(&mut self, packets: Vec<Packet>) {
803+ for packet in packets {
804+ self.coded += packet.data.len();
805+ let i = match packet.level {
806+ Level::Key => 0,
807+ Level::Arf => 1,
808+ Level::Leaf => 2,
809+ Level::ShowExisting => 3,
810+ };
811+ self.bytes[i] += packet.data.len();
812+ self.count[i] += 1;
813+ }
814+ }
815+}
816+
817+/// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the
818+/// target over 48 frames of a real clip, flat and under a pyramid alike,
819+/// across a 5x span of bitrates. This is the accuracy claim of the
820+/// target-bitrate mode: no two-pass, no lookahead, just each frame's size
821+/// predicted from the previous frame of its own level, one clamped
822+/// proportional step, and the level model
823+/// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits.
824+///
825+/// The tolerance was ±10% and every arm was inside ±3.0% when it was cut
826+/// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the
827+/// ENCODER'S OWN CEILING showing through, not the loop's aim: at that
828+/// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a
829+/// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12
830+/// `leaf_q_offset`, so this clip cannot be made to spend much past
831+/// 2.4 Mbit/s under the default pyramid however the budget is split.
832+///
833+/// # Bounded
834+///
835+/// Each arm's encode runs on a worker thread under a per-CALL
836+/// wall-clock ceiling, so this gate FAILS rather than hanging when an
837+/// encode stops terminating (lane-av1enchang: a 3h20m wedge on one host
838+/// and 30min on another, both here, both with the test thread spinning
839+/// and no child process for the crate's child timeout to reap). The cost
840+/// is real and is why the budget is not tight: the two high bitrate arms
841+/// walk `q_idx` from the seed 100 down into the 20s to spend an
842+/// 8000-byte budget on a 640x384 clip, and a frame at `q_idx` 25 costs
843+/// ~15s in a debug build (~1s optimized) against ~0.5s at `q_idx` 100.
844+/// lane-av1enchang: the PYRAMID CONSTRUCTORS fit on a tight stack.
845+///
846+/// `Av1Encoder` used to be 139960 bytes BY VALUE, because each of the
847+/// eight `DpbSlot`s held a 15 KB `CdfSnapshot` inline. The pyramid
848+/// constructors nest three deep -- `with_pyramid_and_rate_target` ->
849+/// `with_pyramid` -> `new` -- and each level materialises the struct in
850+/// an unoptimized build, so ~840 KB of stack was live at the innermost
851+/// `Ok(Self { .. })`. On libtest's default 2 MiB test thread that aborts:
852+/// `fatal runtime error: stack overflow, aborting`, reproduced on the
853+/// pre-fix binary at `crates/ec-av1/src/encoder.rs:1519` via
854+/// `coredumpctl debug`.
855+///
856+/// Boxing the snapshot brought the struct to 18168 bytes. This gate pins
857+/// that: it builds BOTH constructors on a thread with a deliberately
858+/// tight stack, so the old layout ABORTS THE PROCESS and the new one
859+/// returns. It runs in milliseconds, where proving the same thing through
860+/// the 48-frame gate takes 6m35s.
861+///
862+/// Both thresholds were swept, in an unoptimized build:
863+///
864+/// | stack | pre-fix (`CdfSnapshot` by value) | post-fix (boxed) |
865+/// |---|---|---|
866+/// | 256 KiB | overflow | overflow |
867+/// | 384 KiB | overflow | ok |
868+/// | 512 KiB | overflow | ok |
869+/// | 1 MiB | **overflow** | **ok** |
870+/// | 2 MiB | **overflow** (libtest's default) | ok |
871+/// | 3 MiB | ok | ok |
872+///
873+/// 1 MiB is the gate: 2.7x what the boxed layout needs and 2x below what
874+/// the old one did, so it is nowhere near either threshold and cannot
875+/// flake. The pre-fix row at 1 MiB is the red -- which is also why
876+/// `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, a
877+/// workspace-local band-aid this gate makes unnecessary for this struct.
878+///
879+/// `EC_AV1_TIGHT_STACK_BYTES` overrides the size, which is how the sweep
880+/// above is reproduced.
881+#[test]
882+fn the_pyramid_constructors_fit_on_a_tight_stack() {
883+ // 1 MiB: see the threshold table on this test. Red before the Box,
884+ // green after, with 2.7x margin either way.
885+ const STACK: usize = 1024 * 1024;
886+ let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES")
887+ .ok()
888+ .and_then(|v| v.parse().ok())
889+ .unwrap_or(STACK);
890+ let config = EncoderConfig {
891+ width: 640,
892+ height: 384,
893+ base_q_idx: 100,
894+ gop: 48,
895+ colour: Colour::Bt709Limited,
896+ tile_cols_log2: 0,
897+ tile_rows_log2: 0,
898+ };
899+ let rate = RateTarget::Bitrate {
900+ bits_per_second: 1_536_000,
901+ frames_per_second: 24.0,
902+ };
903+ let handle = std::thread::Builder::new()
904+ .stack_size(stack)
905+ .spawn(move || {
906+ let flat = Av1Encoder::with_rate_target(config, rate)
907+ .expect("with_rate_target")
908+ .rate_loop
909+ .is_some();
910+ let pyr = Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate)
911+ .expect("with_pyramid_and_rate_target")
912+ .pyramid
913+ .is_some();
914+ (flat, pyr)
915+ })
916+ .expect("spawn tight-stack thread");
917+ let (flat, pyr) = handle
918+ .join()
919+ .unwrap_or_else(|_| panic!("the encoder constructors overflowed a {stack}-byte stack"));
920+ assert!(flat, "with_rate_target lost its rate loop");
921+ assert!(pyr, "with_pyramid_and_rate_target lost its pyramid");
922+ eprintln!(
923+ "TIGHTSTACK {stack} bytes: Av1Encoder={} bytes, both constructors returned",
924+ std::mem::size_of::<Av1Encoder>()
925+ );
926+}
927+
928+const CLEAN_START: u32 = 23;
929+
930+#[test]
931+fn bitrate_target_lands_within_5_percent_over_48_frames() {
932+ let _knobs = crate::speed::knob_read();
933+ let (width, height, frames) = (640usize, 384usize, 48usize);
934+ let Some(pictures) = h264_clip_frames_at(CLEAN_START, width, height, frames) else {
935+ return;
936+ };
937+ let fps = 24.0;
938+ let pictures = std::sync::Arc::new(pictures);
939+ for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] {
239940 let config = EncoderConfig {
240- width: 64,
241- height: 64,
941+ width,
942+ height,
242943 base_q_idx: 100,
243- gop: 2,
944+ gop: frames,
244945 colour: Colour::Bt709Limited,
245946 tile_cols_log2: 0,
246947 tile_rows_log2: 0,
247948 };
248- let delay = crate::encode::tpl_depth() as u64 - 1;
249- let pictures = delay + 5;
250- let mut enc = Av1Encoder::new(config).unwrap();
251- for t in 0..pictures {
252- let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
253- if t < delay {
254- assert!(packet.data.is_empty(), "call {t} holds its picture back");
255- continue;
256- }
257- assert!(!packet.data.is_empty(), "picture {t}: empty packet");
258- assert_eq!(packet.order, t - delay, "picture {t}: order");
259- }
260- let tail = enc.flush().unwrap();
261- assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
262- for (i, p) in tail.iter().enumerate() {
263- assert_eq!(
264- p.order,
265- pictures - delay + i as u64,
266- "flushed packet {i}: order"
949+ let rate = RateTarget::Bitrate {
950+ bits_per_second,
951+ frames_per_second: fps,
952+ };
953+ for pyramid in [None, Some(Pyramid::default())] {
954+ let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some());
955+ // Shared, not cloned: the 48 decoded frames are ~35 MB of
956+ // `u16` luma+chroma, and all eight arms want the same ones.
957+ let pictures = std::sync::Arc::clone(&pictures);
958+ // `None` is a progress ticket: THIS call returned. `Some` is
959+ // the arm's result, sent after `flush` -- which is itself a
960+ // call that can spin, so it needs a ticket too, not a bare
961+ // `join` that would block forever.
962+ let (tx, rx) = std::sync::mpsc::channel::<Option<ArmResult>>();
963+ let worker = std::thread::spawn(move || {
964+ let mut enc = match pyramid {
965+ None => Av1Encoder::with_rate_target(config, rate).unwrap(),
966+ Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),
967+ };
968+ let targets = enc.rate_loop.as_ref().unwrap().target;
969+ let mut out = ArmResult {
970+ targets,
971+ coded: 0,
972+ bytes: [0; 4],
973+ count: [0; 4],
974+ };
975+ for picture in pictures.iter() {
976+ out.take(enc.encode_frames(picture).unwrap());
977+ if tx.send(None).is_err() {
978+ return;
979+ }
980+ }
981+ out.take(enc.flush().unwrap());
982+ let _ = tx.send(Some(out));
983+ });
984+ let out = loop {
985+ match rx.recv() {
986+ Ok(Some(out)) => break out,
987+ Ok(None) => {}
988+ Err(_) => {
989+ worker.join().expect("encode worker panicked");
990+ panic!("AV1 encode worker for {arm} died without a result");
991+ }
992+ }
993+ };
994+ let ArmResult {
995+ targets,
996+ coded,
997+ bytes,
998+ count,
999+ } = out;
1000+ let seconds = frames as f64 / fps;
1001+ let achieved = coded as f64 * 8.0 / seconds;
1002+ let error = achieved / f64::from(bits_per_second) - 1.0;
1003+ let per = |i: usize| match count[i] {
1004+ 0 => "-".to_string(),
1005+ n => format!("{n}x{}", bytes[i] / n),
1006+ };
1007+ eprintln!(
1008+ "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
1009+ = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \
1010+ coded key {} arf {} leaf {}",
1011+ pyramid.is_some(),
1012+ 100.0 * error,
1013+ targets[0],
1014+ targets[1],
1015+ targets[2],
1016+ per(0),
1017+ per(1),
1018+ per(2),
1019+ );
1020+ assert!(
1021+ error.abs() <= 0.05,
1022+ "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
1023+ (pyramid {})",
1024+ 100.0 * error,
1025+ pyramid.is_some(),
2671026 );
268- assert!(!p.data.is_empty(), "flushed packet {i}: empty");
2691027 }
270- assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
2711028 }
272-
273- /// A screen-like card: hard-edged 4-pixel bands of two flat luma values
274- /// with a moving block over the lower half — few colours per 16x16 block
275- /// at high variance, which is exactly what
276- /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the
277- /// gate below runs the real detector rather than an override.
278- fn screen_card(width: usize, height: usize, shift: usize) -> Picture {
1029+}
1030+/// The `BytesPerFrame` controller's own windup bound: no frame's coded
1031+/// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
1032+/// clip's full range of content (so a scene cut can't be the one frame
1033+/// that breaks the bound).
1034+///
1035+/// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot
1036+/// that has coded nothing yet is still sitting on the caller's
1037+/// `base_q_idx` guess, and its first step is the acquisition jump, not
1038+/// windup. Exactly one frame is exempt -- the loop below asserts the
1039+/// bound on every frame after it, which is where a scene cut would
1040+/// break it.
1041+#[test]
1042+fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
1043+ let _knobs = crate::speed::knob_read();
1044+ let Some(pictures) = h264_clip_frames(640, 384, 24) else {
1045+ return;
1046+ };
1047+ let config = EncoderConfig {
1048+ width: 640,
1049+ height: 384,
1050+ base_q_idx: 100,
1051+ gop: 24,
1052+ colour: Colour::Bt709Limited,
1053+ tile_cols_log2: 0,
1054+ tile_rows_log2: 0,
1055+ };
1056+ let mut enc = Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
1057+ let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1058+ // The first frame this encoder EMITS is several `encode_frames` calls
1059+ // in (the lookahead queue holds the earlier ones), so the seeding
1060+ // step is not frame zero -- it is the first frame `q` moves at all.
1061+ let mut seeded = false;
1062+ let mut seed_frame = None;
1063+ for (frame, picture) in pictures.iter().enumerate() {
1064+ enc.encode_frames(picture).unwrap();
1065+ let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1066+ let step = (i32::from(q) - i32::from(prev_q)).abs();
1067+ if step > 0 && !seeded {
1068+ seeded = true;
1069+ seed_frame = Some(frame);
1070+ } else {
1071+ assert!(
1072+ f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
1073+ "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp",
1074+ RateLoop::STEP_CLAMP
1075+ );
1076+ }
1077+ prev_q = q;
1078+ }
1079+ assert!(
1080+ seed_frame.is_some(),
1081+ "the controller never steered at all -- the bound below is vacuous"
1082+ );
1083+}
1084+
1085+fn psnr(a: &[u16], b: &[u16]) -> f64 {
1086+ let squared: f64 = a
1087+ .iter()
1088+ .zip(b)
1089+ .map(|(&x, &y)| {
1090+ let d = f64::from(x) - f64::from(y);
1091+ d * d
1092+ })
1093+ .sum();
1094+ if squared == 0.0 {
1095+ return f64::INFINITY;
1096+ }
1097+ 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
1098+}
1099+
1100+/// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
1101+/// entry per coded frame, in order — this facade's own equivalent of
1102+/// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
1103+/// PSNR check needs the decoded pixels, not just the coded byte count.
1104+fn ffmpeg_decode_planes(
1105+ stream: &[u8],
1106+ width: usize,
1107+ height: usize,
1108+) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
1109+ let path = std::env::temp_dir().join(format!(
1110+ "ec-av1-facade-rate-decode-{}-{}.obu",
1111+ std::process::id(),
1112+ std::ptr::addr_of!(stream) as usize
1113+ ));
1114+ std::fs::write(&path, stream).expect("writing the decode probe stream");
1115+ let out = ec_testkit::ffmpeg()
1116+ .args(["-v", "error", "-f", "obu", "-i"])
1117+ .arg(&path)
1118+ .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
1119+ .output()
1120+ .expect("ffmpeg failed to run");
1121+ let _ = std::fs::remove_file(&path);
1122+ assert!(
1123+ out.status.success(),
1124+ "{}",
1125+ String::from_utf8_lossy(&out.stderr)
1126+ );
1127+ let (luma, chroma) = (width * height, width * height / 4);
1128+ let frame_len = luma + 2 * chroma;
1129+ out.stdout
1130+ .chunks_exact(frame_len)
1131+ .map(|f| {
1132+ (
1133+ f[..luma].to_vec(),
1134+ f[luma..luma + chroma].to_vec(),
1135+ f[luma + chroma..].to_vec(),
1136+ )
1137+ })
1138+ .collect()
1139+}
1140+
1141+/// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare.
1142+fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
1143+ ffmpeg_decode_planes(stream, width, height)
1144+ .into_iter()
1145+ .map(|(y, _, _)| y)
1146+ .collect()
1147+}
1148+
1149+/// lane-palw: OUR encoder's own witness for the writer half of the
1150+/// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall,
1151+/// so the bottom superblock row's palette blocks hang 8 luma rows off the
1152+/// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN
1153+/// corner only and replicates it outward, and the writer used to code the
1154+/// full block grid -- symbols a conformant decoder never reads, so
1155+/// ffmpeg/dav1d desynced the rest of the tile while our own trial decode
1156+/// (unclamped on both sides) agreed with itself. Class
1157+/// `writer-phantom-units-past-edge`.
1158+///
1159+/// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's
1160+/// export calls), and compared on EVERY plane -- a chroma palette map is
1161+/// cut by the same edge. `palette_cut_maps_written` is asserted non-zero
1162+/// so the row cannot pass on a stream that cuts no palette map (class
1163+/// gate-blind-to-feature).
1164+#[test]
1165+fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() {
1166+ const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg";
1167+ let _knobs = crate::speed::knob_read();
1168+ let (width, height) = (384usize, 152usize);
1169+ // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at
1170+ // most two luma values, so the palette arm wins across the WHOLE
1171+ // frame -- including the bottom superblock row, whose 16x16 blocks at
1172+ // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid.
1173+ // `screen_card`'s 4-px bands fire only 9 palettes here and none of
1174+ // them at the cut edge (class gate-blind-to-feature).
1175+ let card = |shift: usize| -> Picture {
2791176 let mut picture = Picture::grey(width, height);
2801177 for y in 0..height {
2811178 for x in 0..width {
282- let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 };
283- let over = y >= height / 2 && (x + shift) % width < width / 3;
284- picture.y[y * width + x] = if over { 128 } else { band };
1179+ let cell = ((x + shift) / 8 + y / 8) % 2;
1180+ picture.y[y * width + x] = if cell == 0 { 40 } else { 200 };
2851181 }
2861182 }
2871183 picture
288- }
289-
290- /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on
291- /// lane-av1pyrdef): the streaming facade — what the editor's export
292- /// drives — codes byte for byte what [`crate::encode::encode_sequence`]
293- /// codes, which is the path the BD gate measures. Both now drive ONE
294- /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the
295- /// identity is by construction; this pins it anyway, over both content
296- /// classes the content gate splits:
297- ///
298- /// * film-like (the gate's own clip when the fixture is there, a
299- /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the
300- /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two
301- /// paths' whole streams are identical;
302- /// * screen-like: the content gate drops BOTH paths back to flat, one
303- /// packet per picture, identical frame by frame as well as whole.
304- ///
305- /// Never skipped, since a skipped identity gate is the defect it is meant
306- /// to catch.
307- #[test]
308- fn the_facade_codes_the_same_bytes_as_encode_sequence() {
309- let _knobs = crate::speed::knob_read();
310- let frames = 12usize;
311- let film = h264_clip_frames(640, 384, frames)
312- .unwrap_or_else(|| {
313- // The probe inside already printed the ONE line naming the
314- // resolved path and the escape hatch, so this is a note about
315- // what runs instead — not a second SKIP.
316- eprintln!(" ...so the film arm runs on a synthetic card, not real film");
317- (0..frames).map(|t| test_card(64, 64, t)).collect()
318- });
319- let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();
320- let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");
321- for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] {
322- let (width, height) = (pictures[0].width, pictures[0].height);
323- for q in [150u8, 60] {
324- let config = EncoderConfig {
325- width,
326- height,
327- base_q_idx: q,
328- // One key frame then all inter, which is
329- // `encode_sequence`'s only shape, and the gate's recipe.
330- gop: frames,
331- // `encode_sequence` writes an unspecified colour config.
332- colour: Colour::Unspecified,
333- tile_cols_log2: 0,
334- tile_rows_log2: 0,
335- };
336- let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
337- let mut packets = Vec::new();
338- for picture in pictures {
339- packets.extend(enc.encode_frames(picture).unwrap());
340- }
341- packets.extend(enc.flush().unwrap());
342- assert_eq!(
343- enc.pyramid().is_none(),
344- is_screen,
345- "{content} q={q}: the content gate read this clip the other way round"
346- );
347- let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
348- assert_eq!(
349- (
350- packets.iter().map(|p| p.data.len()).sum::<usize>(),
351- concat(&packets)
352- ),
353- (sequence.stream.len(), sequence.stream.clone()),
354- "{content} q={q}: the facade's stream is not the sequence path's"
355- );
356- assert_eq!(
357- sequence.frames.len(),
358- frames,
359- "{content} q={q}: one entry per picture, in display order"
1184+ };
1185+ let sources: Vec<Picture> = (0..2).map(|t| card(t * 16)).collect();
1186+ let config = EncoderConfig {
1187+ width,
1188+ height,
1189+ base_q_idx: 60,
1190+ gop: 2,
1191+ colour: Colour::Bt709Limited,
1192+ tile_cols_log2: 0,
1193+ tile_rows_log2: 0,
1194+ };
1195+ let mut enc = Av1Encoder::new(config).unwrap();
1196+ crate::tile::reset_palette_cut_maps_written();
1197+ let mut stream = Vec::new();
1198+ for packet in encode_all(&mut enc, &sources) {
1199+ stream.extend_from_slice(&packet.data);
1200+ }
1201+ eprintln!(
1202+ "{NAME}: {} cut colour-index maps written",
1203+ crate::tile::palette_cut_maps_written()
1204+ );
1205+ assert!(
1206+ crate::tile::palette_cut_maps_written() > 0,
1207+ "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind"
1208+ );
1209+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1210+ assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");
1211+ let theirs = ffmpeg_decode_planes(&stream, width, height);
1212+ assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
1213+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1214+ for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] {
1215+ let got: Vec<u8> = got.iter().map(|&v| v as u8).collect();
1216+ if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) {
1217+ let w = if plane == "luma" { width } else { width / 2 };
1218+ panic!(
1219+ "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}",
1220+ at % w,
1221+ at / w,
1222+ got[at],
1223+ want[at],
3601224 );
361- if is_screen {
362- assert_eq!(
363- packets.len(),
364- frames,
365- "{content} q={q}: one packet per picture"
366- );
367- for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() {
368- let cropped = crate::encode::crop_encoded(coded, width, height);
369- assert_eq!(
370- (packet.data.len(), packet.data.clone()),
371- (cropped.stream.len(), cropped.stream.clone()),
372- "{content} q={q} frame {i}: the facade's bytes are not the \
373- sequence path's"
374- );
375- }
376- } else {
377- assert!(
378- packets.iter().any(|p| p.level == Level::Arf),
379- "{content} q={q}: a non-screen stream coded no hidden frame"
380- );
381- }
3821225 }
1226+ assert_eq!(
1227+ got.len(),
1228+ want.len(),
1229+ "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}",
1230+ got.len(),
1231+ want.len()
1232+ );
3831233 }
3841234 }
385-
386- /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by
387- /// the caller but applied only to camera material. Over screen content
388- /// the encoder must drop back to the flat path and code byte for byte
389- /// what a flat encoder codes — that is what keeps the BD gate's screen
390- /// row identical to the flat baseline — and over non-screen content the
391- /// same request must still reorder (class `gate-blind-to-feature`: a gate
392- /// that only checked the screen half would pass with the pyramid deleted).
393- #[test]
394- fn the_content_gate_keeps_screen_streams_flat() {
395- let _knobs = crate::speed::knob_read();
396- let frames = 8usize;
397- let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect();
1235+}
1236+
1237+/// A pyramid stream reorders pictures: the hidden `ALTREF` of each
1238+/// mini-GOP is coded before the leaves that precede it in display order,
1239+/// and a `show_existing_frame` header puts it back. This pins the shape
1240+/// (one packet per source picture plus one `show_existing_frame` per
1241+/// group, `dts` monotone, `order` NOT monotone) and then decodes the
1242+/// whole stream through OUR decoder and through ffmpeg/dav1d and requires
1243+/// the two display-order outputs to agree sample for sample — the
1244+/// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
1245+/// output, or output twice, or output in the wrong position, changes the
1246+/// display-order list and fails here.
1247+#[test]
1248+fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1249+ // `take_ref_frame_hits` is a process-global counter: a reader-locked
1250+ // sibling encoding at the same time zeroes it between our encode and
1251+ // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the
1252+ // exclusive lock.
1253+ let _knobs = crate::speed::knob_write();
1254+ pyramid_round_trip(
1255+ Pyramid {
1256+ mini_gop: 4,
1257+ mid_q_offset: None,
1258+ ..Pyramid::default()
1259+ },
1260+ 2,
1261+ );
1262+}
1263+
1264+/// The same round trip over a THREE-level group (`mid_q_offset`): each
1265+/// mini-GOP now codes two hidden frames -- the top ARF at the group's
1266+/// last picture and the mid ARF at the middle of the leaf run -- and
1267+/// re-outputs both with `show_existing_frame`, so a mid frame emitted in
1268+/// the wrong display position, or twice, fails the display-order compare
1269+/// against ffmpeg exactly as a top ARF does.
1270+#[test]
1271+fn a_three_level_pyramid_stream_decodes_in_display_order() {
1272+ let _knobs = crate::speed::knob_write();
1273+ pyramid_round_trip(
1274+ Pyramid {
1275+ mini_gop: 8,
1276+ mid_q_offset: Some(-8),
1277+ ..Pyramid::default()
1278+ },
1279+ 2,
1280+ );
1281+}
1282+
1283+/// The same round trip over a FOUR-level group
1284+/// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four
1285+/// hidden frames -- the top ARF at picture 8, the mid at 4 and the two
1286+/// quarters at 2 and 6 -- each re-output by its own
1287+/// `show_existing_frame`. Every leaf reads a different pair of DPB slots
1288+/// than it did at three levels, so a slot map that lets one level
1289+/// overwrite a picture another is still reading shows up here as a
1290+/// display-order mismatch against ffmpeg.
1291+#[test]
1292+fn a_four_level_pyramid_stream_decodes_in_display_order() {
1293+ let _knobs = crate::speed::knob_write();
1294+ pyramid_round_trip(
1295+ Pyramid {
1296+ mini_gop: 8,
1297+ mid_q_offset: Some(-8),
1298+ quarter_q_offset: Some(4),
1299+ ..Pyramid::default()
1300+ },
1301+ 4,
1302+ );
1303+}
1304+
1305+/// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads
1306+/// the key, so an offset that never arrived would be invisible in the BD
1307+/// table except as "no change" (class symbol-consumption-gap). A finer
1308+/// key must cost strictly more bytes than the same picture at base q.
1309+#[test]
1310+fn the_key_q_offset_reaches_the_key_frame() {
1311+ let _knobs = crate::speed::knob_read();
1312+ crate::encode::force_screen(Some(false));
1313+ let key_bytes = |offset: i16| {
3981314 let config = EncoderConfig {
399- width: 64,
400- height: 64,
1315+ width: 128,
1316+ height: 128,
4011317 base_q_idx: 120,
402- gop: frames,
403- colour: Colour::Unspecified,
1318+ gop: 32,
1319+ colour: Colour::Bt709Limited,
4041320 tile_cols_log2: 0,
4051321 tile_rows_log2: 0,
4061322 };
407- crate::encode::force_screen(Some(true));
408- let mut flat = Av1Encoder::new(config).unwrap();
409- let flat_packets = encode_all(&mut flat, &pictures);
410- let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
411- let gated_packets = encode_all(&mut gated, &pictures);
412- assert_eq!(
413- gated.pyramid(),
414- None,
415- "the gate left a screen stream on the pyramid"
416- );
417- assert_eq!(
418- concat(&gated_packets),
419- concat(&flat_packets),
420- "a screen stream's bytes are not the flat path's"
421- );
422- crate::encode::force_screen(Some(false));
423- let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
424- let kept_packets = encode_all(&mut kept, &pictures);
425- assert_eq!(
426- kept.pyramid(),
427- Some(Pyramid::default()),
428- "the gate ate a film stream"
429- );
430- assert!(
431- kept_packets.iter().any(|p| p.level == Level::Arf),
432- "a non-screen stream coded no hidden frame"
433- );
434- crate::encode::force_screen(None);
435- }
436-
437- /// A key frame every `gop` pictures, inter otherwise — checked against
438- /// what the facade itself reports, and (below) against what `ffprobe`
439- /// reads back out of the coded bytes.
440- #[test]
441- fn gop_cadence_is_honored() {
442- let _knobs = crate::speed::knob_read();
1323+ let pyramid = Pyramid {
1324+ key_q_offset: offset,
1325+ ..Pyramid::default()
1326+ };
1327+ let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
1328+ let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap();
1329+ let key = packets
1330+ .iter()
1331+ .find(|p| p.level == Level::Key)
1332+ .expect("key frame");
1333+ key.data.len()
1334+ };
1335+ let (base, finer) = (key_bytes(0), key_bytes(-48));
1336+ eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes");
1337+ assert!(
1338+ finer > base,
1339+ "key_q_offset -48 did not reach the key frame ({finer} <= {base})"
1340+ );
1341+}
1342+
1343+/// lane-last2's witness: a clip whose pictures ALTERNATE between two
1344+/// textures, so for every leaf the picture two back is an exact match and
1345+/// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf
1346+/// chain alternates its refresh over [`LEAF_SLOTS`] and names the older
1347+/// slot `LAST2_FRAME`; blocks must actually be CODED off it
1348+/// ([[gate-blind-to-feature]]: a slot that is retained but never chosen
1349+/// proves only that the bookkeeping compiles), the stream must decode
1350+/// sample-exact through OUR decoder and through ffmpeg, and the hidden
1351+/// frames must still come out in display order. With the lever OFF the
1352+/// same clip codes ZERO `LAST2` blocks, which is what makes the counter a
1353+/// measurement of this lane and not of the reference set we already had.
1354+#[test]
1355+fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() {
1356+ let _knobs = crate::speed::knob_write();
1357+ crate::encode::force_screen(Some(false));
1358+ let (width, height) = (128usize, 128usize);
1359+ let sources: Vec<Picture> = (0..9)
1360+ .map(|t| test_card(width, height, (t % 2) * 24))
1361+ .collect();
1362+ let run = |on: bool| -> ([usize; 8], Vec<u8>, Vec<Packet>) {
1363+ set_last2(Some(on));
4431364 let config = EncoderConfig {
444- width: 64,
445- height: 64,
446- base_q_idx: 100,
447- gop: 3,
448- colour: Colour::Unspecified,
1365+ width,
1366+ height,
1367+ base_q_idx: 120,
1368+ gop: 32,
1369+ colour: Colour::Bt709Limited,
4491370 tile_cols_log2: 0,
4501371 tile_rows_log2: 0,
4511372 };
452- let mut enc = Av1Encoder::new(config).unwrap();
453- let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect();
454- let keys: Vec<bool> = encode_all(&mut enc, &pictures)
455- .iter()
456- .map(|p| p.key)
457- .collect();
458- assert_eq!(keys, vec![true, false, false, true, false, false, true]);
459- }
460-
461- fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
462- let path = std::env::temp_dir().join(format!(
463- "ec-av1-facade-probe-{}-{}.obu",
464- std::process::id(),
465- std::ptr::addr_of!(stream) as usize
466- ));
467- std::fs::write(&path, stream).expect("writing the probe stream");
468- let out = ec_testkit::ffprobe()
469- .args([
470- "-v",
471- "error",
472- "-f",
473- "obu",
474- "-select_streams",
475- "v:0",
476- "-show_entries",
477- "frame=key_frame,width,height",
478- "-of",
479- "csv=p=0",
480- ])
481- .arg(&path).output()
482- .expect("ffprobe failed to run");
483- let _ = std::fs::remove_file(&path);
484- assert!(
485- out.status.success(),
486- "ffprobe refused the stream: {}",
487- String::from_utf8_lossy(&out.stderr)
488- );
489- String::from_utf8_lossy(&out.stdout)
490- .lines()
491- .map(|line| {
492- let mut f = line.trim().split(',');
493- let key: u32 = f.next().unwrap().parse().unwrap();
494- let width: u32 = f.next().unwrap().parse().unwrap();
495- let height: u32 = f.next().unwrap().parse().unwrap();
496- (key == 1, width, height)
497- })
498- .collect()
499- }
500-
501- fn ffprobe_colour(stream: &[u8]) -> String {
502- let path = std::env::temp_dir().join(format!(
503- "ec-av1-facade-colour-probe-{}-{}.obu",
504- std::process::id(),
505- std::ptr::addr_of!(stream) as usize
506- ));
507- std::fs::write(&path, stream).expect("writing the probe stream");
508- let out = ec_testkit::ffprobe()
509- .args([
510- "-v",
511- "error",
512- "-f",
513- "obu",
514- "-select_streams",
515- "v:0",
516- "-show_entries",
517- "stream=color_primaries,color_transfer,color_space,color_range",
518- "-of",
519- "csv=p=0",
520- ])
521- .arg(&path).output()
522- .expect("ffprobe failed to run");
523- let _ = std::fs::remove_file(&path);
524- assert!(
525- out.status.success(),
526- "ffprobe refused the stream: {}",
527- String::from_utf8_lossy(&out.stderr)
528- );
529- String::from_utf8_lossy(&out.stdout).trim().to_string()
1373+ let pyramid = Pyramid {
1374+ mini_gop: 4,
1375+ mid_q_offset: None,
1376+ ..Pyramid::default()
1377+ };
1378+ let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
1379+ let _ = crate::encode::take_ref_frame_hits();
1380+ let mut packets = Vec::new();
1381+ for picture in &sources {
1382+ packets.extend(enc.encode_frames(picture).unwrap());
1383+ }
1384+ packets.extend(enc.flush().unwrap());
1385+ let hits = crate::encode::take_ref_frame_hits();
1386+ (hits, concat(&packets), packets)
1387+ };
1388+ let (off_hits, off_stream, _) = run(false);
1389+ let (on_hits, stream, packets) = run(true);
1390+ set_last2(None);
1391+ eprintln!(
1392+ "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \
1393+ on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)",
1394+ off_hits[1],
1395+ off_hits[2],
1396+ off_hits[4],
1397+ off_hits[7],
1398+ off_stream.len(),
1399+ on_hits[1],
1400+ on_hits[2],
1401+ on_hits[4],
1402+ on_hits[7],
1403+ stream.len(),
1404+ );
1405+ assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF");
1406+ assert!(
1407+ on_hits[2] >= 8,
1408+ "the picture two back matches exactly and only {} blocks were coded off LAST2",
1409+ on_hits[2],
1410+ );
1411+
1412+ // Display order and sample-exactness, both decoders (the same shape
1413+ // `pyramid_round_trip` gates the hidden frames with).
1414+ let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1415+ assert_eq!(
1416+ ours.len(),
1417+ sources.len(),
1418+ "our decoder's display-order count"
1419+ );
1420+ let theirs = ffmpeg_decode_luma(&stream, width, height);
1421+ assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
1422+ for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1423+ let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1424+ assert_eq!(got.len(), b.len(), "frame {i}: luma size");
1425+ if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1426+ panic!(
1427+ "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1428+ at % width,
1429+ at / width,
1430+ got[at],
1431+ b[at],
1432+ );
1433+ }
5301434 }
531-
532- /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
533- /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
534- /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
535- /// coded size confirm what the facade already reported.
536- #[test]
537- fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
538- let _knobs = crate::speed::knob_read();
539- let (width, height) = (96usize, 96usize);
1435+ // The reordering itself is unchanged by the second leaf slot.
1436+ let shown = packets
1437+ .iter()
1438+ .filter(|p| p.level == Level::ShowExisting)
1439+ .count();
1440+ let arfs = packets.iter().filter(|p| p.level == Level::Arf).count();
1441+ assert_eq!(shown, arfs, "one show_existing_frame per hidden frame");
1442+}
1443+
1444+/// A picture whose content is a static gradient plus a per-picture
1445+/// pseudo-random +-2 of noise: motion search matches the neighbours
1446+/// almost exactly, so the ARF temporal filter's weights are near 1 and
1447+/// the filter actually changes the source (a moving test card gives every
1448+/// neighbour a large MSE, weight ~0, and the filter is a no-op that would
1449+/// make the future-window witness below pass blind).
1450+fn noisy_card(width: usize, height: usize, t: usize) -> Picture {
1451+ let mut picture = Picture::grey(width, height);
1452+ let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15);
1453+ for y in 0..height {
1454+ for x in 0..width {
1455+ seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
1456+ let noise = ((seed >> 33) % 5) as i32 - 2;
1457+ let base = 40 + (x + y) as i32 / 2;
1458+ picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16;
1459+ }
1460+ }
1461+ for i in 0..(width / 2) * (height / 2) {
1462+ picture.u[i] = 110;
1463+ picture.v[i] = 140;
1464+ }
1465+ picture
1466+}
1467+
1468+/// lane-lookahead's correctness witness. One group of lookahead
1469+/// (`Av1Encoder::drain_pending` hands the closed group to `ready` and
1470+/// codes the group before it) must not change WHAT is coded:
1471+///
1472+/// * with the future half of the filter window empty AND the top ARF's
1473+/// temporal lambda window pinned to the past (`TPL_FUT=0`) the stream
1474+/// is byte for byte the one the encoder coded without a lookahead, at
1475+/// every run length -- 1 picture (no hidden frame at all), 7 (a short
1476+/// group), 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 --
1477+/// and at a GOP short enough (8) that key frames drain the buffer
1478+/// mid-run. lane-tplhalf's WIN=11 default also reads that buffer, so
1479+/// the identity arm pins the lambda window off or this witness tests
1480+/// a different lever;
1481+/// * every run decodes to exactly its picture count through OUR decoder
1482+/// and through ffmpeg, sample-exact between the two, so the flush and
1483+/// the `show_existing_frame` order survive the delay;
1484+/// * and with ONE future neighbour the top ARF's source filter actually
1485+/// reads it -- the stream MOVES (class gate-blind-to-feature: a
1486+/// buffered picture nothing consumes would pass every check above).
1487+#[test]
1488+fn the_lookahead_holds_one_group_and_still_codes_every_picture() {
1489+ let _knobs = crate::speed::knob_write();
1490+ // The preset is PROCESS-GLOBAL and another test may have left it
1491+ // anywhere: at a high one every block of this fixture codes as skip
1492+ // (17 pictures in 493 bytes) and the source filter cannot change a
1493+ // byte, which failed the future-half assertion below in the suite and
1494+ // passed it standalone (class process-global-knob-races-tests).
1495+ let was = crate::speed::speed();
1496+ crate::speed::set_speed(0);
1497+ crate::encode::force_screen(Some(false));
1498+ let (width, height) = (128usize, 128usize);
1499+ let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec<u8>, Vec<Packet>) {
1500+ set_lookahead(Some(on));
1501+ set_arf_tf_future(Some(fut));
1502+ set_tpl_fut(Some(0));
5401503 let config = EncoderConfig {
1504+ // FINE (not the 120 the other facade tests use): at a coarse
1505+ // quantizer this fixture's ARF codes almost pure skip (17
1506+ // pictures in 493 bytes) and a filtered source quantizes back
1507+ // to the same bytes, which made the future-half assertion
1508+ // below depend on where the suite's other tests had left the
1509+ // process-global preset. At q=60 the anchor carries real
1510+ // coefficients and the filter must move them.
1511+ base_q_idx: 60,
crates/ec-av1/src/film_grain.rsmodified+17 -17
@@ -789,7 +789,11 @@ fn chroma_noise_row_scalar(
789789 pair: bool,
790790 ) {
791791 if pair {
792- for ((c, lpair), &g) in chroma.iter_mut().zip(luma.as_chunks::<2>().0.iter()).zip(grain) {
792+ for ((c, lpair), &g) in chroma
793+ .iter_mut()
794+ .zip(luma.as_chunks::<2>().0.iter())
795+ .zip(grain)
796+ {
793797 let average_luma = (lpair[0] as i32 + lpair[1] as i32 + 1) >> 1;
794798 let scaled = (((average_luma * luma_mult + mult * *c as i32) >> 6) + offset)
795799 .clamp(0, p.index_max);
@@ -1287,12 +1291,6 @@ thread_local! {
12871291 static GRAIN_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
12881292 }
12891293
1290-/// Current value of [`GRAIN_HITS`].
1291-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1292-pub(crate) fn grain_hits() -> usize {
1293- GRAIN_HITS.with(|c| c.get())
1294-}
1295-
12961294 /// Copies the clean rows `*lcur..l_to` (luma) and `*ccur..c_to` (chroma) of
12971295 /// `src` into `out`, advancing the cursors. [`apply_grain`]'s bands fill
12981296 /// their own uninitialised destination rows with this before adding noise.
@@ -2571,16 +2569,18 @@ mod ragged_grain_tests {
25712569 }
25722570 for col in 0..w {
25732571 let mut g = sl[(i * w + col) as usize];
2574- if overlap && i < 2
2575- && let Some((p, _, _)) = &prev {
2576- let old = p[((i + 32) * w + col) as usize];
2577- g = if i == 0 {
2578- old * 27 + g * 17
2579- } else {
2580- old * 17 + g * 27
2581- };
2582- g = round2(g, 5).clamp(gmin, gmax);
2583- }
2572+ if overlap
2573+ && i < 2
2574+ && let Some((p, _, _)) = &prev
2575+ {
2576+ let old = p[((i + 32) * w + col) as usize];
2577+ g = if i == 0 {
2578+ old * 27 + g * 17
2579+ } else {
2580+ old * 17 + g * 27
2581+ };
2582+ g = round2(g, 5).clamp(gmin, gmax);
2583+ }
25842584 nl[(row * w + col) as usize] = g;
25852585 }
25862586 }
crates/ec-av1/src/intra.rsmodified+55 -40
@@ -152,7 +152,8 @@ impl Edges {
152152 left: Option<&[u16]>,
153153 corner: Option<u16>,
154154 bw: usize,
155- bh: usize, fctx: &crate::decode::FrameCtx,
155+ bh: usize,
156+ fctx: &crate::decode::FrameCtx,
156157 ) -> Self {
157158 let want = bw + bh;
158159 // Spec 7.11.2.2's no-neighbour fallback is `base = 1 << (BitDepth - 1)`
@@ -249,25 +250,6 @@ thread_local! {
249250 static EDGE_FILTER_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
250251 }
251252
252-/// How many blocks were predicted with SMOOTH/SMOOTH_V/SMOOTH_H on this thread.
253-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
254-pub(crate) fn smooth_pred_hits() -> usize {
255- SMOOTH_PRED_HITS.with(|c| c.get())
256-}
257-
258-/// How many blocks were predicted with PAETH_PRED on this thread.
259-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
260-pub(crate) fn paeth_pred_hits() -> usize {
261- PAETH_PRED_HITS.with(|c| c.get())
262-}
263-
264-/// How many directional edges [`filter_intra_edge`] actually smoothed
265-/// (strength != 0) on this thread -- the `--enable-intra-edge-filter` proof.
266-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
267-pub(crate) fn intra_edge_filter_hits() -> usize {
268- EDGE_FILTER_HITS.with(|c| c.get())
269-}
270-
271253 #[allow(clippy::too_many_arguments)]
272254 pub(crate) fn predict(
273255 mode: u8,
@@ -279,7 +261,8 @@ pub(crate) fn predict(
279261 bh: usize,
280262 enable_edge_filter: bool,
281263 smooth_neighbor: bool,
282- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
264+ dst: &mut [u16],
265+ fctx: &crate::decode::FrameCtx,
283266 ) {
284267 assert_eq!(dst.len(), bw * bh, "the destination is the block");
285268 let edges = Edges::build(above, left, corner, bw, bh, fctx);
@@ -306,7 +289,8 @@ pub(crate) fn predict(
306289 smooth_neighbor,
307290 n_top,
308291 n_left,
309- dst, fctx,
292+ dst,
293+ fctx,
310294 );
311295 return;
312296 }
@@ -530,7 +514,8 @@ fn directional(
530514 smooth_neighbor: bool,
531515 n_top: usize,
532516 n_left: usize,
533- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
517+ dst: &mut [u16],
518+ fctx: &crate::decode::FrameCtx,
534519 ) {
535520 let (w, h) = (bw as i32, bh as i32);
536521 let reach = w + h; // `av1_dr_prediction_z{1,3}_c`'s `max_base_{x,y}` reach.
@@ -542,7 +527,10 @@ fn directional(
542527 // Spec position `-1..=w + h - 1`, `above[0]`/`left[0]` the shared corner:
543528 // that is exactly `Edges`' own layout (lane-alloc), so take the buffers
544529 // rather than copying them into two fresh ones per directional block.
545- let Edges { mut above, mut left } = edges;
530+ let Edges {
531+ mut above,
532+ mut left,
533+ } = edges;
546534
547535 if enable_edge_filter && angle != 90 && angle != 180 {
548536 if need_above && need_left && reach >= 24 {
@@ -599,7 +587,10 @@ fn directional(
599587 // the blend's `&dyn Fn` indirection all used to sit inside the pixel
600588 // loop; they are per-block (per-row for the shift) constants.
601589 let blend = |edge: &[i32], off: i32, base: i32, shift: i32| {
602- round2(edge[(base + off) as usize] * (32 - shift) + edge[(base + off + 1) as usize] * shift, 5)
590+ round2(
591+ edge[(base + off) as usize] * (32 - shift) + edge[(base + off + 1) as usize] * shift,
592+ 5,
593+ )
603594 };
604595 if angle < 90 {
605596 let dx = dr_intra_derivative(angle);
@@ -656,7 +647,12 @@ fn directional(
656647 blend(above_buf, above_off, base, ((x << up_a) & 0x3F) >> 1)
657648 } else {
658649 let y2 = yrow - (col as i32 + 1) * dy;
659- blend(left_buf, left_off, y2 >> frac_bits_y, ((y2 << up_l) & 0x3F) >> 1)
650+ blend(
651+ left_buf,
652+ left_off,
653+ y2 >> frac_bits_y,
654+ ((y2 << up_l) & 0x3F) >> 1,
655+ )
660656 };
661657 *d = value.clamp(0, max) as u16;
662658 }
@@ -673,7 +669,13 @@ fn directional(
673669 /// before `dc_predictor` averages, so a slice truncated short by the true
674670 /// frame edge must be extended by repetition here too, not averaged over its
675671 /// own shorter length.
676-fn dc(above: Option<&[u16]>, left: Option<&[u16]>, bw: usize, bh: usize, fctx: &crate::decode::FrameCtx) -> i32 {
672+fn dc(
673+ above: Option<&[u16]>,
674+ left: Option<&[u16]>,
675+ bw: usize,
676+ bh: usize,
677+ fctx: &crate::decode::FrameCtx,
678+) -> i32 {
677679 // lane-perf4: the replication is only ever *summed*, never indexed, so
678680 // the extended edge is a sum rather than the `Vec<u16>` it used to be
679681 // built as (two allocations per intra block, 0.9% of a 1080p decode's
@@ -807,7 +809,8 @@ pub(crate) fn predict_filter_intra(
807809 corner: Option<u16>,
808810 bw: usize,
809811 bh: usize,
810- dst: &mut [u16], fctx: &crate::decode::FrameCtx,
812+ dst: &mut [u16],
813+ fctx: &crate::decode::FrameCtx,
811814 ) {
812815 assert_eq!(dst.len(), bw * bh, "the destination is the block");
813816 assert_eq!(bw % 4, 0, "filter intra patches are 4 wide");
@@ -842,7 +845,8 @@ pub(crate) fn predict_filter_intra(
842845 for k in 0..8 {
843846 let (r_off, c_off) = (k >> 2, k & 3);
844847 let pr: i32 = taps[k].iter().zip(&p).map(|(t, s)| t * s).sum();
845- let value = round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max(fctx));
848+ let value =
849+ round2(pr, FILTER_INTRA_SCALE_BITS).clamp(0, crate::decode::sample_max(fctx));
846850 let idx = (r + r_off) * (bw + 1) + c + c_off;
847851 buffer[idx] = value;
848852 }
@@ -1021,7 +1025,7 @@ mod tests {
10211025 /// on three seeded random edges.
10221026 #[test]
10231027 fn filter_intra_matches_the_libaom_predictor_for_every_mode_and_shape() {
1024- let fctx = &crate::decode::FrameCtx::new();
1028+ let fctx = &crate::decode::FrameCtx::new();
10251029 // xorshift64*: a seeded stream, so a failure names one (shape, mode,
10261030 // seed) triple that reproduces.
10271031 let rng = |state: &mut u64| {
@@ -1064,9 +1068,7 @@ mod tests {
10641068 let mut want = vec![0u16; bw * bh];
10651069 let mut c_above = vec![corner];
10661070 c_above.extend_from_slice(&above);
1067- libaom_filter_intra_predictor(
1068- &mut want, bw, bh, &c_above, &left, mode, bd,
1069- );
1071+ libaom_filter_intra_predictor(&mut want, bw, bh, &c_above, &left, mode, bd);
10701072 let mut got = vec![0u16; bw * bh];
10711073 predict_filter_intra(
10721074 mode,
@@ -1075,7 +1077,8 @@ mod tests {
10751077 Some(corner),
10761078 bw,
10771079 bh,
1078- &mut got, fctx,
1080+ &mut got,
1081+ fctx,
10791082 );
10801083 assert_eq!(
10811084 got, want,
@@ -1087,7 +1090,11 @@ mod tests {
10871090 }
10881091 }
10891092 crate::decode::set_bit_depth(8, fctx);
1090- assert_eq!(compared, 2 * 14 * 5 * 3, "every shape/mode/seed was compared");
1093+ assert_eq!(
1094+ compared,
1095+ 2 * 14 * 5 * 3,
1096+ "every shape/mode/seed was compared"
1097+ );
10911098 }
10921099
10931100 /// Spec 7.11.2.5 divides the rect DC average exactly. A 4x16 block (a 1:4
@@ -1126,7 +1133,7 @@ mod tests {
11261133 /// /tmp/intrarect_dump > lanes/intrarect_dump.expected.txt`).
11271134 #[test]
11281135 fn rect_predictors_match_c_dump() {
1129- let fctx = &crate::decode::FrameCtx::new();
1136+ let fctx = &crate::decode::FrameCtx::new();
11301137 let expected_txt = std::fs::read_to_string(concat!(
11311138 env!("CARGO_MANIFEST_DIR"),
11321139 "/../../lanes/intrarect_dump.expected.txt"
@@ -1203,7 +1210,11 @@ mod tests {
12031210 let left = fill(reach, 2);
12041211 let corner = ((bw * 3 + bh * 5) % 256) as u16;
12051212
1206- for (name, mode) in [("DC", DC_PRED), ("SMOOTH", SMOOTH_PRED), ("PAETH", PAETH_PRED)] {
1213+ for (name, mode) in [
1214+ ("DC", DC_PRED),
1215+ ("SMOOTH", SMOOTH_PRED),
1216+ ("PAETH", PAETH_PRED),
1217+ ] {
12071218 let mut dst = vec![0u16; bw * bh];
12081219 predict(
12091220 mode,
@@ -1215,7 +1226,8 @@ mod tests {
12151226 bh,
12161227 false,
12171228 false,
1218- &mut dst, fctx,
1229+ &mut dst,
1230+ fctx,
12191231 );
12201232 let got = if name == "DC" {
12211233 u64::from(dst[0])
@@ -1243,12 +1255,15 @@ mod tests {
12431255 bh,
12441256 ef,
12451257 sn,
1246- &mut dst, fctx,
1258+ &mut dst,
1259+ fctx,
12471260 );
12481261 let got = checksum(&dst);
12491262 let key = ("DR", bw, bh, angle, i32::from(ef), i32::from(sn));
12501263 let want = *expected.get(&key).unwrap_or_else(|| {
1251- panic!("missing DR {bw}x{bh} angle={angle} ef={ef} sn={sn} in the C dump")
1264+ panic!(
1265+ "missing DR {bw}x{bh} angle={angle} ef={ef} sn={sn} in the C dump"
1266+ )
12521267 });
12531268 assert_eq!(
12541269 got, want,
crates/ec-av1/src/mc.rsmodified+32 -11
@@ -515,7 +515,16 @@ mod simd {
515515 c += 16;
516516 }
517517 if c < block_w {
518- hpass_sse2(t.v2(), &sp[c..], 0, 1, block_w - c, t16, &mut op[c..], round0);
518+ hpass_sse2(
519+ t.v2(),
520+ &sp[c..],
521+ 0,
522+ 1,
523+ block_w - c,
524+ t16,
525+ &mut op[c..],
526+ round0,
527+ );
519528 }
520529 }
521530 }
@@ -966,7 +975,17 @@ mod simd {
966975 round1: u32,
967976 ) {
968977 let t = archmage::X64V3Token::summon().expect("avx2 entry on a CPU without avx2");
969- super::vpass_row_u16_avx2(t, intermediate, block_w, src_stride, rows, taps, max, dst, round1)
978+ super::vpass_row_u16_avx2(
979+ t,
980+ intermediate,
981+ block_w,
982+ src_stride,
983+ rows,
984+ taps,
985+ max,
986+ dst,
987+ round1,
988+ )
970989 }
971990
972991 #[allow(unused_variables, clippy::too_many_arguments)]
@@ -981,7 +1000,17 @@ mod simd {
9811000 round1: u32,
9821001 ) {
9831002 let t = archmage::X64V2Token::summon().expect("sse4.1 entry on a CPU without sse4.1");
984- super::vpass_row_u16_sse41(t, intermediate, block_w, src_stride, rows, taps, max, dst, round1)
1003+ super::vpass_row_u16_sse41(
1004+ t,
1005+ intermediate,
1006+ block_w,
1007+ src_stride,
1008+ rows,
1009+ taps,
1010+ max,
1011+ dst,
1012+ round1,
1013+ )
9851014 }
9861015 }
9871016 }
@@ -1533,7 +1562,6 @@ pub(crate) fn predict_with_filters_kern(
15331562
15341563 let (h_wide, h_narrow) = h_kind.tables();
15351564 let (v_wide, v_narrow) = v_kind.tables();
1536- note_narrow_kern(block_w, block_h, kern_w, kern_h);
15371565 let h_filter = if kern_w <= 4 {
15381566 &h_narrow[xfrac]
15391567 } else {
@@ -1753,11 +1781,6 @@ pub fn reset_rect_narrow_kern_hits() {
17531781 RECT_NARROW_KERN_HITS.with(|c| c.set(0));
17541782 }
17551783
1756-/// Bumps [`RECT_NARROW_KERN_HITS`] when the block's true dims pick a kernel
1757-/// the destination buffer's dims would not have.
1758-fn note_narrow_kern(block_w: usize, block_h: usize, kern_w: usize, kern_h: usize) {
1759-}
1760-
17611784 /// Current value of [`INTER_PRED_HITS`].
17621785 pub fn inter_pred_hits() -> usize {
17631786 INTER_PRED_HITS.with(|c| c.get())
@@ -2081,7 +2104,6 @@ pub(crate) fn predict_scaled_kern(
20812104 // Q10; off/pos_x_q10 fold the block's own x_q4 (Q4) into that same Q10
20822105 // grid (spec 7.11.3.3's `dec_calc_subpel_params`).
20832106 let (v_wide, v_narrow) = v_kind.tables();
2084- note_narrow_kern(block_w, block_h, kern_w, kern_h);
20852107 let v_filter = if kern_h <= 4 {
20862108 &v_narrow[yfrac]
20872109 } else {
@@ -2305,7 +2327,6 @@ pub(crate) fn predict_compound_intermediate_kern(
23052327 }
23062328
23072329 let (v_wide, v_narrow) = v_kind.tables();
2308- note_narrow_kern(block_w, block_h, kern_w, kern_h);
23092330 let v_filter = if kern_h <= 4 {
23102331 &v_narrow[yfrac]
23112332 } else {
crates/ec-av1/src/motion_field.rsmodified+23 -33
@@ -76,18 +76,6 @@ impl MotionField {
7676 }
7777 }
7878
79- /// lane-mergefix r5 rung (`EC_TRACE_TPL`): occupancy map of the SAVED
80- /// field, the input side of [`setup_motion_field`]'s projection.
81- pub fn occupancy(&self) -> Vec<String> {
82- (0..self.rows)
83- .map(|r| {
84- (0..self.cols)
85- .map(|c| if self.cells[r * self.cols + c].is_some() { '#' } else { '.' })
86- .collect()
87- })
88- .collect()
89- }
90-
9179 /// lane-mf: the cell grid itself (`cols`, `rows`, cells in row-major
9280 /// order), so [`crate::decode::build_motion_field`] can fill disjoint
9381 /// row bands of it in parallel. Cell row `r` owns `cells[r * cols..][..cols]`.
@@ -126,7 +114,6 @@ impl TplField {
126114 pub fn filled_cells(&self) -> usize {
127115 self.cells.iter().filter(|c| c.1 != 0).count()
128116 }
129-
130117 }
131118
132119 /// spec `get_relative_dist` (5.9.3): `a - b` wrapped into the signed range
@@ -413,21 +400,6 @@ pub fn setup_motion_field<M: std::borrow::Borrow<MotionField>>(
413400
414401 let mut ref_stamp = 2i32; // MFMV_STACK_SIZE - 1
415402
416- // Gate counter (lane-refstamp): frames whose forward references include at
417- // least two key/intra-only frames, i.e. exactly the `ref_stamp` path the
418- // early return above fixes.
419- let intra_forward_refs = [
420- BWDREF_FRAME,
421- crate::mvstack::ALTREF2_FRAME,
422- ALTREF_FRAME,
423- ]
424- .into_iter()
425- .filter(|&rf| {
426- get_relative_dist(order_hint_bits, order_hint_of(rf), cur_order_hint) > 0
427- && slot_of(rf).is_some_and(|m| m.is_intra)
428- })
429- .count();
430-
431403 if let Some(last) = slot_of(LAST_FRAME) {
432404 let alt_of_lst = last.ref_order_hints[(ALTREF_FRAME - LAST_FRAME) as usize];
433405 let is_lst_overlay = alt_of_lst == order_hint_of(GOLDEN_FRAME);
@@ -554,7 +526,9 @@ pub fn add_tpl_ref_mv(
554526 let probe = tpl.probe(mi_row, mi_col).cell(blk_row, blk_col);
555527 if crate::envflags::env_flag!("EC_TRACE_TPL") {
556528 match probe {
557- None => eprintln!("EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"),
529+ None => eprintln!(
530+ "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) INVALID"
531+ ),
558532 Some((m, rfo)) => eprintln!(
559533 "EC_TPL mi_row={mi_row} mi_col={mi_col} blk=({blk_row},{blk_col}) mfmv0=({},{}) rfo={rfo}",
560534 m.0, m.1
@@ -655,8 +629,16 @@ mod tests {
655629 for blk_row in -4isize..=16 {
656630 for blk_col in -4isize..=16 {
657631 // the spec's own derivation (7.10.2.8)
658- let pos_row = if mi_row & 1 != 0 { blk_row } else { blk_row + 1 };
659- let pos_col = if mi_col & 1 != 0 { blk_col } else { blk_col + 1 };
632+ let pos_row = if mi_row & 1 != 0 {
633+ blk_row
634+ } else {
635+ blk_row + 1
636+ };
637+ let pos_col = if mi_col & 1 != 0 {
638+ blk_col
639+ } else {
640+ blk_col + 1
641+ };
660642 let row8 = mi_row as isize + pos_row;
661643 let col8 = mi_col as isize + pos_col;
662644 let want = if row8 < 0 || col8 < 0 {
@@ -740,8 +722,16 @@ mod tests {
740722 // ref_frame_offset = get_relative_dist(2,1) = 1, scaling (-64,0) by
741723 // 2/1 -> (-128,0); get_block_position's sign_bias (dir=2) subtracts
742724 // the offset, landing at 8x8 cell (2, 0).
743- let cand =
744- add_tpl_ref_mv(&tpl, 4, 0, 0isize, 0isize, get_relative_dist(7, 4, 2), true, false);
725+ let cand = add_tpl_ref_mv(
726+ &tpl,
727+ 4,
728+ 0,
729+ 0isize,
730+ 0isize,
731+ get_relative_dist(7, 4, 2),
732+ true,
733+ false,
734+ );
745735 assert!(cand.is_some(), "expected a projected temporal candidate");
746736 }
747737
crates/ec-av1/src/msac.rsmodified+2 -90
@@ -312,36 +312,7 @@ pub struct SymbolDecoder<'a> {
312312 }
313313
314314 impl Drop for SymbolDecoder<'_> {
315- fn drop(&mut self) {
316- }
317-}
318-
319-thread_local! {
320- /// The `(mi_row, mi_col)` the enclosing block reader is inside, for the
321- /// `EC_SYMR` trace. A symbol read carries no mi of its own, so without it
322- /// the per-read stream can only be located by correlating it against a
323- /// SEPARATE trace -- and that correlation is what mis-attributed reads in
324- /// rounds 22 and 23. Set by the mode readers at entry; `(-1,-1)` outside.
325- pub(crate) static SYMR_MI: std::cell::Cell<(i64, i64)> =
326- const { std::cell::Cell::new((-1, -1)) };
327- /// A short tag for the READER PHASE ("intra", "inter", "mv", ...), printed
328- /// on every `EC_SYMR` line. The coefficient rungs stop well before some
329- /// divergences, so the per-read stream is the only instrument that covers
330- /// the inter path; without a phase its reads are unattributable.
331- pub(crate) static SYMR_PHASE: std::cell::Cell<&'static str> =
332- const { std::cell::Cell::new("") };
333- /// The CDF TABLE NAME for the NEXT read, mirroring the oracle's
334- /// `ec_symr_cdf_tag`. `cdf0` alone cannot identify a table -- two rows
335- /// can share a first entry -- so this is what turns "two 2-symbol reads"
336- /// into a named pair.
337- ///
338- /// ONE-SHOT, consumed by the next `symbol()`. Round 30: it used to be
339- /// sticky, so every read after a tagged one carried that tag -- which is
340- /// how an 8-symbol read came to be labelled `interintra`, a 2-symbol
341- /// table. An EMPTY `cdf=` therefore means "no table set for this read",
342- /// never "the previous read's table".
343- pub(crate) static SYMR_CDF: std::cell::Cell<&'static str> =
344- const { std::cell::Cell::new("") };
315+ fn drop(&mut self) {}
345316 }
346317
347318 impl<'a> SymbolDecoder<'a> {
@@ -420,44 +391,8 @@ impl<'a> SymbolDecoder<'a> {
420391
421392 /// `decode_symbol` (spec 8.2.6), with the adaptation of 8.3.2.
422393 ///
423- pub(crate) fn set_symr_cdf(t: &'static str) {
424- SYMR_CDF.with(|c| c.set(t));
425- }
426-
427- pub(crate) fn set_symr_phase(p: &'static str) {
428- SYMR_PHASE.with(|c| c.set(p));
429- }
430-
431- pub(crate) fn set_symr_mi(mi_r: i64, mi_c: i64) {
432- SYMR_MI.with(|c| c.set((mi_r, mi_c)));
433- }
434-
435- /// The `(mi_row, mi_col)` the enclosing block reader last stamped, READ
436- /// back. `set_symr_mi` only writes; a per-unit interval rung needs to print
437- /// the mi, and a coefficient read carries none of its own -- without this a
438- /// ladder cannot be attributed to the block that read it. A copy, not a
439- /// borrow: the rungs call it from a `&SymbolDecoder`.
440- pub(crate) fn symr_mi() -> (i64, i64) {
441- SYMR_MI.with(std::cell::Cell::get)
442- }
443-
444- /// `EC_SYMR=1` dumps every symbol read's PRE state (before the read and
445- /// before the adaptation) together with the symbol and the post-read
446- /// range, so a divergence against a reference decoder can be bisected
447- /// read by read. `cdf0` is the PRE-adapt row[0] -- the reference's own
448- /// print of the same row is POST-adapt, so compare `32768 - ours_cdf0`
449- /// against its `cdf0`, never the raw numbers.
450394 #[inline]
451395 pub fn symbol(&mut self, cdf: &mut [u16]) -> usize {
452- // lane-av1422warp r33 (reviewer P2): this ran on EVERY symbol read of
453- // EVERY stream, production formats included, and `std::env::var_os`
454- // is a real environment scan each time (~30ns x every symbol).
455- // `env_flag!` keeps one `LazyLock<bool>` per call SITE, so the check
456- // compiles to an atomic load. The trace is byte-identical: same
457- // condition, same format, same fields.
458- let symr = crate::envflags::env_flag!("EC_SYMR");
459- let (pre_value, pre_range, pre_bit) = (self.value, self.range, self.bit);
460- let pre_cdf0 = cdf.first().copied().unwrap_or(0);
461396 let s = self.symbol_fixed(cdf);
462397 // lane-av1txr: spec 5.9.2's `disable_cdf_update` -- a frame that sets
463398 // it codes every symbol against the tables it started with, so this
@@ -467,22 +402,6 @@ impl<'a> SymbolDecoder<'a> {
467402 if self.adapt {
468403 update_cdf(cdf, s);
469404 }
470- if symr {
471- eprintln!(
472- "EC_SYMR ph={} cdf={} mi=({},{}) pre=({},{},{}) cdf0={} n={} s={} post_rng={}",
473- SYMR_PHASE.with(std::cell::Cell::get),
474- SYMR_CDF.with(|c| c.replace("")),
475- SYMR_MI.with(std::cell::Cell::get).0,
476- SYMR_MI.with(std::cell::Cell::get).1,
477- pre_value,
478- pre_range,
479- pre_bit,
480- pre_cdf0,
481- cdf.len() - 1,
482- s,
483- self.range
484- );
485- }
486405 s
487406 }
488407
@@ -570,17 +489,11 @@ impl<'a> SymbolDecoder<'a> {
570489 self.max_bits -= bits as i32;
571490 }
572491
573- /// Debug-only: the current bit offset into `data`, for cross-checking
574- /// against a reference decoder's own `aom_reader_tell()` while chasing a
575- /// desync (see `EC_AV1_TRACE`). Not spec state, just `self.bit`.
576- pub(crate) fn debug_bitpos(&self) -> usize {
577- self.bit
578- }
579-
580492 /// Debug-only: the raw coder state (`range`, `value`) entering the next
581493 /// read, for a byte-for-byte diff against a reference decoder's own
582494 /// `r->ec.rng`/`r->ec.dif` while chasing a desync (see
583495 /// `EC_AV1_EOBPT_CDF`). Not spec output, just the two live fields.
496+ #[cfg(test)]
584497 pub(crate) fn debug_state(&self) -> (u32, u32) {
585498 (self.range, self.value)
586499 }
@@ -950,4 +863,3 @@ pub(crate) mod tests {
950863 );
951864 }
952865 }
953-
crates/ec-av1/src/mvstack.rsmodified+171 -80
@@ -92,14 +92,6 @@ thread_local! {
9292 static TMV_HITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
9393 }
9494
95-/// The number of query blocks that received at least one temporal MV
96-/// candidate so far, across every [`find_mv_stack_with_sign_bias`] call in
97-/// this process.
98-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
99-pub(crate) fn tmv_hits() -> usize {
100- TMV_HITS.with(|c| c.get())
101-}
102-
10395 thread_local! {
10496 /// lane-mvtwin r1 firing counters, one per divergence this round closed.
10597 /// `COMP_GM_FILL_HITS`: compound extension candidates whose `comp_list` slot
@@ -117,24 +109,6 @@ thread_local! {
117109 static TILE_REACH_CLIPS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
118110 }
119111
120-/// [`COMP_GM_FILL_HITS`].
121-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
122-pub(crate) fn comp_gm_fill_hits() -> usize {
123- COMP_GM_FILL_HITS.with(|c| c.get())
124-}
125-
126-/// [`STACK_FULL_DROPS`].
127-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
128-pub(crate) fn stack_full_drops() -> usize {
129- STACK_FULL_DROPS.with(|c| c.get())
130-}
131-
132-/// [`TILE_REACH_CLIPS`].
133-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
134-pub(crate) fn tile_reach_clips() -> usize {
135- TILE_REACH_CLIPS.with(|c| c.get())
136-}
137-
138112 /// Everything [`find_mv_stack_with_sign_bias`] needs to fold temporal MV
139113 /// candidates into a block's stack (spec 7.10.2.8, only reached when the
140114 /// frame header's own `use_ref_frame_mvs` is set): the current frame's own
@@ -431,10 +405,8 @@ impl MiGrid {
431405 for r in row..(row + h).min(self.rows) {
432406 let c1 = (col + w).min(self.cols);
433407 let n = c1 - col;
434- self.cells[r * self.cols + col..r * self.cols + c1]
435- .copy_from_slice(&snap.0[i..i + n]);
436- self.skips[r * self.cols + col..r * self.cols + c1]
437- .copy_from_slice(&snap.1[i..i + n]);
408+ self.cells[r * self.cols + col..r * self.cols + c1].copy_from_slice(&snap.0[i..i + n]);
409+ self.skips[r * self.cols + col..r * self.cols + c1].copy_from_slice(&snap.1[i..i + n]);
438410 i += n;
439411 }
440412 }
@@ -860,8 +832,11 @@ fn scan_row(
860832 };
861833 // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd
862834 // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf).
863- let col_shift: usize =
864- if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { 1 } else { 0 };
835+ let col_shift: usize = if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) {
836+ 1
837+ } else {
838+ 0
839+ };
865840 let use_step_16 = bw4 >= 16;
866841 let end_mi = bw4.min(16);
867842 let mut found = false;
@@ -948,8 +923,11 @@ fn scan_col(
948923 };
949924 // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row
950925 // under a 4-high block.
951- let row_shift: usize =
952- if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { 1 } else { 0 };
926+ let row_shift: usize = if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) {
927+ 1
928+ } else {
929+ 0
930+ };
953931 let use_step_16 = bh4 >= 16;
954932 let end_mi = bh4.min(16);
955933 let mut found = false;
@@ -1021,7 +999,13 @@ fn top_right_scan_allowed(bw4: usize, bh4: usize) -> bool {
1021999 /// here) is still missing -- ceiling is a square INTER leaf inside a VERT_A
10221000 /// partition whose warp-sample top-right probe may answer 1 where libaom says
10231001 /// 0; upgrade path = thread `partition` into this call.
1024-pub(crate) fn has_top_right(mi_row: usize, mi_col: usize, bw4: usize, bh4: usize, fctx: &crate::decode::FrameCtx) -> bool {
1002+pub(crate) fn has_top_right(
1003+ mi_row: usize,
1004+ mi_col: usize,
1005+ bw4: usize,
1006+ bh4: usize,
1007+ fctx: &crate::decode::FrameCtx,
1008+) -> bool {
10251009 let sb_mi_size = crate::decode::sb_mi_cur(fctx) as usize;
10261010 let bs0 = bw4.max(bh4);
10271011 if bs0 > 16 {
@@ -1168,11 +1152,6 @@ fn clamp_mv_ref(
11681152 let to_right = signed(mi_cols, bw4, mi_col);
11691153 let to_top = -to_subpel(mi_row);
11701154 let to_bottom = signed(mi_rows, bh4, mi_row);
1171- if to_right < 0 || to_bottom < 0 {
1172- let (row, col) = mv;
1173- let clamped_row = row.clamp(to_top - bh8 - MV_BORDER, to_bottom + bh8 + MV_BORDER);
1174- let clamped_col = col.clamp(to_left - bw8 - MV_BORDER, to_right + bw8 + MV_BORDER);
1175- }
11761155
11771156 let (row, col) = mv;
11781157 (
@@ -1503,7 +1482,6 @@ pub fn find_mv_stack_with_sign_bias(
15031482 force_integer_mv,
15041483 }) = tpl
15051484 {
1506- let mut any_hit = false;
15071485 let voffset = bh4.max(2);
15081486 let hoffset = bw4.max(2);
15091487 let blk_row_end = bh4.min(16);
@@ -1539,12 +1517,11 @@ pub fn find_mv_stack_with_sign_bias(
15391517 let mut blk_col = 0usize;
15401518 while blk_col < blk_col_end {
15411519 if let Some(mv) = sample(blk_row as isize, blk_col as isize) {
1542- any_hit = true;
15431520 if blk_row == 0 && blk_col == 0 {
15441521 first_sample_missing = false;
15451522 let this_gm_mv = gm_mv(gm, ref_frame);
1546- first_sample_far = (mv.0 - this_gm_mv.0).abs() >= 16
1547- || (mv.1 - this_gm_mv.1).abs() >= 16;
1523+ first_sample_far =
1524+ (mv.0 - this_gm_mv.0).abs() >= 16 || (mv.1 - this_gm_mv.1).abs() >= 16;
15481525 }
15491526 add_candidate(&mut candidates, mv, 2);
15501527 }
@@ -1570,7 +1547,6 @@ pub fn find_mv_stack_with_sign_bias(
15701547 continue;
15711548 }
15721549 if let Some(mv) = sample(row_off, col_off) {
1573- any_hit = true;
15741550 add_candidate(&mut candidates, mv, 2);
15751551 }
15761552 }
@@ -1955,8 +1931,11 @@ fn scan_row_compound(
19551931 };
19561932 // libaom `scan_row_mbmi` (mvref_common.c:157): the shift steps BACK on an odd
19571933 // mi_col when the block is narrower than 8px (a 4-wide 1:4 strip / sub-8x8 leaf).
1958- let col_shift: usize =
1959- if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) { 1 } else { 0 };
1934+ let col_shift: usize = if row_offset.unsigned_abs() > 1 && !(mi_col & 1 != 0 && bw4 < 2) {
1935+ 1
1936+ } else {
1937+ 0
1938+ };
19601939 let use_step_16 = bw4 >= 16;
19611940 let end_mi = bw4.min(16);
19621941 let mut found = false;
@@ -1982,12 +1961,24 @@ fn scan_row_compound(
19821961 weight = weight.max(inc as u32);
19831962 *processed_rows = (inc as isize - row_offset - 1).max(0) as usize;
19841963 }
1985- if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1 {
1964+ if info.is_inter
1965+ && info.ref_frame == ref_frame.0
1966+ && info.ref_frame1 > 0
1967+ && info.ref_frame1 == ref_frame.1
1968+ {
19861969 found = true;
19871970 add_compound_candidate(
19881971 candidates,
1989- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },
1990- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },
1972+ if info.is_global_mv0 {
1973+ gm_mv(gm, ref_frame.0)
1974+ } else {
1975+ mv32(info.mv)
1976+ },
1977+ if info.is_global_mv1 {
1978+ gm_mv(gm, ref_frame.1)
1979+ } else {
1980+ mv32(info.mv1)
1981+ },
19911982 len as u32 * weight,
19921983 );
19931984 *newmv_count += u32::from(info.is_new_mv);
@@ -2018,8 +2009,11 @@ fn scan_col_compound(
20182009 };
20192010 // libaom `scan_col_mbmi` (mvref_common.c:206): same step-back on an odd mi_row
20202011 // under a 4-high block.
2021- let row_shift: usize =
2022- if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) { 1 } else { 0 };
2012+ let row_shift: usize = if col_offset.unsigned_abs() > 1 && !(mi_row & 1 != 0 && bh4 < 2) {
2013+ 1
2014+ } else {
2015+ 0
2016+ };
20232017 let use_step_16 = bh4 >= 16;
20242018 let end_mi = bh4.min(16);
20252019 let mut found = false;
@@ -2045,12 +2039,24 @@ fn scan_col_compound(
20452039 weight = weight.max(inc as u32);
20462040 *processed_cols = (inc as isize - col_offset - 1).max(0) as usize;
20472041 }
2048- if info.is_inter && info.ref_frame == ref_frame.0 && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1 {
2042+ if info.is_inter
2043+ && info.ref_frame == ref_frame.0
2044+ && info.ref_frame1 > 0
2045+ && info.ref_frame1 == ref_frame.1
2046+ {
20492047 found = true;
20502048 add_compound_candidate(
20512049 candidates,
2052- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },
2053- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },
2050+ if info.is_global_mv0 {
2051+ gm_mv(gm, ref_frame.0)
2052+ } else {
2053+ mv32(info.mv)
2054+ },
2055+ if info.is_global_mv1 {
2056+ gm_mv(gm, ref_frame.1)
2057+ } else {
2058+ mv32(info.mv1)
2059+ },
20542060 len as u32 * weight,
20552061 );
20562062 *newmv_count += u32::from(info.is_new_mv);
@@ -2079,12 +2085,21 @@ fn scan_top_right_compound(
20792085 if let Some(info) = grid.get(row, col)
20802086 && info.is_inter
20812087 && info.ref_frame == ref_frame.0
2082- && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1
2088+ && info.ref_frame1 > 0
2089+ && info.ref_frame1 == ref_frame.1
20832090 {
20842091 add_compound_candidate(
20852092 candidates,
2086- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },
2087- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },
2093+ if info.is_global_mv0 {
2094+ gm_mv(gm, ref_frame.0)
2095+ } else {
2096+ mv32(info.mv)
2097+ },
2098+ if info.is_global_mv1 {
2099+ gm_mv(gm, ref_frame.1)
2100+ } else {
2101+ mv32(info.mv1)
2102+ },
20882103 CORNER_WEIGHT,
20892104 );
20902105 *newmv_count += u32::from(info.is_new_mv);
@@ -2109,12 +2124,21 @@ fn scan_corner_compound(
21092124 if let Some(info) = grid.get(row, col)
21102125 && info.is_inter
21112126 && info.ref_frame == ref_frame.0
2112- && info.ref_frame1 > 0 && info.ref_frame1 == ref_frame.1
2127+ && info.ref_frame1 > 0
2128+ && info.ref_frame1 == ref_frame.1
21132129 {
21142130 add_compound_candidate(
21152131 candidates,
2116- if info.is_global_mv0 { gm_mv(gm, ref_frame.0) } else { mv32(info.mv) },
2117- if info.is_global_mv1 { gm_mv(gm, ref_frame.1) } else { mv32(info.mv1) },
2132+ if info.is_global_mv0 {
2133+ gm_mv(gm, ref_frame.0)
2134+ } else {
2135+ mv32(info.mv)
2136+ },
2137+ if info.is_global_mv1 {
2138+ gm_mv(gm, ref_frame.1)
2139+ } else {
2140+ mv32(info.mv1)
2141+ },
21182142 CORNER_WEIGHT,
21192143 );
21202144 *newmv_count += u32::from(info.is_new_mv);
@@ -2202,9 +2226,10 @@ fn combine_compound_candidates(
22022226 .copied()
22032227 .collect();
22042228 std::array::from_fn(|i| {
2205- merged.get(i).copied().unwrap_or_else(|| {
2206- gm_mv_candidates[side]
2207- })
2229+ merged
2230+ .get(i)
2231+ .copied()
2232+ .unwrap_or_else(|| gm_mv_candidates[side])
22082233 })
22092234 };
22102235 let side0 = side_slots(0);
@@ -2345,7 +2370,6 @@ pub fn find_mv_stack_compound(
23452370 force_integer_mv,
23462371 }) = tpl
23472372 {
2348- let mut any_hit = false;
23492373 let blk_row_end = bh4.min(16);
23502374 let blk_col_end = bw4.min(16);
23512375 let step_h = if bh4 >= 16 { 4 } else { 2 };
@@ -2379,7 +2403,6 @@ pub fn find_mv_stack_compound(
23792403 let mut blk_col = 0usize;
23802404 while blk_col < blk_col_end {
23812405 if let Some((mv0, mv1)) = sample(blk_row as isize, blk_col as isize) {
2382- any_hit = true;
23832406 if blk_row == 0 && blk_col == 0 {
23842407 first_sample_missing = false;
23852408 let this_gm0 = gm_mv(gm, ref_frame.0);
@@ -2418,7 +2441,6 @@ pub fn find_mv_stack_compound(
24182441 continue;
24192442 }
24202443 if let Some((mv0, mv1)) = sample(row_off, col_off) {
2421- any_hit = true;
24222444 add_compound_candidate(&mut candidates, mv0, mv1, 2);
24232445 }
24242446 }
@@ -2691,8 +2713,16 @@ fn ref_ctx(
26912713 b_set: &[i8],
26922714 ) -> usize {
26932715 let refs = [above0, above1, left0, left1];
2694- let a = refs.into_iter().flatten().filter(|r| a_set.contains(r)).count();
2695- let b = refs.into_iter().flatten().filter(|r| b_set.contains(r)).count();
2716+ let a = refs
2717+ .into_iter()
2718+ .flatten()
2719+ .filter(|r| a_set.contains(r))
2720+ .count();
2721+ let b = refs
2722+ .into_iter()
2723+ .flatten()
2724+ .filter(|r| b_set.contains(r))
2725+ .count();
26962726 match a.cmp(&b) {
26972727 std::cmp::Ordering::Less => 0,
26982728 std::cmp::Ordering::Equal => 1,
@@ -2768,7 +2798,14 @@ pub(crate) fn single_ref_p5_ctx(
27682798 left0: Option<i8>,
27692799 left1: Option<i8>,
27702800 ) -> usize {
2771- ref_ctx(above0, above1, left0, left1, &[LAST3_FRAME], &[GOLDEN_FRAME])
2801+ ref_ctx(
2802+ above0,
2803+ above1,
2804+ left0,
2805+ left1,
2806+ &[LAST3_FRAME],
2807+ &[GOLDEN_FRAME],
2808+ )
27722809 }
27732810
27742811 /// `av1_get_pred_context_single_ref_p6`
@@ -2779,7 +2816,14 @@ pub(crate) fn single_ref_p6_ctx(
27792816 left0: Option<i8>,
27802817 left1: Option<i8>,
27812818 ) -> usize {
2782- ref_ctx(above0, above1, left0, left1, &[BWDREF_FRAME], &[ALTREF2_FRAME])
2819+ ref_ctx(
2820+ above0,
2821+ above1,
2822+ left0,
2823+ left1,
2824+ &[BWDREF_FRAME],
2825+ &[ALTREF2_FRAME],
2826+ )
27832827 }
27842828
27852829 /// `av1_get_pred_context_uni_comp_ref_p1`: `LAST2` vs. `LAST3`/`GOLDEN`,
@@ -2921,7 +2965,6 @@ mod tests {
29212965
29222966 use super::*;
29232967
2924-
29252968 /// lane-mvstack2: the mi grid is one cell per 4x4 unit of the frame and
29262969 /// `find_mv_stack` walks it for every inter block, so the cell's SIZE is
29272970 /// the scan's memory traffic. `ref_frame1`/`mv1` are validity-tagged by
@@ -3516,7 +3559,19 @@ mod tests {
35163559 let (mv0, mv1) = ((2, 2), (-6, 3));
35173560 grid.set(2, 1, comp_inter(mv0, mv1));
35183561
3519- let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
3562+ let stack = find_mv_stack_compound(
3563+ &grid,
3564+ 2,
3565+ 2,
3566+ 2,
3567+ 2,
3568+ COMP_PAIR,
3569+ 8,
3570+ 8,
3571+ &NO_SIGN_BIAS,
3572+ &NO_GM_MV,
3573+ None,
3574+ );
35203575
35213576 // The exact-pair immediate scan lands one boosted entry; the
35223577 // compound extension pass (short stack, len < MAX_MV_REF_CANDIDATES)
@@ -3540,7 +3595,19 @@ mod tests {
35403595 grid.set(2, 1, comp_inter(mv0, mv1));
35413596 grid.set(3, 1, comp_inter(mv0, mv1));
35423597
3543- let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
3598+ let stack = find_mv_stack_compound(
3599+ &grid,
3600+ 2,
3601+ 2,
3602+ 2,
3603+ 2,
3604+ COMP_PAIR,
3605+ 8,
3606+ 8,
3607+ &NO_SIGN_BIAS,
3608+ &NO_GM_MV,
3609+ None,
3610+ );
35443611
35453612 // Exact libaom `is_dup` port: with exactly one entry already in the
35463613 // stack (the four identical-pair neighbours deduped by the
@@ -3572,7 +3639,19 @@ mod tests {
35723639 grid.set(4, 2, comp_inter(left.0, left.1));
35733640 grid.set(5, 2, comp_inter(left.0, left.1));
35743641
3575- let stack = find_mv_stack_compound(&grid, 3, 3, 2, 3, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
3642+ let stack = find_mv_stack_compound(
3643+ &grid,
3644+ 3,
3645+ 3,
3646+ 2,
3647+ 3,
3648+ COMP_PAIR,
3649+ 8,
3650+ 8,
3651+ &NO_SIGN_BIAS,
3652+ &NO_GM_MV,
3653+ None,
3654+ );
35763655
35773656 assert_eq!(stack.entries.len(), 2);
35783657 assert_eq!(stack.entries[0].mv0, left.0);
@@ -3661,7 +3740,19 @@ mod tests {
36613740 },
36623741 );
36633742
3664- let stack = find_mv_stack_compound(&grid, 2, 2, 2, 2, COMP_PAIR, 8, 8, &NO_SIGN_BIAS, &NO_GM_MV, None);
3743+ let stack = find_mv_stack_compound(
3744+ &grid,
3745+ 2,
3746+ 2,
3747+ 2,
3748+ 2,
3749+ COMP_PAIR,
3750+ 8,
3751+ 8,
3752+ &NO_SIGN_BIAS,
3753+ &NO_GM_MV,
3754+ None,
3755+ );
36653756
36663757 // The combine step (libaom's real "Handle compound reference frame
36673758 // extension") zips each side's ref_id-then-ref_diff lists
@@ -3711,11 +3802,9 @@ mod tests {
37113802 for i in 0..MAX_STACK_SIZE as i32 {
37123803 add_candidate(&mut candidates, (i, i), 2);
37133804 }
3714- let before = stack_full_drops();
37153805 add_candidate(&mut candidates, (99, 99), 10_000);
37163806 assert_eq!(candidates.len(), MAX_STACK_SIZE);
37173807 assert!(!candidates.iter().any(|e| e.mv == (99, 99)));
3718- assert_eq!(stack_full_drops(), before + 1);
37193808 // A full stack still takes the dedup weight bump libaom applies
37203809 // before the cap check.
37213810 add_candidate(&mut candidates, (0, 0), 6);
@@ -3782,7 +3871,9 @@ mod tests {
37823871 let clamped = clamp_mv_ref((384, -320), 400, 368, 16, 16, 960, 402);
37833872 assert_eq!(clamped, (192, -320));
37843873 // A block fully inside the frame keeps the wide window.
3785- assert_eq!(clamp_mv_ref((384, -320), 100, 368, 16, 16, 960, 402), (384, -320));
3874+ assert_eq!(
3875+ clamp_mv_ref((384, -320), 100, 368, 16, 16, 960, 402),
3876+ (384, -320)
3877+ );
37863878 }
3787-
37883879 }
crates/ec-av1/src/par.rsmodified+9 -31
@@ -86,14 +86,6 @@ pub(crate) fn filter_threads() -> usize {
8686 }
8787 }
8888
89-/// Test-only override of [`filter_threads`]. Process-global, so a gate using
90-/// it must hold `stream.rs`'s gate-counter lock (which also keeps the
91-/// counter-delta gates from decoding while the workers are on).
92-#[cfg(test)]
93-pub(crate) fn set_filter_threads(n: usize) {
94- FILTER_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
95-}
96-
9789 /// `EC_AV1_TILE_THREADS`, how many workers the ENCODER spreads a frame's
9890 /// tiles across -- both the RD/motion SEARCH (`encode::search_tiles`) and the
9991 /// entropy WRITE (`encode::write_tiles`); default 1 = the shipped
@@ -196,7 +188,10 @@ pub(crate) fn run_bands_mut<T, F>(
196188 /// Carves `data` into one `&mut` slice per element range, `ranges` ascending
197189 /// and non-overlapping (`split_at_mut` only, so no `unsafe`). Elements outside
198190 /// every range are left alone.
199-pub(crate) fn carve_ranges<'a, T>(data: &'a mut [T], ranges: &[(usize, usize)]) -> Vec<&'a mut [T]> {
191+pub(crate) fn carve_ranges<'a, T>(
192+ data: &'a mut [T],
193+ ranges: &[(usize, usize)],
194+) -> Vec<&'a mut [T]> {
200195 split_bands_mut(ranges, 1, data)
201196 }
202197
@@ -341,12 +336,6 @@ pub(crate) fn recon_threads() -> usize {
341336 }
342337 }
343338
344-/// Test-only override of [`recon_threads`] -- see [`set_filter_threads`].
345-#[cfg(test)]
346-pub(crate) fn set_recon_threads(n: usize) {
347- RECON_THREADS.store(n.clamp(1, 64), std::sync::atomic::Ordering::Relaxed);
348-}
349-
350339 // --- lane-pool1: persistent worker pools ---------------------------------
351340 //
352341 // Every threaded stage of the decoder used to spawn its threads per unit of
@@ -687,8 +676,7 @@ pub(crate) const S_FIRST: usize = 9;
687676
688677 static STAGE_NS: [std::sync::atomic::AtomicU64; STAGES.len()] =
689678 [const { std::sync::atomic::AtomicU64::new(0) }; STAGES.len()];
690-/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES`, or
691-/// [`set_stage_times`] from a gate (the env snapshot is process-constant).
679+/// 0 = not read yet, 1 = off, 2 = on. `EC_AV1_STAGE_TIMES` (the env snapshot is process-constant).
692680 static STAGE_ON: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
693681
694682 pub(crate) fn stage_times() -> bool {
@@ -702,12 +690,6 @@ pub(crate) fn stage_times() -> bool {
702690 }
703691 }
704692
705-/// Test-only override of [`stage_times`]; process-global.
706-#[cfg(test)]
707-pub(crate) fn set_stage_times(on: bool) {
708- STAGE_ON.store(1 + usize::from(on), std::sync::atomic::Ordering::Relaxed);
709-}
710-
711693 /// A live stage measurement: added to stage `i` when it drops. `None` when
712694 /// the breakdown is off, so a call site is `let _t = par::timer(S_X);`.
713695 pub(crate) struct Timer(usize, std::time::Instant);
@@ -719,13 +701,9 @@ pub(crate) fn timer(i: usize) -> Option<Timer> {
719701
720702 impl Drop for Timer {
721703 fn drop(&mut self) {
722- STAGE_NS[self.0]
723- .fetch_add(self.1.elapsed().as_nanos() as u64, std::sync::atomic::Ordering::Relaxed);
704+ STAGE_NS[self.0].fetch_add(
705+ self.1.elapsed().as_nanos() as u64,
706+ std::sync::atomic::Ordering::Relaxed,
707+ );
724708 }
725709 }
726-
727-/// Takes and clears the breakdown, in [`STAGES`] order.
728-#[cfg(test)]
729-pub(crate) fn take_stage_ns() -> [u64; STAGES.len()] {
730- std::array::from_fn(|i| STAGE_NS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
731-}
crates/ec-av1/src/quant.rsmodified+0 -13
@@ -216,7 +216,6 @@ pub fn dequant_coeff_wh(
216216 dq2.clamp(-bound, bound - 1) as i32
217217 }
218218
219-
220219 thread_local! {
221220 /// lane-av1-qmatrix: transform units whose dequantisation actually
222221 /// scaled at least one NONZERO level through a quantisation matrix --
@@ -226,18 +225,6 @@ thread_local! {
226225 static QM_SCALED_UNITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
227226 }
228227
229-/// Current value of [`QM_SCALED_UNITS`].
230-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
231-pub(crate) fn qm_scaled_units() -> usize {
232- QM_SCALED_UNITS.with(|c| c.get())
233-}
234-
235-/// Zeroes [`QM_SCALED_UNITS`] (the witness gate's per-arm reset).
236-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
237-pub(crate) fn reset_qm_scaled_units() {
238- QM_SCALED_UNITS.with(|c| c.set(0));
239-}
240-
241228 /// Dequantize a whole raster-order coefficient grid of a `side` x `side`
242229 /// transform.
243230 pub fn dequant(levels: &[i32], side: usize, bit_depth: u8, q_idx: i32) -> Vec<i32> {
crates/ec-av1/src/restoration.rsmodified+28 -54
@@ -609,35 +609,6 @@ thread_local! {
609609 const MI_SIZE_8PX: u32 = 8;
610610 /// `SCALE_NUMERATOR` (aom_scale.h): the superres scale's fixed point, 8.
611611 const SCALE_NUMERATOR: u32 = 8;
612-/// Current value of [`LR_STRIPE0_HITS`].
613-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
614-pub(crate) fn lr_stripe0_hits() -> usize {
615- LR_STRIPE0_HITS.with(|c| c.get())
616-}
617-/// Current value of [`LR_LAST_STRIPE_HITS`].
618-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
619-pub(crate) fn lr_last_stripe_hits() -> usize {
620- LR_LAST_STRIPE_HITS.with(|c| c.get())
621-}
622-
623-/// Current value of [`WIENER_HITS`].
624-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
625-pub(crate) fn wiener_hits() -> usize {
626- WIENER_HITS.with(|c| c.get())
627-}
628-/// Current value of [`SGRPROJ_HITS`].
629-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
630-pub(crate) fn sgrproj_hits() -> usize {
631- SGRPROJ_HITS.with(|c| c.get())
632-}
633-/// Current value of [`SWITCHABLE_HITS`] -- bumped once per unit whose frame
634-/// `restoration_type` is `Switchable`, regardless of which `RestoreType`
635-/// (`None`/Wiener/Sgrproj) that unit's own symbol resolved to.
636-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
637-pub(crate) fn switchable_hits() -> usize {
638- SWITCHABLE_HITS.with(|c| c.get())
639-}
640-
641612 fn read_lr_unit(
642613 dec: &mut SymbolDecoder,
643614 cdfs: &mut crate::cdf_state::Cdfs,
@@ -650,12 +621,8 @@ fn read_lr_unit(
650621 let t = dec.symbol(&mut cdfs.restore_switchable);
651622 match t {
652623 0 => UnitFilter::None,
653- 1 => {
654- UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0))
655- }
656- _ => {
657- UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1))
658- }
624+ 1 => UnitFilter::Wiener(read_wiener_filter(dec, chroma, &mut reference.0)),
625+ _ => UnitFilter::Sgrproj(read_sgrproj_filter(dec, &mut reference.1)),
659626 }
660627 }
661628 RestorationType::Wiener => {
@@ -1181,7 +1148,7 @@ fn ab_row(
11811148 /// [`ab_row`]'s AVX2 kernel.
11821149 #[cfg(target_arch = "x86_64")]
11831150 mod sgr_simd {
1184- use super::{SGRPROJ_MTABLE_BITS, SGRPROJ_RECIP_BITS, SGR_X_BY_XPLUS1};
1151+ use super::{SGR_X_BY_XPLUS1, SGRPROJ_MTABLE_BITS, SGRPROJ_RECIP_BITS};
11851152 use archmage::{X64V3Token, arcane};
11861153 use std::arch::x86_64::*;
11871154
@@ -1461,8 +1428,8 @@ fn apply_sgrproj_stripe(
14611428 }
14621429 }
14631430 let out_v = round2(v, SGRPROJ_PRJ_BITS as u32 + SGRPROJ_RST_BITS).clamp(0, smax) as u16;
1464- out[(v_start as i64 + i - row0 as i64) as usize * stride + (h_start as i64 + j) as usize] =
1465- out_v;
1431+ out[(v_start as i64 + i - row0 as i64) as usize * stride
1432+ + (h_start as i64 + j) as usize] = out_v;
14661433 }
14671434 }
14681435 SGR_AB_SCRATCH.with(|c| *c.borrow_mut() = (buf0, buf1));
@@ -1582,20 +1549,27 @@ pub(crate) fn apply_loop_restoration_plane(
15821549 }
15831550 // Each band's RU rows write one contiguous run of `out` rows (the
15841551 // rows run `v_start..v_end` back to back), so a band owns its own slice.
1585- let pbands: Vec<(usize, usize)> = crate::par::bands(rows.len(), crate::par::filter_threads())
1586- .into_iter()
1587- .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize))
1588- .collect();
1589- crate::par::run_bands_mut(&pbands, stride, fctx, out.as_mut_slice(), |lo, hi, mine, fctx| {
1590- let r_lo = rows.partition_point(|r| (r.0 as usize) < lo);
1591- let r_hi = rows.partition_point(|r| (r.0 as usize) < hi);
1592- for rrow in r_lo..r_hi {
1593- lr_unit_row(
1594- mine, lo, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid,
1595- plane, rrow, &rows, fctx,
1596- );
1597- }
1598- });
1552+ let pbands: Vec<(usize, usize)> =
1553+ crate::par::bands(rows.len(), crate::par::filter_threads())
1554+ .into_iter()
1555+ .map(|(a, b)| (rows[a].0 as usize, rows[b - 1].1 as usize))
1556+ .collect();
1557+ crate::par::run_bands_mut(
1558+ &pbands,
1559+ stride,
1560+ fctx,
1561+ out.as_mut_slice(),
1562+ |lo, hi, mine, fctx| {
1563+ let r_lo = rows.partition_point(|r| (r.0 as usize) < lo);
1564+ let r_hi = rows.partition_point(|r| (r.0 as usize) < hi);
1565+ for rrow in r_lo..r_hi {
1566+ lr_unit_row(
1567+ mine, lo, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid,
1568+ plane, rrow, &rows, fctx,
1569+ );
1570+ }
1571+ },
1572+ );
15991573 debug_assert_eq!(
16001574 rows.len(),
16011575 grid.vert_units[plane],
@@ -1608,8 +1582,8 @@ pub(crate) fn apply_loop_restoration_plane(
16081582 let (a, b) = (v_start as usize * stride, v_end as usize * stride);
16091583 out[a..b].copy_from_slice(&cdef[a..b]);
16101584 lr_unit_row(
1611- out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane,
1612- rrow, &rows, fctx,
1585+ out, 0, cdef, deblocked, stride, plane_w, plane_h, ss_y, unit_size, grid, plane, rrow,
1586+ &rows, fctx,
16131587 );
16141588 }
16151589 }
crates/ec-av1/src/stream/mod.rsmodified+6 -61
@@ -29,15 +29,6 @@ use crate::decode;
2929 use crate::decode::{decode_inter_frame_tile_with_cdfs, decode_key_frame_tile_with_cdfs, q_ctx_of};
3030 use crate::encode::Picture;
3131
32-/// lane-midcut r1: `EC_AV1_NO_GRAIN=1` skips film grain synthesis at output, so a
33-/// mid-film mismatch splits into "reconstruction" (compare against
34-/// `ffmpeg -c:v libdav1d -filmgrain 0`) and "grain synthesis" in one run.
35-fn no_grain() -> bool {
36- std::env::var_os("EC_AV1_NO_GRAIN").is_some()
37-}
38-
39-
40-
4132 /// Decode every frame in a raw AV1 OBU stream, in coding order.
4233 ///
4334 /// A key frame becomes the reference for the inter frames that follow it,
@@ -767,7 +758,7 @@ impl StreamDecoder {
767758 let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
768759 let value = promise.wait()?;
769760 let shown_picture = value.pixels.wait()?;
770- let output = if grain.apply_grain && !no_grain() {
761+ let output = if grain.apply_grain {
771762 std::sync::Arc::new(crate::film_grain::apply_grain(
772763 &shown_picture,
773764 &grain,
@@ -814,7 +805,7 @@ impl StreamDecoder {
814805 }
815806 picture
816807 };
817- let output = if header.film_grain.apply_grain && !no_grain() {
808+ let output = if header.film_grain.apply_grain {
818809 // lane-hbd10 r1: grain synthesis is bit-depth generic
819810 // (`film_grain.rs`'s `grain_range`/`scale_lut`, spec 7.18.3).
820811 let bit_depth = parser
@@ -987,7 +978,7 @@ impl StreamDecoder {
987978 }
988979 }
989980 }
990- let (job_seq, decode_idx, shown_idx) = (emit_seq, pictures_decoded, pictures_shown);
981+ let (job_seq, decode_idx) = (emit_seq, pictures_decoded);
991982 emit_seq += 1;
992983 pictures_decoded += 1;
993984 let shown = header.show_frame;
@@ -1155,7 +1146,6 @@ impl StreamDecoder {
11551146 seq,
11561147 snap,
11571148 decode_idx,
1158- shown_idx,
11591149 // lane-twostage publishes a frame's meta at its tile
11601150 // boundary instead of after its filters, so a consumer
11611151 // parses over its producer's filter tail. It is ON by
@@ -1195,7 +1185,7 @@ impl StreamDecoder {
11951185 // Grain is synthesised for OUTPUT only: a hidden frame is
11961186 // reported to the sink clean, exactly as the inline path
11971187 // below reports it (spec 7.18.3.1).
1198- let output = if shown && header.film_grain.apply_grain && !no_grain() {
1188+ let output = if shown && header.film_grain.apply_grain {
11991189 std::sync::Arc::new(crate::film_grain::apply_grain(
12001190 &picture,
12011191 &header.film_grain,
@@ -1259,16 +1249,7 @@ impl StreamDecoder {
12591249 stored_cdfs,
12601250 motion_field,
12611251 seg_map: decoded_seg_map,
1262- } = decode_frame(
1263- fctx,
1264- &header,
1265- &tile_bufs,
1266- seq,
1267- snap,
1268- pictures_decoded,
1269- pictures_shown,
1270- None,
1271- )?;
1252+ } = decode_frame(fctx, &header, &tile_bufs, seq, snap, pictures_decoded, None)?;
12721253 let motion_field = motion_field.expect("the inline path passes no stage-1 sink");
12731254 pictures_decoded += 1;
12741255 // lane-pool1: one allocation, then every slot store and the output
@@ -1319,7 +1300,7 @@ impl StreamDecoder {
13191300 decode::note_fwd_kf();
13201301 }
13211302 if header.show_frame {
1322- let output = if header.film_grain.apply_grain && !no_grain() {
1303+ let output = if header.film_grain.apply_grain {
13231304 let mc_identity = seq.mc_identity;
13241305 std::sync::Arc::new(crate::film_grain::apply_grain(
13251306 &picture,
@@ -1502,16 +1483,6 @@ impl<'a> RefSnapshot<'a> {
15021483 header.mi_cols as usize,
15031484 )
15041485 });
1505- if std::env::var_os("EC_TPL").is_some() {
1506- eprintln!(
1507- "EC_TPL order_hint={} use_ref_frame_mvs={} cells={}",
1508- header.order_hint,
1509- header.use_ref_frame_mvs,
1510- tpl_field
1511- .as_ref()
1512- .map_or(0, crate::motion_field::TplField::filled_cells)
1513- );
1514- }
15151486 Self {
15161487 refpix,
15171488 primary_cdfs: primary.and_then(|slot| cdf_slots[slot].cloned()),
@@ -1572,7 +1543,6 @@ fn decode_frame(
15721543 seq: SeqFlags,
15731544 snap: RefSnapshot<'_>,
15741545 decode_idx: usize,
1575- shown_idx: usize,
15761546 // lane-twostage: see `decode_inter_frame_tile_with_cdfs`'s own `stage1`.
15771547 stage1: Option<&dyn Fn(Cdfs, crate::motion_field::MotionField, usize, usize)>,
15781548 ) -> Result<FrameOutput> {
@@ -1990,34 +1960,9 @@ fn decode_frame(
19901960 };
19911961 let started_from = initial_cdfs.clone();
19921962 // lane-frame80: narrow the EC_TRACE_COEFF rungs to one DECODE-order frame.
1993- decode::set_coeff_trace_frame(decode_idx);
19941963 // lane-t900 r9: one line per DECODE-order frame naming the header
19951964 // fields a desync cliff is usually keyed on (frame type, base q,
19961965 // primary_ref, the 7 ref slots, refresh mask, order hints).
1997- if std::env::var_os("EC_PROBE_HDR").is_some() {
1998- eprintln!(
1999- "EC_HDR decode_idx={decode_idx} type={:?} show={} show_existing={} base_q={} primary_ref={} ref_idx={:?} refresh=0x{:02x} order_hint={} tiles={}x{} txmode={:?} interp={:?} reduced_tx={} allow_warp={} switchable_mo={} ref_mvs={} skip_mode={} cdef={:?} lr={:?}",
2000- header.frame_type,
2001- header.show_frame,
2002- header.show_existing_frame,
2003- header.quantization.base_q_idx,
2004- header.primary_ref_frame,
2005- header.ref_frame_idx,
2006- header.refresh_frame_flags,
2007- header.order_hint,
2008- header.tile_info.cols,
2009- header.tile_info.rows,
2010- header.tx_mode,
2011- header.interpolation_filter,
2012- header.reduced_tx_set,
2013- header.allow_warped_motion,
2014- header.is_motion_mode_switchable,
2015- header.use_ref_frame_mvs,
2016- header.skip_mode_present,
2017- header.cdef.bits,
2018- header.loop_restoration.frame_restoration_type,
2019- );
2020- }
20211966
20221967 let order_hint_bits = seq.order_hint_bits;
20231968 // spec 7.9/7.20: this frame's own `ref_order_hints` -- the OrderHint
crates/ec-av1/src/tile/blocks.rsmodified+10 -38
@@ -19,7 +19,8 @@ pub(super) static PALETTE_HITS: [std::sync::atomic::AtomicUsize; 9] =
1919 /// i.e. palette blocks this writer cut at the frame's right/bottom mi edge.
2020 /// A gate asserts it non-zero so it cannot pass on a stream that never cuts
2121 /// one (class `gate-blind-to-feature`).
22-pub(super) static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
22+pub(super) static PALETTE_CUT_MAPS: std::sync::atomic::AtomicUsize =
23+ std::sync::atomic::AtomicUsize::new(0);
2324
2425 /// Current value of [`PALETTE_CUT_MAPS`] (colour-index maps).
2526 pub fn palette_cut_maps_written() -> usize {
@@ -1334,16 +1335,6 @@ pub(crate) fn arm_pricing_cdfs(base: Option<&Cdfs>, screen: bool) {
13341335 /// arming calls, not frames: a multi-tile frame arms one worker per tile.
13351336 pub(crate) static PRICING_HITS: [AtomicUsize; 2] = [AtomicUsize::new(0), AtomicUsize::new(0)];
13361337
1337-/// Reads and clears [`PRICING_HITS`]: (default-table armings, real-table
1338-/// armings).
1339-#[cfg(test)]
1340-pub(crate) fn take_pricing_hits() -> (usize, usize) {
1341- (
1342- PRICING_HITS[0].swap(0, Ordering::Relaxed),
1343- PRICING_HITS[1].swap(0, Ordering::Relaxed),
1344- )
1345-}
1346-
13471338 /// The pricer census (`pricer_census_on`): for every transform block the tile
13481339 /// writer really codes, the bits it spent against the bits [`coeff_bits`]
13491340 /// prices those very levels at -- the search's rate term measured against the
@@ -1998,7 +1989,11 @@ pub(super) fn mv_class_of(z: i32) -> usize {
19981989 /// # Errors
19991990 /// Returns an error when `diff` needs eighth-pel precision in a frame coded
20001991 /// without `allow_high_precision_mv`.
2001-pub(super) fn write_mv_component(enc: &mut SymbolEncoder, c: &mut MvComponentCdfs, diff: i32) -> Result<()> {
1992+pub(super) fn write_mv_component(
1993+ enc: &mut SymbolEncoder,
1994+ c: &mut MvComponentCdfs,
1995+ diff: i32,
1996+) -> Result<()> {
20021997 debug_assert_ne!(diff, 0);
20031998 let hp_frame = high_precision_mv();
20041999 let sign = diff < 0;
@@ -2176,18 +2171,13 @@ pub(super) static REF_HITS: [std::sync::atomic::AtomicUsize; 7] = [
21762171 std::sync::atomic::AtomicUsize::new(0),
21772172 ];
21782173
2179-/// Takes and clears the per-reference histogram.
2180-#[cfg(test)]
2181-pub(crate) fn take_ref_hits() -> [usize; 7] {
2182- std::array::from_fn(|i| REF_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2183-}
2184-
21852174 /// Bumps the two histograms for one coded inter block.
21862175 /// How many blocks this process wrote whose search-chosen `ref_mv_idx` the
21872176 /// write-time stack could not carry, so the writer signalled a SMALLER index
21882177 /// (lane-sb128b). Every one of these used to price its residual against a
21892178 /// predictor the decoder never derives.
2190-pub(super) static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2179+pub(super) static DRL_CLAMP_HITS: std::sync::atomic::AtomicUsize =
2180+ std::sync::atomic::AtomicUsize::new(0);
21912181
21922182 /// Counts one clamped DRL index whose predictor differs from the one the
21932183 /// search asked for -- the harmful case, and the only one a witness can see.
@@ -2214,18 +2204,6 @@ pub(super) fn note_inter_mode(mode: usize, drl: usize) {
22142204 DRL_HITS[drl.min(3)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
22152205 }
22162206
2217-/// Takes and clears the inter-mode histogram (NEAREST/NEAR/GLOBAL/NEW).
2218-#[cfg(test)]
2219-pub(crate) fn take_inter_mode_hits() -> [usize; 4] {
2220- [0, 1, 2, 3].map(|i| INTER_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2221-}
2222-
2223-/// Takes and clears the DRL-index histogram (0, 1, 2, 3+).
2224-#[cfg(test)]
2225-pub(crate) fn take_drl_hits() -> [usize; 4] {
2226- [0, 1, 2, 3].map(|i| DRL_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2227-}
2228-
22292207 /// Writes the DRL index of one block: the loop the decoder runs (spec
22302208 /// 5.11.24 `read_drl_idx`, decode.rs' two copies at ~26655 and ~26695), one
22312209 /// `drl_mode` bit per stack entry past `start`, `1` to advance and `0` to
@@ -2713,13 +2691,7 @@ pub(crate) fn sb_coeff_inter_frame_tile_cdfs(
27132691 + usize::from(neighbours.left_skip[mi_r]);
27142692 enc.symbol(usize::from(block.skip), &mut cdfs.skip[skip_ctx]);
27152693 write_cdef_idx(&mut enc, (mi_r, mi_c), block.skip);
2716- write_delta_q(
2717- &mut enc,
2718- cdfs,
2719- (mi_r, mi_c),
2720- !sb128_armed(),
2721- block.skip,
2722- );
2694+ write_delta_q(&mut enc, cdfs, (mi_r, mi_c), !sb128_armed(), block.skip);
27232695 let ii_ctx = intra_inter_ctx(
27242696 has_above,
27252697 has_left,
crates/ec-av1/src/tile/mod.rsmodified+0 -49
@@ -1275,13 +1275,6 @@ fn filter_intra_armed() -> bool {
12751275 static FILTER_INTRA_HITS: [std::sync::atomic::AtomicUsize; 6] =
12761276 [const { std::sync::atomic::AtomicUsize::new(0) }; 6];
12771277
1278-/// Reads [`FILTER_INTRA_HITS`] and zeroes it, so a gate can attribute the
1279-/// counts to its own encode.
1280-#[cfg(test)]
1281-pub(crate) fn take_filter_intra_hits() -> [usize; 6] {
1282- std::array::from_fn(|i| FILTER_INTRA_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1283-}
1284-
12851278 /// `filter_intra_mode_info` (spec 5.11.14) written out, mirrored symbol for
12861279 /// symbol from decode.rs `read_intra_mode`: a `use_filter_intra` flag on every
12871280 /// DC_PRED block whose sides `av1_filter_intra_allowed_bsize` admits (both <=
@@ -1347,13 +1340,6 @@ fn note_intrabc(dv: (i32, i32)) {
13471340 INTRABC_HITS[bucket.clamp(1, 6)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13481341 }
13491342
1350-/// Reads [`INTRABC_HITS`] and zeroes it, so a gate can attribute the counts
1351-/// to its own encode.
1352-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1353-pub(crate) fn take_intrabc_hits() -> [usize; 7] {
1354- std::array::from_fn(|i| INTRABC_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1355-}
1356-
13571343 thread_local! {
13581344 /// This frame header's own `reference_select` bit (spec 5.9.22), armed
13591345 /// the same way `arm_sign_bias` arms the sign-bias table rather than
@@ -1415,13 +1401,6 @@ pub(crate) fn arm_motion_mode(on: bool) {
14151401 static MOTION_MODE_HITS: [std::sync::atomic::AtomicUsize; 9] =
14161402 [const { std::sync::atomic::AtomicUsize::new(0) }; 9];
14171403
1418-/// Reads [`MOTION_MODE_HITS`] and zeroes it, so a gate can attribute the
1419-/// counts to its own encode.
1420-#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1421-pub(crate) fn take_motion_mode_hits() -> [usize; 9] {
1422- std::array::from_fn(|i| MOTION_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1423-}
1424-
14251404 /// What the 3-symbol `motion_mode` symbol costs, in bits, against the same
14261405 /// frame tables [`obmc_symbol_bits`] prices the 2-symbol alphabet off --
14271406 /// which alphabet a block reads is `motion_mode_allowed`'s own choice
@@ -1726,19 +1705,6 @@ static COMPOUND_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
17261705 static COMPOUND_PAIR_HITS: [std::sync::atomic::AtomicUsize; 7] =
17271706 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
17281707
1729-/// Takes and clears the compound mode histogram.
1730-#[cfg(test)]
1731-pub(crate) fn take_compound_mode_hits() -> [usize; 8] {
1732- std::array::from_fn(|i| COMPOUND_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1733-}
1734-
1735-/// Takes and clears the compound pair histogram, indexed by the SECOND
1736-/// reference (`LAST` = 0 .. `ALTREF` = 6).
1737-#[cfg(test)]
1738-pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
1739- std::array::from_fn(|i| COMPOUND_PAIR_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1740-}
1741-
17421708 /// Per-SIZE fire counts of [`write_compound_block`], indexed by
17431709 /// `log2(bw4)` (1 = 8x8, 2 = 16x16, 3 = 32x32 and up): compound started as a
17441710 /// 32x32-only tool, so the share by size is what says whether the leaf
@@ -1746,12 +1712,6 @@ pub(crate) fn take_compound_pair_hits() -> [usize; 7] {
17461712 static COMPOUND_SIZE_HITS: [std::sync::atomic::AtomicUsize; 4] =
17471713 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
17481714
1749-/// Takes and clears the compound size histogram.
1750-#[cfg(test)]
1751-pub(crate) fn take_compound_size_hits() -> [usize; 4] {
1752- std::array::from_fn(|i| COMPOUND_SIZE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1753-}
1754-
17551715 /// The compound mode histogram of the LEAVES alone (`bw4 <= 4`, so 16x16 and
17561716 /// below). The frame-wide histogram above cannot say whether a mode reaches
17571717 /// the leaves at all, which is exactly the question every leaf compound step
@@ -1761,14 +1721,6 @@ pub(crate) fn take_compound_size_hits() -> [usize; 4] {
17611721 static COMPOUND_LEAF_MODE_HITS: [std::sync::atomic::AtomicUsize; 8] =
17621722 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
17631723
1764-/// Takes and clears the leaf-only compound mode histogram.
1765-#[cfg(test)]
1766-pub(crate) fn take_compound_leaf_mode_hits() -> [usize; 8] {
1767- std::array::from_fn(|i| {
1768- COMPOUND_LEAF_MODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed)
1769- })
1770-}
1771-
17721724 /// Writes one COMPOUND_REFERENCE block's whole mode chain -- the writer side
17731725 /// of decode.rs' `read_compound_ref_frames` / `read_inter_compound_mode` /
17741726 /// `assign_compound_mv` / `comp_group_idx` / `compound_idx` sequence, in that
@@ -2493,7 +2445,6 @@ pub fn split_dc_key_frame_tile(
24932445 mod syntax;
24942446 pub use self::syntax::*;
24952447
2496-
24972448 mod blocks;
24982449 pub use self::blocks::*;
24992450 mod leaf;